Merge "Add VTS for setNullCipherAndIntegrityEnabled"
diff --git a/audio/aidl/Android.bp b/audio/aidl/Android.bp
index 8c32f14..92d7d54 100644
--- a/audio/aidl/Android.bp
+++ b/audio/aidl/Android.bp
@@ -23,9 +23,18 @@
default_applicable_licenses: ["hardware_interfaces_license"],
}
+aidl_interface_defaults {
+ name: "android.hardware.audio_defaults",
+ host_supported: true,
+ vendor_available: true,
+ stability: "vintf",
+}
+
aidl_interface {
name: "android.hardware.audio.common",
- vendor_available: true,
+ defaults: [
+ "android.hardware.audio_defaults",
+ ],
srcs: [
"android/hardware/audio/common/PlaybackTrackMetadata.aidl",
"android/hardware/audio/common/RecordTrackMetadata.aidl",
@@ -35,7 +44,6 @@
imports: [
"android.media.audio.common.types-V2",
],
- stability: "vintf",
backend: {
cpp: {
enabled: true,
@@ -87,9 +95,18 @@
],
}
+cc_defaults {
+ name: "latest_android_hardware_audio_common_ndk_shared",
+ shared_libs: [
+ latest_android_hardware_audio_common + "-ndk",
+ ],
+}
+
aidl_interface {
name: "android.hardware.audio.core",
- vendor_available: true,
+ defaults: [
+ "android.hardware.audio_defaults",
+ ],
srcs: [
"android/hardware/audio/core/AudioMode.aidl",
"android/hardware/audio/core/AudioPatch.aidl",
@@ -110,7 +127,6 @@
"android.hardware.audio.common-V1",
"android.media.audio.common.types-V2",
],
- stability: "vintf",
backend: {
// The C++ backend is disabled transitively due to use of FMQ.
cpp: {
@@ -148,7 +164,9 @@
aidl_interface {
name: "android.hardware.audio.effect",
- vendor_available: true,
+ defaults: [
+ "android.hardware.audio_defaults",
+ ],
srcs: [
"android/hardware/audio/effect/BassBoost.aidl",
"android/hardware/audio/effect/Capability.aidl",
@@ -177,7 +195,6 @@
"android.hardware.audio.common-V1",
"android.media.audio.common.types-V2",
],
- stability: "vintf",
backend: {
// The C++ backend is disabled transitively due to use of FMQ.
cpp: {
diff --git a/audio/aidl/default/Android.bp b/audio/aidl/default/Android.bp
index 0a92e99..2b9ed5b 100644
--- a/audio/aidl/default/Android.bp
+++ b/audio/aidl/default/Android.bp
@@ -66,6 +66,7 @@
name: "aidlaudioeffectservice_defaults",
defaults: [
"latest_android_media_audio_common_types_ndk_shared",
+ "latest_android_hardware_audio_effect_ndk_shared",
],
vendor: true,
shared_libs: [
@@ -78,7 +79,6 @@
"libutils",
"android.hardware.common-V2-ndk",
"android.hardware.common.fmq-V1-ndk",
- "android.hardware.audio.effect-V1-ndk",
],
header_libs: [
"libaudioaidl_headers",
@@ -111,10 +111,11 @@
"libbassboostsw",
"libbundleaidl",
"libdynamicsprocessingsw",
+ "libenvreverbsw",
"libequalizersw",
"libhapticgeneratorsw",
"libloudnessenhancersw",
- "libreverbsw",
+ "libpresetreverbsw",
"libtinyxml2",
"libvirtualizersw",
"libvisualizersw",
diff --git a/audio/aidl/default/audio_effects_config.xml b/audio/aidl/default/audio_effects_config.xml
index b6fea27..f4ac8fe 100644
--- a/audio/aidl/default/audio_effects_config.xml
+++ b/audio/aidl/default/audio_effects_config.xml
@@ -34,7 +34,8 @@
<library name="equalizersw" path="libequalizersw.so"/>
<library name="haptic_generatorsw" path="libhapticgeneratorsw.so"/>
<library name="loudness_enhancersw" path="libloudnessenhancersw.so"/>
- <library name="reverbsw" path="libreverbsw.so"/>
+ <library name="env_reverbsw" path="libenvreverbsw.so"/>
+ <library name="preset_reverbsw" path="libpresetreverbsw.so"/>
<library name="virtualizersw" path="libvirtualizersw.so"/>
<library name="visualizersw" path="libvisualizersw.so"/>
<library name="volumesw" path="libvolumesw.so"/>
@@ -64,11 +65,12 @@
<effect name="dynamics_processing" library="dynamics_processingsw" uuid="fa818d78-588b-11ed-9b6a-0242ac120002"/>
<effect name="haptic_generator" library="haptic_generatorsw" uuid="fa819110-588b-11ed-9b6a-0242ac120002"/>
<effect name="loudness_enhancer" library="loudness_enhancersw" uuid="fa819610-588b-11ed-9b6a-0242ac120002"/>
- <effect name="reverb" library="reverbsw" uuid="fa8199c6-588b-11ed-9b6a-0242ac120002"/>
+ <effect name="env_reverb" library="env_reverbsw" uuid="fa819886-588b-11ed-9b6a-0242ac120002"/>
+ <effect name="preset_reverb" library="preset_reverbsw" uuid="fa8199c6-588b-11ed-9b6a-0242ac120002"/>
<effect name="virtualizer" library="virtualizersw" uuid="fa819d86-588b-11ed-9b6a-0242ac120002"/>
<effect name="visualizer" library="visualizersw" uuid="fa81a0f6-588b-11ed-9b6a-0242ac120002"/>
<effect name="volume" library="volumesw" uuid="fa81a718-588b-11ed-9b6a-0242ac120002"/>
- <effectProxy name="equalizer" uuid="14804144-a5ee-4d24-aa88-0002a5d5c51b">
+ <effectProxy name="equalizer" uuid="c8e70ecd-48ca-456e-8a4f-0002a5d5c51b">
<libsw library="equalizersw" uuid="0bed4300-847d-11df-bb17-0002a5d5c51b"/>
<libsw library="bundle" uuid="ce772f20-847d-11df-bb17-0002a5d5c51b"/>
</effectProxy>
diff --git a/audio/aidl/default/bassboost/BassBoostSw.cpp b/audio/aidl/default/bassboost/BassBoostSw.cpp
index 3c39824..c52d16f 100644
--- a/audio/aidl/default/bassboost/BassBoostSw.cpp
+++ b/audio/aidl/default/bassboost/BassBoostSw.cpp
@@ -26,14 +26,14 @@
#include "BassBoostSw.h"
using aidl::android::hardware::audio::effect::BassBoostSw;
-using aidl::android::hardware::audio::effect::BassBoostSwImplUUID;
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kBassBoostSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != BassBoostSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kBassBoostSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/bassboost/BassBoostSw.h b/audio/aidl/default/bassboost/BassBoostSw.h
index fe9c640..90a8887 100644
--- a/audio/aidl/default/bassboost/BassBoostSw.h
+++ b/audio/aidl/default/bassboost/BassBoostSw.h
@@ -39,8 +39,8 @@
public:
BassBoostSw() { LOG(DEBUG) << __func__; }
~BassBoostSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -57,13 +57,14 @@
const BassBoost::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = BassBoostTypeUUID,
- .uuid = BassBoostSwImplUUID,
+ .common = {.id = {.type = kBassBoostTypeUUID,
+ .uuid = kBassBoostSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "BassBoostSw"},
+ .name = "BassBoostSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::bassBoost>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/config/audio_policy_configuration.xsd b/audio/aidl/default/config/audio_policy_configuration.xsd
index 823b217..2c18a1e 100644
--- a/audio/aidl/default/config/audio_policy_configuration.xsd
+++ b/audio/aidl/default/config/audio_policy_configuration.xsd
@@ -424,6 +424,8 @@
<xs:enumeration value="AUDIO_FORMAT_DRA"/>
<xs:enumeration value="AUDIO_FORMAT_APTX_ADAPTIVE_QLEA"/>
<xs:enumeration value="AUDIO_FORMAT_APTX_ADAPTIVE_R4"/>
+ <xs:enumeration value="AUDIO_FORMAT_DTS_HD_MA"/>
+ <xs:enumeration value="AUDIO_FORMAT_DTS_UHD_P2"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="extendableAudioFormat">
diff --git a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp
index 52403e1..3920a58 100644
--- a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp
+++ b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.cpp
@@ -26,14 +26,14 @@
#include "DynamicsProcessingSw.h"
using aidl::android::hardware::audio::effect::DynamicsProcessingSw;
-using aidl::android::hardware::audio::effect::DynamicsProcessingSwImplUUID;
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kDynamicsProcessingSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != DynamicsProcessingSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kDynamicsProcessingSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h
index fc26902..2bc2762 100644
--- a/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h
+++ b/audio/aidl/default/dynamicProcessing/DynamicsProcessingSw.h
@@ -39,8 +39,8 @@
public:
DynamicsProcessingSw() { LOG(DEBUG) << __func__; }
~DynamicsProcessingSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -57,13 +57,14 @@
const DynamicsProcessing::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = DynamicsProcessingTypeUUID,
- .uuid = DynamicsProcessingSwImplUUID,
+ .common = {.id = {.type = kDynamicsProcessingTypeUUID,
+ .uuid = kDynamicsProcessingSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "DynamicsProcessingSw"},
+ .name = "DynamicsProcessingSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::dynamicsProcessing>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/reverb/Android.bp b/audio/aidl/default/envReverb/Android.bp
similarity index 95%
copy from audio/aidl/default/reverb/Android.bp
copy to audio/aidl/default/envReverb/Android.bp
index 955038c..c239ee5 100644
--- a/audio/aidl/default/reverb/Android.bp
+++ b/audio/aidl/default/envReverb/Android.bp
@@ -24,14 +24,14 @@
}
cc_library_shared {
- name: "libreverbsw",
+ name: "libenvreverbsw",
defaults: [
"aidlaudioeffectservice_defaults",
"latest_android_media_audio_common_types_ndk_shared",
"latest_android_hardware_audio_effect_ndk_shared",
],
srcs: [
- "ReverbSw.cpp",
+ "EnvReverbSw.cpp",
":effectCommonFile",
],
visibility: [
diff --git a/audio/aidl/default/reverb/ReverbSw.cpp b/audio/aidl/default/envReverb/EnvReverbSw.cpp
similarity index 77%
copy from audio/aidl/default/reverb/ReverbSw.cpp
copy to audio/aidl/default/envReverb/EnvReverbSw.cpp
index 639f1a2..ad447ab 100644
--- a/audio/aidl/default/reverb/ReverbSw.cpp
+++ b/audio/aidl/default/envReverb/EnvReverbSw.cpp
@@ -15,7 +15,7 @@
*/
#include <cstddef>
-#define LOG_TAG "AHAL_ReverbSw"
+#define LOG_TAG "AHAL_EnvReverbSw"
#include <Utils.h>
#include <algorithm>
#include <unordered_set>
@@ -23,22 +23,22 @@
#include <android-base/logging.h>
#include <fmq/AidlMessageQueue.h>
-#include "ReverbSw.h"
+#include "EnvReverbSw.h"
+using aidl::android::hardware::audio::effect::EnvReverbSw;
using aidl::android::hardware::audio::effect::IEffect;
-using aidl::android::hardware::audio::effect::ReverbSw;
-using aidl::android::hardware::audio::effect::ReverbSwImplUUID;
+using aidl::android::hardware::audio::effect::kEnvReverbSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != ReverbSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kEnvReverbSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
if (instanceSpp) {
- *instanceSpp = ndk::SharedRefBase::make<ReverbSw>();
+ *instanceSpp = ndk::SharedRefBase::make<EnvReverbSw>();
LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
@@ -64,13 +64,13 @@
namespace aidl::android::hardware::audio::effect {
-ndk::ScopedAStatus ReverbSw::getDescriptor(Descriptor* _aidl_return) {
+ndk::ScopedAStatus EnvReverbSw::getDescriptor(Descriptor* _aidl_return) {
LOG(DEBUG) << __func__ << kDescriptor.toString();
*_aidl_return = kDescriptor;
return ndk::ScopedAStatus::ok();
}
-ndk::ScopedAStatus ReverbSw::setParameterSpecific(const Parameter::Specific& specific) {
+ndk::ScopedAStatus EnvReverbSw::setParameterSpecific(const Parameter::Specific& specific) {
RETURN_IF(Parameter::Specific::reverb != specific.getTag(), EX_ILLEGAL_ARGUMENT,
"EffectNotSupported");
std::lock_guard lg(mMutex);
@@ -81,24 +81,24 @@
return ndk::ScopedAStatus::ok();
}
-ndk::ScopedAStatus ReverbSw::getParameterSpecific(const Parameter::Id& id,
- Parameter::Specific* specific) {
+ndk::ScopedAStatus EnvReverbSw::getParameterSpecific(const Parameter::Id& id,
+ Parameter::Specific* specific) {
auto tag = id.getTag();
RETURN_IF(Parameter::Id::reverbTag != tag, EX_ILLEGAL_ARGUMENT, "wrongIdTag");
specific->set<Parameter::Specific::reverb>(mSpecificParam);
return ndk::ScopedAStatus::ok();
}
-std::shared_ptr<EffectContext> ReverbSw::createContext(const Parameter::Common& common) {
+std::shared_ptr<EffectContext> EnvReverbSw::createContext(const Parameter::Common& common) {
if (mContext) {
LOG(DEBUG) << __func__ << " context already exist";
return mContext;
}
- mContext = std::make_shared<ReverbSwContext>(1 /* statusFmqDepth */, common);
+ mContext = std::make_shared<EnvReverbSwContext>(1 /* statusFmqDepth */, common);
return mContext;
}
-RetCode ReverbSw::releaseContext() {
+RetCode EnvReverbSw::releaseContext() {
if (mContext) {
mContext.reset();
}
@@ -106,7 +106,7 @@
}
// Processing method running in EffectWorker thread.
-IEffect::Status ReverbSw::effectProcessImpl(float* in, float* out, int process) {
+IEffect::Status EnvReverbSw::effectProcessImpl(float* in, float* out, int process) {
// TODO: get data buffer and process.
LOG(DEBUG) << __func__ << " in " << in << " out " << out << " process " << process;
for (int i = 0; i < process; i++) {
diff --git a/audio/aidl/default/reverb/ReverbSw.h b/audio/aidl/default/envReverb/EnvReverbSw.h
similarity index 79%
rename from audio/aidl/default/reverb/ReverbSw.h
rename to audio/aidl/default/envReverb/EnvReverbSw.h
index e00956f..5a9ab27 100644
--- a/audio/aidl/default/reverb/ReverbSw.h
+++ b/audio/aidl/default/envReverb/EnvReverbSw.h
@@ -26,21 +26,21 @@
namespace aidl::android::hardware::audio::effect {
-class ReverbSwContext final : public EffectContext {
+class EnvReverbSwContext final : public EffectContext {
public:
- ReverbSwContext(int statusDepth, const Parameter::Common& common)
+ EnvReverbSwContext(int statusDepth, const Parameter::Common& common)
: EffectContext(statusDepth, common) {
LOG(DEBUG) << __func__;
}
// TODO: add specific context here
};
-class ReverbSw final : public EffectImpl {
+class EnvReverbSw final : public EffectImpl {
public:
- ReverbSw() { LOG(DEBUG) << __func__; }
- ~ReverbSw() {
+ EnvReverbSw() { LOG(DEBUG) << __func__; }
+ ~EnvReverbSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -52,18 +52,19 @@
RetCode releaseContext() override;
private:
- std::shared_ptr<ReverbSwContext> mContext;
+ std::shared_ptr<EnvReverbSwContext> mContext;
/* capabilities */
const Reverb::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = ReverbTypeUUID,
- .uuid = ReverbSwImplUUID,
+ .common = {.id = {.type = kEnvReverbTypeUUID,
+ .uuid = kEnvReverbSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "ReverbSw"},
+ .name = "EnvReverbSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::reverb>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/equalizer/EqualizerSw.cpp b/audio/aidl/default/equalizer/EqualizerSw.cpp
index 32c3969..d61ef97 100644
--- a/audio/aidl/default/equalizer/EqualizerSw.cpp
+++ b/audio/aidl/default/equalizer/EqualizerSw.cpp
@@ -26,14 +26,14 @@
#include "EqualizerSw.h"
using aidl::android::hardware::audio::effect::EqualizerSw;
-using aidl::android::hardware::audio::effect::EqualizerSwImplUUID;
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kEqualizerSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != EqualizerSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kEqualizerSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/equalizer/EqualizerSw.h b/audio/aidl/default/equalizer/EqualizerSw.h
index 8762f5d..aa4587a 100644
--- a/audio/aidl/default/equalizer/EqualizerSw.h
+++ b/audio/aidl/default/equalizer/EqualizerSw.h
@@ -82,8 +82,8 @@
public:
EqualizerSw() { LOG(DEBUG) << __func__; }
~EqualizerSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -109,13 +109,14 @@
const Equalizer::Capability kEqCap = {.bandFrequencies = mBandFrequency, .presets = mPresets};
// Effect descriptor.
- const Descriptor kDesc = {.common = {.id = {.type = EqualizerTypeUUID,
- .uuid = EqualizerSwImplUUID,
- .proxy = std::nullopt},
+ const Descriptor kDesc = {.common = {.id = {.type = kEqualizerTypeUUID,
+ .uuid = kEqualizerSwImplUUID,
+ .proxy = kEqualizerProxyUUID},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "EqualizerSw"},
+ .name = "EqualizerSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::equalizer>(kEqCap)};
ndk::ScopedAStatus getParameterEqualizer(const Equalizer::Tag& tag,
diff --git a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp
index 90675c2..fd5ea34 100644
--- a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp
+++ b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.cpp
@@ -26,14 +26,14 @@
#include "HapticGeneratorSw.h"
using aidl::android::hardware::audio::effect::HapticGeneratorSw;
-using aidl::android::hardware::audio::effect::HapticGeneratorSwImplUUID;
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kHapticGeneratorSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != HapticGeneratorSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kHapticGeneratorSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h
index b5a5036..518aa87 100644
--- a/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h
+++ b/audio/aidl/default/hapticGenerator/HapticGeneratorSw.h
@@ -39,8 +39,8 @@
public:
HapticGeneratorSw() { LOG(DEBUG) << __func__; }
~HapticGeneratorSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -57,13 +57,14 @@
const HapticGenerator::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = HapticGeneratorTypeUUID,
- .uuid = HapticGeneratorSwImplUUID,
+ .common = {.id = {.type = kHapticGeneratorTypeUUID,
+ .uuid = kHapticGeneratorSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "HapticGeneratorSw"},
+ .name = "HapticGeneratorSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::hapticGenerator>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/include/effect-impl/EffectImpl.h b/audio/aidl/default/include/effect-impl/EffectImpl.h
index cb395b7..d9825da 100644
--- a/audio/aidl/default/include/effect-impl/EffectImpl.h
+++ b/audio/aidl/default/include/effect-impl/EffectImpl.h
@@ -30,11 +30,8 @@
class EffectImpl : public BnEffect, public EffectWorker {
public:
- EffectImpl() { LOG(DEBUG) << __func__; }
- ~EffectImpl() {
- cleanUp();
- LOG(DEBUG) << __func__;
- }
+ EffectImpl() = default;
+ virtual ~EffectImpl() = default;
/**
* Each effect implementation CAN override these methods if necessary
@@ -78,9 +75,9 @@
State mState GUARDED_BY(mMutex) = State::INIT;
IEffect::Status status(binder_status_t status, size_t consumed, size_t produced);
+ void cleanUp();
private:
- void cleanUp();
std::shared_ptr<EffectContext> mContext GUARDED_BY(mMutex);
};
} // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/include/effect-impl/EffectUUID.h b/audio/aidl/default/include/effect-impl/EffectUUID.h
index 184a587..7709eab 100644
--- a/audio/aidl/default/include/effect-impl/EffectUUID.h
+++ b/audio/aidl/default/include/effect-impl/EffectUUID.h
@@ -23,150 +23,160 @@
using ::aidl::android::media::audio::common::AudioUuid;
-// Null UUID
-static const AudioUuid EffectNullUuid = {static_cast<int32_t>(0xec7178ec),
- 0xe5e1,
- 0x4432,
- 0xa3f4,
- {0x46, 0x57, 0xe6, 0x79, 0x52, 0x10}};
-
+// ec7178ec-e5e1-4432-a3f4-4657e6795210
+static const AudioUuid kEffectNullUuid = {static_cast<int32_t>(0xec7178ec),
+ 0xe5e1,
+ 0x4432,
+ 0xa3f4,
+ {0x46, 0x57, 0xe6, 0x79, 0x52, 0x10}};
// Zero UUID
-static const AudioUuid EffectZeroUuid = {
+static const AudioUuid kEffectZeroUuid = {
static_cast<int32_t>(0x0), 0x0, 0x0, 0x0, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0}};
-// Equalizer type UUID.
-static const AudioUuid EqualizerTypeUUID = {static_cast<int32_t>(0x0bed4300),
- 0xddd6,
- 0x11db,
- 0x8f34,
- {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
-
-// 0bed4300-847d-11df-bb17-0002a5d5c51b
-static const AudioUuid EqualizerSwImplUUID = {static_cast<int32_t>(0x0bed4300),
- 0x847d,
- 0x11df,
- 0xbb17,
- {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
-
-// ce772f20-847d-11df-bb17-0002a5d5c51b
-static const AudioUuid EqualizerBundleImplUUID = {static_cast<int32_t>(0xce772f20),
- 0x847d,
- 0x11df,
- 0xbb17,
- {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
-
-// fa8184a4-588b-11ed-9b6a-0242ac120002
-static const AudioUuid BassBoostTypeUUID = {static_cast<int32_t>(0xfa8184a4),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// 0634f220-ddd4-11db-a0fc-0002a5d5c51b
+static const AudioUuid kBassBoostTypeUUID = {static_cast<int32_t>(0x0634f220),
+ 0xddd4,
+ 0x11db,
+ 0xa0fc,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
// fa8181f2-588b-11ed-9b6a-0242ac120002
-static const AudioUuid BassBoostSwImplUUID = {static_cast<int32_t>(0xfa8181f2),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa81862a-588b-11ed-9b6a-0242ac120002
-static const AudioUuid DownmixTypeUUID = {static_cast<int32_t>(0xfa81862a),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa8187ba-588b-11ed-9b6a-0242ac120002
-static const AudioUuid DownmixSwImplUUID = {static_cast<int32_t>(0xfa8187ba),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa818954-588b-11ed-9b6a-0242ac120002
-static const AudioUuid DynamicsProcessingTypeUUID = {static_cast<int32_t>(0xfa818954),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa818d78-588b-11ed-9b6a-0242ac120002
-static const AudioUuid DynamicsProcessingSwImplUUID = {static_cast<int32_t>(0xfa818d78),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa818f62-588b-11ed-9b6a-0242ac120002
-static const AudioUuid HapticGeneratorTypeUUID = {static_cast<int32_t>(0xfa818f62),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa819110-588b-11ed-9b6a-0242ac120002
-static const AudioUuid HapticGeneratorSwImplUUID = {static_cast<int32_t>(0xfa819110),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-
-// fa8194a8-588b-11ed-9b6a-0242ac120002
-static const AudioUuid LoudnessEnhancerTypeUUID = {static_cast<int32_t>(0xfa8194a8),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa819610-588b-11ed-9b6a-0242ac120002
-static const AudioUuid LoudnessEnhancerSwImplUUID = {static_cast<int32_t>(0xfa819610),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa819886-588b-11ed-9b6a-0242ac120002
-static const AudioUuid ReverbTypeUUID = {static_cast<int32_t>(0xfa819886),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa8199c6-588b-11ed-9b6a-0242ac120002
-static const AudioUuid ReverbSwImplUUID = {static_cast<int32_t>(0xfa8199c6),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-
-// fa819af2-588b-11ed-9b6a-0242ac120002
-static const AudioUuid VirtualizerTypeUUID = {static_cast<int32_t>(0xfa819af2),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa819d86-588b-11ed-9b6a-0242ac120002
-static const AudioUuid VirtualizerSwImplUUID = {static_cast<int32_t>(0xfa819d86),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-
-// fa819f3e-588b-11ed-9b6a-0242ac120002
-static const AudioUuid VisualizerTypeUUID = {static_cast<int32_t>(0xfa819f3e),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa81a0f6-588b-11ed-9b6a-0242ac120002
-static const AudioUuid VisualizerSwImplUUID = {static_cast<int32_t>(0xfa81a0f6),
+static const AudioUuid kBassBoostSwImplUUID = {static_cast<int32_t>(0xfa8181f2),
0x588b,
0x11ed,
0x9b6a,
{0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-
-// fa81a2b8-588b-11ed-9b6a-0242ac120002
-static const AudioUuid VolumeTypeUUID = {static_cast<int32_t>(0xfa81a2b8),
- 0x588b,
- 0x11ed,
- 0x9b6a,
- {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
-// fa81a718-588b-11ed-9b6a-0242ac120002
-static const AudioUuid VolumeSwImplUUID = {static_cast<int32_t>(0xfa81a718),
+// fa81862a-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kDownmixTypeUUID = {static_cast<int32_t>(0xfa81862a),
0x588b,
0x11ed,
0x9b6a,
{0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// fa8187ba-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kDownmixSwImplUUID = {static_cast<int32_t>(0xfa8187ba),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// 0bed4300-ddd6-11db-8f34-0002a5d5c51b.
+static const AudioUuid kEqualizerTypeUUID = {static_cast<int32_t>(0x0bed4300),
+ 0xddd6,
+ 0x11db,
+ 0x8f34,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+// 0bed4300-847d-11df-bb17-0002a5d5c51b
+static const AudioUuid kEqualizerSwImplUUID = {static_cast<int32_t>(0x0bed4300),
+ 0x847d,
+ 0x11df,
+ 0xbb17,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+// ce772f20-847d-11df-bb17-0002a5d5c51b
+static const AudioUuid kEqualizerBundleImplUUID = {static_cast<int32_t>(0xce772f20),
+ 0x847d,
+ 0x11df,
+ 0xbb17,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+// c8e70ecd-48ca-456e-8a4f-0002a5d5c51b
+static const AudioUuid kEqualizerProxyUUID = {static_cast<int32_t>(0xc8e70ecd),
+ 0x48ca,
+ 0x456e,
+ 0x8a4f,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+// 7261676f-6d75-7369-6364-28e2fd3ac39e
+static const AudioUuid kDynamicsProcessingTypeUUID = {static_cast<int32_t>(0x7261676f),
+ 0x6d75,
+ 0x7369,
+ 0x6364,
+ {0x28, 0xe2, 0xfd, 0x3a, 0xc3, 0x9e}};
+// fa818d78-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kDynamicsProcessingSwImplUUID = {static_cast<int32_t>(0xfa818d78),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// 1411e6d6-aecd-4021-a1cf-a6aceb0d71e5
+static const AudioUuid kHapticGeneratorTypeUUID = {static_cast<int32_t>(0x1411e6d6),
+ 0xaecd,
+ 0x4021,
+ 0xa1cf,
+ {0xa6, 0xac, 0xeb, 0x0d, 0x71, 0xe5}};
+// fa819110-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kHapticGeneratorSwImplUUID = {static_cast<int32_t>(0xfa819110),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// fe3199be-aed0-413f-87bb-11260eb63cf1
+static const AudioUuid kLoudnessEnhancerTypeUUID = {static_cast<int32_t>(0xfe3199be),
+ 0xaed0,
+ 0x413f,
+ 0x87bb,
+ {0x11, 0x26, 0x0e, 0xb6, 0x3c, 0xf1}};
+// fa819610-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kLoudnessEnhancerSwImplUUID = {static_cast<int32_t>(0xfa819610),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// c2e5d5f0-94bd-4763-9cac-4e234d06839e
+static const AudioUuid kEnvReverbTypeUUID = {static_cast<int32_t>(0xc2e5d5f0),
+ 0x94bd,
+ 0x4763,
+ 0x9cac,
+ {0x4e, 0x23, 0x4d, 0x06, 0x83, 0x9e}};
+// fa819886-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kEnvReverbSwImplUUID = {static_cast<int32_t>(0xfa819886),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// 47382d60-ddd8-11db-bf3a-0002a5d5c51b
+static const AudioUuid kPresetReverbTypeUUID = {static_cast<int32_t>(0x47382d60),
+ 0xddd8,
+ 0x11db,
+ 0xbf3a,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+// fa8199c6-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kPresetReverbSwImplUUID = {static_cast<int32_t>(0xfa8199c6),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// 37cc2c00-dddd-11db-8577-0002a5d5c51b
+static const AudioUuid kVirtualizerTypeUUID = {static_cast<int32_t>(0x37cc2c00),
+ 0xdddd,
+ 0x11db,
+ 0x8577,
+ {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
+// fa819d86-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kVirtualizerSwImplUUID = {static_cast<int32_t>(0xfa819d86),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// fa819f3e-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kVisualizerTypeUUID = {static_cast<int32_t>(0xfa819f3e),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// fa81a0f6-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kVisualizerSwImplUUID = {static_cast<int32_t>(0xfa81a0f6),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// fa81a2b8-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kVolumeTypeUUID = {static_cast<int32_t>(0xfa81a2b8),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
+// fa81a718-588b-11ed-9b6a-0242ac120002
+static const AudioUuid kVolumeSwImplUUID = {static_cast<int32_t>(0xfa81a718),
+ 0x588b,
+ 0x11ed,
+ 0x9b6a,
+ {0x02, 0x42, 0xac, 0x12, 0x00, 0x02}};
/**
* @brief A map between effect name and effect type UUID.
@@ -174,20 +184,21 @@
* We need this map is because existing audio_effects.xml don't have a type UUID defined.
*/
static const std::map<const std::string /* effect type */, const AudioUuid&> kUuidNameTypeMap = {
- {"bassboost", BassBoostTypeUUID},
- {"downmix", DownmixTypeUUID},
- {"dynamics_processing", DynamicsProcessingTypeUUID},
- {"equalizer", EqualizerTypeUUID},
- {"haptic_generator", HapticGeneratorTypeUUID},
- {"loudness_enhancer", LoudnessEnhancerTypeUUID},
- {"reverb", ReverbTypeUUID},
- {"reverb_env_aux", ReverbTypeUUID},
- {"reverb_env_ins", ReverbTypeUUID},
- {"reverb_pre_aux", ReverbTypeUUID},
- {"reverb_pre_ins", ReverbTypeUUID},
- {"virtualizer", VirtualizerTypeUUID},
- {"visualizer", VisualizerTypeUUID},
- {"volume", VolumeTypeUUID},
+ {"bassboost", kBassBoostTypeUUID},
+ {"downmix", kDownmixTypeUUID},
+ {"dynamics_processing", kDynamicsProcessingTypeUUID},
+ {"equalizer", kEqualizerTypeUUID},
+ {"haptic_generator", kHapticGeneratorTypeUUID},
+ {"loudness_enhancer", kLoudnessEnhancerTypeUUID},
+ {"env_reverb", kEnvReverbTypeUUID},
+ {"preset_reverb", kPresetReverbTypeUUID},
+ {"reverb_env_aux", kEnvReverbTypeUUID},
+ {"reverb_env_ins", kEnvReverbTypeUUID},
+ {"reverb_pre_aux", kPresetReverbTypeUUID},
+ {"reverb_pre_ins", kPresetReverbTypeUUID},
+ {"virtualizer", kVirtualizerTypeUUID},
+ {"visualizer", kVisualizerTypeUUID},
+ {"volume", kVolumeTypeUUID},
};
} // namespace aidl::android::hardware::audio::effect
diff --git a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp
index 27b9169..9d2b978 100644
--- a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp
+++ b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.cpp
@@ -26,14 +26,14 @@
#include "LoudnessEnhancerSw.h"
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kLoudnessEnhancerSwImplUUID;
using aidl::android::hardware::audio::effect::LoudnessEnhancerSw;
-using aidl::android::hardware::audio::effect::LoudnessEnhancerSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != LoudnessEnhancerSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kLoudnessEnhancerSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h
index 478aebc..856bf0b 100644
--- a/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h
+++ b/audio/aidl/default/loudnessEnhancer/LoudnessEnhancerSw.h
@@ -48,8 +48,8 @@
public:
LoudnessEnhancerSw() { LOG(DEBUG) << __func__; }
~LoudnessEnhancerSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -66,13 +66,14 @@
const LoudnessEnhancer::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = LoudnessEnhancerTypeUUID,
- .uuid = LoudnessEnhancerSwImplUUID,
+ .common = {.id = {.type = kLoudnessEnhancerTypeUUID,
+ .uuid = kLoudnessEnhancerSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "LoudnessEnhancerSw"},
+ .name = "LoudnessEnhancerSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::loudnessEnhancer>(kCapability)};
ndk::ScopedAStatus getParameterLoudnessEnhancer(const LoudnessEnhancer::Tag& tag,
diff --git a/audio/aidl/default/reverb/Android.bp b/audio/aidl/default/presetReverb/Android.bp
similarity index 95%
rename from audio/aidl/default/reverb/Android.bp
rename to audio/aidl/default/presetReverb/Android.bp
index 955038c..4148511 100644
--- a/audio/aidl/default/reverb/Android.bp
+++ b/audio/aidl/default/presetReverb/Android.bp
@@ -24,14 +24,14 @@
}
cc_library_shared {
- name: "libreverbsw",
+ name: "libpresetreverbsw",
defaults: [
"aidlaudioeffectservice_defaults",
"latest_android_media_audio_common_types_ndk_shared",
"latest_android_hardware_audio_effect_ndk_shared",
],
srcs: [
- "ReverbSw.cpp",
+ "PresetReverbSw.cpp",
":effectCommonFile",
],
visibility: [
diff --git a/audio/aidl/default/reverb/ReverbSw.cpp b/audio/aidl/default/presetReverb/PresetReverbSw.cpp
similarity index 77%
rename from audio/aidl/default/reverb/ReverbSw.cpp
rename to audio/aidl/default/presetReverb/PresetReverbSw.cpp
index 639f1a2..069d0ff 100644
--- a/audio/aidl/default/reverb/ReverbSw.cpp
+++ b/audio/aidl/default/presetReverb/PresetReverbSw.cpp
@@ -15,7 +15,7 @@
*/
#include <cstddef>
-#define LOG_TAG "AHAL_ReverbSw"
+#define LOG_TAG "AHAL_PresetReverbSw"
#include <Utils.h>
#include <algorithm>
#include <unordered_set>
@@ -23,22 +23,22 @@
#include <android-base/logging.h>
#include <fmq/AidlMessageQueue.h>
-#include "ReverbSw.h"
+#include "PresetReverbSw.h"
using aidl::android::hardware::audio::effect::IEffect;
-using aidl::android::hardware::audio::effect::ReverbSw;
-using aidl::android::hardware::audio::effect::ReverbSwImplUUID;
+using aidl::android::hardware::audio::effect::kPresetReverbSwImplUUID;
+using aidl::android::hardware::audio::effect::PresetReverbSw;
using aidl::android::hardware::audio::effect::State;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != ReverbSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kPresetReverbSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
if (instanceSpp) {
- *instanceSpp = ndk::SharedRefBase::make<ReverbSw>();
+ *instanceSpp = ndk::SharedRefBase::make<PresetReverbSw>();
LOG(DEBUG) << __func__ << " instance " << instanceSpp->get() << " created";
return EX_NONE;
} else {
@@ -64,13 +64,13 @@
namespace aidl::android::hardware::audio::effect {
-ndk::ScopedAStatus ReverbSw::getDescriptor(Descriptor* _aidl_return) {
+ndk::ScopedAStatus PresetReverbSw::getDescriptor(Descriptor* _aidl_return) {
LOG(DEBUG) << __func__ << kDescriptor.toString();
*_aidl_return = kDescriptor;
return ndk::ScopedAStatus::ok();
}
-ndk::ScopedAStatus ReverbSw::setParameterSpecific(const Parameter::Specific& specific) {
+ndk::ScopedAStatus PresetReverbSw::setParameterSpecific(const Parameter::Specific& specific) {
RETURN_IF(Parameter::Specific::reverb != specific.getTag(), EX_ILLEGAL_ARGUMENT,
"EffectNotSupported");
std::lock_guard lg(mMutex);
@@ -81,24 +81,24 @@
return ndk::ScopedAStatus::ok();
}
-ndk::ScopedAStatus ReverbSw::getParameterSpecific(const Parameter::Id& id,
- Parameter::Specific* specific) {
+ndk::ScopedAStatus PresetReverbSw::getParameterSpecific(const Parameter::Id& id,
+ Parameter::Specific* specific) {
auto tag = id.getTag();
RETURN_IF(Parameter::Id::reverbTag != tag, EX_ILLEGAL_ARGUMENT, "wrongIdTag");
specific->set<Parameter::Specific::reverb>(mSpecificParam);
return ndk::ScopedAStatus::ok();
}
-std::shared_ptr<EffectContext> ReverbSw::createContext(const Parameter::Common& common) {
+std::shared_ptr<EffectContext> PresetReverbSw::createContext(const Parameter::Common& common) {
if (mContext) {
LOG(DEBUG) << __func__ << " context already exist";
return mContext;
}
- mContext = std::make_shared<ReverbSwContext>(1 /* statusFmqDepth */, common);
+ mContext = std::make_shared<PresetReverbSwContext>(1 /* statusFmqDepth */, common);
return mContext;
}
-RetCode ReverbSw::releaseContext() {
+RetCode PresetReverbSw::releaseContext() {
if (mContext) {
mContext.reset();
}
@@ -106,7 +106,7 @@
}
// Processing method running in EffectWorker thread.
-IEffect::Status ReverbSw::effectProcessImpl(float* in, float* out, int process) {
+IEffect::Status PresetReverbSw::effectProcessImpl(float* in, float* out, int process) {
// TODO: get data buffer and process.
LOG(DEBUG) << __func__ << " in " << in << " out " << out << " process " << process;
for (int i = 0; i < process; i++) {
diff --git a/audio/aidl/default/reverb/ReverbSw.h b/audio/aidl/default/presetReverb/PresetReverbSw.h
similarity index 78%
copy from audio/aidl/default/reverb/ReverbSw.h
copy to audio/aidl/default/presetReverb/PresetReverbSw.h
index e00956f..75a5a94 100644
--- a/audio/aidl/default/reverb/ReverbSw.h
+++ b/audio/aidl/default/presetReverb/PresetReverbSw.h
@@ -26,21 +26,21 @@
namespace aidl::android::hardware::audio::effect {
-class ReverbSwContext final : public EffectContext {
+class PresetReverbSwContext final : public EffectContext {
public:
- ReverbSwContext(int statusDepth, const Parameter::Common& common)
+ PresetReverbSwContext(int statusDepth, const Parameter::Common& common)
: EffectContext(statusDepth, common) {
LOG(DEBUG) << __func__;
}
// TODO: add specific context here
};
-class ReverbSw final : public EffectImpl {
+class PresetReverbSw final : public EffectImpl {
public:
- ReverbSw() { LOG(DEBUG) << __func__; }
- ~ReverbSw() {
+ PresetReverbSw() { LOG(DEBUG) << __func__; }
+ ~PresetReverbSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -52,18 +52,19 @@
RetCode releaseContext() override;
private:
- std::shared_ptr<ReverbSwContext> mContext;
+ std::shared_ptr<PresetReverbSwContext> mContext;
/* capabilities */
const Reverb::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = ReverbTypeUUID,
- .uuid = ReverbSwImplUUID,
+ .common = {.id = {.type = kPresetReverbTypeUUID,
+ .uuid = kPresetReverbSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "ReverbSw"},
+ .name = "PresetReverbSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::reverb>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/virtualizer/VirtualizerSw.cpp b/audio/aidl/default/virtualizer/VirtualizerSw.cpp
index ccb7b4b..9688fc8 100644
--- a/audio/aidl/default/virtualizer/VirtualizerSw.cpp
+++ b/audio/aidl/default/virtualizer/VirtualizerSw.cpp
@@ -26,14 +26,14 @@
#include "VirtualizerSw.h"
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kVirtualizerSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::hardware::audio::effect::VirtualizerSw;
-using aidl::android::hardware::audio::effect::VirtualizerSwImplUUID;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != VirtualizerSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kVirtualizerSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/virtualizer/VirtualizerSw.h b/audio/aidl/default/virtualizer/VirtualizerSw.h
index da1998b..e4de8b3 100644
--- a/audio/aidl/default/virtualizer/VirtualizerSw.h
+++ b/audio/aidl/default/virtualizer/VirtualizerSw.h
@@ -39,8 +39,8 @@
public:
VirtualizerSw() { LOG(DEBUG) << __func__; }
~VirtualizerSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -57,13 +57,14 @@
const Virtualizer::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = VirtualizerTypeUUID,
- .uuid = VirtualizerSwImplUUID,
+ .common = {.id = {.type = kVirtualizerTypeUUID,
+ .uuid = kVirtualizerSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "VirtualizerSw"},
+ .name = "VirtualizerSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::virtualizer>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/visualizer/VisualizerSw.cpp b/audio/aidl/default/visualizer/VisualizerSw.cpp
index 5a24f18..24a7bef 100644
--- a/audio/aidl/default/visualizer/VisualizerSw.cpp
+++ b/audio/aidl/default/visualizer/VisualizerSw.cpp
@@ -26,14 +26,14 @@
#include "VisualizerSw.h"
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kVisualizerSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::hardware::audio::effect::VisualizerSw;
-using aidl::android::hardware::audio::effect::VisualizerSwImplUUID;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != VisualizerSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kVisualizerSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/visualizer/VisualizerSw.h b/audio/aidl/default/visualizer/VisualizerSw.h
index 21101dd..bccd6e9 100644
--- a/audio/aidl/default/visualizer/VisualizerSw.h
+++ b/audio/aidl/default/visualizer/VisualizerSw.h
@@ -39,8 +39,8 @@
public:
VisualizerSw() { LOG(DEBUG) << __func__; }
~VisualizerSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -57,13 +57,14 @@
const Visualizer::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = VisualizerTypeUUID,
- .uuid = VisualizerSwImplUUID,
+ .common = {.id = {.type = kVisualizerTypeUUID,
+ .uuid = kVisualizerSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "VisualizerSw"},
+ .name = "VisualizerSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::visualizer>(kCapability)};
/* parameters */
diff --git a/audio/aidl/default/volume/VolumeSw.cpp b/audio/aidl/default/volume/VolumeSw.cpp
index e2f42d7..b8af921 100644
--- a/audio/aidl/default/volume/VolumeSw.cpp
+++ b/audio/aidl/default/volume/VolumeSw.cpp
@@ -26,14 +26,14 @@
#include "VolumeSw.h"
using aidl::android::hardware::audio::effect::IEffect;
+using aidl::android::hardware::audio::effect::kVolumeSwImplUUID;
using aidl::android::hardware::audio::effect::State;
using aidl::android::hardware::audio::effect::VolumeSw;
-using aidl::android::hardware::audio::effect::VolumeSwImplUUID;
using aidl::android::media::audio::common::AudioUuid;
extern "C" binder_exception_t createEffect(const AudioUuid* in_impl_uuid,
std::shared_ptr<IEffect>* instanceSpp) {
- if (!in_impl_uuid || *in_impl_uuid != VolumeSwImplUUID) {
+ if (!in_impl_uuid || *in_impl_uuid != kVolumeSwImplUUID) {
LOG(ERROR) << __func__ << "uuid not supported";
return EX_ILLEGAL_ARGUMENT;
}
diff --git a/audio/aidl/default/volume/VolumeSw.h b/audio/aidl/default/volume/VolumeSw.h
index e46c864..86e01c1 100644
--- a/audio/aidl/default/volume/VolumeSw.h
+++ b/audio/aidl/default/volume/VolumeSw.h
@@ -39,8 +39,8 @@
public:
VolumeSw() { LOG(DEBUG) << __func__; }
~VolumeSw() {
+ cleanUp();
LOG(DEBUG) << __func__;
- releaseContext();
}
ndk::ScopedAStatus getDescriptor(Descriptor* _aidl_return) override;
@@ -57,13 +57,14 @@
const Volume::Capability kCapability;
/* Effect descriptor */
const Descriptor kDescriptor = {
- .common = {.id = {.type = VolumeTypeUUID,
- .uuid = VolumeSwImplUUID,
+ .common = {.id = {.type = kVolumeTypeUUID,
+ .uuid = kVolumeSwImplUUID,
.proxy = std::nullopt},
.flags = {.type = Flags::Type::INSERT,
.insert = Flags::Insert::FIRST,
.volume = Flags::Volume::CTRL},
- .name = "VolumeSw"},
+ .name = "VolumeSw",
+ .implementor = "The Android Open Source Project"},
.capability = Capability::make<Capability::volume>(kCapability)};
/* parameters */
diff --git a/audio/aidl/vts/EffectFactoryHelper.h b/audio/aidl/vts/EffectFactoryHelper.h
index d58fcf2..dc766dd 100644
--- a/audio/aidl/vts/EffectFactoryHelper.h
+++ b/audio/aidl/vts/EffectFactoryHelper.h
@@ -29,10 +29,7 @@
using namespace android;
using aidl::android::hardware::audio::effect::Descriptor;
-using aidl::android::hardware::audio::effect::EffectNullUuid;
-using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::IFactory;
-using aidl::android::hardware::audio::effect::Processing;
using aidl::android::media::audio::common::AudioUuid;
class EffectFactoryHelper {
@@ -48,122 +45,36 @@
ASSERT_NE(mEffectFactory, nullptr);
mEffectFactory = IFactory::fromBinder(binderUtil.restartService());
ASSERT_NE(mEffectFactory, nullptr);
- ClearEffectMap();
}
- void QueryEffects(const std::optional<AudioUuid>& in_type,
- const std::optional<AudioUuid>& in_instance,
- const std::optional<AudioUuid>& in_proxy,
- std::vector<Descriptor::Identity>* _aidl_return) {
- ASSERT_NE(mEffectFactory, nullptr);
- EXPECT_IS_OK(mEffectFactory->queryEffects(in_type, in_instance, in_proxy, _aidl_return));
- mIds = *_aidl_return;
- }
+ std::shared_ptr<IFactory> GetFactory() const { return mEffectFactory; }
- void QueryProcessing(const std::optional<Processing::Type>& in_type,
- std::vector<Processing>* _aidl_return) {
- ASSERT_NE(mEffectFactory, nullptr);
- EXPECT_IS_OK(mEffectFactory->queryProcessing(in_type, _aidl_return));
- // only update the whole list if no filter applied
- if (!in_type.has_value()) {
- mProcesses = *_aidl_return;
- }
- }
+ static std::vector<std::pair<std::shared_ptr<IFactory>, Descriptor::Identity>>
+ getAllEffectDescriptors(std::string serviceName, std::optional<AudioUuid> type = std::nullopt) {
+ AudioHalBinderServiceUtil util;
+ auto names = android::getAidlHalInstanceNames(serviceName);
+ std::vector<std::pair<std::shared_ptr<IFactory>, Descriptor::Identity>> result;
- void CreateEffects() {
- for (const auto& id : mIds) {
- std::shared_ptr<IEffect> effect;
- EXPECT_IS_OK(mEffectFactory->createEffect(id.uuid, &effect));
- EXPECT_NE(effect, nullptr) << id.toString();
- if (effect) {
- mEffectIdMap[effect] = id;
+ for (const auto& name : names) {
+ auto factory = IFactory::fromBinder(util.connectToService(name));
+ if (factory) {
+ if (std::vector<Descriptor::Identity> ids;
+ factory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids).isOk()) {
+ for (const auto& id : ids) {
+ if (type.has_value() && id.type != type.value()) {
+ continue;
+ }
+ result.emplace_back(factory, id);
+ }
+ }
}
}
- }
- void QueryAndCreateEffects(const AudioUuid& type = EffectNullUuid) {
- std::vector<Descriptor::Identity> ids;
- ASSERT_NE(mEffectFactory, nullptr);
-
- if (type == EffectNullUuid) {
- EXPECT_IS_OK(
- mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
- } else {
- EXPECT_IS_OK(mEffectFactory->queryEffects(type, std::nullopt, std::nullopt, &ids));
- }
- for (const auto& id : ids) {
- ASSERT_EQ(id.type, type);
- std::shared_ptr<IEffect> effect;
- EXPECT_IS_OK(mEffectFactory->createEffect(id.uuid, &effect));
- EXPECT_NE(effect, nullptr) << id.toString();
- if (effect) {
- mEffectIdMap[effect] = id;
- }
- }
+ return result;
}
- void CreateEffectsAndExpect(
- const std::vector<std::pair<Descriptor::Identity, binder_exception_t>>& uuid_status) {
- ASSERT_NE(mEffectFactory, nullptr);
- for (const auto& it : uuid_status) {
- std::shared_ptr<IEffect> effect;
- auto status = mEffectFactory->createEffect(it.first.uuid, &effect);
- EXPECT_STATUS(it.second, status);
- if (effect) {
- mEffectIdMap[effect] = it.first;
- }
- }
- }
-
- void DestroyEffectAndExpect(std::shared_ptr<IEffect>& instance, binder_exception_t exception) {
- ASSERT_NE(mEffectFactory, nullptr);
- auto status = mEffectFactory->destroyEffect(instance);
- EXPECT_STATUS(exception, status);
- }
-
- void QueryAndCreateAllEffects() {
- ASSERT_NE(mEffectFactory, nullptr);
- EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt,
- &mCompleteIds));
- for (const auto& id : mCompleteIds) {
- std::shared_ptr<IEffect> effect;
- EXPECT_IS_OK(mEffectFactory->createEffect(id.uuid, &effect));
- EXPECT_NE(effect, nullptr) << id.toString();
- mEffectIdMap[effect] = id;
- }
- }
-
- void DestroyEffects(const binder_exception_t expected = EX_NONE, const int remaining = 0) {
- ASSERT_NE(mEffectFactory, nullptr);
-
- for (auto it = mEffectIdMap.begin(); it != mEffectIdMap.end();) {
- auto erased = it++;
- auto status = mEffectFactory->destroyEffect(erased->first);
- EXPECT_STATUS(expected, status);
- if (status.isOk()) {
- mEffectIdMap.erase(erased);
- }
- }
- EXPECT_EQ((unsigned int)remaining, mEffectIdMap.size());
- }
-
- std::shared_ptr<IFactory> GetFactory() { return mEffectFactory; }
- const std::vector<Descriptor::Identity>& GetEffectIds() { return mIds; }
- const std::vector<Descriptor::Identity>& GetCompleteEffectIdList() const {
- return mCompleteIds;
- }
- const std::map<std::shared_ptr<IEffect>, Descriptor::Identity>& GetEffectMap() const {
- return mEffectIdMap;
- }
- void ClearEffectMap() { mEffectIdMap.clear(); }
-
private:
std::shared_ptr<IFactory> mEffectFactory;
std::string mServiceName;
AudioHalBinderServiceUtil binderUtil;
- std::vector<Descriptor::Identity> mIds;
- std::vector<Descriptor::Identity> mCompleteIds;
- std::vector<Processing> mProcesses;
-
- std::map<std::shared_ptr<IEffect>, Descriptor::Identity> mEffectIdMap;
};
diff --git a/audio/aidl/vts/EffectHelper.h b/audio/aidl/vts/EffectHelper.h
index 623ac37..73a1f49 100644
--- a/audio/aidl/vts/EffectHelper.h
+++ b/audio/aidl/vts/EffectHelper.h
@@ -16,6 +16,7 @@
#pragma once
+#include <algorithm>
#include <memory>
#include <string>
#include <unordered_map>
@@ -24,7 +25,6 @@
#include <aidl/android/hardware/audio/effect/IEffect.h>
#include <aidl/android/hardware/audio/effect/IFactory.h>
#include <aidl/android/media/audio/common/AudioChannelLayout.h>
-#include <aidl/android/media/audio/common/AudioDeviceType.h>
#include <android/binder_auto_utils.h>
#include <fmq/AidlMessageQueue.h>
@@ -35,275 +35,139 @@
using namespace android;
using aidl::android::hardware::audio::effect::CommandId;
using aidl::android::hardware::audio::effect::Descriptor;
-using aidl::android::hardware::audio::effect::EffectNullUuid;
-using aidl::android::hardware::audio::effect::EffectZeroUuid;
using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::Parameter;
using aidl::android::hardware::audio::effect::State;
using aidl::android::hardware::common::fmq::SynchronizedReadWrite;
using aidl::android::media::audio::common::AudioChannelLayout;
-using aidl::android::media::audio::common::AudioDeviceType;
using aidl::android::media::audio::common::AudioFormatDescription;
using aidl::android::media::audio::common::AudioFormatType;
using aidl::android::media::audio::common::AudioUuid;
using aidl::android::media::audio::common::PcmType;
-const AudioFormatDescription DefaultFormat = {
+const AudioFormatDescription kDefaultFormatDescription = {
.type = AudioFormatType::PCM, .pcm = PcmType::FLOAT_32_BIT, .encoding = ""};
+typedef ::android::AidlMessageQueue<IEffect::Status,
+ ::aidl::android::hardware::common::fmq::SynchronizedReadWrite>
+ StatusMQ;
+typedef ::android::AidlMessageQueue<float,
+ ::aidl::android::hardware::common::fmq::SynchronizedReadWrite>
+ DataMQ;
+
class EffectHelper {
public:
- explicit EffectHelper(const std::string& name) : mFactoryHelper(EffectFactoryHelper(name)) {
- mFactoryHelper.ConnectToFactoryService();
+ static void create(std::shared_ptr<IFactory> factory, std::shared_ptr<IEffect>& effect,
+ Descriptor::Identity id, binder_status_t status = EX_NONE) {
+ ASSERT_NE(factory, nullptr);
+ EXPECT_STATUS(status, factory->createEffect(id.uuid, &effect));
+ if (status == EX_NONE) {
+ ASSERT_NE(effect, nullptr) << id.uuid.toString();
+ }
}
- void OpenEffects(const AudioUuid& type = EffectNullUuid) {
- auto open = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- IEffect::OpenEffectReturn ret;
- EXPECT_IS_OK(effect->open(mCommon, mSpecific, &ret));
- EffectParam params;
- params.statusMQ = std::make_unique<StatusMQ>(ret.statusMQ);
- params.inputMQ = std::make_unique<DataMQ>(ret.inputDataMQ);
- params.outputMQ = std::make_unique<DataMQ>(ret.outputDataMQ);
- mEffectParams.push_back(std::move(params));
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(open, type));
+ static void destroy(std::shared_ptr<IFactory> factory, std::shared_ptr<IEffect> effect,
+ binder_status_t status = EX_NONE) {
+ ASSERT_NE(factory, nullptr);
+ ASSERT_NE(effect, nullptr);
+ EXPECT_STATUS(status, factory->destroyEffect(effect));
}
- void CloseEffects(const binder_status_t status = EX_NONE) {
- auto close = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
+ static void open(std::shared_ptr<IEffect> effect, const Parameter::Common& common,
+ const std::optional<Parameter::Specific>& specific,
+ IEffect::OpenEffectReturn* ret, binder_status_t status = EX_NONE) {
+ ASSERT_NE(effect, nullptr);
+ EXPECT_STATUS(status, effect->open(common, specific, ret));
+ }
+
+ static void open(std::shared_ptr<IEffect> effect, int session = 0,
+ binder_status_t status = EX_NONE) {
+ ASSERT_NE(effect, nullptr);
+ Parameter::Common common = EffectHelper::createParamCommon(session);
+ IEffect::OpenEffectReturn ret;
+ open(effect, common, std::nullopt /* specific */, &ret, status);
+ }
+
+ static void close(std::shared_ptr<IEffect> effect, binder_status_t status = EX_NONE) {
+ if (effect) {
EXPECT_STATUS(status, effect->close());
- };
-
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(close));
- }
-
- void CreateEffects(const int n = 1) {
- for (int i = 0; i < n; i++) {
- ASSERT_NO_FATAL_FAILURE(mFactoryHelper.QueryAndCreateAllEffects());
}
}
-
- void CreateEffectsWithUUID(const AudioUuid& type = EffectNullUuid) {
- ASSERT_NO_FATAL_FAILURE(mFactoryHelper.QueryAndCreateEffects(type));
+ static void getDescriptor(std::shared_ptr<IEffect> effect, Descriptor& desc,
+ binder_status_t status = EX_NONE) {
+ ASSERT_NE(effect, nullptr);
+ EXPECT_STATUS(status, effect->getDescriptor(&desc));
}
-
- void QueryEffects() { ASSERT_NO_FATAL_FAILURE(mFactoryHelper.QueryAndCreateAllEffects()); }
-
- void DestroyEffects(const binder_status_t status = EX_NONE, const int remaining = 0) {
- ASSERT_NO_FATAL_FAILURE(mFactoryHelper.DestroyEffects(status, remaining));
- mEffectDescriptors.clear();
+ static void expectState(std::shared_ptr<IEffect> effect, State expectState,
+ binder_status_t status = EX_NONE) {
+ ASSERT_NE(effect, nullptr);
+ State state;
+ EXPECT_STATUS(status, effect->getState(&state));
+ EXPECT_EQ(expectState, state);
}
-
- void GetEffectDescriptors() {
- auto get = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- Descriptor desc;
- EXPECT_IS_OK(effect->getDescriptor(&desc));
- mEffectDescriptors.push_back(std::move(desc));
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(get));
+ static void command(std::shared_ptr<IEffect> effect, CommandId command,
+ binder_status_t status = EX_NONE) {
+ ASSERT_NE(effect, nullptr);
+ EXPECT_STATUS(status, effect->command(command));
}
-
- void CommandEffects(CommandId command) {
- auto close = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- EXPECT_IS_OK(effect->command(command));
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(close));
+ static void allocateInputData(const Parameter::Common common, std::unique_ptr<DataMQ>& mq,
+ std::vector<float>& buffer) {
+ ASSERT_NE(mq, nullptr);
+ auto frameSize = android::hardware::audio::common::getFrameSizeInBytes(
+ common.input.base.format, common.input.base.channelMask);
+ const size_t floatsToWrite = mq->availableToWrite();
+ EXPECT_NE(0UL, floatsToWrite);
+ EXPECT_EQ(frameSize * common.input.frameCount, floatsToWrite * sizeof(float));
+ buffer.resize(floatsToWrite);
+ std::fill(buffer.begin(), buffer.end(), 0x5a);
}
-
- void CommandEffectsExpectStatus(CommandId command, const binder_status_t status) {
- auto func = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- EXPECT_STATUS(status, effect->command(command));
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(func));
+ static void writeToFmq(std::unique_ptr<DataMQ>& mq, const std::vector<float>& buffer) {
+ const size_t available = mq->availableToWrite();
+ EXPECT_NE(0Ul, available);
+ auto bufferFloats = buffer.size();
+ auto floatsToWrite = std::min(available, bufferFloats);
+ EXPECT_TRUE(mq->write(buffer.data(), floatsToWrite));
}
-
- void ExpectState(State expected) {
- auto get = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- State state = State::INIT;
- EXPECT_IS_OK(effect->getState(&state));
- EXPECT_EQ(expected, state);
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(get));
- }
-
- void SetParameter() {
- auto func = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- Parameter param;
- param.set<Parameter::common>(mCommon);
- EXPECT_IS_OK(effect->setParameter(param));
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(func));
- }
-
- void VerifyParameters() {
- auto func = [&](const std::shared_ptr<IEffect>& effect) {
- ASSERT_NE(effect, nullptr);
- Parameter paramCommonGet = Parameter(), paramCommonExpect = Parameter();
- Parameter::Id id;
- id.set<Parameter::Id::commonTag>(Parameter::common);
- paramCommonExpect.set<Parameter::common>(mCommon);
- EXPECT_IS_OK(effect->getParameter(id, ¶mCommonGet));
- EXPECT_EQ(paramCommonExpect, paramCommonGet)
- << paramCommonExpect.toString() << " vs " << paramCommonGet.toString();
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(func));
- }
-
- void QueryEffects(const std::optional<AudioUuid>& in_type,
- const std::optional<AudioUuid>& in_instance,
- const std::optional<AudioUuid>& in_proxy,
- std::vector<Descriptor::Identity>* _aidl_return) {
- mFactoryHelper.QueryEffects(in_type, in_instance, in_proxy, _aidl_return);
- }
-
- template <typename Functor>
- void ForEachEffect(Functor functor, const std::optional<AudioUuid>& type = EffectNullUuid) {
- auto effectMap = mFactoryHelper.GetEffectMap();
- for (const auto& it : effectMap) {
- SCOPED_TRACE(it.second.toString());
- if (type != EffectNullUuid && it.second.type != type) continue;
- functor(it.first);
+ static void readFromFmq(std::unique_ptr<StatusMQ>& statusMq, size_t statusNum,
+ std::unique_ptr<DataMQ>& dataMq, size_t expectFloats,
+ std::vector<float>& buffer) {
+ IEffect::Status status{};
+ EXPECT_TRUE(statusMq->readBlocking(&status, statusNum));
+ EXPECT_EQ(STATUS_OK, status.status);
+ if (statusNum != 0) {
+ EXPECT_EQ(expectFloats, (unsigned)status.fmqProduced);
+ EXPECT_EQ(expectFloats, dataMq->availableToRead());
+ if (expectFloats != 0) {
+ EXPECT_TRUE(dataMq->read(buffer.data(), expectFloats));
+ }
}
}
+ static Parameter::Common createParamCommon(
+ int session = 0, int ioHandle = -1, int iSampleRate = 48000, int oSampleRate = 48000,
+ long iFrameCount = 0x100, long oFrameCount = 0x100,
+ AudioChannelLayout inputChannelLayout =
+ AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
+ AudioChannelLayout::LAYOUT_STEREO),
+ AudioChannelLayout outputChannelLayout =
+ AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
+ AudioChannelLayout::LAYOUT_STEREO)) {
+ Parameter::Common common;
+ common.session = session;
+ common.ioHandle = ioHandle;
- template <typename Functor>
- void ForEachDescriptor(Functor functor) {
- for (size_t i = 0; i < mEffectDescriptors.size(); i++) {
- SCOPED_TRACE(mEffectDescriptors[i].toString());
- functor(i, mEffectDescriptors[i]);
- }
- }
-
- static const size_t mWriteMQBytes = 0x400;
-
- enum class IO : char { INPUT = 0, OUTPUT = 1, INOUT = 2 };
-
- void initParamCommonFormat(IO io = IO::INOUT,
- const AudioFormatDescription& format = DefaultFormat) {
- if (io == IO::INPUT || io == IO::INOUT) {
- mCommon.input.base.format = format;
- }
- if (io == IO::OUTPUT || io == IO::INOUT) {
- mCommon.output.base.format = format;
- }
- }
-
- void initParamCommonSampleRate(IO io = IO::INOUT, const int& sampleRate = 48000) {
- if (io == IO::INPUT || io == IO::INOUT) {
- mCommon.input.base.sampleRate = sampleRate;
- }
- if (io == IO::OUTPUT || io == IO::INOUT) {
- mCommon.output.base.sampleRate = sampleRate;
- }
- }
-
- void initParamCommonFrameCount(IO io = IO::INOUT, const long& frameCount = 48000) {
- if (io == IO::INPUT || io == IO::INOUT) {
- mCommon.input.frameCount = frameCount;
- }
- if (io == IO::OUTPUT || io == IO::INOUT) {
- mCommon.output.frameCount = frameCount;
- }
- }
- void initParamCommon(int session = 0, int ioHandle = -1, int iSampleRate = 48000,
- int oSampleRate = 48000, long iFrameCount = 0x100,
- long oFrameCount = 0x100) {
- mCommon.session = session;
- mCommon.ioHandle = ioHandle;
-
- auto& input = mCommon.input;
- auto& output = mCommon.output;
+ auto& input = common.input;
+ auto& output = common.output;
input.base.sampleRate = iSampleRate;
- input.base.channelMask = mInputChannelLayout;
+ input.base.channelMask = inputChannelLayout;
+ input.base.format = kDefaultFormatDescription;
input.frameCount = iFrameCount;
- input.base.format = DefaultFormat;
output.base.sampleRate = oSampleRate;
- output.base.channelMask = mOutputChannelLayout;
- output.base.format = DefaultFormat;
+ output.base.channelMask = outputChannelLayout;
+ output.base.format = kDefaultFormatDescription;
output.frameCount = oFrameCount;
- output.base.format = DefaultFormat;
- inputFrameSize = android::hardware::audio::common::getFrameSizeInBytes(
- input.base.format, input.base.channelMask);
- outputFrameSize = android::hardware::audio::common::getFrameSizeInBytes(
- output.base.format, output.base.channelMask);
+ return common;
}
- void setSpecific(Parameter::Specific& specific) { mSpecific = specific; }
-
- // usually this function only call once.
- void PrepareInputData(size_t bytes = mWriteMQBytes) {
- size_t maxInputBytes = mWriteMQBytes;
- for (auto& it : mEffectParams) {
- auto& mq = it.inputMQ;
- EXPECT_NE(nullptr, mq);
- EXPECT_TRUE(mq->isValid());
- const size_t bytesToWrite = mq->availableToWrite() * sizeof(float);
- EXPECT_EQ(inputFrameSize * mCommon.input.frameCount, bytesToWrite);
- EXPECT_NE(0UL, bytesToWrite);
- EXPECT_TRUE(bytes <= bytesToWrite);
- maxInputBytes = std::max(maxInputBytes, bytesToWrite);
- }
- mInputBuffer.resize(maxInputBytes / sizeof(float));
- std::fill(mInputBuffer.begin(), mInputBuffer.end(), 0x5a);
- }
-
- void writeToFmq(size_t bytes = mWriteMQBytes) {
- for (auto& it : mEffectParams) {
- auto& mq = it.inputMQ;
- EXPECT_NE(nullptr, mq);
- const size_t bytesToWrite = mq->availableToWrite() * sizeof(float);
- EXPECT_NE(0Ul, bytesToWrite);
- EXPECT_TRUE(bytes <= bytesToWrite);
- EXPECT_TRUE(mq->write(mInputBuffer.data(), bytes / sizeof(float)));
- }
- }
-
- void readFromFmq(size_t expectBytes = mWriteMQBytes) {
- for (auto& it : mEffectParams) {
- IEffect::Status status{};
- auto& statusMq = it.statusMQ;
- EXPECT_NE(nullptr, statusMq);
- EXPECT_TRUE(statusMq->readBlocking(&status, 1));
- EXPECT_EQ(STATUS_OK, status.status);
- EXPECT_EQ(expectBytes, (unsigned)status.fmqProduced * sizeof(float));
-
- auto& outputMq = it.outputMQ;
- EXPECT_NE(nullptr, outputMq);
- EXPECT_EQ(expectBytes, outputMq->availableToRead() * sizeof(float));
- }
- }
-
- void setInputChannelLayout(AudioChannelLayout input) { mInputChannelLayout = input; }
- void setOutputChannelLayout(AudioChannelLayout output) { mOutputChannelLayout = output; }
- const std::vector<Descriptor::Identity>& GetCompleteEffectIdList() const {
- return mFactoryHelper.GetCompleteEffectIdList();
- }
- const std::vector<Descriptor>& getDescriptorVec() const { return mEffectDescriptors; }
-
- private:
- EffectFactoryHelper mFactoryHelper;
-
- AudioChannelLayout mInputChannelLayout =
- AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
- AudioChannelLayout::LAYOUT_STEREO);
- AudioChannelLayout mOutputChannelLayout =
- AudioChannelLayout::make<AudioChannelLayout::layoutMask>(
- AudioChannelLayout::LAYOUT_STEREO);
-
- Parameter::Common mCommon;
- std::optional<Parameter::Specific> mSpecific = std::nullopt;
-
- size_t inputFrameSize, outputFrameSize;
- std::vector<float> mInputBuffer; // reuse same buffer for all effects testing
-
typedef ::android::AidlMessageQueue<
IEffect::Status, ::aidl::android::hardware::common::fmq::SynchronizedReadWrite>
StatusMQ;
@@ -317,6 +181,4 @@
std::unique_ptr<DataMQ> inputMQ;
std::unique_ptr<DataMQ> outputMQ;
};
- std::vector<EffectParam> mEffectParams;
- std::vector<Descriptor> mEffectDescriptors;
};
diff --git a/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp
index d30dff4..8ae963e 100644
--- a/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectFactoryTargetTest.cpp
@@ -15,6 +15,7 @@
*/
#include <memory>
+#include <set>
#include <string>
#include <vector>
@@ -37,23 +38,81 @@
using namespace android;
using aidl::android::hardware::audio::effect::Descriptor;
-using aidl::android::hardware::audio::effect::EffectNullUuid;
-using aidl::android::hardware::audio::effect::EffectZeroUuid;
+using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::IFactory;
+using aidl::android::hardware::audio::effect::kEffectNullUuid;
+using aidl::android::hardware::audio::effect::kEffectZeroUuid;
using aidl::android::hardware::audio::effect::Processing;
+using aidl::android::media::audio::common::AudioSource;
+using aidl::android::media::audio::common::AudioStreamType;
using aidl::android::media::audio::common::AudioUuid;
/// Effect factory testing.
class EffectFactoryTest : public testing::TestWithParam<std::string> {
public:
- void SetUp() override { ASSERT_NO_FATAL_FAILURE(mFactory.ConnectToFactoryService()); }
+ void SetUp() override {
+ mFactoryHelper = std::make_unique<EffectFactoryHelper>(GetParam());
+ connectAndGetFactory();
+ }
- void TearDown() override { mFactory.DestroyEffects(); }
+ void TearDown() override {
+ for (auto& effect : mEffects) {
+ const auto status = mEffectFactory->destroyEffect(effect);
+ EXPECT_STATUS(EX_NONE, status);
+ }
+ }
- EffectFactoryHelper mFactory = EffectFactoryHelper(GetParam());
+ std::unique_ptr<EffectFactoryHelper> mFactoryHelper;
+ std::shared_ptr<IFactory> mEffectFactory;
+ std::vector<std::shared_ptr<IEffect>> mEffects;
+ const Descriptor::Identity kNullDesc = {.uuid = kEffectNullUuid};
+ const Descriptor::Identity kZeroDesc = {.uuid = kEffectZeroUuid};
- const Descriptor::Identity nullDesc = {.uuid = EffectNullUuid};
- const Descriptor::Identity zeroDesc = {.uuid = EffectZeroUuid};
+ template <typename Functor>
+ void ForEachId(const std::vector<Descriptor::Identity> ids, Functor functor) {
+ for (const auto& id : ids) {
+ SCOPED_TRACE(id.toString());
+ functor(id);
+ }
+ }
+ template <typename Functor>
+ void ForEachEffect(std::vector<std::shared_ptr<IEffect>> effects, Functor functor) {
+ for (auto& effect : effects) {
+ functor(effect);
+ }
+ }
+
+ std::vector<std::shared_ptr<IEffect>> createWithIds(
+ const std::vector<Descriptor::Identity> ids,
+ const binder_status_t expectStatus = EX_NONE) {
+ std::vector<std::shared_ptr<IEffect>> effects;
+ for (const auto& id : ids) {
+ std::shared_ptr<IEffect> effect;
+ EXPECT_STATUS(expectStatus, mEffectFactory->createEffect(id.uuid, &effect));
+ if (expectStatus == EX_NONE) {
+ EXPECT_NE(effect, nullptr) << " null effect with uuid: " << id.uuid.toString();
+ effects.push_back(std::move(effect));
+ }
+ }
+ return effects;
+ }
+ void destroyEffects(std::vector<std::shared_ptr<IEffect>> effects,
+ const binder_status_t expectStatus = EX_NONE) {
+ for (const auto& effect : effects) {
+ EXPECT_STATUS(expectStatus, mEffectFactory->destroyEffect(effect));
+ }
+ }
+ void creatAndDestroyIds(const std::vector<Descriptor::Identity> ids) {
+ for (const auto& id : ids) {
+ auto effects = createWithIds({id});
+ ASSERT_NO_FATAL_FAILURE(destroyEffects(effects));
+ }
+ }
+ void connectAndGetFactory() {
+ ASSERT_NO_FATAL_FAILURE(mFactoryHelper->ConnectToFactoryService());
+ mEffectFactory = mFactoryHelper->GetFactory();
+ ASSERT_NE(mEffectFactory, nullptr);
+ }
};
TEST_P(EffectFactoryTest, SetupAndTearDown) {
@@ -61,165 +120,160 @@
}
TEST_P(EffectFactoryTest, CanBeRestarted) {
- ASSERT_NO_FATAL_FAILURE(mFactory.RestartFactoryService());
+ ASSERT_NO_FATAL_FAILURE(mFactoryHelper->RestartFactoryService());
}
-TEST_P(EffectFactoryTest, QueriedDescriptorList) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- EXPECT_NE(descriptors.size(), 0UL);
-}
+/**
+ * @brief Check at least support list of effect must be supported by aosp:
+ * https://developer.android.com/reference/android/media/audiofx/AudioEffect
+ */
+TEST_P(EffectFactoryTest, ExpectAllAospEffectTypes) {
+ std::vector<Descriptor::Identity> ids;
+ std::set<AudioUuid> typeUuidSet(
+ {aidl::android::hardware::audio::effect::kBassBoostTypeUUID,
+ aidl::android::hardware::audio::effect::kEqualizerTypeUUID,
+ aidl::android::hardware::audio::effect::kEnvReverbTypeUUID,
+ aidl::android::hardware::audio::effect::kPresetReverbTypeUUID,
+ aidl::android::hardware::audio::effect::kDynamicsProcessingTypeUUID,
+ aidl::android::hardware::audio::effect::kHapticGeneratorTypeUUID,
+ aidl::android::hardware::audio::effect::kVirtualizerTypeUUID});
-TEST_P(EffectFactoryTest, DescriptorUUIDNotNull) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- // TODO: Factory eventually need to return the full list of MUST supported AOSP effects.
- for (auto& desc : descriptors) {
- EXPECT_NE(desc.type, EffectNullUuid);
- EXPECT_NE(desc.uuid, EffectNullUuid);
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_TRUE(ids.size() >= typeUuidSet.size());
+ for (const auto& id : ids) {
+ typeUuidSet.erase(id.type);
}
+ std::string msg = " missing type UUID:\n";
+ for (const auto& uuid : typeUuidSet) {
+ msg += (uuid.toString() + "\n");
+ }
+ SCOPED_TRACE(msg);
+ EXPECT_EQ(0UL, typeUuidSet.size());
}
-TEST_P(EffectFactoryTest, QueriedDescriptorNotExistType) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(EffectNullUuid, std::nullopt, std::nullopt, &descriptors);
- EXPECT_EQ(descriptors.size(), 0UL);
+TEST_P(EffectFactoryTest, QueryNullTypeUuid) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(kEffectNullUuid, std::nullopt, std::nullopt, &ids));
+ EXPECT_EQ(ids.size(), 0UL);
}
-TEST_P(EffectFactoryTest, QueriedDescriptorNotExistInstance) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, EffectNullUuid, std::nullopt, &descriptors);
- EXPECT_EQ(descriptors.size(), 0UL);
+TEST_P(EffectFactoryTest, QueriedNullImplUuid) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, kEffectNullUuid, std::nullopt, &ids));
+ EXPECT_EQ(ids.size(), 0UL);
}
-TEST_P(EffectFactoryTest, CreateAndDestroyOnce) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- auto numIds = mFactory.GetEffectIds().size();
- EXPECT_NE(numIds, 0UL);
-
- auto& effectMap = mFactory.GetEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- mFactory.DestroyEffects();
- EXPECT_EQ(effectMap.size(), 0UL);
+TEST_P(EffectFactoryTest, QueriedNullProxyUuid) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, kEffectNullUuid, &ids));
+ EXPECT_EQ(ids.size(), 0UL);
}
-TEST_P(EffectFactoryTest, CreateAndDestroyRepeat) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- auto numIds = mFactory.GetEffectIds().size();
- EXPECT_NE(numIds, 0UL);
+// create all effects, and then destroy them all together
+TEST_P(EffectFactoryTest, CreateAndDestroyEffects) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_NE(ids.size(), 0UL);
- auto& effectMap = mFactory.GetEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- mFactory.DestroyEffects();
- EXPECT_EQ(effectMap.size(), 0UL);
-
- // Create and destroy again
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- mFactory.DestroyEffects();
- EXPECT_EQ(effectMap.size(), 0UL);
+ std::vector<std::shared_ptr<IEffect>> effects;
+ effects = createWithIds(ids);
+ EXPECT_EQ(ids.size(), effects.size());
+ destroyEffects(effects);
}
TEST_P(EffectFactoryTest, CreateMultipleInstanceOfSameEffect) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- auto numIds = mFactory.GetEffectIds().size();
- EXPECT_NE(numIds, 0UL);
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_NE(ids.size(), 0UL);
- auto& effectMap = mFactory.GetEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- // Create effect instances of same implementation
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), 2 * numIds);
+ std::vector<std::shared_ptr<IEffect>> effects = createWithIds(ids);
+ EXPECT_EQ(ids.size(), effects.size());
+ std::vector<std::shared_ptr<IEffect>> effects2 = createWithIds(ids);
+ EXPECT_EQ(ids.size(), effects2.size());
+ std::vector<std::shared_ptr<IEffect>> effects3 = createWithIds(ids);
+ EXPECT_EQ(ids.size(), effects3.size());
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), 3 * numIds);
+ destroyEffects(effects);
+ destroyEffects(effects2);
+ destroyEffects(effects3);
+}
- mFactory.DestroyEffects();
- EXPECT_EQ(effectMap.size(), 0UL);
+// create and destroy each effect one by one
+TEST_P(EffectFactoryTest, CreateAndDestroyEffectsOneByOne) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_NE(ids.size(), 0UL);
+
+ creatAndDestroyIds(ids);
+}
+
+// for each effect: repeat 3 times create and destroy
+TEST_P(EffectFactoryTest, CreateAndDestroyRepeat) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_NE(ids.size(), 0UL);
+
+ creatAndDestroyIds(ids);
+ creatAndDestroyIds(ids);
+ creatAndDestroyIds(ids);
}
// Expect EX_ILLEGAL_ARGUMENT when create with invalid UUID.
TEST_P(EffectFactoryTest, CreateWithInvalidUuid) {
- std::vector<std::pair<Descriptor::Identity, binder_status_t>> descriptors;
- descriptors.push_back(std::make_pair(nullDesc, EX_ILLEGAL_ARGUMENT));
- descriptors.push_back(std::make_pair(zeroDesc, EX_ILLEGAL_ARGUMENT));
-
- auto& effectMap = mFactory.GetEffectMap();
- mFactory.CreateEffectsAndExpect(descriptors);
- EXPECT_EQ(effectMap.size(), 0UL);
+ std::vector<Descriptor::Identity> ids = {kNullDesc, kZeroDesc};
+ auto effects = createWithIds(ids, EX_ILLEGAL_ARGUMENT);
+ EXPECT_EQ(effects.size(), 0UL);
}
// Expect EX_ILLEGAL_ARGUMENT when destroy null interface.
TEST_P(EffectFactoryTest, DestroyWithInvalidInterface) {
std::shared_ptr<IEffect> spDummyEffect(nullptr);
-
- mFactory.DestroyEffectAndExpect(spDummyEffect, EX_ILLEGAL_ARGUMENT);
+ destroyEffects({spDummyEffect}, EX_ILLEGAL_ARGUMENT);
}
-TEST_P(EffectFactoryTest, CreateAndRemoveReference) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- auto numIds = mFactory.GetEffectIds().size();
- EXPECT_NE(numIds, 0UL);
+// Same descriptor ID should work after service restart.
+TEST_P(EffectFactoryTest, CreateDestroyWithRestart) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_NE(ids.size(), 0UL);
+ creatAndDestroyIds(ids);
- auto& effectMap = mFactory.GetEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- // remove all reference
- mFactory.ClearEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
+ mFactoryHelper->RestartFactoryService();
+
+ connectAndGetFactory();
+ creatAndDestroyIds(ids);
}
-TEST_P(EffectFactoryTest, CreateRemoveReferenceAndCreateDestroy) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- auto numIds = mFactory.GetEffectIds().size();
- EXPECT_NE(numIds, 0UL);
+// Effect handle invalid after restart.
+TEST_P(EffectFactoryTest, EffectInvalidAfterRestart) {
+ std::vector<Descriptor::Identity> ids;
+ EXPECT_IS_OK(mEffectFactory->queryEffects(std::nullopt, std::nullopt, std::nullopt, &ids));
+ EXPECT_NE(ids.size(), 0UL);
+ std::vector<std::shared_ptr<IEffect>> effects = createWithIds(ids);
- auto& effectMap = mFactory.GetEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- // remove all reference
- mFactory.ClearEffectMap();
- EXPECT_EQ(effectMap.size(), 0UL);
+ ASSERT_NO_FATAL_FAILURE(mFactoryHelper->RestartFactoryService());
- // Create and destroy again
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- mFactory.DestroyEffects();
- EXPECT_EQ(effectMap.size(), 0UL);
+ connectAndGetFactory();
+ destroyEffects(effects, EX_ILLEGAL_ARGUMENT);
}
-TEST_P(EffectFactoryTest, CreateRestartAndCreateDestroy) {
- std::vector<Descriptor::Identity> descriptors;
- mFactory.QueryEffects(std::nullopt, std::nullopt, std::nullopt, &descriptors);
- auto numIds = mFactory.GetEffectIds().size();
- auto& effectMap = mFactory.GetEffectMap();
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- ASSERT_NO_FATAL_FAILURE(mFactory.RestartFactoryService());
-
- mFactory.CreateEffects();
- EXPECT_EQ(effectMap.size(), numIds);
- mFactory.DestroyEffects();
- EXPECT_EQ(effectMap.size(), 0UL);
-}
-
+// expect no error with the queryProcessing interface, but don't check number of processing
TEST_P(EffectFactoryTest, QueryProcess) {
std::vector<Processing> processing;
- mFactory.QueryProcessing(std::nullopt, &processing);
- // TODO: verify the number of process in example implementation after audio_effects.xml migrated
+ EXPECT_IS_OK(mEffectFactory->queryProcessing(std::nullopt, &processing));
+
+ Processing::Type streamType =
+ Processing::Type::make<Processing::Type::streamType>(AudioStreamType::SYSTEM);
+ std::vector<Processing> processingFilteredByStream;
+ EXPECT_IS_OK(mEffectFactory->queryProcessing(streamType, &processingFilteredByStream));
+
+ Processing::Type source =
+ Processing::Type::make<Processing::Type::source>(AudioSource::DEFAULT);
+ std::vector<Processing> processingFilteredBySource;
+ EXPECT_IS_OK(mEffectFactory->queryProcessing(source, &processingFilteredBySource));
+
+ EXPECT_TRUE(processing.size() >= processingFilteredByStream.size());
+ EXPECT_TRUE(processing.size() >= processingFilteredBySource.size());
}
INSTANTIATE_TEST_SUITE_P(EffectFactoryTest, EffectFactoryTest,
diff --git a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
index 3ea67bc..8212149 100644
--- a/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalAudioEffectTargetTest.cpp
@@ -16,26 +16,24 @@
#define LOG_TAG "VtsHalAudioEffectTargetTest"
+#include <chrono>
#include <memory>
#include <string>
-#include <unordered_map>
-#include <unordered_set>
#include <vector>
+#include <Utils.h>
#include <aidl/Gtest.h>
#include <aidl/Vintf.h>
+#include <aidl/android/hardware/audio/effect/IEffect.h>
+#include <aidl/android/hardware/audio/effect/IFactory.h>
#include <android-base/logging.h>
-#include <android-base/properties.h>
#include <android/binder_interface_utils.h>
#include <android/binder_manager.h>
#include <android/binder_process.h>
-
-#include <Utils.h>
-#include <aidl/android/hardware/audio/effect/IEffect.h>
-#include <aidl/android/hardware/audio/effect/IFactory.h>
-#include <aidl/android/media/audio/common/AudioDeviceType.h>
+#include <fmq/AidlMessageQueue.h>
#include "AudioHalBinderServiceUtil.h"
+#include "EffectFactoryHelper.h"
#include "EffectHelper.h"
#include "TestUtils.h"
@@ -49,309 +47,725 @@
using aidl::android::hardware::audio::effect::IFactory;
using aidl::android::hardware::audio::effect::Parameter;
using aidl::android::hardware::audio::effect::State;
-using aidl::android::media::audio::common::AudioDeviceType;
-class AudioEffectTest : public testing::TestWithParam<std::string>, public EffectHelper {
+enum ParamName { PARAM_INSTANCE_NAME };
+using EffectTestParam = std::tuple<std::pair<std::shared_ptr<IFactory>, Descriptor::Identity>>;
+
+class AudioEffectTest : public testing::TestWithParam<EffectTestParam>, public EffectHelper {
public:
- AudioEffectTest() : EffectHelper(GetParam()) {}
+ AudioEffectTest() { std::tie(mFactory, mIdentity) = std::get<PARAM_INSTANCE_NAME>(GetParam()); }
- void SetUp() override {
- CreateEffects();
- initParamCommonFormat();
- initParamCommon();
- }
+ void SetUp() override {}
+ void TearDown() override {}
- void TearDown() override {
- CloseEffects();
- DestroyEffects();
- }
+ static const long kInputFrameCount = 0x100, kOutputFrameCount = 0x100;
+ std::shared_ptr<IFactory> mFactory;
+ Descriptor::Identity mIdentity;
};
-TEST_P(AudioEffectTest, OpenEffectTest) {
- OpenEffects();
+TEST_P(AudioEffectTest, SetupAndTearDown) {
+ // Intentionally empty test body.
}
-TEST_P(AudioEffectTest, OpenAndCloseEffect) {
- OpenEffects();
- CloseEffects();
+TEST_P(AudioEffectTest, CreateAndDestroy) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-TEST_P(AudioEffectTest, CloseUnopenedEffectTest) {
- CloseEffects();
+TEST_P(AudioEffectTest, OpenAndClose) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-TEST_P(AudioEffectTest, DoubleOpenCloseEffects) {
- OpenEffects();
- CloseEffects();
- OpenEffects();
- CloseEffects();
-
- OpenEffects();
- OpenEffects();
- CloseEffects();
-
- OpenEffects();
- CloseEffects();
- CloseEffects();
+TEST_P(AudioEffectTest, CloseUnopenedEffect) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-TEST_P(AudioEffectTest, GetDescriptors) {
- GetEffectDescriptors();
+TEST_P(AudioEffectTest, DoubleOpenAndClose) {
+ std::shared_ptr<IEffect> effect1, effect2;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect1, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect2, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect1));
+ ASSERT_NO_FATAL_FAILURE(open(effect2, 1 /* session */));
+ ASSERT_NO_FATAL_FAILURE(close(effect1));
+ ASSERT_NO_FATAL_FAILURE(close(effect2));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect1));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect2));
}
-TEST_P(AudioEffectTest, DescriptorIdExistAndUnique) {
- auto checker = [&](const std::shared_ptr<IEffect>& effect) {
- Descriptor desc;
- std::vector<Descriptor::Identity> idList;
- EXPECT_IS_OK(effect->getDescriptor(&desc));
- QueryEffects(desc.common.id.type, desc.common.id.uuid, desc.common.id.proxy, &idList);
- // Must have at least one instance.
- EXPECT_NE(idList.size(), 0UL);
- };
- ForEachEffect(checker);
+TEST_P(AudioEffectTest, TripleOpenAndClose) {
+ std::shared_ptr<IEffect> effect1, effect2, effect3;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect1, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect2, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect3, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect1));
+ ASSERT_NO_FATAL_FAILURE(open(effect2, 1 /* session */));
+ ASSERT_NO_FATAL_FAILURE(open(effect3, 2 /* session */));
+ ASSERT_NO_FATAL_FAILURE(close(effect1));
+ ASSERT_NO_FATAL_FAILURE(close(effect2));
+ ASSERT_NO_FATAL_FAILURE(close(effect3));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect1));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect2));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect3));
+}
- // Check unique with a set
- auto stringHash = [](const Descriptor::Identity& id) {
- return std::hash<std::string>()(id.toString());
- };
- auto vec = GetCompleteEffectIdList();
- std::unordered_set<Descriptor::Identity, decltype(stringHash)> idSet(0, stringHash);
- for (auto it : vec) {
- EXPECT_EQ(idSet.count(it), 0UL) << it.toString();
- idSet.insert(it);
+TEST_P(AudioEffectTest, GetDescritorBeforeOpen) {
+ std::shared_ptr<IEffect> effect;
+ Descriptor desc;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(getDescriptor(effect, desc));
+ EXPECT_EQ(mIdentity.toString(), desc.common.id.toString());
+ EXPECT_NE("", desc.common.name);
+ EXPECT_NE("", desc.common.implementor);
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+TEST_P(AudioEffectTest, GetDescritorAfterOpen) {
+ std::shared_ptr<IEffect> effect;
+ Descriptor beforeOpen, afterOpen, afterClose;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(getDescriptor(effect, beforeOpen));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(getDescriptor(effect, afterOpen));
+ EXPECT_EQ(beforeOpen.toString(), afterOpen.toString()) << "\n"
+ << beforeOpen.toString() << "\n"
+ << afterOpen.toString();
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(getDescriptor(effect, afterClose));
+ EXPECT_EQ(beforeOpen.toString(), afterClose.toString()) << "\n"
+ << beforeOpen.toString() << "\n"
+ << afterClose.toString();
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+TEST_P(AudioEffectTest, DescriptorExistAndUnique) {
+ std::shared_ptr<IEffect> effect;
+ Descriptor desc;
+
+ auto descList = EffectFactoryHelper::getAllEffectDescriptors(IFactory::descriptor);
+ std::set<Descriptor::Identity> idSet;
+ for (const auto& it : descList) {
+ auto& id = it.second;
+ EXPECT_EQ(0ul, idSet.count(id));
+ idSet.insert(id);
}
+
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(getDescriptor(effect, desc));
+ EXPECT_EQ(1ul, idSet.count(desc.common.id));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
/// State testing.
// An effect instance is in INIT state by default after it was created.
TEST_P(AudioEffectTest, InitStateAfterCreation) {
- ExpectState(State::INIT);
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::INIT));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// An effect instance transfer to INIT state after it was open successfully with IEffect.open().
+// An effect instance transfer to IDLE state after IEffect.ASSERT_NO_FATAL_FAILURE(open().
TEST_P(AudioEffectTest, IdleStateAfterOpen) {
- OpenEffects();
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// An effect instance is in PROCESSING state after it receive an START command.
TEST_P(AudioEffectTest, ProcessingStateAfterStart) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::INIT));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// An effect instance transfer to IDLE state after Command.Id.STOP in PROCESSING state.
TEST_P(AudioEffectTest, IdleStateAfterStop) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// An effect instance transfer to IDLE state after Command.Id.RESET in PROCESSING state.
TEST_P(AudioEffectTest, IdleStateAfterReset) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::RESET);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// An effect instance transfer to INIT if instance receive a close() call.
+// An effect instance transfer to INIT after IEffect.ASSERT_NO_FATAL_FAILURE(close().
TEST_P(AudioEffectTest, InitStateAfterClose) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CloseEffects();
- ExpectState(State::INIT);
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::INIT));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// An effect instance shouldn't accept any command before open.
TEST_P(AudioEffectTest, NoCommandAcceptedBeforeOpen) {
- ExpectState(State::INIT);
- CommandEffectsExpectStatus(CommandId::START, EX_ILLEGAL_STATE);
- CommandEffectsExpectStatus(CommandId::STOP, EX_ILLEGAL_STATE);
- CommandEffectsExpectStatus(CommandId::RESET, EX_ILLEGAL_STATE);
- ExpectState(State::INIT);
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START, EX_ILLEGAL_STATE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP, EX_ILLEGAL_STATE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET, EX_ILLEGAL_STATE));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// No-op when receive STOP command in IDLE state.
TEST_P(AudioEffectTest, StopCommandInIdleStateNoOp) {
- ExpectState(State::INIT);
- OpenEffects();
- ExpectState(State::IDLE);
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// No-op when receive STOP command in IDLE state.
+// No-op when receive RESET command in IDLE state.
TEST_P(AudioEffectTest, ResetCommandInIdleStateNoOp) {
- ExpectState(State::INIT);
- OpenEffects();
- ExpectState(State::IDLE);
- CommandEffects(CommandId::RESET);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// Repeat START and STOP command.
TEST_P(AudioEffectTest, RepeatStartAndStop) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// Repeat START and RESET command.
TEST_P(AudioEffectTest, RepeatStartAndReset) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::RESET);
- ExpectState(State::IDLE);
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::RESET);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// Repeat START and STOP command, try to close at PROCESSING state.
+// Try to close an effect instance at PROCESSING state.
TEST_P(AudioEffectTest, CloseProcessingStateEffects) {
- OpenEffects();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- CloseEffects(EX_ILLEGAL_STATE);
- // cleanup
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ ASSERT_NO_FATAL_FAILURE(close(effect, EX_ILLEGAL_STATE));
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// Expect EX_ILLEGAL_STATE if the effect instance is not in a proper state to be destroyed.
TEST_P(AudioEffectTest, DestroyOpenEffects) {
- // cleanup all effects.
- CloseEffects();
- DestroyEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
- // open effects, destroy without close, expect to get EX_ILLEGAL_STATE status.
- CreateEffects();
- OpenEffects();
- auto vec = GetCompleteEffectIdList();
- DestroyEffects(EX_ILLEGAL_STATE, vec.size());
- CloseEffects();
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect, EX_ILLEGAL_STATE));
+}
+
+// Expect EX_ILLEGAL_STATE if the effect instance is not in a proper state to be destroyed.
+TEST_P(AudioEffectTest, DestroyProcessingEffects) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect, EX_ILLEGAL_STATE));
+}
+
+TEST_P(AudioEffectTest, NormalSequenceStates) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::INIT));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
/// Parameter testing.
// Verify parameters pass in open can be successfully get.
-TEST_P(AudioEffectTest, VerifyParametersAfterOpen) {
- OpenEffects();
- VerifyParameters();
- CloseEffects();
+TEST_P(AudioEffectTest, VerifyCommonParametersAfterOpen) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon();
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+
+ Parameter get = Parameter(), expect = Parameter();
+ expect.set<Parameter::common>(common);
+ Parameter::Id id;
+ id.set<Parameter::Id::commonTag>(Parameter::common);
+ EXPECT_IS_OK(effect->getParameter(id, &get));
+ EXPECT_EQ(expect, get) << expect.toString() << " vs " << get.toString();
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
// Verify parameters pass in set can be successfully get.
-TEST_P(AudioEffectTest, SetAndGetParameter) {
- OpenEffects();
- VerifyParameters();
- initParamCommon(1 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */,
- 44100 /* oSampleRate */);
- SetParameter();
- VerifyParameters();
- CloseEffects();
+TEST_P(AudioEffectTest, SetAndGetCommonParameter) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */);
+ Parameter get = Parameter(), set = Parameter();
+ set.set<Parameter::common>(common);
+ EXPECT_IS_OK(effect->setParameter(set));
+
+ Parameter::Id id;
+ id.set<Parameter::Id::commonTag>(Parameter::common);
+ EXPECT_IS_OK(effect->getParameter(id, &get));
+ EXPECT_EQ(set, get) << set.toString() << " vs " << get.toString();
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// Verify parameters pass in set can be successfully get.
+// Verify parameters set and get in PROCESSING state.
TEST_P(AudioEffectTest, SetAndGetParameterInProcessing) {
- OpenEffects();
- VerifyParameters();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- initParamCommon(1 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */,
- 44100 /* oSampleRate */);
- SetParameter();
- VerifyParameters();
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CloseEffects();
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */);
+ Parameter get = Parameter(), set = Parameter();
+ set.set<Parameter::common>(common);
+ EXPECT_IS_OK(effect->setParameter(set));
+
+ Parameter::Id id;
+ id.set<Parameter::Id::commonTag>(Parameter::common);
+ EXPECT_IS_OK(effect->getParameter(id, &get));
+ EXPECT_EQ(set, get) << set.toString() << " vs " << get.toString();
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// Parameters kept after reset.
-TEST_P(AudioEffectTest, ResetAndVerifyParameter) {
- OpenEffects();
- VerifyParameters();
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- initParamCommon(1 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */,
- 44100 /* oSampleRate */);
- SetParameter();
- VerifyParameters();
- CommandEffects(CommandId::RESET);
- ExpectState(State::IDLE);
- VerifyParameters();
- CloseEffects();
+// Verify parameters set and get in IDLE state.
+TEST_P(AudioEffectTest, SetAndGetParameterInIdle) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */);
+ Parameter get = Parameter(), set = Parameter();
+ set.set<Parameter::common>(common);
+ EXPECT_IS_OK(effect->setParameter(set));
+
+ Parameter::Id id;
+ id.set<Parameter::Id::commonTag>(Parameter::common);
+ EXPECT_IS_OK(effect->getParameter(id, &get));
+ EXPECT_EQ(set, get) << set.toString() << " vs " << get.toString();
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-// TODO: need a way to support setting different sessionId to different effect instances
-#if 0
-// Multiple instances of same implementation running.
-TEST_P(AudioEffectTest, MultipleInstancesRunningWithDiffSessionId) {
- CreateEffects();
- ExpectState(State::INIT);
- OpenEffects();
- ExpectState(State::IDLE);
- CommandEffects(CommandId::START);
- ExpectState(State::PROCESSING);
- initParamCommon(1 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */,
- 44100 /* oSampleRate */);
- SetParameter();
- VerifyParameters();
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- VerifyParameters();
- CloseEffects();
-}
-#endif
+// Verify Parameters kept after stop.
+TEST_P(AudioEffectTest, SetAndGetParameterAfterStop) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
-// Send data to effects and expect it to consume by check statusMQ.
-TEST_P(AudioEffectTest, ExpectEffectsToConsumeDataInMQ) {
- OpenEffects();
- PrepareInputData(mWriteMQBytes);
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */);
+ Parameter get = Parameter(), set = Parameter();
+ set.set<Parameter::common>(common);
+ EXPECT_IS_OK(effect->setParameter(set));
- CommandEffects(CommandId::START);
- writeToFmq(mWriteMQBytes);
- readFromFmq(mWriteMQBytes);
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
- ExpectState(State::PROCESSING);
- CommandEffects(CommandId::STOP);
- // cleanup
- CommandEffects(CommandId::STOP);
- ExpectState(State::IDLE);
- CloseEffects();
+ Parameter::Id id;
+ id.set<Parameter::Id::commonTag>(Parameter::common);
+ EXPECT_IS_OK(effect->getParameter(id, &get));
+ EXPECT_EQ(set, get) << set.toString() << " vs " << get.toString();
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
}
-INSTANTIATE_TEST_SUITE_P(AudioEffectTestTest, AudioEffectTest,
- testing::ValuesIn(android::getAidlHalInstanceNames(IFactory::descriptor)),
- android::PrintInstanceNameToString);
+// Verify Parameters kept after reset.
+TEST_P(AudioEffectTest, SetAndGetParameterAfterReset) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(open(effect));
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */);
+ Parameter get = Parameter(), set = Parameter();
+ set.set<Parameter::common>(common);
+ EXPECT_IS_OK(effect->setParameter(set));
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::RESET));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ Parameter::Id id;
+ id.set<Parameter::Id::commonTag>(Parameter::common);
+ EXPECT_IS_OK(effect->getParameter(id, &get));
+ EXPECT_EQ(set, get) << set.toString() << " vs " << get.toString();
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+/// Data processing test
+// Send data to effects and expect it to be consumed by checking statusMQ.
+TEST_P(AudioEffectTest, ConsumeDataInProcessingState) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+ auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+ auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+ auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ std::vector<float> buffer;
+ EffectHelper::allocateInputData(common, inputMQ, buffer);
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+// Send data to effects and expect it to be consumed after effect restart.
+TEST_P(AudioEffectTest, ConsumeDataAfterRestart) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+ auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+ auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+ auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ std::vector<float> buffer;
+ EffectHelper::allocateInputData(common, inputMQ, buffer);
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+// Send data to IDLE effects and expect it to be consumed after effect start.
+TEST_P(AudioEffectTest, SendDataAtIdleAndConsumeDataInProcessing) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+ auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+ auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+ auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+
+ std::vector<float> buffer;
+ EffectHelper::allocateInputData(common, inputMQ, buffer);
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+// Send data multiple times.
+TEST_P(AudioEffectTest, ProcessDataMultipleTimes) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+ auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+ auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+ auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+
+ std::vector<float> buffer;
+ EffectHelper::allocateInputData(common, inputMQ, buffer);
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+
+ EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer);
+ // expect no status and data after consume
+ EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer);
+
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer);
+ // expect no status and data after consume
+ EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+// Send data to IDLE state effects and expect it not be consumed.
+TEST_P(AudioEffectTest, NotConsumeDataInIdleState) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+ auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+ auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+ auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ std::vector<float> buffer;
+ EffectHelper::allocateInputData(common, inputMQ, buffer);
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::PROCESSING));
+ EffectHelper::readFromFmq(statusMQ, 1, outputMQ, buffer.size(), buffer);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect, State::IDLE));
+
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+// Send data to closed effects and expect it not be consumed.
+TEST_P(AudioEffectTest, NotConsumeDataByClosedEffect) {
+ std::shared_ptr<IEffect> effect;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect, mIdentity));
+
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(effect, common, std::nullopt /* specific */, &ret, EX_NONE));
+ ASSERT_NO_FATAL_FAILURE(close(effect));
+
+ auto statusMQ = std::make_unique<EffectHelper::StatusMQ>(ret.statusMQ);
+ auto inputMQ = std::make_unique<EffectHelper::DataMQ>(ret.inputDataMQ);
+ auto outputMQ = std::make_unique<EffectHelper::DataMQ>(ret.outputDataMQ);
+
+ std::vector<float> buffer;
+ EffectHelper::allocateInputData(common, inputMQ, buffer);
+ EffectHelper::writeToFmq(inputMQ, buffer);
+ EffectHelper::readFromFmq(statusMQ, 0, outputMQ, 0, buffer);
+
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect));
+}
+
+// Send data to multiple effects.
+TEST_P(AudioEffectTest, ConsumeDataMultipleEffects) {
+ std::shared_ptr<IEffect> effect1, effect2;
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect1, mIdentity));
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, effect2, mIdentity));
+
+ Parameter::Common common1 = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ Parameter::Common common2 = EffectHelper::createParamCommon(
+ 1 /* session */, 1 /* ioHandle */, 48000 /* iSampleRate */, 48000 /* oSampleRate */,
+ 2 * kInputFrameCount /* iFrameCount */, 2 * kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret1, ret2;
+ ASSERT_NO_FATAL_FAILURE(open(effect1, common1, std::nullopt /* specific */, &ret1, EX_NONE));
+ ASSERT_NO_FATAL_FAILURE(open(effect2, common2, std::nullopt /* specific */, &ret2, EX_NONE));
+ ASSERT_NO_FATAL_FAILURE(command(effect1, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect1, State::PROCESSING));
+ ASSERT_NO_FATAL_FAILURE(command(effect2, CommandId::START));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect2, State::PROCESSING));
+
+ auto statusMQ1 = std::make_unique<EffectHelper::StatusMQ>(ret1.statusMQ);
+ auto inputMQ1 = std::make_unique<EffectHelper::DataMQ>(ret1.inputDataMQ);
+ auto outputMQ1 = std::make_unique<EffectHelper::DataMQ>(ret1.outputDataMQ);
+
+ std::vector<float> buffer1, buffer2;
+ EffectHelper::allocateInputData(common1, inputMQ1, buffer1);
+ EffectHelper::writeToFmq(inputMQ1, buffer1);
+ EffectHelper::readFromFmq(statusMQ1, 1, outputMQ1, buffer1.size(), buffer1);
+
+ auto statusMQ2 = std::make_unique<EffectHelper::StatusMQ>(ret2.statusMQ);
+ auto inputMQ2 = std::make_unique<EffectHelper::DataMQ>(ret2.inputDataMQ);
+ auto outputMQ2 = std::make_unique<EffectHelper::DataMQ>(ret2.outputDataMQ);
+ EffectHelper::allocateInputData(common2, inputMQ2, buffer2);
+ EffectHelper::writeToFmq(inputMQ2, buffer2);
+ EffectHelper::readFromFmq(statusMQ2, 1, outputMQ2, buffer2.size(), buffer2);
+
+ ASSERT_NO_FATAL_FAILURE(command(effect1, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect1, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect1));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect1));
+
+ ASSERT_NO_FATAL_FAILURE(command(effect2, CommandId::STOP));
+ ASSERT_NO_FATAL_FAILURE(expectState(effect2, State::IDLE));
+ ASSERT_NO_FATAL_FAILURE(close(effect2));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, effect2));
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ SingleEffectInstanceTest, AudioEffectTest,
+ ::testing::Combine(testing::ValuesIn(
+ EffectFactoryHelper::getAllEffectDescriptors(IFactory::descriptor))),
+ [](const testing::TestParamInfo<AudioEffectTest::ParamType>& info) {
+ auto msSinceEpoch = std::chrono::duration_cast<std::chrono::nanoseconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
+ auto instance = std::get<PARAM_INSTANCE_NAME>(info.param);
+ std::ostringstream address;
+ address << msSinceEpoch << "_factory_" << instance.first.get();
+ std::string name = address.str() + "_UUID_timeLow_" +
+ ::android::internal::ToString(instance.second.uuid.timeLow) +
+ "_timeMid_" +
+ ::android::internal::ToString(instance.second.uuid.timeMid);
+ std::replace_if(
+ name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
+ return name;
+ });
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AudioEffectTest);
int main(int argc, char** argv) {
diff --git a/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp b/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp
index 4162551..f19dff6 100644
--- a/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalEqualizerTargetTest.cpp
@@ -35,8 +35,6 @@
#include <Utils.h>
#include <aidl/android/hardware/audio/effect/IEffect.h>
#include <aidl/android/hardware/audio/effect/IFactory.h>
-#include <aidl/android/media/audio/common/AudioChannelLayout.h>
-#include <aidl/android/media/audio/common/AudioDeviceType.h>
#include "AudioHalBinderServiceUtil.h"
#include "EffectHelper.h"
@@ -47,103 +45,126 @@
using aidl::android::hardware::audio::effect::Capability;
using aidl::android::hardware::audio::effect::Descriptor;
-using aidl::android::hardware::audio::effect::EffectNullUuid;
using aidl::android::hardware::audio::effect::Equalizer;
-using aidl::android::hardware::audio::effect::EqualizerTypeUUID;
using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::IFactory;
+using aidl::android::hardware::audio::effect::kEqualizerTypeUUID;
using aidl::android::hardware::audio::effect::Parameter;
/**
- * Here we focus on specific parameter checking, general IEffect interfaces testing performed in
- * VtsAudioEfectTargetTest.
+ * Here we focus on specific effect (equalizer) parameter checking, general IEffect interfaces
+ * testing performed in VtsAudioEfectTargetTest.
*/
-enum ParamName { PARAM_INSTANCE_NAME, PARAM_PRESET_INDEX, PARAM_BAND_INDEX, PARAM_BAND_LEVEL };
-using EqualizerParamTestParam = std::tuple<std::string, int, int, int>;
+
+enum ParamName { PARAM_INSTANCE_NAME, PARAM_BAND_LEVEL };
+using EqualizerParamTestParam =
+ std::tuple<std::pair<std::shared_ptr<IFactory>, Descriptor::Identity>, int>;
/*
Testing parameter range, assuming the parameter supported by effect is in this range.
This range is verified with IEffect.getDescriptor(), for any index supported vts expect EX_NONE
from IEffect.setParameter(), otherwise expect EX_ILLEGAL_ARGUMENT.
*/
-constexpr std::pair<int, int> kPresetIndexRange = {-1, 10}; // valid range [0, 9]
-constexpr std::pair<int, int> kBandIndexRange = {-1, 5}; // valid range [0, 4]
-constexpr std::pair<int, int> kBandLevelRange = {-5, 5}; // needs update with implementation
+const std::vector<int> kBandLevels = {0, -10, 10}; // needs update with implementation
-class EqualizerParamTest : public ::testing::TestWithParam<EqualizerParamTestParam>,
- public EffectHelper {
+class EqualizerTest : public ::testing::TestWithParam<EqualizerParamTestParam>,
+ public EffectHelper {
public:
- EqualizerParamTest()
- : EffectHelper(std::get<PARAM_INSTANCE_NAME>(GetParam())),
- mParamPresetIndex(std::get<PARAM_PRESET_INDEX>(GetParam())),
- mParamBandIndex(std::get<PARAM_BAND_INDEX>(GetParam())),
- mParamBandLevel(std::get<PARAM_BAND_LEVEL>(GetParam())) {}
+ EqualizerTest() : mBandLevel(std::get<PARAM_BAND_LEVEL>(GetParam())) {
+ std::tie(mFactory, mIdentity) = std::get<PARAM_INSTANCE_NAME>(GetParam());
+ }
void SetUp() override {
- CreateEffectsWithUUID(EqualizerTypeUUID);
- initParamCommonFormat();
- initParamCommon();
- initParamSpecific();
- OpenEffects(EqualizerTypeUUID);
- SCOPED_TRACE(testing::Message() << "preset: " << mParamPresetIndex << " bandIdx "
- << mParamBandIndex << " level " << mParamBandLevel);
- }
+ ASSERT_NE(nullptr, mFactory);
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mIdentity));
+ Parameter::Specific specific = getDefaultParamSpecific();
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(mEffect, common, specific, &ret, EX_NONE));
+ ASSERT_NE(nullptr, mEffect);
+ ASSERT_NO_FATAL_FAILURE(setTagRange());
+ }
void TearDown() override {
- CloseEffects();
- DestroyEffects();
- CleanUp();
+ ASSERT_NO_FATAL_FAILURE(close(mEffect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
}
- int mParamPresetIndex = 0;
- int mParamBandIndex = 0;
- int mParamBandLevel = 0;
+ std::pair<int, int> setPresetIndexRange(const Equalizer::Capability& cap) const {
+ const auto [min, max] =
+ std::minmax_element(cap.presets.begin(), cap.presets.end(),
+ [](const auto& a, const auto& b) { return a.index < b.index; });
+ return {min->index, max->index};
+ }
+ std::pair<int, int> setBandIndexRange(const Equalizer::Capability& cap) const {
+ const auto [min, max] =
+ std::minmax_element(cap.bandFrequencies.begin(), cap.bandFrequencies.end(),
+ [](const auto& a, const auto& b) { return a.index < b.index; });
+ return {min->index, max->index};
+ }
+ void setTagRange() {
+ Descriptor desc;
+ ASSERT_STATUS(EX_NONE, mEffect->getDescriptor(&desc));
+ Equalizer::Capability& eqCap = desc.capability.get<Capability::equalizer>();
+ mPresetIndex = setPresetIndexRange(eqCap);
+ mBandIndex = setBandIndexRange(eqCap);
+ }
+
+ static const long kInputFrameCount = 0x100, kOutputFrameCount = 0x100;
+ std::shared_ptr<IFactory> mFactory;
+ std::shared_ptr<IEffect> mEffect;
+ Descriptor::Identity mIdentity;
+ std::pair<int, int> mPresetIndex;
+ std::pair<int, int> mBandIndex;
+ const int mBandLevel;
+ Descriptor mDesc;
void SetAndGetEqualizerParameters() {
- auto functor = [&](const std::shared_ptr<IEffect>& effect) {
- for (auto& it : mTags) {
- auto& tag = it.first;
- auto& eq = it.second;
+ ASSERT_NE(nullptr, mEffect);
+ for (auto& it : mTags) {
+ auto& tag = it.first;
+ auto& eq = it.second;
- // validate parameter
- Descriptor desc;
- ASSERT_STATUS(EX_NONE, effect->getDescriptor(&desc));
- const bool valid = isTagInRange(it.first, it.second, desc);
- const binder_exception_t expected = valid ? EX_NONE : EX_ILLEGAL_ARGUMENT;
+ // validate parameter
+ const bool valid = isTagInRange(it.first, it.second);
+ const binder_exception_t expected = valid ? EX_NONE : EX_ILLEGAL_ARGUMENT;
- // set
- Parameter expectParam;
- Parameter::Specific specific;
- specific.set<Parameter::Specific::equalizer>(*eq.get());
- expectParam.set<Parameter::specific>(specific);
- EXPECT_STATUS(expected, effect->setParameter(expectParam))
- << expectParam.toString();
+ // set
+ Parameter expectParam;
+ Parameter::Specific specific;
+ specific.set<Parameter::Specific::equalizer>(eq);
+ expectParam.set<Parameter::specific>(specific);
+ EXPECT_STATUS(expected, mEffect->setParameter(expectParam))
+ << expectParam.toString() << "\n"
+ << mDesc.toString();
- // only get if parameter in range and set success
- if (expected == EX_NONE) {
- Parameter getParam;
- Parameter::Id id;
- Equalizer::Id eqId;
- eqId.set<Equalizer::Id::commonTag>(tag);
- id.set<Parameter::Id::equalizerTag>(eqId);
- // if set success, then get should match
- EXPECT_STATUS(expected, effect->getParameter(id, &getParam));
- EXPECT_TRUE(isEqParameterExpected(expectParam, getParam));
- }
+ // only get if parameter in range and set success
+ if (expected == EX_NONE) {
+ Parameter getParam;
+ Parameter::Id id;
+ Equalizer::Id eqId;
+ eqId.set<Equalizer::Id::commonTag>(tag);
+ id.set<Parameter::Id::equalizerTag>(eqId);
+ // if set success, then get should match
+ EXPECT_STATUS(expected, mEffect->getParameter(id, &getParam));
+ EXPECT_TRUE(isEqParameterExpected(expectParam, getParam))
+ << "\nexpect:" << expectParam.toString()
+ << "\ngetParam:" << getParam.toString();
}
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(functor));
+ }
}
bool isEqParameterExpected(const Parameter& expect, const Parameter& target) {
- // if parameter same, then for sure matched
+ // if parameter same, then for sure they are matched
if (expect == target) return true;
// if not, see if target include the expect parameter, and others all default (0).
/*
- This is verify the case of client setParameter to a single bandLevel ({3, -1} for
- example), and return of getParameter must be [{0, 0}, {1, 0}, {2, 0}, {3, -1}, {4, 0}]
- */
+ * This is to verify the case of client setParameter to a single bandLevel ({3, -1} for
+ * example), and return of getParameter must be [{0, 0}, {1, 0}, {2, 0}, {3, -1}, {4, 0}]
+ */
EXPECT_EQ(expect.getTag(), Parameter::specific);
EXPECT_EQ(target.getTag(), Parameter::specific);
@@ -160,10 +181,16 @@
switch (eqTag) {
case Equalizer::bandLevels: {
auto expectBl = expectEq.get<Equalizer::bandLevels>();
+ std::sort(expectBl.begin(), expectBl.end(),
+ [](const auto& a, const auto& b) { return a.index < b.index; });
+ expectBl.erase(std::unique(expectBl.begin(), expectBl.end()), expectBl.end());
auto targetBl = targetEq.get<Equalizer::bandLevels>();
return std::includes(targetBl.begin(), targetBl.end(), expectBl.begin(),
expectBl.end());
}
+ case Equalizer::preset: {
+ return expectEq.get<Equalizer::preset>() == targetEq.get<Equalizer::preset>();
+ }
default:
return false;
}
@@ -173,27 +200,24 @@
void addPresetParam(int preset) {
Equalizer eq;
eq.set<Equalizer::preset>(preset);
- mTags.push_back({Equalizer::preset, std::make_unique<Equalizer>(std::move(eq))});
+ mTags.push_back({Equalizer::preset, eq});
}
void addBandLevelsParam(std::vector<Equalizer::BandLevel>& bandLevels) {
Equalizer eq;
eq.set<Equalizer::bandLevels>(bandLevels);
- mTags.push_back({Equalizer::bandLevels, std::make_unique<Equalizer>(std::move(eq))});
+ mTags.push_back({Equalizer::bandLevels, eq});
}
- bool isTagInRange(const Equalizer::Tag& tag, const std::unique_ptr<Equalizer>& eq,
- const Descriptor& desc) const {
- std::cout << "xxx" << toString(tag) << " " << desc.toString();
- const Equalizer::Capability& eqCap = desc.capability.get<Capability::equalizer>();
+ bool isTagInRange(const Equalizer::Tag& tag, const Equalizer& eq) const {
switch (tag) {
case Equalizer::preset: {
- int index = eq->get<Equalizer::preset>();
- return isPresetIndexInRange(eqCap, index);
+ int index = eq.get<Equalizer::preset>();
+ return index >= mPresetIndex.first && index <= mPresetIndex.second;
}
case Equalizer::bandLevels: {
- auto& bandLevel = eq->get<Equalizer::bandLevels>();
- return isBandIndexInRange(eqCap, bandLevel);
+ auto& bandLevel = eq.get<Equalizer::bandLevels>();
+ return isBandInRange(bandLevel);
}
default:
return false;
@@ -201,78 +225,125 @@
return false;
}
- bool isPresetIndexInRange(const Equalizer::Capability& cap, int idx) const {
- const auto [min, max] =
- std::minmax_element(cap.presets.begin(), cap.presets.end(),
- [](const auto& a, const auto& b) { return a.index < b.index; });
- return idx >= min->index && idx <= max->index;
- }
-
- bool isBandIndexInRange(const Equalizer::Capability& cap,
- const std::vector<Equalizer::BandLevel>& bandLevel) const {
+ bool isBandInRange(const std::vector<Equalizer::BandLevel>& bandLevel) const {
for (auto& it : bandLevel) {
- if (!isBandIndexInRange(cap, it.index)) return false;
+ if (it.index < mBandIndex.first || it.index > mBandIndex.second) return false;
}
return true;
}
- bool isBandIndexInRange(const Equalizer::Capability& cap, int idx) const {
- const auto [min, max] =
- std::minmax_element(cap.bandFrequencies.begin(), cap.bandFrequencies.end(),
- [](const auto& a, const auto& b) { return a.index < b.index; });
- return idx >= min->index && idx <= max->index;
+ Parameter::Specific getDefaultParamSpecific() {
+ Equalizer eq = Equalizer::make<Equalizer::preset>(0);
+ Parameter::Specific specific =
+ Parameter::Specific::make<Parameter::Specific::equalizer>(eq);
+ return specific;
}
private:
- std::vector<std::pair<Equalizer::Tag, std::unique_ptr<Equalizer>>> mTags;
+ std::vector<std::pair<Equalizer::Tag, Equalizer>> mTags;
bool validCapabilityTag(Capability& cap) { return cap.getTag() == Capability::equalizer; }
- void initParamSpecific() {
- Equalizer eq;
- eq.set<Equalizer::preset>(0);
- Parameter::Specific specific;
- specific.set<Parameter::Specific::equalizer>(eq);
- setSpecific(specific);
- }
-
void CleanUp() { mTags.clear(); }
};
-TEST_P(EqualizerParamTest, SetAndGetPreset) {
- EXPECT_NO_FATAL_FAILURE(addPresetParam(mParamPresetIndex));
- SetAndGetEqualizerParameters();
+TEST_P(EqualizerTest, SetAndGetPresetOutOfLowerBound) {
+ addPresetParam(mPresetIndex.second - 1);
+ ASSERT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
}
-TEST_P(EqualizerParamTest, SetAndGetSingleBand) {
- std::vector<Equalizer::BandLevel> bandLevels;
- Equalizer::BandLevel bandLevel = {mParamBandIndex, mParamBandLevel};
- bandLevels.push_back(bandLevel);
- EXPECT_NO_FATAL_FAILURE(addBandLevelsParam(bandLevels));
- SetAndGetEqualizerParameters();
+TEST_P(EqualizerTest, SetAndGetPresetOutOfUpperBound) {
+ addPresetParam(mPresetIndex.second + 1);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetPresetAtLowerBound) {
+ addPresetParam(mPresetIndex.first);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetPresetAtHigherBound) {
+ addPresetParam(mPresetIndex.second);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetPresetInBound) {
+ addPresetParam((mPresetIndex.first + mPresetIndex.second) >> 1);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetBandOutOfLowerBound) {
+ std::vector<Equalizer::BandLevel> bandLevels{{mBandIndex.first - 1, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetBandOutOfUpperBound) {
+ std::vector<Equalizer::BandLevel> bandLevels{{mBandIndex.second + 1, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetBandAtLowerBound) {
+ std::vector<Equalizer::BandLevel> bandLevels{{mBandIndex.first, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetBandAtHigherBound) {
+ std::vector<Equalizer::BandLevel> bandLevels{{mBandIndex.second, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetBandInBound) {
+ std::vector<Equalizer::BandLevel> bandLevels{
+ {(mBandIndex.first + mBandIndex.second) >> 1, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetMultiBands) {
+ addPresetParam(mPresetIndex.first);
+ std::vector<Equalizer::BandLevel> bandLevels{
+ {mBandIndex.first, mBandLevel},
+ {mBandIndex.second, mBandLevel},
+ {(mBandIndex.first + mBandIndex.second) >> 1, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
+}
+
+TEST_P(EqualizerTest, SetAndGetMultipleParams) {
+ std::vector<Equalizer::BandLevel> bandLevels{
+ {(mBandIndex.first + mBandIndex.second) >> 1, mBandLevel}};
+ addBandLevelsParam(bandLevels);
+ addPresetParam((mPresetIndex.first + mPresetIndex.second) >> 1);
+ EXPECT_NO_FATAL_FAILURE(SetAndGetEqualizerParameters());
}
INSTANTIATE_TEST_SUITE_P(
- EqualizerTest, EqualizerParamTest,
- ::testing::Combine(
- testing::ValuesIn(android::getAidlHalInstanceNames(IFactory::descriptor)),
- testing::Range(kPresetIndexRange.first, kPresetIndexRange.second),
- testing::Range(kBandIndexRange.first, kBandIndexRange.second),
- testing::Range(kBandLevelRange.first, kBandLevelRange.second)),
- [](const testing::TestParamInfo<EqualizerParamTest::ParamType>& info) {
- std::string instance = std::get<PARAM_INSTANCE_NAME>(info.param);
- std::string presetIdx = std::to_string(std::get<PARAM_PRESET_INDEX>(info.param));
- std::string bandIdx = std::to_string(std::get<PARAM_BAND_INDEX>(info.param));
+ EqualizerTest, EqualizerTest,
+ ::testing::Combine(testing::ValuesIn(EffectFactoryHelper::getAllEffectDescriptors(
+ IFactory::descriptor, kEqualizerTypeUUID)),
+ testing::ValuesIn(kBandLevels)),
+ [](const testing::TestParamInfo<EqualizerTest::ParamType>& info) {
+ auto msSinceEpoch = std::chrono::duration_cast<std::chrono::nanoseconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
+ auto instance = std::get<PARAM_INSTANCE_NAME>(info.param);
std::string bandLevel = std::to_string(std::get<PARAM_BAND_LEVEL>(info.param));
-
- std::string name = instance + "_presetIndex" + presetIdx + "_bandIndex" + bandIdx +
- "_bandLevel" + bandLevel;
+ std::ostringstream address;
+ address << msSinceEpoch << "_factory_" << instance.first.get();
+ std::string name = address.str() + "_UUID_timeLow_" +
+ ::android::internal::ToString(instance.second.uuid.timeLow) +
+ "_timeMid_" +
+ ::android::internal::ToString(instance.second.uuid.timeMid) +
+ "_bandLevel_" + bandLevel;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
});
-
-GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(EqualizerParamTest);
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(EqualizerTest);
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
diff --git a/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp b/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
index 2ad016d..1485657 100644
--- a/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
+++ b/audio/aidl/vts/VtsHalLoudnessEnhancerTargetTest.cpp
@@ -27,8 +27,8 @@
using aidl::android::hardware::audio::effect::Descriptor;
using aidl::android::hardware::audio::effect::IEffect;
using aidl::android::hardware::audio::effect::IFactory;
+using aidl::android::hardware::audio::effect::kLoudnessEnhancerTypeUUID;
using aidl::android::hardware::audio::effect::LoudnessEnhancer;
-using aidl::android::hardware::audio::effect::LoudnessEnhancerTypeUUID;
using aidl::android::hardware::audio::effect::Parameter;
/**
@@ -36,7 +36,8 @@
* VtsAudioEffectTargetTest.
*/
enum ParamName { PARAM_INSTANCE_NAME, PARAM_GAIN_MB };
-using LoudnessEnhancerParamTestParam = std::tuple<std::string, int>;
+using LoudnessEnhancerParamTestParam =
+ std::tuple<std::pair<std::shared_ptr<IFactory>, Descriptor::Identity>, int>;
// Every int 32 bit value is a valid gain, so testing the corner cases and one regular value.
// TODO : Update the test values once range/capability is updated by implementation.
@@ -46,53 +47,64 @@
class LoudnessEnhancerParamTest : public ::testing::TestWithParam<LoudnessEnhancerParamTestParam>,
public EffectHelper {
public:
- LoudnessEnhancerParamTest()
- : EffectHelper(std::get<PARAM_INSTANCE_NAME>(GetParam())),
- mParamGainMb(std::get<PARAM_GAIN_MB>(GetParam())) {}
+ LoudnessEnhancerParamTest() : mParamGainMb(std::get<PARAM_GAIN_MB>(GetParam())) {
+ std::tie(mFactory, mIdentity) = std::get<PARAM_INSTANCE_NAME>(GetParam());
+ }
void SetUp() override {
- CreateEffectsWithUUID(LoudnessEnhancerTypeUUID);
- initParamCommonFormat();
- initParamCommon();
- initParamSpecific();
- OpenEffects(LoudnessEnhancerTypeUUID);
- SCOPED_TRACE(testing::Message() << "gainMb: " << mParamGainMb);
- }
+ ASSERT_NE(nullptr, mFactory);
+ ASSERT_NO_FATAL_FAILURE(create(mFactory, mEffect, mIdentity));
+ Parameter::Specific specific = getDefaultParamSpecific();
+ Parameter::Common common = EffectHelper::createParamCommon(
+ 0 /* session */, 1 /* ioHandle */, 44100 /* iSampleRate */, 44100 /* oSampleRate */,
+ kInputFrameCount /* iFrameCount */, kOutputFrameCount /* oFrameCount */);
+ IEffect::OpenEffectReturn ret;
+ ASSERT_NO_FATAL_FAILURE(open(mEffect, common, specific, &ret, EX_NONE));
+ ASSERT_NE(nullptr, mEffect);
+ }
void TearDown() override {
- CloseEffects();
- DestroyEffects();
- CleanUp();
+ ASSERT_NO_FATAL_FAILURE(close(mEffect));
+ ASSERT_NO_FATAL_FAILURE(destroy(mFactory, mEffect));
}
+ Parameter::Specific getDefaultParamSpecific() {
+ LoudnessEnhancer le = LoudnessEnhancer::make<LoudnessEnhancer::gainMb>(0);
+ Parameter::Specific specific =
+ Parameter::Specific::make<Parameter::Specific::loudnessEnhancer>(le);
+ return specific;
+ }
+
+ static const long kInputFrameCount = 0x100, kOutputFrameCount = 0x100;
+ std::shared_ptr<IFactory> mFactory;
+ std::shared_ptr<IEffect> mEffect;
+ Descriptor::Identity mIdentity;
int mParamGainMb = 0;
- void SetAndGetLoudnessEnhancerParameters() {
- auto functor = [&](const std::shared_ptr<IEffect>& effect) {
- for (auto& it : mTags) {
- auto& tag = it.first;
- auto& le = it.second;
+ void SetAndGetParameters() {
+ for (auto& it : mTags) {
+ auto& tag = it.first;
+ auto& le = it.second;
- // set parameter
- Parameter expectParam;
- Parameter::Specific specific;
- specific.set<Parameter::Specific::loudnessEnhancer>(le);
- expectParam.set<Parameter::specific>(specific);
- // All values are valid, set parameter should succeed
- EXPECT_STATUS(EX_NONE, effect->setParameter(expectParam)) << expectParam.toString();
+ // set parameter
+ Parameter expectParam;
+ Parameter::Specific specific;
+ specific.set<Parameter::Specific::loudnessEnhancer>(le);
+ expectParam.set<Parameter::specific>(specific);
+ // All values are valid, set parameter should succeed
+ EXPECT_STATUS(EX_NONE, mEffect->setParameter(expectParam)) << expectParam.toString();
- // get parameter
- Parameter getParam;
- Parameter::Id id;
- LoudnessEnhancer::Id leId;
- leId.set<LoudnessEnhancer::Id::commonTag>(tag);
- id.set<Parameter::Id::loudnessEnhancerTag>(leId);
- EXPECT_STATUS(EX_NONE, effect->getParameter(id, &getParam));
+ // get parameter
+ Parameter getParam;
+ Parameter::Id id;
+ LoudnessEnhancer::Id leId;
+ leId.set<LoudnessEnhancer::Id::commonTag>(tag);
+ id.set<Parameter::Id::loudnessEnhancerTag>(leId);
+ EXPECT_STATUS(EX_NONE, mEffect->getParameter(id, &getParam));
- EXPECT_EQ(expectParam, getParam);
- }
- };
- EXPECT_NO_FATAL_FAILURE(ForEachEffect(functor));
+ EXPECT_EQ(expectParam, getParam) << "\nexpect:" << expectParam.toString()
+ << "\ngetParam:" << getParam.toString();
+ }
}
void addGainMbParam(int gainMb) {
@@ -103,33 +115,33 @@
private:
std::vector<std::pair<LoudnessEnhancer::Tag, LoudnessEnhancer>> mTags;
-
- void initParamSpecific() {
- LoudnessEnhancer le;
- le.set<LoudnessEnhancer::gainMb>(0);
- Parameter::Specific specific;
- specific.set<Parameter::Specific::loudnessEnhancer>(le);
- setSpecific(specific);
- }
-
void CleanUp() { mTags.clear(); }
};
TEST_P(LoudnessEnhancerParamTest, SetAndGetGainMb) {
EXPECT_NO_FATAL_FAILURE(addGainMbParam(mParamGainMb));
- SetAndGetLoudnessEnhancerParameters();
+ SetAndGetParameters();
}
INSTANTIATE_TEST_SUITE_P(
LoudnessEnhancerTest, LoudnessEnhancerParamTest,
- ::testing::Combine(
- testing::ValuesIn(android::getAidlHalInstanceNames(IFactory::descriptor)),
- testing::ValuesIn(kGainMbValues)),
+ ::testing::Combine(testing::ValuesIn(EffectFactoryHelper::getAllEffectDescriptors(
+ IFactory::descriptor, kLoudnessEnhancerTypeUUID)),
+ testing::ValuesIn(kGainMbValues)),
[](const testing::TestParamInfo<LoudnessEnhancerParamTest::ParamType>& info) {
- std::string instance = std::get<PARAM_INSTANCE_NAME>(info.param);
+ auto msSinceEpoch = std::chrono::duration_cast<std::chrono::nanoseconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count();
+ auto instance = std::get<PARAM_INSTANCE_NAME>(info.param);
std::string gainMb = std::to_string(std::get<PARAM_GAIN_MB>(info.param));
- std::string name = instance + "_gainMb" + gainMb;
+ std::ostringstream address;
+ address << msSinceEpoch << "_factory_" << instance.first.get();
+ std::string name = address.str() + "_UUID_timeLow_" +
+ ::android::internal::ToString(instance.second.uuid.timeLow) +
+ "_timeMid_" +
+ ::android::internal::ToString(instance.second.uuid.timeMid) +
+ "_gainMb" + gainMb;
std::replace_if(
name.begin(), name.end(), [](const char c) { return !std::isalnum(c); }, '_');
return name;
diff --git a/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h b/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h
index 0ca6a58..98e49a2 100644
--- a/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h
+++ b/audio/core/all-versions/vts/functional/AudioPrimaryHidlHalTest.h
@@ -1274,6 +1274,8 @@
if (!xsd::isTelephonyDevice(address.deviceType)) {
metadata.source = toString(xsd::AudioSource::AUDIO_SOURCE_UNPROCESSED);
metadata.channelMask = getConfig().base.channelMask;
+ } else {
+ address.deviceType = toString(xsd::AudioDevice::AUDIO_DEVICE_IN_DEFAULT);
}
#if MAJOR_VERSION == 7 && MINOR_VERSION >= 1
auto flagsIt = std::find(flags.begin(), flags.end(),
diff --git a/automotive/remoteaccess/test_grpc_server/README.md b/automotive/remoteaccess/test_grpc_server/README.md
index 28035de..6bc1829 100644
--- a/automotive/remoteaccess/test_grpc_server/README.md
+++ b/automotive/remoteaccess/test_grpc_server/README.md
@@ -79,6 +79,8 @@
* `make -j TestWakeupClientServer`
+* `make -j ApPowerControlLib`
+
## How to push the test wakeup client to a TCU which runs Android.
* Make the target device writable:
@@ -97,6 +99,8 @@
* `adb push vendor/bin/TestWakeupClientServer /vendor/bin`
+* `adb push vendor/lib/ApPowerControlLib.so /vendor/lib`
+
* `adb shell`
* `su`
diff --git a/automotive/remoteaccess/test_grpc_server/impl/Android.bp b/automotive/remoteaccess/test_grpc_server/impl/Android.bp
index e978c8c..152b528 100644
--- a/automotive/remoteaccess/test_grpc_server/impl/Android.bp
+++ b/automotive/remoteaccess/test_grpc_server/impl/Android.bp
@@ -31,6 +31,7 @@
"libutils",
"libgrpc++",
"libprotobuf-cpp-full",
+ "//hardware/interfaces/automotive/remoteaccess/test_grpc_server/lib:ApPowerControlLib",
],
whole_static_libs: [
"wakeup_client_protos",
diff --git a/automotive/remoteaccess/test_grpc_server/impl/include/TestWakeupClientServiceImpl.h b/automotive/remoteaccess/test_grpc_server/impl/include/TestWakeupClientServiceImpl.h
index 12bd93b..6b86b35 100644
--- a/automotive/remoteaccess/test_grpc_server/impl/include/TestWakeupClientServiceImpl.h
+++ b/automotive/remoteaccess/test_grpc_server/impl/include/TestWakeupClientServiceImpl.h
@@ -119,7 +119,7 @@
// A variable to notify server is stopping.
std::condition_variable mServerStoppedCv;
// Whether wakeup AP is required for executing tasks.
- std::atomic<bool> mWakeupRequired = false;
+ std::atomic<bool> mWakeupRequired = true;
std::mutex mLock;
bool mServerStopped GUARDED_BY(mLock);
diff --git a/automotive/remoteaccess/test_grpc_server/impl/src/TestWakeupClientServiceImpl.cpp b/automotive/remoteaccess/test_grpc_server/impl/src/TestWakeupClientServiceImpl.cpp
index 795265f..7dcd31e 100644
--- a/automotive/remoteaccess/test_grpc_server/impl/src/TestWakeupClientServiceImpl.cpp
+++ b/automotive/remoteaccess/test_grpc_server/impl/src/TestWakeupClientServiceImpl.cpp
@@ -16,6 +16,8 @@
#include "TestWakeupClientServiceImpl.h"
+#include "ApPowerControl.h"
+
#include <android-base/stringprintf.h>
#include <inttypes.h>
#include <utils/Looper.h>
@@ -245,8 +247,7 @@
}
void TestWakeupClientServiceImpl::wakeupApplicationProcessor() {
- printf("Waking up application processor...\n");
- // TODO(b/254547153): Send can bus message using socket CAN once we know what the message is.
+ wakeupAp();
}
} // namespace remoteaccess
diff --git a/automotive/remoteaccess/test_grpc_server/lib/Android.bp b/automotive/remoteaccess/test_grpc_server/lib/Android.bp
new file mode 100644
index 0000000..7e95f53
--- /dev/null
+++ b/automotive/remoteaccess/test_grpc_server/lib/Android.bp
@@ -0,0 +1,32 @@
+// Copyright (C) 2022 The Android Open Source Project
+//
+// 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.
+
+soong_namespace {}
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "hardware_interfaces_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_library_shared {
+ name: "ApPowerControlLib",
+ vendor: true,
+ srcs: ["*.cpp"],
+ local_include_dirs: ["."],
+ export_include_dirs: ["."],
+}
diff --git a/automotive/remoteaccess/test_grpc_server/lib/ApPowerControl.cpp b/automotive/remoteaccess/test_grpc_server/lib/ApPowerControl.cpp
new file mode 100644
index 0000000..862fed1
--- /dev/null
+++ b/automotive/remoteaccess/test_grpc_server/lib/ApPowerControl.cpp
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "ApPowerControl.h"
+
+#include <cstdio>
+
+void wakeupAp() {
+ printf("Waking up application processor...\n");
+}
diff --git a/automotive/remoteaccess/test_grpc_server/lib/ApPowerControl.h b/automotive/remoteaccess/test_grpc_server/lib/ApPowerControl.h
new file mode 100644
index 0000000..9560576
--- /dev/null
+++ b/automotive/remoteaccess/test_grpc_server/lib/ApPowerControl.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// Wakeup application processor if not already waken up.
+void wakeupAp();
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/automotive/vehicle/2.0/types.hal b/automotive/vehicle/2.0/types.hal
index 7c8e1f5..9e4f252 100644
--- a/automotive/vehicle/2.0/types.hal
+++ b/automotive/vehicle/2.0/types.hal
@@ -1632,10 +1632,8 @@
*
* The Android properties are:
*
- * int32Values[0] : Input code identifying the function representing this event. Valid event
- * types are defined by CustomInputType.CUSTOM_EVENT_F1 up to
- * CustomInputType.CUSTOM_EVENT_F10. They represent the custom event to be
- * defined by OEM partners.
+ * int32Values[0] : Input code identifying the function representing this event. OEMs are free
+ * to use any signed 32 bits number to represent the input code value.
* int32Values[1] : target display type defined in VehicleDisplay. Events not tied to specific
* display must be sent to VehicleDisplay#MAIN.
* int32Values[2] : repeat counter, if 0 then event is not repeated. Values 1 or above means
@@ -5326,10 +5324,11 @@
*/
enum CustomInputType : int32_t {
/**
- * Ten functions representing the custom input code to be defined and implemented by OEM
- * partners.
+ * Ten optional function codes to be used in case OEM don't need more than 10 input code values.
*
- * OEMs need to formally contact Android team if more than 10 functions are required.
+ * OEMs are free to use any signed 32 bits number to represent the input code value.
+ * The following function keys are only for convenience and any other integer values are
+ * also allowed.
*/
CUSTOM_EVENT_F1 = 1001,
CUSTOM_EVENT_F2 = 1002,
diff --git a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleProperty.aidl b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleProperty.aidl
index 392c82e..24fd518 100644
--- a/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleProperty.aidl
+++ b/automotive/vehicle/aidl/aidl_api/android.hardware.automotive.vehicle/current/android/hardware/automotive/vehicle/VehicleProperty.aidl
@@ -126,6 +126,8 @@
MIRROR_Y_MOVE = 339741507,
MIRROR_LOCK = 287312708,
MIRROR_FOLD = 287312709,
+ MIRROR_AUTO_FOLD_ENABLED = 337644358,
+ MIRROR_AUTO_TILT_ENABLED = 337644359,
SEAT_MEMORY_SELECT = 356518784,
SEAT_MEMORY_SET = 356518785,
SEAT_BELT_BUCKLED = 354421634,
@@ -153,6 +155,12 @@
SEAT_HEADREST_ANGLE_MOVE = 356518808,
SEAT_HEADREST_FORE_AFT_POS = 356518809,
SEAT_HEADREST_FORE_AFT_MOVE = 356518810,
+ SEAT_EASY_ACCESS_ENABLED = 354421661,
+ SEAT_AIRBAG_ENABLED = 354421662,
+ SEAT_CUSHION_SIDE_SUPPORT_POS = 356518815,
+ SEAT_CUSHION_SIDE_SUPPORT_MOVE = 356518816,
+ SEAT_LUMBAR_VERTICAL_POS = 356518817,
+ SEAT_LUMBAR_VERTICAL_MOVE = 356518818,
SEAT_OCCUPANCY = 356518832,
WINDOW_POS = 322964416,
WINDOW_MOVE = 322964417,
@@ -163,6 +171,7 @@
STEERING_WHEEL_HEIGHT_MOVE = 289410019,
STEERING_WHEEL_THEFT_LOCK_ENABLED = 287312868,
STEERING_WHEEL_LOCKED = 287312869,
+ STEERING_WHEEL_EASY_ACCESS_ENABLED = 287312870,
VEHICLE_MAP_SERVICE = 299895808,
OBD2_LIVE_FRAME = 299896064,
OBD2_FREEZE_FRAME = 299896065,
diff --git a/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleProperty.aidl b/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleProperty.aidl
index e9df5bd..b6886c0 100644
--- a/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleProperty.aidl
+++ b/automotive/vehicle/aidl/android/hardware/automotive/vehicle/VehicleProperty.aidl
@@ -1391,6 +1391,35 @@
*/
MIRROR_FOLD = 0x0B45 + 0x10000000 + 0x01000000
+ 0x00200000, // VehiclePropertyGroup:SYSTEM,VehicleArea:GLOBAL,VehiclePropertyType:BOOLEAN
+
+ /**
+ * Represents property for Mirror Auto Fold feature.
+ *
+ * This property is true when the feature for automatically folding the vehicle's side mirrors
+ * (for example, when the mirrors fold inward automatically when one exits and locks the
+ * vehicle) is enabled.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+
+ MIRROR_AUTO_FOLD_ENABLED =
+ 0x0B46 + VehiclePropertyGroup.SYSTEM + VehicleArea.MIRROR + VehiclePropertyType.BOOLEAN,
+
+ /**
+ * Represents property for Mirror Auto Tilt feature.
+ *
+ * This property is true when the feature for automatically tilting the vehicle's side mirrors
+ * (for example, when the mirrors tilt downward automatically when one reverses the vehicle) is
+ * enabled.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+
+ MIRROR_AUTO_TILT_ENABLED =
+ 0x0B47 + VehiclePropertyGroup.SYSTEM + VehicleArea.MIRROR + VehiclePropertyType.BOOLEAN,
+
/**
* Seat memory select
*
@@ -1693,6 +1722,102 @@
SEAT_HEADREST_FORE_AFT_MOVE = 0x0B9A + 0x10000000 + 0x05000000
+ 0x00400000, // VehiclePropertyGroup:SYSTEM,VehicleArea:SEAT,VehiclePropertyType:INT32
/**
+ * Represents property for Seat easy access feature.
+ *
+ * If true, the seat will automatically adjust to make it easier for the occupant to enter and
+ * exit the vehicle.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+ SEAT_EASY_ACCESS_ENABLED =
+ 0x0B9D + VehiclePropertyGroup.SYSTEM + VehicleArea.SEAT + VehiclePropertyType.BOOLEAN,
+ /**
+ * Represents feature to enable/disable a seat's ability to deploy airbag(s) when triggered
+ * (e.g. by a crash).
+ *
+ * If true, it means the seat's airbags are enabled, and if triggered (e.g. by a crash), they
+ * will deploy. If false, it means the seat's airbags are disabled, and they will not deploy
+ * under any circumstance. This property does not indicate if the airbags are deployed or not.
+ *
+ * This property can be set to VehiclePropertyAccess.READ read only for the sake of regulation
+ * or safety concerns.
+ */
+ SEAT_AIRBAG_ENABLED =
+ 0x0B9E + VehiclePropertyGroup.SYSTEM + VehicleArea.SEAT + VehiclePropertyType.BOOLEAN,
+ /**
+ * Represents property for seat’s hipside (bottom cushion’s side) support position.
+ *
+ * The maxInt32Value and minInt32Value in VehicleAreaConfig must be defined. All integers
+ * between minInt32Value and maxInt32Value are supported.
+ *
+ * maxInt32Value indicates the widest cushion side support setting (i.e. least support).
+ * minInt32Value indicates the thinnest cushion side support setting (i.e most support).
+ *
+ * This value is not in any particular unit but in a specified range of steps.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+ SEAT_CUSHION_SIDE_SUPPORT_POS =
+ 0x0B9F + VehiclePropertyGroup.SYSTEM + VehicleArea.SEAT + VehiclePropertyType.INT32,
+ /**
+ * Represents property for movement direction and speed of seat cushion side support.
+ *
+ * The maxInt32Value and minInt32Value in VehicleAreaConfig must be defined. All integers
+ * between minInt32Value and maxInt32Value must be supported.
+ *
+ * maxInt32Value in default area's VehicleAreaConfig represents the maximum movement speed of
+ * the seat cushion side support in the growing wider direction (i.e. less support).
+ * minInt32Value in default area's VehicleAreaConfig represents the maximum movement speed of
+ * the seat cushion side support in the growing thinner direction (i.e. more support).
+ *
+ * Larger absolute values, either positive or negative, indicate a faster movement speed. Once
+ * the seat cushion side support reaches the positional limit, the value resets to 0.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+ SEAT_CUSHION_SIDE_SUPPORT_MOVE =
+ 0x0BA0 + VehiclePropertyGroup.SYSTEM + VehicleArea.SEAT + VehiclePropertyType.INT32,
+ /**
+ * Represents property for seat’s lumbar support vertical position.
+ *
+ * The maxInt32Value and minInt32Value in VehicleAreaConfig must be defined. All integers
+ * between minInt32Value and maxInt32Value are supported.
+ *
+ * maxInt32Value indicates the highest position.
+ * minInt32Value indicates the lowest position.
+ *
+ * This value is not in any particular unit but in a specified range of steps.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+ SEAT_LUMBAR_VERTICAL_POS =
+ 0x0BA1 + VehiclePropertyGroup.SYSTEM + VehicleArea.SEAT + VehiclePropertyType.INT32,
+ /**
+ * Represents property for vertical movement direction and speed of seat lumbar support.
+ *
+ * The maxInt32Value and minInt32Value in VehicleAreaConfig must be defined. All integers
+ * between minInt32Value and maxInt32Value must be supported.
+ *
+ * maxInt32Value in default area's VehicleAreaConfig indicates the lumbar support is moving at
+ * the fastest upward speed.
+ * minInt32Value in default area's VehicleAreaConfig indicates the lumbar support is moving at
+ * the fastest downward speed.
+ *
+ * Larger absolute values, either positive or negative, indicate a faster movement speed. Once
+ * the seat cushion side support reaches the positional limit, the value resets to 0.
+ *
+ * This value is not in any particular unit but in a specified range of steps.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+ SEAT_LUMBAR_VERTICAL_MOVE =
+ 0x0BA2 + VehiclePropertyGroup.SYSTEM + VehicleArea.SEAT + VehiclePropertyType.INT32,
+ /**
* Seat Occupancy
*
* Indicates whether a particular seat is occupied or not, to the best of the car's ability
@@ -1856,6 +1981,17 @@
STEERING_WHEEL_LOCKED =
0x0BE5 + VehiclePropertyGroup.SYSTEM + VehicleArea.GLOBAL + VehiclePropertyType.BOOLEAN,
/**
+ * Steering wheel easy access feature enabled
+ *
+ * If true, the driver’s steering wheel will automatically adjust to make it easier for the
+ * driver to enter and exit the vehicle.
+ *
+ * @change_mode VehiclePropertyChangeMode.ON_CHANGE
+ * @access VehiclePropertyAccess.READ_WRITE
+ */
+ STEERING_WHEEL_EASY_ACCESS_ENABLED =
+ 0x0BE6 + VehiclePropertyGroup.SYSTEM + VehicleArea.GLOBAL + VehiclePropertyType.BOOLEAN,
+ /**
* Vehicle Maps Service (VMS) message
*
* This property uses MIXED data to communicate vms messages.
diff --git a/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h b/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h
index decf250..d5182dd 100644
--- a/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h
+++ b/automotive/vehicle/aidl/generated_lib/cpp/AccessForVehicleProperty.h
@@ -126,6 +126,8 @@
{VehicleProperty::MIRROR_Y_MOVE, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::MIRROR_LOCK, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::MIRROR_FOLD, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::MIRROR_AUTO_FOLD_ENABLED, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::MIRROR_AUTO_TILT_ENABLED, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::SEAT_MEMORY_SELECT, VehiclePropertyAccess::WRITE},
{VehicleProperty::SEAT_MEMORY_SET, VehiclePropertyAccess::WRITE},
{VehicleProperty::SEAT_BELT_BUCKLED, VehiclePropertyAccess::READ_WRITE},
@@ -153,6 +155,12 @@
{VehicleProperty::SEAT_HEADREST_ANGLE_MOVE, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::SEAT_HEADREST_FORE_AFT_POS, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::SEAT_HEADREST_FORE_AFT_MOVE, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::SEAT_EASY_ACCESS_ENABLED, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::SEAT_AIRBAG_ENABLED, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_POS, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_MOVE, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::SEAT_LUMBAR_VERTICAL_POS, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::SEAT_LUMBAR_VERTICAL_MOVE, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::SEAT_OCCUPANCY, VehiclePropertyAccess::READ},
{VehicleProperty::WINDOW_POS, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::WINDOW_MOVE, VehiclePropertyAccess::READ_WRITE},
@@ -163,6 +171,7 @@
{VehicleProperty::STEERING_WHEEL_HEIGHT_MOVE, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::STEERING_WHEEL_THEFT_LOCK_ENABLED, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::STEERING_WHEEL_LOCKED, VehiclePropertyAccess::READ_WRITE},
+ {VehicleProperty::STEERING_WHEEL_EASY_ACCESS_ENABLED, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::VEHICLE_MAP_SERVICE, VehiclePropertyAccess::READ_WRITE},
{VehicleProperty::OBD2_LIVE_FRAME, VehiclePropertyAccess::READ},
{VehicleProperty::OBD2_FREEZE_FRAME, VehiclePropertyAccess::READ},
diff --git a/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h b/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h
index 7e507d7..47bad2c 100644
--- a/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h
+++ b/automotive/vehicle/aidl/generated_lib/cpp/ChangeModeForVehicleProperty.h
@@ -126,6 +126,8 @@
{VehicleProperty::MIRROR_Y_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::MIRROR_LOCK, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::MIRROR_FOLD, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::MIRROR_AUTO_FOLD_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::MIRROR_AUTO_TILT_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::SEAT_MEMORY_SELECT, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::SEAT_MEMORY_SET, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::SEAT_BELT_BUCKLED, VehiclePropertyChangeMode::ON_CHANGE},
@@ -153,6 +155,12 @@
{VehicleProperty::SEAT_HEADREST_ANGLE_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::SEAT_HEADREST_FORE_AFT_POS, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::SEAT_HEADREST_FORE_AFT_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::SEAT_EASY_ACCESS_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::SEAT_AIRBAG_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_POS, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::SEAT_LUMBAR_VERTICAL_POS, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::SEAT_LUMBAR_VERTICAL_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::SEAT_OCCUPANCY, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::WINDOW_POS, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::WINDOW_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
@@ -163,6 +171,7 @@
{VehicleProperty::STEERING_WHEEL_HEIGHT_MOVE, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::STEERING_WHEEL_THEFT_LOCK_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::STEERING_WHEEL_LOCKED, VehiclePropertyChangeMode::ON_CHANGE},
+ {VehicleProperty::STEERING_WHEEL_EASY_ACCESS_ENABLED, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::VEHICLE_MAP_SERVICE, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::OBD2_LIVE_FRAME, VehiclePropertyChangeMode::ON_CHANGE},
{VehicleProperty::OBD2_FREEZE_FRAME, VehiclePropertyChangeMode::ON_CHANGE},
diff --git a/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java b/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java
index 62b2b73..85a62d3 100644
--- a/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java
+++ b/automotive/vehicle/aidl/generated_lib/java/AccessForVehicleProperty.java
@@ -118,6 +118,8 @@
Map.entry(VehicleProperty.MIRROR_Y_MOVE, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.MIRROR_LOCK, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.MIRROR_FOLD, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.MIRROR_AUTO_FOLD_ENABLED, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.MIRROR_AUTO_TILT_ENABLED, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.SEAT_MEMORY_SELECT, VehiclePropertyAccess.WRITE),
Map.entry(VehicleProperty.SEAT_MEMORY_SET, VehiclePropertyAccess.WRITE),
Map.entry(VehicleProperty.SEAT_BELT_BUCKLED, VehiclePropertyAccess.READ_WRITE),
@@ -145,6 +147,12 @@
Map.entry(VehicleProperty.SEAT_HEADREST_ANGLE_MOVE, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.SEAT_HEADREST_FORE_AFT_POS, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.SEAT_HEADREST_FORE_AFT_MOVE, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.SEAT_EASY_ACCESS_ENABLED, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.SEAT_AIRBAG_ENABLED, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.SEAT_CUSHION_SIDE_SUPPORT_POS, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.SEAT_CUSHION_SIDE_SUPPORT_MOVE, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.SEAT_LUMBAR_VERTICAL_POS, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.SEAT_LUMBAR_VERTICAL_MOVE, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.SEAT_OCCUPANCY, VehiclePropertyAccess.READ),
Map.entry(VehicleProperty.WINDOW_POS, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.WINDOW_MOVE, VehiclePropertyAccess.READ_WRITE),
@@ -155,6 +163,7 @@
Map.entry(VehicleProperty.STEERING_WHEEL_HEIGHT_MOVE, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.STEERING_WHEEL_THEFT_LOCK_ENABLED, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.STEERING_WHEEL_LOCKED, VehiclePropertyAccess.READ_WRITE),
+ Map.entry(VehicleProperty.STEERING_WHEEL_EASY_ACCESS_ENABLED, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.VEHICLE_MAP_SERVICE, VehiclePropertyAccess.READ_WRITE),
Map.entry(VehicleProperty.OBD2_LIVE_FRAME, VehiclePropertyAccess.READ),
Map.entry(VehicleProperty.OBD2_FREEZE_FRAME, VehiclePropertyAccess.READ),
diff --git a/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java b/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java
index a1f0127..46b9663 100644
--- a/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java
+++ b/automotive/vehicle/aidl/generated_lib/java/ChangeModeForVehicleProperty.java
@@ -118,6 +118,8 @@
Map.entry(VehicleProperty.MIRROR_Y_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.MIRROR_LOCK, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.MIRROR_FOLD, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.MIRROR_AUTO_FOLD_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.MIRROR_AUTO_TILT_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.SEAT_MEMORY_SELECT, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.SEAT_MEMORY_SET, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.SEAT_BELT_BUCKLED, VehiclePropertyChangeMode.ON_CHANGE),
@@ -145,6 +147,12 @@
Map.entry(VehicleProperty.SEAT_HEADREST_ANGLE_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.SEAT_HEADREST_FORE_AFT_POS, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.SEAT_HEADREST_FORE_AFT_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.SEAT_EASY_ACCESS_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.SEAT_AIRBAG_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.SEAT_CUSHION_SIDE_SUPPORT_POS, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.SEAT_CUSHION_SIDE_SUPPORT_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.SEAT_LUMBAR_VERTICAL_POS, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.SEAT_LUMBAR_VERTICAL_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.SEAT_OCCUPANCY, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.WINDOW_POS, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.WINDOW_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
@@ -155,6 +163,7 @@
Map.entry(VehicleProperty.STEERING_WHEEL_HEIGHT_MOVE, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.STEERING_WHEEL_THEFT_LOCK_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.STEERING_WHEEL_LOCKED, VehiclePropertyChangeMode.ON_CHANGE),
+ Map.entry(VehicleProperty.STEERING_WHEEL_EASY_ACCESS_ENABLED, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.VEHICLE_MAP_SERVICE, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.OBD2_LIVE_FRAME, VehiclePropertyChangeMode.ON_CHANGE),
Map.entry(VehicleProperty.OBD2_FREEZE_FRAME, VehiclePropertyChangeMode.ON_CHANGE),
diff --git a/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json b/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json
index 99e52e9..bd80ad5 100644
--- a/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json
+++ b/automotive/vehicle/aidl/impl/default_config/config/DefaultProperties.json
@@ -1036,6 +1036,178 @@
]
},
{
+ "property": "VehicleProperty::SEAT_EASY_ACCESS_ENABLED",
+ "defaultValue": {
+ "int32Values": [
+ 1
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::SEAT_1_LEFT"
+ },
+ {
+ "areaId": "Constants::SEAT_1_RIGHT"
+ }
+ ]
+ },
+ {
+ "property": "VehicleProperty::SEAT_AIRBAG_ENABLED",
+ "defaultValue": {
+ "int32Values": [
+ 1
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::SEAT_1_LEFT"
+ },
+ {
+ "areaId": "Constants::SEAT_1_RIGHT"
+ }
+ ]
+ },
+ {
+ "property": "VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_POS",
+ "defaultValue": {
+ "int32Values": [
+ 0
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::SEAT_1_LEFT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_1_RIGHT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_2_LEFT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_2_RIGHT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_2_CENTER",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ }
+ ]
+ },
+ {
+ "property": "VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_MOVE",
+ "defaultValue": {
+ "int32Values": [
+ 0
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::SEAT_1_LEFT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_1_RIGHT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_2_LEFT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_2_RIGHT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_2_CENTER",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ }
+ ]
+ },
+ {
+ "property": "VehicleProperty::SEAT_LUMBAR_VERTICAL_POS",
+ "defaultValue": {
+ "int32Values": [
+ 0
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::SEAT_1_LEFT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_1_RIGHT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_2_LEFT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_2_RIGHT",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ },
+ {
+ "areaId": "Constants::SEAT_2_CENTER",
+ "minInt32Value": -10,
+ "maxInt32Value": 10
+ }
+ ]
+ },
+ {
+ "property": "VehicleProperty::SEAT_LUMBAR_VERTICAL_MOVE",
+ "defaultValue": {
+ "int32Values": [
+ 0
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::SEAT_1_LEFT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_1_RIGHT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_2_LEFT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_2_RIGHT",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ },
+ {
+ "areaId": "Constants::SEAT_2_CENTER",
+ "minInt32Value": -1,
+ "maxInt32Value": 1
+ }
+ ]
+ },
+ {
"property": "VehicleProperty::SEAT_OCCUPANCY",
"areas": [
{
@@ -2126,6 +2298,32 @@
}
},
{
+ "property": "VehicleProperty::MIRROR_AUTO_FOLD_ENABLED",
+ "defaultValue": {
+ "int32Values": [
+ 1
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::MIRROR_DRIVER_LEFT_RIGHT"
+ }
+ ]
+ },
+ {
+ "property": "VehicleProperty::MIRROR_AUTO_TILT_ENABLED",
+ "defaultValue": {
+ "int32Values": [
+ 1
+ ]
+ },
+ "areas": [
+ {
+ "areaId": "Constants::MIRROR_DRIVER_LEFT_RIGHT"
+ }
+ ]
+ },
+ {
"property": "VehicleProperty::WINDOW_LOCK",
"areas": [
{
@@ -2285,6 +2483,14 @@
}
},
{
+ "property": "VehicleProperty::STEERING_WHEEL_EASY_ACCESS_ENABLED",
+ "defaultValue": {
+ "int32Values": [
+ 0
+ ]
+ }
+ },
+ {
"property": "VehicleProperty::WHEEL_TICK",
"defaultValue": {
"int64Values": [
diff --git a/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp b/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp
index 13244ce..7eefe2a 100644
--- a/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp
+++ b/automotive/vehicle/vts/src/VtsHalAutomotiveVehicle_TargetTest.cpp
@@ -523,6 +523,60 @@
VehicleArea::GLOBAL, VehiclePropertyType::BOOLEAN);
}
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySteeringWheelEasyAccessEnabledConfig) {
+ verifyProperty(VehicleProperty::STEERING_WHEEL_EASY_ACCESS_ENABLED,
+ VehiclePropertyAccess::READ_WRITE, VehiclePropertyChangeMode::ON_CHANGE,
+ VehiclePropertyGroup::SYSTEM, VehicleArea::GLOBAL, VehiclePropertyType::BOOLEAN);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifyMirrorAutoFoldEnabledConfig) {
+ verifyProperty(VehicleProperty::MIRROR_AUTO_FOLD_ENABLED, VehiclePropertyAccess::READ_WRITE,
+ VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+ VehicleArea::MIRROR, VehiclePropertyType::BOOLEAN);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifyMirrorAutoTiltEnabledConfig) {
+ verifyProperty(VehicleProperty::MIRROR_AUTO_TILT_ENABLED, VehiclePropertyAccess::READ_WRITE,
+ VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+ VehicleArea::MIRROR, VehiclePropertyType::BOOLEAN);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySeatEasyAccessEnabledConfig) {
+ verifyProperty(VehicleProperty::SEAT_EASY_ACCESS_ENABLED, VehiclePropertyAccess::READ_WRITE,
+ VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+ VehicleArea::SEAT, VehiclePropertyType::BOOLEAN);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySeatAirbagEnabledConfig) {
+ verifyProperty(VehicleProperty::SEAT_AIRBAG_ENABLED, VehiclePropertyAccess::READ_WRITE,
+ VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+ VehicleArea::SEAT, VehiclePropertyType::BOOLEAN);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySeatCushionSideSupportPosConfig) {
+ verifyProperty(VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_POS,
+ VehiclePropertyAccess::READ_WRITE, VehiclePropertyChangeMode::ON_CHANGE,
+ VehiclePropertyGroup::SYSTEM, VehicleArea::SEAT, VehiclePropertyType::INT32);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySeatCushionSideSupportMoveConfig) {
+ verifyProperty(VehicleProperty::SEAT_CUSHION_SIDE_SUPPORT_MOVE,
+ VehiclePropertyAccess::READ_WRITE, VehiclePropertyChangeMode::ON_CHANGE,
+ VehiclePropertyGroup::SYSTEM, VehicleArea::SEAT, VehiclePropertyType::INT32);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySeatLumbarVerticalPosConfig) {
+ verifyProperty(VehicleProperty::SEAT_LUMBAR_VERTICAL_POS, VehiclePropertyAccess::READ_WRITE,
+ VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+ VehicleArea::SEAT, VehiclePropertyType::INT32);
+}
+
+TEST_P(VtsHalAutomotiveVehicleTargetTest, verifySeatLumbarVerticalMoveConfig) {
+ verifyProperty(VehicleProperty::SEAT_LUMBAR_VERTICAL_MOVE, VehiclePropertyAccess::READ_WRITE,
+ VehiclePropertyChangeMode::ON_CHANGE, VehiclePropertyGroup::SYSTEM,
+ VehicleArea::SEAT, VehiclePropertyType::INT32);
+}
+
std::vector<ServiceDescriptor> getDescriptors() {
std::vector<ServiceDescriptor> descriptors;
for (std::string name : getAidlHalInstanceNames(IVehicle::descriptor)) {
diff --git a/biometrics/fingerprint/aidl/OWNERS b/biometrics/OWNERS
similarity index 100%
rename from biometrics/fingerprint/aidl/OWNERS
rename to biometrics/OWNERS
diff --git a/biometrics/common/aidl/Android.bp b/biometrics/common/aidl/Android.bp
index 167e0c7..3cd76fd 100644
--- a/biometrics/common/aidl/Android.bp
+++ b/biometrics/common/aidl/Android.bp
@@ -31,7 +31,5 @@
version: "2",
imports: [],
},
-
],
-
}
diff --git a/biometrics/common/aidl/OWNERS b/biometrics/common/aidl/OWNERS
deleted file mode 100644
index 36d7261..0000000
--- a/biometrics/common/aidl/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-ilyamaty@google.com
-kchyn@google.com
diff --git a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/CommonProps.aidl b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/CommonProps.aidl
index d4433c5..1eb8541 100644
--- a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/CommonProps.aidl
+++ b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/CommonProps.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.common;
+/* @hide */
@VintfStability
parcelable CommonProps {
int sensorId;
diff --git a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ComponentInfo.aidl b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ComponentInfo.aidl
index ad11dda..471ed2b 100644
--- a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ComponentInfo.aidl
+++ b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ComponentInfo.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.common;
+/* @hide */
@VintfStability
parcelable ComponentInfo {
String componentId;
diff --git a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ICancellationSignal.aidl b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ICancellationSignal.aidl
index 2bc6a6d..670114f 100644
--- a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ICancellationSignal.aidl
+++ b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/ICancellationSignal.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.common;
+/* @hide */
@VintfStability
interface ICancellationSignal {
oneway void cancel();
diff --git a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationContext.aidl b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationContext.aidl
index 9d1cb8f..5e184bc 100644
--- a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationContext.aidl
+++ b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationContext.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.common;
+/* @hide */
@VintfStability
parcelable OperationContext {
int id = 0;
diff --git a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationReason.aidl b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationReason.aidl
index 3da3a6a..a5b2990 100644
--- a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationReason.aidl
+++ b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/OperationReason.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.common;
+/* @hide */
@Backing(type="byte") @VintfStability
enum OperationReason {
UNKNOWN = 0,
diff --git a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/SensorStrength.aidl b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/SensorStrength.aidl
index 6675d09..aa77322 100644
--- a/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/SensorStrength.aidl
+++ b/biometrics/common/aidl/aidl_api/android.hardware.biometrics.common/current/android/hardware/biometrics/common/SensorStrength.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.common;
+/* @hide */
@Backing(type="byte") @VintfStability
enum SensorStrength {
CONVENIENCE = 0,
diff --git a/biometrics/common/aidl/android/hardware/biometrics/common/CommonProps.aidl b/biometrics/common/aidl/android/hardware/biometrics/common/CommonProps.aidl
index 2f5af5d..cdedf4f 100644
--- a/biometrics/common/aidl/android/hardware/biometrics/common/CommonProps.aidl
+++ b/biometrics/common/aidl/android/hardware/biometrics/common/CommonProps.aidl
@@ -18,7 +18,9 @@
import android.hardware.biometrics.common.ComponentInfo;
import android.hardware.biometrics.common.SensorStrength;
-
+/**
+ * @hide
+ */
@VintfStability
parcelable CommonProps {
/**
diff --git a/biometrics/common/aidl/android/hardware/biometrics/common/ComponentInfo.aidl b/biometrics/common/aidl/android/hardware/biometrics/common/ComponentInfo.aidl
index b268eef..1da9cf6 100644
--- a/biometrics/common/aidl/android/hardware/biometrics/common/ComponentInfo.aidl
+++ b/biometrics/common/aidl/android/hardware/biometrics/common/ComponentInfo.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.common;
-
+/**
+ * @hide
+ */
@VintfStability
parcelable ComponentInfo {
/**
diff --git a/biometrics/common/aidl/android/hardware/biometrics/common/ICancellationSignal.aidl b/biometrics/common/aidl/android/hardware/biometrics/common/ICancellationSignal.aidl
index 1010256..b9b1f39 100644
--- a/biometrics/common/aidl/android/hardware/biometrics/common/ICancellationSignal.aidl
+++ b/biometrics/common/aidl/android/hardware/biometrics/common/ICancellationSignal.aidl
@@ -15,9 +15,10 @@
*/
package android.hardware.biometrics.common;
-
+/**
+ * @hide
+ */
@VintfStability
oneway interface ICancellationSignal {
void cancel();
}
-
diff --git a/biometrics/common/aidl/android/hardware/biometrics/common/OperationContext.aidl b/biometrics/common/aidl/android/hardware/biometrics/common/OperationContext.aidl
index 72fe660..a1c7a1f 100644
--- a/biometrics/common/aidl/android/hardware/biometrics/common/OperationContext.aidl
+++ b/biometrics/common/aidl/android/hardware/biometrics/common/OperationContext.aidl
@@ -20,6 +20,7 @@
/**
* Additional context associated with an operation.
+ * @hide
*/
@VintfStability
parcelable OperationContext {
diff --git a/biometrics/common/aidl/android/hardware/biometrics/common/OperationReason.aidl b/biometrics/common/aidl/android/hardware/biometrics/common/OperationReason.aidl
index abc25ed..a93cebc 100644
--- a/biometrics/common/aidl/android/hardware/biometrics/common/OperationReason.aidl
+++ b/biometrics/common/aidl/android/hardware/biometrics/common/OperationReason.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.common;
-
+/**
+ * @hide
+ */
@VintfStability
@Backing(type="byte")
enum OperationReason {
diff --git a/biometrics/common/aidl/android/hardware/biometrics/common/SensorStrength.aidl b/biometrics/common/aidl/android/hardware/biometrics/common/SensorStrength.aidl
index 790691c..b5c0999 100644
--- a/biometrics/common/aidl/android/hardware/biometrics/common/SensorStrength.aidl
+++ b/biometrics/common/aidl/android/hardware/biometrics/common/SensorStrength.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.common;
-
+/**
+ * @hide
+ */
@VintfStability
@Backing(type="byte")
enum SensorStrength {
@@ -40,4 +42,4 @@
* HardwareAuthToken(s).
*/
STRONG,
-}
\ No newline at end of file
+}
diff --git a/biometrics/common/util/Android.bp b/biometrics/common/util/Android.bp
index 918ef72..b990812 100644
--- a/biometrics/common/util/Android.bp
+++ b/biometrics/common/util/Android.bp
@@ -13,6 +13,6 @@
shared_libs: [
"libbase",
"libbinder_ndk",
- "android.hardware.biometrics.common-V2-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
],
}
diff --git a/biometrics/face/1.0/vts/functional/OWNERS b/biometrics/face/1.0/vts/functional/OWNERS
deleted file mode 100644
index 7651b69..0000000
--- a/biometrics/face/1.0/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 432605
-ilyamaty@google.com
diff --git a/biometrics/face/aidl/Android.bp b/biometrics/face/aidl/Android.bp
index 0bec0c5..7b11335 100644
--- a/biometrics/face/aidl/Android.bp
+++ b/biometrics/face/aidl/Android.bp
@@ -14,9 +14,9 @@
"android/hardware/biometrics/face/**/*.aidl",
],
imports: [
- "android.hardware.biometrics.common",
+ "android.hardware.biometrics.common-V3",
"android.hardware.common-V2",
- "android.hardware.keymaster-V3",
+ "android.hardware.keymaster-V4",
],
stability: "vintf",
backend: {
diff --git a/biometrics/face/aidl/OWNERS b/biometrics/face/aidl/OWNERS
deleted file mode 100644
index 36d7261..0000000
--- a/biometrics/face/aidl/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-ilyamaty@google.com
-kchyn@google.com
diff --git a/biometrics/face/aidl/default/Android.bp b/biometrics/face/aidl/default/Android.bp
index 63a3645..876a91f 100644
--- a/biometrics/face/aidl/default/Android.bp
+++ b/biometrics/face/aidl/default/Android.bp
@@ -16,8 +16,8 @@
shared_libs: [
"libbase",
"libbinder_ndk",
- "android.hardware.biometrics.face-V2-ndk",
- "android.hardware.biometrics.common-V2-ndk",
+ "android.hardware.biometrics.face-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
"android.hardware.biometrics.common.thread",
"android.hardware.biometrics.common.util",
],
@@ -49,9 +49,9 @@
],
static_libs: [
"libandroid.hardware.biometrics.face.VirtualProps",
- "android.hardware.biometrics.face-V2-ndk",
- "android.hardware.biometrics.common-V2-ndk",
- "android.hardware.keymaster-V3-ndk",
+ "android.hardware.biometrics.face-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
+ "android.hardware.keymaster-V4-ndk",
"android.hardware.biometrics.common.util",
],
vendor: true,
diff --git a/biometrics/face/aidl/default/face-default.xml b/biometrics/face/aidl/default/face-default.xml
index e6ef842..8f2fbb8 100644
--- a/biometrics/face/aidl/default/face-default.xml
+++ b/biometrics/face/aidl/default/face-default.xml
@@ -1,7 +1,7 @@
<manifest version="1.0" type="device">
<hal format="aidl">
<name>android.hardware.biometrics.face</name>
- <version>2</version>
+ <version>3</version>
<fqname>IFace/default</fqname>
</hal>
</manifest>
diff --git a/biometrics/face/aidl/vts/Android.bp b/biometrics/face/aidl/vts/Android.bp
index 4171ac3..f62c4e4 100644
--- a/biometrics/face/aidl/vts/Android.bp
+++ b/biometrics/face/aidl/vts/Android.bp
@@ -15,10 +15,10 @@
],
srcs: ["VtsHalBiometricsFaceTargetTest.cpp"],
static_libs: [
- "android.hardware.biometrics.common-V2-ndk",
- "android.hardware.biometrics.face-V2-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
+ "android.hardware.biometrics.face-V3-ndk",
"android.hardware.common-V2-ndk",
- "android.hardware.keymaster-V3-ndk",
+ "android.hardware.keymaster-V4-ndk",
],
shared_libs: [
"libbinder_ndk",
diff --git a/biometrics/fingerprint/2.1/vts/functional/OWNERS b/biometrics/fingerprint/2.1/vts/functional/OWNERS
deleted file mode 100644
index 0014ce9..0000000
--- a/biometrics/fingerprint/2.1/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 114777
-ilyamaty@google.com
diff --git a/biometrics/fingerprint/2.2/vts/functional/OWNERS b/biometrics/fingerprint/2.2/vts/functional/OWNERS
deleted file mode 100644
index 0014ce9..0000000
--- a/biometrics/fingerprint/2.2/vts/functional/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-# Bug component: 114777
-ilyamaty@google.com
diff --git a/biometrics/fingerprint/aidl/Android.bp b/biometrics/fingerprint/aidl/Android.bp
index 0bd6422..f749822 100644
--- a/biometrics/fingerprint/aidl/Android.bp
+++ b/biometrics/fingerprint/aidl/Android.bp
@@ -14,8 +14,8 @@
"android/hardware/biometrics/fingerprint/**/*.aidl",
],
imports: [
- "android.hardware.biometrics.common",
- "android.hardware.keymaster-V3",
+ "android.hardware.biometrics.common-V3",
+ "android.hardware.keymaster-V4",
],
stability: "vintf",
backend: {
@@ -41,7 +41,5 @@
"android.hardware.keymaster-V3",
],
},
-
],
-
}
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl
index c51aa03..0cc619f 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@Backing(type="byte") @VintfStability
enum AcquiredInfo {
UNKNOWN = 0,
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/Error.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/Error.aidl
index af7bc3c..45ce2eb 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/Error.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/Error.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@Backing(type="byte") @VintfStability
enum Error {
UNKNOWN = 0,
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl
index 9c208c4..67af20d 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@Backing(type="byte") @VintfStability
enum FingerprintSensorType {
UNKNOWN = 0,
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/IFingerprint.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/IFingerprint.aidl
index 5d3df6f..0b6f300 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/IFingerprint.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/IFingerprint.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@VintfStability
interface IFingerprint {
android.hardware.biometrics.fingerprint.SensorProps[] getSensorProps();
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISession.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISession.aidl
index 30f299d..f305855 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISession.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISession.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@VintfStability
interface ISession {
void generateChallenge();
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISessionCallback.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISessionCallback.aidl
index 3c40ad6..be18ffe 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISessionCallback.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/ISessionCallback.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@VintfStability
interface ISessionCallback {
void onChallengeGenerated(in long challenge);
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/PointerContext.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/PointerContext.aidl
index 43db6cf..999b324 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/PointerContext.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/PointerContext.aidl
@@ -32,7 +32,8 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
-@VintfStability
+/* @hide */
+@JavaDerive(equals=true) @VintfStability
parcelable PointerContext {
int pointerId = -1;
float x = 0.000000f;
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorLocation.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorLocation.aidl
index 295fde9..dc6a62d 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorLocation.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorLocation.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@VintfStability
parcelable SensorLocation {
int displayId;
diff --git a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorProps.aidl b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorProps.aidl
index 782d289..a77d5f2 100644
--- a/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorProps.aidl
+++ b/biometrics/fingerprint/aidl/aidl_api/android.hardware.biometrics.fingerprint/current/android/hardware/biometrics/fingerprint/SensorProps.aidl
@@ -32,6 +32,7 @@
// later when a module using the interface is updated, e.g., Mainline modules.
package android.hardware.biometrics.fingerprint;
+/* @hide */
@VintfStability
parcelable SensorProps {
android.hardware.biometrics.common.CommonProps commonProps;
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl
index 8ec8574..d3aa98a 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/AcquiredInfo.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.fingerprint;
-
+/**
+ * @hide
+ */
@VintfStability
@Backing(type="byte")
enum AcquiredInfo {
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/Error.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/Error.aidl
index e69859a..d8d47fa 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/Error.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/Error.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.fingerprint;
-
+/**
+ * @hide
+ */
@VintfStability
@Backing(type="byte")
enum Error {
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl
index dbe7137..7caa154 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/FingerprintSensorType.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.fingerprint;
-
+/**
+ * @hide
+ */
@VintfStability
@Backing(type="byte")
enum FingerprintSensorType {
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/IFingerprint.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/IFingerprint.aidl
index 75f90a1..f4febad 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/IFingerprint.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/IFingerprint.aidl
@@ -19,7 +19,9 @@
import android.hardware.biometrics.fingerprint.ISession;
import android.hardware.biometrics.fingerprint.ISessionCallback;
import android.hardware.biometrics.fingerprint.SensorProps;
-
+/**
+ * @hide
+ */
@VintfStability
interface IFingerprint {
/**
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISession.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISession.aidl
index db01145..f4f7804 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISession.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISession.aidl
@@ -45,6 +45,7 @@
* ISession only supports execution of one non-interrupting operation at a time, regardless of
* whether it's cancellable. The framework must wait for a callback indicating the end of the
* current non-interrupting operation before a new non-interrupting operation can be started.
+ * @hide
*/
@VintfStability
interface ISession {
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISessionCallback.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISessionCallback.aidl
index f699966..24b169e 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISessionCallback.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/ISessionCallback.aidl
@@ -19,7 +19,9 @@
import android.hardware.biometrics.fingerprint.AcquiredInfo;
import android.hardware.biometrics.fingerprint.Error;
import android.hardware.keymaster.HardwareAuthToken;
-
+/**
+ * @hide
+ */
@VintfStability
interface ISessionCallback {
/**
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/PointerContext.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/PointerContext.aidl
index e025d34..582e6cf 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/PointerContext.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/PointerContext.aidl
@@ -18,7 +18,9 @@
/**
* Additional context associated with a pointer event.
+ * @hide
*/
+@JavaDerive(equals=true)
@VintfStability
parcelable PointerContext {
/**
@@ -64,7 +66,7 @@
boolean isAod = false;
/**
- * The time of the user interaction that produced this event, in milliseconds.
+ * The time when this event was created, in milliseconds.
*
* This is obtained from MotionEvent#getEventTime, which uses SystemClock.uptimeMillis() as
* the clock.
@@ -74,10 +76,10 @@
long time = 0;
/**
- * The time of the first user interaction in this gesture, in milliseconds.
+ * This event is part of some gesture. This is the time when MotionEvent#ACTION_DOWN was
+ * created for that gesture, in milliseconds.
*
- * If this event is MotionEvent#ACTION_DOWN, it means it's the first event in this gesture,
- * and `gestureStart` will be equal to `time`.
+ * If this event is MotionEvent#ACTION_DOWN, then this value is equal to `time`.
*
* This is obtained from MotionEvent#getDownTime, which uses SystemClock.uptimeMillis() as
* the clock.
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorLocation.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorLocation.aidl
index d12605c..a065a7c 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorLocation.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorLocation.aidl
@@ -15,7 +15,9 @@
*/
package android.hardware.biometrics.fingerprint;
-
+/**
+ * @hide
+ */
@VintfStability
parcelable SensorLocation {
/**
diff --git a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorProps.aidl b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorProps.aidl
index fb516da..d4e9ec6 100644
--- a/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorProps.aidl
+++ b/biometrics/fingerprint/aidl/android/hardware/biometrics/fingerprint/SensorProps.aidl
@@ -19,7 +19,9 @@
import android.hardware.biometrics.common.CommonProps;
import android.hardware.biometrics.fingerprint.FingerprintSensorType;
import android.hardware.biometrics.fingerprint.SensorLocation;
-
+/**
+ * @hide
+ */
@VintfStability
parcelable SensorProps {
/**
diff --git a/biometrics/fingerprint/aidl/default/Android.bp b/biometrics/fingerprint/aidl/default/Android.bp
index 77c74e1..fe224c9 100644
--- a/biometrics/fingerprint/aidl/default/Android.bp
+++ b/biometrics/fingerprint/aidl/default/Android.bp
@@ -27,8 +27,8 @@
shared_libs: [
"libbase",
"libbinder_ndk",
- "android.hardware.biometrics.fingerprint-V2-ndk",
- "android.hardware.biometrics.common-V2-ndk",
+ "android.hardware.biometrics.fingerprint-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
"android.hardware.biometrics.common.thread",
"android.hardware.biometrics.common.util",
],
@@ -50,9 +50,9 @@
],
static_libs: [
"libandroid.hardware.biometrics.fingerprint.VirtualProps",
- "android.hardware.biometrics.fingerprint-V2-ndk",
- "android.hardware.biometrics.common-V2-ndk",
- "android.hardware.keymaster-V3-ndk",
+ "android.hardware.biometrics.fingerprint-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
+ "android.hardware.keymaster-V4-ndk",
"android.hardware.biometrics.common.util",
],
vendor: true,
@@ -76,9 +76,9 @@
],
static_libs: [
"libandroid.hardware.biometrics.fingerprint.VirtualProps",
- "android.hardware.biometrics.fingerprint-V2-ndk",
- "android.hardware.biometrics.common-V2-ndk",
- "android.hardware.keymaster-V3-ndk",
+ "android.hardware.biometrics.fingerprint-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
+ "android.hardware.keymaster-V4-ndk",
"android.hardware.biometrics.common.util",
],
vendor: true,
@@ -100,9 +100,9 @@
],
static_libs: [
"libandroid.hardware.biometrics.fingerprint.VirtualProps",
- "android.hardware.biometrics.fingerprint-V2-ndk",
- "android.hardware.biometrics.common-V2-ndk",
- "android.hardware.keymaster-V3-ndk",
+ "android.hardware.biometrics.fingerprint-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
+ "android.hardware.keymaster-V4-ndk",
"android.hardware.biometrics.common.util",
],
vendor: true,
diff --git a/biometrics/fingerprint/aidl/default/fingerprint-example.xml b/biometrics/fingerprint/aidl/default/fingerprint-example.xml
index 05d1279..e977b98 100644
--- a/biometrics/fingerprint/aidl/default/fingerprint-example.xml
+++ b/biometrics/fingerprint/aidl/default/fingerprint-example.xml
@@ -1,7 +1,7 @@
<manifest version="1.0" type="device">
<hal format="aidl">
<name>android.hardware.biometrics.fingerprint</name>
- <version>2</version>
+ <version>3</version>
<fqname>IFingerprint/virtual</fqname>
</hal>
</manifest>
diff --git a/biometrics/fingerprint/aidl/vts/Android.bp b/biometrics/fingerprint/aidl/vts/Android.bp
index a474f66..1652905 100644
--- a/biometrics/fingerprint/aidl/vts/Android.bp
+++ b/biometrics/fingerprint/aidl/vts/Android.bp
@@ -15,9 +15,9 @@
],
srcs: ["VtsHalBiometricsFingerprintTargetTest.cpp"],
static_libs: [
- "android.hardware.biometrics.common-V2-ndk",
- "android.hardware.biometrics.fingerprint-V2-ndk",
- "android.hardware.keymaster-V3-ndk",
+ "android.hardware.biometrics.common-V3-ndk",
+ "android.hardware.biometrics.fingerprint-V3-ndk",
+ "android.hardware.keymaster-V4-ndk",
],
shared_libs: [
"libbinder_ndk",
diff --git a/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl b/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl
index 617979d..ecbfc93 100644
--- a/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl
+++ b/camera/metadata/aidl/aidl_api/android.hardware.camera.metadata/current/android/hardware/camera/metadata/CameraMetadataTag.aidl
@@ -94,9 +94,10 @@
ANDROID_CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS_MAXIMUM_RESOLUTION = 65584,
ANDROID_CONTROL_SETTINGS_OVERRIDE = 65588,
ANDROID_CONTROL_AVAILABLE_SETTINGS_OVERRIDES = 65589,
- ANDROID_CONTROL_AUTOFRAMING = 65590,
- ANDROID_CONTROL_AUTOFRAMING_AVAILABLE = 65591,
- ANDROID_CONTROL_AUTOFRAMING_STATE = 65592,
+ ANDROID_CONTROL_SETTINGS_OVERRIDING_FRAME_NUMBER = 65590,
+ ANDROID_CONTROL_AUTOFRAMING = 65591,
+ ANDROID_CONTROL_AUTOFRAMING_AVAILABLE = 65592,
+ ANDROID_CONTROL_AUTOFRAMING_STATE = 65593,
ANDROID_DEMOSAIC_MODE = 131072,
ANDROID_EDGE_MODE = 196608,
ANDROID_EDGE_STRENGTH = 196609,
diff --git a/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl b/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
index 85e56bc..2e9bde9 100644
--- a/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
+++ b/camera/metadata/aidl/android/hardware/camera/metadata/CameraMetadataTag.aidl
@@ -464,6 +464,12 @@
*/
ANDROID_CONTROL_AVAILABLE_SETTINGS_OVERRIDES,
/**
+ * android.control.settingsOverridingFrameNumber [dynamic, int32, system]
+ *
+ * <p>The frame number of the newer request overriding this capture.</p>
+ */
+ ANDROID_CONTROL_SETTINGS_OVERRIDING_FRAME_NUMBER,
+ /**
* android.control.autoframing [dynamic, enum, public]
*
* <p>Automatic crop, pan and zoom to keep objects in the center of the frame.</p>
diff --git a/camera/provider/aidl/Android.bp b/camera/provider/aidl/Android.bp
index bb30e43..d7e613e 100644
--- a/camera/provider/aidl/Android.bp
+++ b/camera/provider/aidl/Android.bp
@@ -17,6 +17,7 @@
"android.hardware.camera.device-V2",
"android.hardware.camera.common-V1",
],
+ frozen: false,
stability: "vintf",
backend: {
java: {
diff --git a/camera/provider/aidl/aidl_api/android.hardware.camera.provider/current/android/hardware/camera/provider/ICameraProvider.aidl b/camera/provider/aidl/aidl_api/android.hardware.camera.provider/current/android/hardware/camera/provider/ICameraProvider.aidl
index c6a3b9a..c15bdee 100644
--- a/camera/provider/aidl/aidl_api/android.hardware.camera.provider/current/android/hardware/camera/provider/ICameraProvider.aidl
+++ b/camera/provider/aidl/aidl_api/android.hardware.camera.provider/current/android/hardware/camera/provider/ICameraProvider.aidl
@@ -41,7 +41,6 @@
void notifyDeviceStateChange(long deviceState);
android.hardware.camera.provider.ConcurrentCameraIdCombination[] getConcurrentCameraIds();
boolean isConcurrentStreamCombinationSupported(in android.hardware.camera.provider.CameraIdAndStreamCombination[] configs);
- void placeholder();
const long DEVICE_STATE_NORMAL = 0;
const long DEVICE_STATE_BACK_COVERED = 1;
const long DEVICE_STATE_FRONT_COVERED = 2;
diff --git a/camera/provider/aidl/android/hardware/camera/provider/ICameraProvider.aidl b/camera/provider/aidl/android/hardware/camera/provider/ICameraProvider.aidl
index 5442058..c4eba8d 100644
--- a/camera/provider/aidl/android/hardware/camera/provider/ICameraProvider.aidl
+++ b/camera/provider/aidl/android/hardware/camera/provider/ICameraProvider.aidl
@@ -304,12 +304,4 @@
*
*/
boolean isConcurrentStreamCombinationSupported(in CameraIdAndStreamCombination[] configs);
-
- /*
- * Due to a bug in vintf regarding aidl changes that are contained to fields,
- * we need a placeholder method that will be removed after this patch.
- *
- * TODO(b/237048744): Remove this once fixed.
- */
- void placeholder();
}
diff --git a/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp b/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
index 017f6ef..747ea33 100644
--- a/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
+++ b/camera/provider/aidl/vts/VtsAidlHalCameraProvider_TargetTest.cpp
@@ -2065,6 +2065,28 @@
}
}
+TEST_P(CameraAidlTest, processZoomSettingsOverrideRequests) {
+ const int32_t kFrameCount = 5;
+ const int32_t kTestCases = 2;
+ const bool kOverrideSequence[kTestCases][kFrameCount] = {
+ // ZOOM, ZOOM, ZOOM, ZOOM, ZOOM;
+ { true, true, true, true, true },
+ // OFF, OFF, ZOOM, ZOOM, OFF;
+ { false, false, true, true, false } };
+ const bool kExpectedOverrideResults[kTestCases][kFrameCount] = {
+ // All resuls should be overridden except the last one. The last result's
+ // zoom doesn't have speed-up.
+ { true, true, true, true, false },
+ // Because we require at least 2 frames speed-up, request #1, #2 and #3
+ // will be overridden.
+ { true, true, true, false, false } };
+
+ for (int i = 0; i < kTestCases; i++) {
+ processZoomSettingsOverrideRequests(kFrameCount, kOverrideSequence[i],
+ kExpectedOverrideResults[i]);
+ }
+}
+
// Generate and verify a burst containing alternating sensor sensitivity values
TEST_P(CameraAidlTest, processCaptureRequestBurstISO) {
std::vector<std::string> cameraDeviceNames = getCameraDeviceNames(mProvider);
diff --git a/camera/provider/aidl/vts/camera_aidl_test.cpp b/camera/provider/aidl/vts/camera_aidl_test.cpp
index ca316e5..b9e30ab 100644
--- a/camera/provider/aidl/vts/camera_aidl_test.cpp
+++ b/camera/provider/aidl/vts/camera_aidl_test.cpp
@@ -363,10 +363,15 @@
retcode = find_camera_metadata_ro_entry(metadata,
ANDROID_REQUEST_AVAILABLE_RESULT_KEYS, &entry);
bool hasSettingsOverrideResultKey = false;
+ bool hasOverridingFrameNumberKey = false;
if ((0 == retcode) && (entry.count > 0)) {
hasSettingsOverrideResultKey =
std::find(entry.data.i32, entry.data.i32 + entry.count,
ANDROID_CONTROL_SETTINGS_OVERRIDE) != entry.data.i32 + entry.count;
+ hasOverridingFrameNumberKey =
+ std::find(entry.data.i32, entry.data.i32 + entry.count,
+ ANDROID_CONTROL_SETTINGS_OVERRIDING_FRAME_NUMBER)
+ != entry.data.i32 + entry.count;
} else {
ADD_FAILURE() << "Get camera availableResultKeys failed!";
}
@@ -385,6 +390,7 @@
ASSERT_EQ(supportSettingsOverride, hasSettingsOverrideRequestKey);
ASSERT_EQ(supportSettingsOverride, hasSettingsOverrideResultKey);
+ ASSERT_EQ(supportSettingsOverride, hasOverridingFrameNumberKey);
ASSERT_EQ(supportSettingsOverride, hasSettingsOverrideCharacteristicsKey);
}
@@ -1579,7 +1585,7 @@
// Check settings override
camera_metadata_ro_entry settingsOverrideEntry;
int foundSettingsOverride = find_camera_metadata_ro_entry(metadata,
- ANDROID_CONTROL_SETTINGS_OVERRIDE,&settingsOverrideEntry);
+ ANDROID_CONTROL_SETTINGS_OVERRIDE, &settingsOverrideEntry);
if (foundSettingsOverride == 0) {
ASSERT_EQ(settingsOverrideEntry.count, 1);
ASSERT_EQ(settingsOverrideEntry.data.u8[0], ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF);
@@ -3019,6 +3025,30 @@
}
}
+bool CameraAidlTest::supportZoomSettingsOverride(const camera_metadata_t* staticMeta) {
+ camera_metadata_ro_entry availableOverridesEntry;
+ int rc = find_camera_metadata_ro_entry(staticMeta, ANDROID_CONTROL_AVAILABLE_SETTINGS_OVERRIDES,
+ &availableOverridesEntry);
+ if (rc == 0) {
+ for (size_t i = 0; i < availableOverridesEntry.count; i++) {
+ if (availableOverridesEntry.data.i32[i] == ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool CameraAidlTest::isPerFrameControl(const camera_metadata_t* staticMeta) {
+ camera_metadata_ro_entry syncLatencyEntry;
+ int rc = find_camera_metadata_ro_entry(staticMeta, ANDROID_SYNC_MAX_LATENCY,
+ &syncLatencyEntry);
+ if (rc == 0 && syncLatencyEntry.data.i32[0] == ANDROID_SYNC_MAX_LATENCY_PER_FRAME_CONTROL) {
+ return true;
+ }
+ return false;
+}
+
void CameraAidlTest::configurePreviewStream(
const std::string& name, const std::shared_ptr<ICameraProvider>& provider,
const AvailableStream* previewThreshold, std::shared_ptr<ICameraDeviceSession>* session,
@@ -3385,3 +3415,158 @@
ASSERT_TRUE(ret.isOk());
}
}
+
+void CameraAidlTest::processZoomSettingsOverrideRequests(
+ int32_t frameCount, const bool *overrideSequence, const bool *expectedResults) {
+ std::vector<std::string> cameraDeviceNames = getCameraDeviceNames(mProvider);
+ AvailableStream previewThreshold = {kMaxPreviewWidth, kMaxPreviewHeight,
+ static_cast<int32_t>(PixelFormat::IMPLEMENTATION_DEFINED)};
+ int64_t bufferId = 1;
+ int32_t frameNumber = 1;
+ CameraMetadata settings;
+ ndk::ScopedAStatus ret;
+ for (const auto& name : cameraDeviceNames) {
+ CameraMetadata meta;
+ std::shared_ptr<ICameraDevice> device;
+ openEmptyDeviceSession(name, mProvider, &mSession /*out*/, &meta /*out*/,
+ &device /*out*/);
+ camera_metadata_t* staticMeta =
+ clone_camera_metadata(reinterpret_cast<camera_metadata_t*>(meta.metadata.data()));
+
+ ret = mSession->close();
+ mSession = nullptr;
+ ASSERT_TRUE(ret.isOk());
+
+ // Device does not support zoom settnigs override
+ if (!supportZoomSettingsOverride(staticMeta)) {
+ continue;
+ }
+
+ if (!isPerFrameControl(staticMeta)) {
+ continue;
+ }
+
+ bool supportsPartialResults = false;
+ bool useHalBufManager = false;
+ int32_t partialResultCount = 0;
+ Stream previewStream;
+ std::vector<HalStream> halStreams;
+ std::shared_ptr<DeviceCb> cb;
+ configurePreviewStream(name, mProvider, &previewThreshold, &mSession /*out*/,
+ &previewStream /*out*/, &halStreams /*out*/,
+ &supportsPartialResults /*out*/, &partialResultCount /*out*/,
+ &useHalBufManager /*out*/, &cb /*out*/);
+ ASSERT_NE(mSession, nullptr);
+
+ ::aidl::android::hardware::common::fmq::MQDescriptor<
+ int8_t, aidl::android::hardware::common::fmq::SynchronizedReadWrite>
+ descriptor;
+ auto resultQueueRet = mSession->getCaptureResultMetadataQueue(&descriptor);
+ ASSERT_TRUE(resultQueueRet.isOk());
+
+ std::shared_ptr<ResultMetadataQueue> resultQueue =
+ std::make_shared<ResultMetadataQueue>(descriptor);
+ if (!resultQueue->isValid() || resultQueue->availableToWrite() <= 0) {
+ ALOGE("%s: HAL returns empty result metadata fmq, not use it", __func__);
+ resultQueue = nullptr;
+ // Don't use the queue onwards.
+ }
+
+ ret = mSession->constructDefaultRequestSettings(RequestTemplate::PREVIEW, &settings);
+ ASSERT_TRUE(ret.isOk());
+
+ mInflightMap.clear();
+ ::android::hardware::camera::common::V1_0::helper::CameraMetadata requestMeta;
+ std::vector<CaptureRequest> requests(frameCount);
+ std::vector<buffer_handle_t> buffers(frameCount);
+ std::vector<std::shared_ptr<InFlightRequest>> inflightReqs(frameCount);
+ std::vector<CameraMetadata> requestSettings(frameCount);
+
+ for (int32_t i = 0; i < frameCount; i++) {
+ std::unique_lock<std::mutex> l(mLock);
+ CaptureRequest& request = requests[i];
+ std::vector<StreamBuffer>& outputBuffers = request.outputBuffers;
+ outputBuffers.resize(1);
+ StreamBuffer& outputBuffer = outputBuffers[0];
+
+ if (useHalBufManager) {
+ outputBuffer = {halStreams[0].id, 0,
+ NativeHandle(), BufferStatus::OK,
+ NativeHandle(), NativeHandle()};
+ } else {
+ allocateGraphicBuffer(previewStream.width, previewStream.height,
+ android_convertGralloc1To0Usage(
+ static_cast<uint64_t>(halStreams[0].producerUsage),
+ static_cast<uint64_t>(halStreams[0].consumerUsage)),
+ halStreams[0].overrideFormat, &buffers[i]);
+ outputBuffer = {halStreams[0].id, bufferId + i, ::android::makeToAidl(buffers[i]),
+ BufferStatus::OK, NativeHandle(), NativeHandle()};
+ }
+
+ // Set appropriate settings override tag
+ requestMeta.append(reinterpret_cast<camera_metadata_t*>(settings.metadata.data()));
+ int32_t settingsOverride = overrideSequence[i] ?
+ ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM : ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF;
+ ASSERT_EQ(::android::OK, requestMeta.update(ANDROID_CONTROL_SETTINGS_OVERRIDE,
+ &settingsOverride, 1));
+ camera_metadata_t* metaBuffer = requestMeta.release();
+ uint8_t* rawMetaBuffer = reinterpret_cast<uint8_t*>(metaBuffer);
+ requestSettings[i].metadata = std::vector(
+ rawMetaBuffer, rawMetaBuffer + get_camera_metadata_size(metaBuffer));
+ overrideRotateAndCrop(&(requestSettings[i]));
+ request.frameNumber = frameNumber + i;
+ request.fmqSettingsSize = 0;
+ request.settings = requestSettings[i];
+ request.inputBuffer = {
+ -1, 0, NativeHandle(), BufferStatus::ERROR, NativeHandle(), NativeHandle()};
+
+ inflightReqs[i] = std::make_shared<InFlightRequest>(1, false, supportsPartialResults,
+ partialResultCount, resultQueue);
+ mInflightMap[frameNumber + i] = inflightReqs[i];
+ }
+
+ int32_t numRequestProcessed = 0;
+ std::vector<BufferCache> cachesToRemove;
+
+ ndk::ScopedAStatus returnStatus =
+ mSession->processCaptureRequest(requests, cachesToRemove, &numRequestProcessed);
+ ASSERT_TRUE(returnStatus.isOk());
+ ASSERT_EQ(numRequestProcessed, frameCount);
+
+ for (size_t i = 0; i < frameCount; i++) {
+ std::unique_lock<std::mutex> l(mLock);
+ while (!inflightReqs[i]->errorCodeValid && ((0 < inflightReqs[i]->numBuffersLeft) ||
+ (!inflightReqs[i]->haveResultMetadata))) {
+ auto timeout = std::chrono::system_clock::now() +
+ std::chrono::seconds(kStreamBufferTimeoutSec);
+ ASSERT_NE(std::cv_status::timeout, mResultCondition.wait_until(l, timeout));
+ }
+
+ ASSERT_FALSE(inflightReqs[i]->errorCodeValid);
+ ASSERT_NE(inflightReqs[i]->resultOutputBuffers.size(), 0u);
+ ASSERT_EQ(previewStream.id, inflightReqs[i]->resultOutputBuffers[0].buffer.streamId);
+ ASSERT_FALSE(inflightReqs[i]->collectedResult.isEmpty());
+ ASSERT_TRUE(inflightReqs[i]->collectedResult.exists(ANDROID_CONTROL_SETTINGS_OVERRIDE));
+ camera_metadata_entry_t overrideResult =
+ inflightReqs[i]->collectedResult.find(ANDROID_CONTROL_SETTINGS_OVERRIDE);
+ ASSERT_EQ(overrideResult.data.i32[0] == ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM,
+ expectedResults[i]);
+ ASSERT_TRUE(inflightReqs[i]->collectedResult.exists(
+ ANDROID_CONTROL_SETTINGS_OVERRIDING_FRAME_NUMBER));
+ camera_metadata_entry_t frameNumberEntry = inflightReqs[i]->collectedResult.find(
+ ANDROID_CONTROL_SETTINGS_OVERRIDING_FRAME_NUMBER);
+ ALOGV("%s: i %zu, expcetedResults[i] %d, overrideResult is %d, frameNumber %d",
+ __FUNCTION__, i, expectedResults[i], overrideResult.data.i32[0],
+ frameNumberEntry.data.i32[0]);
+ if (expectedResults[i]) {
+ ASSERT_GT(frameNumberEntry.data.i32[0], inflightReqs[i]->frameNumber);
+ } else {
+ ASSERT_EQ(frameNumberEntry.data.i32[0], frameNumber + i);
+ }
+ }
+
+ ret = mSession->close();
+ mSession = nullptr;
+ ASSERT_TRUE(ret.isOk());
+ }
+}
diff --git a/camera/provider/aidl/vts/camera_aidl_test.h b/camera/provider/aidl/vts/camera_aidl_test.h
index ff3617f..b6e398b 100644
--- a/camera/provider/aidl/vts/camera_aidl_test.h
+++ b/camera/provider/aidl/vts/camera_aidl_test.h
@@ -406,6 +406,12 @@
aidl::android::hardware::camera::metadata::
RequestAvailableDynamicRangeProfilesMap dynamicRangeProfile);
+ void processZoomSettingsOverrideRequests(
+ int32_t frameCount, const bool *overrideSequence, const bool *expectedResults);
+
+ bool supportZoomSettingsOverride(const camera_metadata_t* staticMeta);
+ bool isPerFrameControl(const camera_metadata_t* staticMeta);
+
protected:
// In-flight queue for tracking completion of capture requests.
struct InFlightRequest {
diff --git a/common/aidl/Android.bp b/common/aidl/Android.bp
index 43f8c4d..7f6890c 100644
--- a/common/aidl/Android.bp
+++ b/common/aidl/Android.bp
@@ -37,6 +37,7 @@
min_sdk_version: "29",
},
},
+ frozen: true,
versions: [
"1",
"2",
diff --git a/common/fmq/aidl/Android.bp b/common/fmq/aidl/Android.bp
index a85597c..95fcc41 100644
--- a/common/fmq/aidl/Android.bp
+++ b/common/fmq/aidl/Android.bp
@@ -37,5 +37,6 @@
min_sdk_version: "29",
},
},
+ frozen: true,
versions: ["1"],
}
diff --git a/compatibility_matrices/compatibility_matrix.current.xml b/compatibility_matrices/compatibility_matrix.current.xml
index ff481f9..f8954a3 100644
--- a/compatibility_matrices/compatibility_matrix.current.xml
+++ b/compatibility_matrices/compatibility_matrix.current.xml
@@ -109,19 +109,19 @@
<name>android.hardware.automotive.vehicle</name>
<interface>
<name>IVehicle</name>
- <regex-instance>.*</regex-instance>
+ <instance>default</instance>
</interface>
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.automotive.remoteaccess</name>
<interface>
<name>IRemoteAccess</name>
- <regex-instance>.*</regex-instance>
+ <instance>default</instance>
</interface>
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.biometrics.face</name>
- <version>2</version>
+ <version>3</version>
<interface>
<name>IFace</name>
<instance>default</instance>
@@ -129,7 +129,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.biometrics.fingerprint</name>
- <version>2</version>
+ <version>3</version>
<interface>
<name>IFingerprint</name>
<instance>default</instance>
@@ -268,7 +268,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.graphics.allocator</name>
- <version>1</version>
+ <version>1-2</version>
<interface>
<name>IAllocator</name>
<instance>default</instance>
@@ -282,7 +282,7 @@
<instance>default</instance>
</interface>
</hal>
- <hal format="hidl" optional="false">
+ <hal format="hidl" optional="true">
<name>android.hardware.graphics.mapper</name>
<!-- New, non-Go devices should use 4.0, tested in vts_treble_vintf_vendor_test -->
<version>2.1</version>
@@ -392,6 +392,15 @@
</interface>
</hal>
<hal format="aidl" optional="true">
+ <name>android.hardware.media.c2</name>
+ <version>1</version>
+ <interface>
+ <name>IComponentStore</name>
+ <regex-instance>default[0-9]*</regex-instance>
+ <regex-instance>vendor[0-9]*_software</regex-instance>
+ </interface>
+ </hal>
+ <hal format="aidl" optional="true">
<name>android.hardware.memtrack</name>
<version>1</version>
<interface>
@@ -439,7 +448,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.radio.config</name>
- <version>1</version>
+ <version>2</version>
<interface>
<name>IRadioConfig</name>
<instance>default</instance>
@@ -447,7 +456,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.radio.data</name>
- <version>1</version>
+ <version>2</version>
<interface>
<name>IRadioData</name>
<instance>slot1</instance>
@@ -457,7 +466,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.radio.messaging</name>
- <version>1</version>
+ <version>2</version>
<interface>
<name>IRadioMessaging</name>
<instance>slot1</instance>
@@ -487,7 +496,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.radio.sim</name>
- <version>1</version>
+ <version>2</version>
<interface>
<name>IRadioSim</name>
<instance>slot1</instance>
@@ -497,7 +506,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.radio.voice</name>
- <version>1</version>
+ <version>2</version>
<interface>
<name>IRadioVoice</name>
<instance>slot1</instance>
@@ -557,6 +566,15 @@
</interface>
</hal>
<hal format="aidl" optional="true">
+ <name>android.hardware.secure_element</name>
+ <version>1</version>
+ <interface>
+ <name>ISecureElement</name>
+ <regex-instance>eSE[1-9][0-9]*</regex-instance>
+ <regex-instance>SIM[1-9][0-9]*</regex-instance>
+ </interface>
+ </hal>
+ <hal format="aidl" optional="true">
<name>android.hardware.security.secureclock</name>
<version>1</version>
<interface>
@@ -644,6 +662,7 @@
</hal>
<hal format="aidl" optional="true">
<name>android.hardware.usb</name>
+ <version>1-2</version>
<interface>
<name>IUsb</name>
<instance>default</instance>
@@ -658,6 +677,13 @@
</interface>
</hal>
<hal format="aidl" optional="true">
+ <name>android.hardware.usb.gadget</name>
+ <interface>
+ <name>IUsbGadget</name>
+ <instance>default</instance>
+ </interface>
+ </hal>
+ <hal format="aidl" optional="true">
<name>android.hardware.vibrator</name>
<version>1-2</version>
<interface>
diff --git a/current.txt b/current.txt
index afde7b1..146ded6 100644
--- a/current.txt
+++ b/current.txt
@@ -929,4 +929,7 @@
1bac6a7c8136dfb0414fe5639eec115aa2d12927e64a0642a43fb53225f099b2 android.hardware.wifi@1.6::IWifiStaIface
0a800e010e8eb6eecdfdc96f04fd2ae2f417a79a74a7c0eec3a9f539199bccd4 android.hardware.wifi@1.6::types
+# ABI preserving changes to HALs during Android U
+2aa559cda86c358c6429114ef6bc72c1b43281e98f9eb6b4df5e7073c8d05767 android.hardware.automotive.vehicle@2.0::types
+
# There will be no more HIDL HALs. Use AIDL instead.
diff --git a/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/GnssData.aidl b/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/GnssData.aidl
index 31426f0..54e3b21 100644
--- a/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/GnssData.aidl
+++ b/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/GnssData.aidl
@@ -39,6 +39,7 @@
android.hardware.gnss.GnssClock clock;
android.hardware.gnss.ElapsedRealtime elapsedRealtime;
android.hardware.gnss.GnssData.GnssAgc[] gnssAgcs = {};
+ boolean isFullTracking;
@VintfStability
parcelable GnssAgc {
double agcLevelDb;
diff --git a/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/IGnssCallback.aidl b/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/IGnssCallback.aidl
index fd07a6e..0247182 100644
--- a/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/IGnssCallback.aidl
+++ b/gnss/aidl/aidl_api/android.hardware.gnss/current/android/hardware/gnss/IGnssCallback.aidl
@@ -61,6 +61,7 @@
const int CAPABILITY_CORRELATION_VECTOR = 4096;
const int CAPABILITY_SATELLITE_PVT = 8192;
const int CAPABILITY_MEASUREMENT_CORRECTIONS_FOR_DRIVING = 16384;
+ const int CAPABILITY_ACCUMULATED_DELTA_RANGE = 32768;
@Backing(type="int") @VintfStability
enum GnssStatusValue {
NONE = 0,
diff --git a/gnss/aidl/android/hardware/gnss/GnssData.aidl b/gnss/aidl/android/hardware/gnss/GnssData.aidl
index 075a039..492ba31 100644
--- a/gnss/aidl/android/hardware/gnss/GnssData.aidl
+++ b/gnss/aidl/android/hardware/gnss/GnssData.aidl
@@ -99,4 +99,15 @@
* weak to be acquired, the AGC value must still be reported.
*/
GnssAgc[] gnssAgcs = {};
+
+ /**
+ * True indicates that the GNSS chipset switches off duty cycling. In such mode, no clock
+ * discontinuities are expected and, when supported, carrier phase should be continuous in good
+ * signal conditions. All non-blocklisted, healthy constellations, satellites and frequency
+ * bands must be tracked and reported in this mode.
+ *
+ * False indicates that the GNSS chipset optimizes power via duty cycling, constellations and
+ * frequency limits, etc.
+ */
+ boolean isFullTracking;
}
diff --git a/gnss/aidl/android/hardware/gnss/IGnssCallback.aidl b/gnss/aidl/android/hardware/gnss/IGnssCallback.aidl
index 2b2592b..ff9feea 100644
--- a/gnss/aidl/android/hardware/gnss/IGnssCallback.aidl
+++ b/gnss/aidl/android/hardware/gnss/IGnssCallback.aidl
@@ -82,6 +82,9 @@
/** Capability bit mask indicating that GNSS supports measurement corrections for driving */
const int CAPABILITY_MEASUREMENT_CORRECTIONS_FOR_DRIVING = 1 << 14;
+ /** Capability bit mask indicating that GNSS supports accumulated delta range */
+ const int CAPABILITY_ACCUMULATED_DELTA_RANGE = 1 << 15;
+
/**
* Callback to inform framework of the GNSS HAL implementation's capabilities.
*
diff --git a/gnss/aidl/default/Gnss.cpp b/gnss/aidl/default/Gnss.cpp
index 8d3fc39..ec86d2e 100644
--- a/gnss/aidl/default/Gnss.cpp
+++ b/gnss/aidl/default/Gnss.cpp
@@ -60,7 +60,8 @@
IGnssCallback::CAPABILITY_SATELLITE_BLOCKLIST |
IGnssCallback::CAPABILITY_SATELLITE_PVT |
IGnssCallback::CAPABILITY_CORRELATION_VECTOR |
- IGnssCallback::CAPABILITY_ANTENNA_INFO);
+ IGnssCallback::CAPABILITY_ANTENNA_INFO |
+ IGnssCallback::CAPABILITY_ACCUMULATED_DELTA_RANGE);
auto status = sGnssCallback->gnssSetCapabilitiesCb(capabilities);
if (!status.isOk()) {
ALOGE("%s: Unable to invoke callback.gnssSetCapabilitiesCb", __func__);
@@ -76,12 +77,12 @@
}
GnssSignalType signalType1 = {
.constellation = GnssConstellationType::GPS,
- .carrierFrequencyHz = 1.59975e+09,
+ .carrierFrequencyHz = 1.57542e+09,
.codeType = GnssSignalType::CODE_TYPE_C,
};
GnssSignalType signalType2 = {
.constellation = GnssConstellationType::GLONASS,
- .carrierFrequencyHz = 1.59975e+09,
+ .carrierFrequencyHz = 1.5980625e+09,
.codeType = GnssSignalType::CODE_TYPE_C,
};
status = sGnssCallback->gnssSetSignalTypeCapabilitiesCb(
diff --git a/gnss/aidl/default/GnssMeasurementInterface.cpp b/gnss/aidl/default/GnssMeasurementInterface.cpp
index 606de07..90056ce 100644
--- a/gnss/aidl/default/GnssMeasurementInterface.cpp
+++ b/gnss/aidl/default/GnssMeasurementInterface.cpp
@@ -54,7 +54,7 @@
ALOGW("GnssMeasurement callback already set. Resetting the callback...");
stop();
}
- start(enableCorrVecOutputs);
+ start(enableCorrVecOutputs, enableFullTracking);
return ndk::ScopedAStatus::ok();
}
@@ -73,7 +73,7 @@
stop();
}
mIntervalMs = std::max(options.intervalMs, 1000);
- start(options.enableCorrVecOutputs);
+ start(options.enableCorrVecOutputs, options.enableFullTracking);
return ndk::ScopedAStatus::ok();
}
@@ -91,7 +91,8 @@
return ndk::ScopedAStatus::ok();
}
-void GnssMeasurementInterface::start(const bool enableCorrVecOutputs) {
+void GnssMeasurementInterface::start(const bool enableCorrVecOutputs,
+ const bool enableFullTracking) {
ALOGD("start");
if (mIsActive) {
@@ -103,7 +104,7 @@
mIsActive = true;
mThreadBlocker.reset();
- mThread = std::thread([this, enableCorrVecOutputs]() {
+ mThread = std::thread([this, enableCorrVecOutputs, enableFullTracking]() {
int intervalMs;
do {
if (!mIsActive) {
@@ -122,7 +123,8 @@
this->reportMeasurement(*measurement);
}
} else {
- auto measurement = Utils::getMockMeasurement(enableCorrVecOutputs);
+ auto measurement =
+ Utils::getMockMeasurement(enableCorrVecOutputs, enableFullTracking);
this->reportMeasurement(measurement);
}
intervalMs =
diff --git a/gnss/aidl/default/GnssMeasurementInterface.h b/gnss/aidl/default/GnssMeasurementInterface.h
index bb08027..d2737e5 100644
--- a/gnss/aidl/default/GnssMeasurementInterface.h
+++ b/gnss/aidl/default/GnssMeasurementInterface.h
@@ -41,7 +41,7 @@
void setLocationEnabled(const bool enabled);
private:
- void start(const bool enableCorrVecOutputs);
+ void start(const bool enableCorrVecOutputs, const bool enableFullTracking);
void stop();
void reportMeasurement(const GnssData&);
void waitForStoppingThreads();
diff --git a/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp b/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp
index a553954..0d15b2a 100644
--- a/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp
+++ b/gnss/aidl/vts/GnssMeasurementCallbackAidl.cpp
@@ -24,9 +24,11 @@
android::binder::Status GnssMeasurementCallbackAidl::gnssMeasurementCb(const GnssData& gnssData) {
ALOGI("gnssMeasurementCb");
- ALOGV("elapsedRealtime: flags = 0x%X, timestampNs: %" PRId64 ", timeUncertaintyNs=%lf",
+ ALOGV("elapsedRealtime: flags = 0x%X, timestampNs: %" PRId64
+ ", timeUncertaintyNs=%lf"
+ " isFullTracking=%s",
gnssData.elapsedRealtime.flags, gnssData.elapsedRealtime.timestampNs,
- gnssData.elapsedRealtime.timeUncertaintyNs);
+ gnssData.elapsedRealtime.timeUncertaintyNs, gnssData.isFullTracking ? "true" : "false");
gnss_data_cbq_.store(gnssData);
return android::binder::Status::ok();
diff --git a/gnss/aidl/vts/gnss_hal_test.cpp b/gnss/aidl/vts/gnss_hal_test.cpp
index 91cd917..7578585 100644
--- a/gnss/aidl/vts/gnss_hal_test.cpp
+++ b/gnss/aidl/vts/gnss_hal_test.cpp
@@ -477,6 +477,28 @@
}
}
+void GnssHalTest::checkGnssDataFields(const sp<GnssMeasurementCallbackAidl>& callback,
+ const int numMeasurementEvents, const int timeoutSeconds,
+ const bool isFullTracking) {
+ for (int i = 0; i < numMeasurementEvents; i++) {
+ GnssData lastGnssData;
+ ASSERT_TRUE(callback->gnss_data_cbq_.retrieve(lastGnssData, timeoutSeconds));
+ EXPECT_EQ(callback->gnss_data_cbq_.calledCount(), i + 1);
+ ASSERT_TRUE(lastGnssData.measurements.size() > 0);
+
+ // Validity check GnssData fields
+ checkGnssMeasurementClockFields(lastGnssData);
+ if (aidl_gnss_hal_->getInterfaceVersion() >= 3) {
+ if (isFullTracking) {
+ EXPECT_EQ(lastGnssData.isFullTracking, isFullTracking);
+ }
+ }
+ for (const auto& measurement : lastGnssData.measurements) {
+ checkGnssMeasurementFields(measurement, lastGnssData);
+ }
+ }
+}
+
void GnssHalTest::assertMeanAndStdev(int intervalMs, std::vector<int>& deltasMs) {
double mean = computeMean(deltasMs);
double stdev = computeStdev(mean, deltasMs);
diff --git a/gnss/aidl/vts/gnss_hal_test.h b/gnss/aidl/vts/gnss_hal_test.h
index c49c1b9..470294c 100644
--- a/gnss/aidl/vts/gnss_hal_test.h
+++ b/gnss/aidl/vts/gnss_hal_test.h
@@ -101,6 +101,9 @@
void collectMeasurementIntervals(const sp<GnssMeasurementCallbackAidl>& callback,
const int numMeasurementEvents, const int timeoutSeconds,
std::vector<int>& deltaMs);
+ void checkGnssDataFields(const sp<GnssMeasurementCallbackAidl>& callback,
+ const int numMeasurementEvents, const int timeoutSeconds,
+ const bool isFullTracking);
void assertMeanAndStdev(int intervalMillis, std::vector<int>& deltasMillis);
sp<IGnssAidl> aidl_gnss_hal_;
diff --git a/gnss/aidl/vts/gnss_hal_test_cases.cpp b/gnss/aidl/vts/gnss_hal_test_cases.cpp
index 7c0a4df..48027b6 100644
--- a/gnss/aidl/vts/gnss_hal_test_cases.cpp
+++ b/gnss/aidl/vts/gnss_hal_test_cases.cpp
@@ -173,6 +173,7 @@
* GnssCapabilities:
* 1. Verifies that GNSS hardware supports measurement capabilities.
* 2. Verifies that GNSS hardware supports Scheduling capabilities.
+ * 3. Verifies that GNSS hardware supports non-empty signal type capabilities.
*/
TEST_P(GnssHalTest, GnssCapabilites) {
if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
@@ -182,6 +183,10 @@
EXPECT_TRUE(aidl_gnss_cb_->last_capabilities_ & IGnssCallback::CAPABILITY_MEASUREMENTS);
}
EXPECT_TRUE(aidl_gnss_cb_->last_capabilities_ & IGnssCallback::CAPABILITY_SCHEDULING);
+ if (aidl_gnss_hal_->getInterfaceVersion() <= 2) {
+ return;
+ }
+ EXPECT_FALSE(aidl_gnss_cb_->last_signal_type_capabilities.empty());
}
/*
@@ -1466,7 +1471,7 @@
/*
* TestGnssMeasurementIntervals:
* 1. start measurement with interval
- * 2. verify that the received measurement intervals have expected mean and stdev
+ * 2. verify that the received measurement intervals have expected mean and stddev
*/
TEST_P(GnssHalTest, TestGnssMeasurementIntervals_LocationOnAfterMeasurement) {
if (aidl_gnss_hal_->getInterfaceVersion() <= 1) {
@@ -1499,11 +1504,18 @@
}
}
+/*
+ * TestGnssMeasurementSetCallback:
+ * This test ensures setCallback() can be called consecutively without close().
+ * 1. Start measurement with 20s interval and wait for 1 measurement.
+ * 2. Start measurement with 1s interval and wait for 5 measurements.
+ * Verify the measurements were received at 1Hz.
+ */
TEST_P(GnssHalTest, TestGnssMeasurementSetCallback) {
if (aidl_gnss_hal_->getInterfaceVersion() <= 2) {
return;
}
-
+ const int kFirstGnssMeasurementTimeoutSeconds = 10;
sp<IGnssMeasurementInterface> iGnssMeasurement;
auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
ASSERT_TRUE(status.isOk());
@@ -1515,12 +1527,14 @@
// setCallback at 20s interval and wait for 1 measurement
startMeasurementWithInterval(20000, iGnssMeasurement, callback);
- collectMeasurementIntervals(callback, /* numEvents= */ 1, /* timeoutSeconds= */ 10, deltas);
+ collectMeasurementIntervals(callback, /* numEvents= */ 1, kFirstGnssMeasurementTimeoutSeconds,
+ deltas);
// setCallback at 1s interval and wait for 5 measurements
callback->gnss_data_cbq_.reset();
startMeasurementWithInterval(1000, iGnssMeasurement, callback);
- collectMeasurementIntervals(callback, /* numEvents= */ 5, /* timeoutSeconds= */ 10, deltas);
+ collectMeasurementIntervals(callback, /* numEvents= */ 5, kFirstGnssMeasurementTimeoutSeconds,
+ deltas);
// verify the measurements were received at 1Hz
assertMeanAndStdev(1000, deltas);
@@ -1528,3 +1542,97 @@
status = iGnssMeasurement->close();
ASSERT_TRUE(status.isOk());
}
+
+/*
+ * TestGnssMeasurementIsFullTracking
+ * 1. Start measurement with enableFullTracking=true. Verify the received measurements have
+ * isFullTracking=true.
+ * 2. Start measurement with enableFullTracking = false. Verify the received measurements have
+ * isFullTracking=false.
+ * 3. Do step 1 again.
+ */
+TEST_P(GnssHalTest, TestGnssMeasurementIsFullTracking) {
+ // GnssData.isFullTracking is added in the interface version 3
+ if (aidl_gnss_hal_->getInterfaceVersion() <= 2) {
+ return;
+ }
+ const int kFirstGnssMeasurementTimeoutSeconds = 10;
+ const int kNumMeasurementEvents = 5;
+ std::vector<bool> isFullTrackingList({true, false, true});
+
+ sp<IGnssMeasurementInterface> iGnssMeasurement;
+ auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
+ ASSERT_TRUE(status.isOk());
+ ASSERT_TRUE(iGnssMeasurement != nullptr);
+
+ ALOGD("TestGnssMeasurementIsFullTracking");
+ auto callback = sp<GnssMeasurementCallbackAidl>::make();
+ IGnssMeasurementInterface::Options options;
+ options.intervalMs = 1000;
+
+ for (auto isFullTracking : isFullTrackingList) {
+ options.enableFullTracking = isFullTracking;
+
+ callback->gnss_data_cbq_.reset();
+ auto status = iGnssMeasurement->setCallbackWithOptions(callback, options);
+ checkGnssDataFields(callback, kNumMeasurementEvents, kFirstGnssMeasurementTimeoutSeconds,
+ isFullTracking);
+ }
+
+ status = iGnssMeasurement->close();
+ ASSERT_TRUE(status.isOk());
+}
+
+/*
+ * TestAccumulatedDeltaRange:
+ * 1. Gets the GnssMeasurementExtension and verifies that it returns a non-null extension.
+ * 2. Start measurement with 1s interval and wait for up to 15 measurements.
+ * 3. Verify at least one measurement has a valid AccumulatedDeltaRange state.
+ */
+TEST_P(GnssHalTest, TestAccumulatedDeltaRange) {
+ if (aidl_gnss_hal_->getInterfaceVersion() <= 2) {
+ return;
+ }
+ if ((aidl_gnss_cb_->last_capabilities_ & IGnssCallback::CAPABILITY_ACCUMULATED_DELTA_RANGE) ==
+ 0) {
+ return;
+ }
+
+ ALOGD("TestAccumulatedDeltaRange");
+
+ auto callback = sp<GnssMeasurementCallbackAidl>::make();
+ sp<IGnssMeasurementInterface> iGnssMeasurement;
+ auto status = aidl_gnss_hal_->getExtensionGnssMeasurement(&iGnssMeasurement);
+ ASSERT_TRUE(status.isOk());
+ ASSERT_TRUE(iGnssMeasurement != nullptr);
+
+ IGnssMeasurementInterface::Options options;
+ options.intervalMs = 1000;
+ options.enableFullTracking = true;
+ status = iGnssMeasurement->setCallbackWithOptions(callback, options);
+ ASSERT_TRUE(status.isOk());
+
+ bool accumulatedDeltaRangeFound = false;
+ const int kNumMeasurementEvents = 15;
+
+ // setCallback at 1s interval and wait for 15 measurements
+ for (int i = 0; i < kNumMeasurementEvents; i++) {
+ GnssData lastGnssData;
+ ASSERT_TRUE(callback->gnss_data_cbq_.retrieve(lastGnssData, 10));
+ EXPECT_EQ(callback->gnss_data_cbq_.calledCount(), i + 1);
+ ASSERT_TRUE(lastGnssData.measurements.size() > 0);
+
+ // Validity check GnssData fields
+ checkGnssMeasurementClockFields(lastGnssData);
+ for (const auto& measurement : lastGnssData.measurements) {
+ if ((measurement.accumulatedDeltaRangeState & measurement.ADR_STATE_VALID) > 0) {
+ accumulatedDeltaRangeFound = true;
+ break;
+ }
+ }
+ if (accumulatedDeltaRangeFound) break;
+ }
+ ASSERT_TRUE(accumulatedDeltaRangeFound);
+ status = iGnssMeasurement->close();
+ ASSERT_TRUE(status.isOk());
+}
\ No newline at end of file
diff --git a/gnss/common/utils/default/Utils.cpp b/gnss/common/utils/default/Utils.cpp
index 4de49f3..2aed29b 100644
--- a/gnss/common/utils/default/Utils.cpp
+++ b/gnss/common/utils/default/Utils.cpp
@@ -147,7 +147,7 @@
return gnssData;
}
-GnssData Utils::getMockMeasurement(const bool enableCorrVecOutputs) {
+GnssData Utils::getMockMeasurement(const bool enableCorrVecOutputs, const bool enableFullTracking) {
aidl::android::hardware::gnss::GnssSignalType signalType = {
.constellation = GnssConstellationType::GLONASS,
.carrierFrequencyHz = 1.59975e+09,
@@ -170,7 +170,7 @@
.agcLevelDb = 2.3,
.pseudorangeRateMps = -484.13739013671875,
.pseudorangeRateUncertaintyMps = 1.0379999876022339,
- .accumulatedDeltaRangeState = GnssMeasurement::ADR_STATE_UNKNOWN,
+ .accumulatedDeltaRangeState = GnssMeasurement::ADR_STATE_VALID,
.accumulatedDeltaRangeM = 1.52,
.accumulatedDeltaRangeUncertaintyM = 2.43,
.multipathIndicator = aidl::android::hardware::gnss::GnssMultipathIndicator::UNKNOWN,
@@ -258,7 +258,8 @@
GnssData gnssData = {.measurements = {measurement},
.clock = clock,
.elapsedRealtime = timestamp,
- .gnssAgcs = std::vector({gnssAgc1, gnssAgc2})};
+ .gnssAgcs = std::vector({gnssAgc1, gnssAgc2}),
+ .isFullTracking = enableFullTracking};
return gnssData;
}
diff --git a/gnss/common/utils/default/include/Utils.h b/gnss/common/utils/default/include/Utils.h
index ad8f539..9be4a19 100644
--- a/gnss/common/utils/default/include/Utils.h
+++ b/gnss/common/utils/default/include/Utils.h
@@ -32,7 +32,7 @@
struct Utils {
static aidl::android::hardware::gnss::GnssData getMockMeasurement(
- const bool enableCorrVecOutputs);
+ const bool enableCorrVecOutputs, const bool enableFullTracking);
static V2_0::IGnssMeasurementCallback::GnssData getMockMeasurementV2_0();
static V2_1::IGnssMeasurementCallback::GnssData getMockMeasurementV2_1();
diff --git a/graphics/Android.bp b/graphics/Android.bp
index 1e9089f..4898dbe 100644
--- a/graphics/Android.bp
+++ b/graphics/Android.bp
@@ -19,14 +19,14 @@
cc_defaults {
name: "android.hardware.graphics.allocator-ndk_static",
static_libs: [
- "android.hardware.graphics.allocator-V1-ndk",
+ "android.hardware.graphics.allocator-V2-ndk",
],
}
cc_defaults {
name: "android.hardware.graphics.allocator-ndk_shared",
shared_libs: [
- "android.hardware.graphics.allocator-V1-ndk",
+ "android.hardware.graphics.allocator-V2-ndk",
],
}
diff --git a/graphics/allocator/aidl/Android.bp b/graphics/allocator/aidl/Android.bp
index 9bdc7a6..67c7fb5 100644
--- a/graphics/allocator/aidl/Android.bp
+++ b/graphics/allocator/aidl/Android.bp
@@ -14,7 +14,7 @@
enabled: true,
support_system_process: true,
},
- vndk_use_version: "1",
+ vndk_use_version: "2",
srcs: ["android/hardware/graphics/allocator/*.aidl"],
imports: [
"android.hardware.common-V2",
@@ -39,6 +39,7 @@
min_sdk_version: "29",
},
},
+ frozen: false,
versions_with_info: [
{
version: "1",
diff --git a/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/BufferDescriptorInfo.aidl b/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/BufferDescriptorInfo.aidl
new file mode 100644
index 0000000..980e246
--- /dev/null
+++ b/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/BufferDescriptorInfo.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.graphics.allocator;
+@VintfStability
+parcelable BufferDescriptorInfo {
+ byte[128] name;
+ int width;
+ int height;
+ int layerCount;
+ android.hardware.graphics.common.PixelFormat format = android.hardware.graphics.common.PixelFormat.UNSPECIFIED;
+ android.hardware.graphics.common.BufferUsage usage = android.hardware.graphics.common.BufferUsage.CPU_READ_NEVER;
+ long reservedSize;
+}
diff --git a/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/IAllocator.aidl b/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/IAllocator.aidl
index fe0b0a2..48bef16 100644
--- a/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/IAllocator.aidl
+++ b/graphics/allocator/aidl/aidl_api/android.hardware.graphics.allocator/current/android/hardware/graphics/allocator/IAllocator.aidl
@@ -34,5 +34,11 @@
package android.hardware.graphics.allocator;
@VintfStability
interface IAllocator {
+ /**
+ * @deprecated As of android.hardware.graphics.allocator-V2, this is deprecated & replaced with allocate2
+ */
android.hardware.graphics.allocator.AllocationResult allocate(in byte[] descriptor, in int count);
+ android.hardware.graphics.allocator.AllocationResult allocate2(in android.hardware.graphics.allocator.BufferDescriptorInfo descriptor, in int count);
+ boolean isSupported(in android.hardware.graphics.allocator.BufferDescriptorInfo descriptor);
+ String getIMapperLibrarySuffix();
}
diff --git a/graphics/allocator/aidl/android/hardware/graphics/allocator/BufferDescriptorInfo.aidl b/graphics/allocator/aidl/android/hardware/graphics/allocator/BufferDescriptorInfo.aidl
new file mode 100644
index 0000000..ffc50b8
--- /dev/null
+++ b/graphics/allocator/aidl/android/hardware/graphics/allocator/BufferDescriptorInfo.aidl
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.graphics.allocator;
+
+import android.hardware.graphics.common.BufferUsage;
+import android.hardware.graphics.common.PixelFormat;
+
+@VintfStability
+parcelable BufferDescriptorInfo {
+ /**
+ * The name of the buffer in ASCII. Useful for debugging/tracing.
+ */
+ byte[128] name;
+
+ /**
+ * The width specifies how many columns of pixels must be in the
+ * allocated buffer, but does not necessarily represent the offset in
+ * columns between the same column in adjacent rows. The rows may be
+ * padded.
+ */
+ int width;
+
+ /**
+ * The height specifies how many rows of pixels must be in the
+ * allocated buffer.
+ */
+ int height;
+
+ /**
+ * The number of image layers that must be in the allocated buffer.
+ */
+ int layerCount;
+
+ /**
+ * Buffer pixel format. See PixelFormat.aidl in graphics/common for
+ * valid values
+ */
+ PixelFormat format = PixelFormat.UNSPECIFIED;
+
+ /**
+ * Buffer usage mask; valid flags can be found in the definition of
+ * BufferUsage.aidl in graphics/common
+ */
+ BufferUsage usage = BufferUsage.CPU_READ_NEVER;
+
+ /**
+ * The size in bytes of the reserved region associated with the buffer.
+ * See getReservedRegion for more information.
+ */
+ long reservedSize;
+}
diff --git a/graphics/allocator/aidl/android/hardware/graphics/allocator/IAllocator.aidl b/graphics/allocator/aidl/android/hardware/graphics/allocator/IAllocator.aidl
index 92dfd4f..71cebd6 100644
--- a/graphics/allocator/aidl/android/hardware/graphics/allocator/IAllocator.aidl
+++ b/graphics/allocator/aidl/android/hardware/graphics/allocator/IAllocator.aidl
@@ -17,6 +17,7 @@
package android.hardware.graphics.allocator;
import android.hardware.graphics.allocator.AllocationResult;
+import android.hardware.graphics.allocator.BufferDescriptorInfo;
@VintfStability
interface IAllocator {
@@ -31,6 +32,43 @@
* @param count The number of buffers to allocate.
* @return An AllocationResult containing the result of the allocation
* @throws AllocationError on failure
+ * @deprecated As of android.hardware.graphics.allocator-V2, this is deprecated & replaced with
+ * allocate2
*/
AllocationResult allocate(in byte[] descriptor, in int count);
+
+ /**
+ * Allocates buffers with the properties specified by the descriptor.
+ *
+ * Allocations should be optimized for usage bits provided in the
+ * descriptor.
+ *
+ * @param descriptor Properties of the buffers to allocate. This must be
+ * obtained from IMapper::createDescriptor().
+ * @param count The number of buffers to allocate.
+ * @return An AllocationResult containing the result of the allocation
+ * @throws AllocationError on failure
+ */
+ AllocationResult allocate2(in BufferDescriptorInfo descriptor, in int count);
+
+ /**
+ * Test whether the given BufferDescriptorInfo is allocatable.
+ *
+ * If this function returns true, it means that a buffer with the given
+ * description can be allocated on this implementation, unless resource
+ * exhaustion occurs. If this function returns false, it means that the
+ * allocation of the given description will never succeed.
+ *
+ * @param description the description of the buffer
+ * @return supported whether the description is supported
+ */
+ boolean isSupported(in BufferDescriptorInfo descriptor);
+
+ /**
+ * Retrieve the library suffix to load for the IMapper SP-HAL. This library must implement the
+ * IMapper stable-C interface (android/hardware/graphics/mapper/IMapper.h).
+ *
+ * The library that will attempt to be loaded is "/vendor/lib[64]/hw/mapper.<imapper_suffix>.so"
+ */
+ String getIMapperLibrarySuffix();
}
diff --git a/graphics/allocator/aidl/vts/Android.bp b/graphics/allocator/aidl/vts/Android.bp
index a38af14..630ab2a 100644
--- a/graphics/allocator/aidl/vts/Android.bp
+++ b/graphics/allocator/aidl/vts/Android.bp
@@ -55,6 +55,7 @@
],
header_libs: [
"libhwui_internal_headers",
+ "libimapper_stablec",
],
cflags: [
"-Wall",
diff --git a/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp b/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp
index 59af5cf..09f1c15 100644
--- a/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp
+++ b/graphics/allocator/aidl/vts/VtsHalGraphicsAllocatorAidl_TargetTest.cpp
@@ -25,7 +25,10 @@
#include <aidl/android/hardware/graphics/common/PixelFormat.h>
#include <aidlcommonsupport/NativeHandle.h>
#include <android/binder_manager.h>
+#include <android/dlext.h>
#include <android/hardware/graphics/mapper/4.0/IMapper.h>
+#include <android/hardware/graphics/mapper/IMapper.h>
+#include <dlfcn.h>
#include <gtest/gtest.h>
#include <hidl/GtestPrinter.h>
#include <hidl/ServiceManagement.h>
@@ -33,6 +36,7 @@
#include <renderthread/EglManager.h>
#include <utils/GLUtils.h>
#include <vndk/hardware_buffer.h>
+#include <vndksupport/linker.h>
#include <initializer_list>
#include <optional>
#include <string>
@@ -42,60 +46,70 @@
using namespace aidl::android::hardware::graphics::common;
using namespace android;
using namespace android::hardware;
-using namespace android::hardware::graphics::mapper::V4_0;
+using IMapper4 = android::hardware::graphics::mapper::V4_0::IMapper;
+using Error = android::hardware::graphics::mapper::V4_0::Error;
+using android::hardware::graphics::mapper::V4_0::BufferDescriptor;
using android::uirenderer::AutoEglImage;
using android::uirenderer::AutoGLFramebuffer;
using android::uirenderer::AutoSkiaGlTexture;
using android::uirenderer::renderthread::EglManager;
-static constexpr uint64_t pack(const std::initializer_list<BufferUsage>& usages) {
- uint64_t ret = 0;
- for (const auto u : usages) {
- ret |= static_cast<uint64_t>(u);
- }
- return ret;
+typedef AIMapper_Error (*AIMapper_loadIMapperFn)(AIMapper* _Nullable* _Nonnull outImplementation);
+
+inline BufferUsage operator|(BufferUsage lhs, BufferUsage rhs) {
+ using T = std::underlying_type_t<BufferUsage>;
+ return static_cast<BufferUsage>(static_cast<T>(lhs) | static_cast<T>(rhs));
}
-static constexpr hardware::graphics::common::V1_2::PixelFormat cast(PixelFormat format) {
- return static_cast<hardware::graphics::common::V1_2::PixelFormat>(format);
+inline BufferUsage& operator|=(BufferUsage& lhs, BufferUsage rhs) {
+ lhs = lhs | rhs;
+ return lhs;
}
+static IMapper4::BufferDescriptorInfo convert(const BufferDescriptorInfo& info) {
+ return IMapper4::BufferDescriptorInfo{
+ .name{reinterpret_cast<const char*>(info.name.data())},
+ .width = static_cast<uint32_t>(info.width),
+ .height = static_cast<uint32_t>(info.height),
+ .layerCount = static_cast<uint32_t>(info.layerCount),
+ .format = static_cast<hardware::graphics::common::V1_2::PixelFormat>(info.format),
+ .usage = static_cast<uint64_t>(info.usage),
+ .reservedSize = 0,
+ };
+}
+
+class GraphicsTestsBase;
+
class BufferHandle {
- sp<IMapper> mMapper;
+ GraphicsTestsBase& mTestBase;
native_handle_t* mRawHandle;
bool mImported = false;
uint32_t mStride;
- const IMapper::BufferDescriptorInfo mInfo;
+ const BufferDescriptorInfo mInfo;
BufferHandle(const BufferHandle&) = delete;
void operator=(const BufferHandle&) = delete;
public:
- BufferHandle(const sp<IMapper> mapper, native_handle_t* handle, bool imported, uint32_t stride,
- const IMapper::BufferDescriptorInfo& info)
- : mMapper(mapper), mRawHandle(handle), mImported(imported), mStride(stride), mInfo(info) {}
+ BufferHandle(GraphicsTestsBase& testBase, native_handle_t* handle, bool imported,
+ uint32_t stride, const BufferDescriptorInfo& info)
+ : mTestBase(testBase),
+ mRawHandle(handle),
+ mImported(imported),
+ mStride(stride),
+ mInfo(info) {}
- ~BufferHandle() {
- if (mRawHandle == nullptr) return;
-
- if (mImported) {
- Error error = mMapper->freeBuffer(mRawHandle);
- EXPECT_EQ(Error::NONE, error) << "failed to free buffer " << mRawHandle;
- } else {
- native_handle_close(mRawHandle);
- native_handle_delete(mRawHandle);
- }
- }
+ ~BufferHandle();
uint32_t stride() const { return mStride; }
AHardwareBuffer_Desc describe() const {
return {
- .width = mInfo.width,
- .height = mInfo.height,
- .layers = mInfo.layerCount,
+ .width = static_cast<uint32_t>(mInfo.width),
+ .height = static_cast<uint32_t>(mInfo.height),
+ .layers = static_cast<uint32_t>(mInfo.layerCount),
.format = static_cast<uint32_t>(mInfo.format),
- .usage = mInfo.usage,
+ .usage = static_cast<uint64_t>(mInfo.usage),
.stride = stride(),
.rfu0 = 0,
.rfu1 = 0,
@@ -114,25 +128,43 @@
class GraphicsTestsBase {
private:
+ friend class BufferHandle;
+ int32_t mIAllocatorVersion = 1;
std::shared_ptr<IAllocator> mAllocator;
- sp<IMapper> mMapper;
+ sp<IMapper4> mMapper4;
+ AIMapper* mAIMapper = nullptr;
protected:
- void Initialize(std::string allocatorService, std::string mapperService) {
+ void Initialize(std::string allocatorService) {
mAllocator = IAllocator::fromBinder(
ndk::SpAIBinder(AServiceManager_checkService(allocatorService.c_str())));
- mMapper = IMapper::getService(mapperService);
+ ASSERT_TRUE(mAllocator->getInterfaceVersion(&mIAllocatorVersion).isOk());
+ if (mIAllocatorVersion >= 2) {
+ std::string mapperSuffix;
+ auto status = mAllocator->getIMapperLibrarySuffix(&mapperSuffix);
+ ASSERT_TRUE(status.isOk());
+ std::string lib_name = "mapper." + mapperSuffix + ".so";
+ void* so = android_load_sphal_library(lib_name.c_str(), RTLD_LOCAL | RTLD_NOW);
+ ASSERT_NE(nullptr, so) << "Failed to load " << lib_name;
+ auto loadIMapper = (AIMapper_loadIMapperFn)dlsym(so, "AIMapper_loadIMapper");
+ ASSERT_NE(nullptr, loadIMapper) << "AIMapper_locaIMapper missing from " << lib_name;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, loadIMapper(&mAIMapper));
+ ASSERT_NE(mAIMapper, nullptr);
+ } else {
+ // Don't have IMapper 5, fall back to IMapper 4
+ mMapper4 = IMapper4::getService();
+ ASSERT_NE(nullptr, mMapper4.get()) << "failed to get mapper service";
+ ASSERT_FALSE(mMapper4->isRemote()) << "mapper is not in passthrough mode";
+ }
ASSERT_NE(nullptr, mAllocator.get()) << "failed to get allocator service";
- ASSERT_NE(nullptr, mMapper.get()) << "failed to get mapper service";
- ASSERT_FALSE(mMapper->isRemote()) << "mapper is not in passthrough mode";
}
- public:
- BufferDescriptor createDescriptor(const IMapper::BufferDescriptorInfo& descriptorInfo) {
+ private:
+ BufferDescriptor createDescriptor(const BufferDescriptorInfo& descriptorInfo) {
BufferDescriptor descriptor;
- mMapper->createDescriptor(
- descriptorInfo, [&](const auto& tmpError, const auto& tmpDescriptor) {
+ mMapper4->createDescriptor(
+ convert(descriptorInfo), [&](const auto& tmpError, const auto& tmpDescriptor) {
ASSERT_EQ(Error::NONE, tmpError) << "failed to create descriptor";
descriptor = tmpDescriptor;
});
@@ -140,14 +172,22 @@
return descriptor;
}
- std::unique_ptr<BufferHandle> allocate(const IMapper::BufferDescriptorInfo& descriptorInfo) {
- auto descriptor = createDescriptor(descriptorInfo);
- if (::testing::Test::HasFatalFailure()) {
- return nullptr;
- }
-
+ public:
+ std::unique_ptr<BufferHandle> allocate(const BufferDescriptorInfo& descriptorInfo) {
AllocationResult result;
- auto status = mAllocator->allocate(descriptor, 1, &result);
+ ::ndk::ScopedAStatus status;
+ if (mIAllocatorVersion >= 2) {
+ status = mAllocator->allocate2(descriptorInfo, 1, &result);
+ } else {
+ auto descriptor = createDescriptor(descriptorInfo);
+ if (::testing::Test::HasFatalFailure()) {
+ return nullptr;
+ }
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ status = mAllocator->allocate(descriptor, 1, &result);
+#pragma clang diagnostic pop // deprecation
+ }
if (!status.isOk()) {
status_t error = status.getExceptionCode();
if (error == EX_SERVICE_SPECIFIC) {
@@ -158,28 +198,48 @@
}
return nullptr;
} else {
- return std::make_unique<BufferHandle>(mMapper, dupFromAidl(result.buffers[0]), false,
+ return std::make_unique<BufferHandle>(*this, dupFromAidl(result.buffers[0]), false,
result.stride, descriptorInfo);
}
}
- bool isSupported(const IMapper::BufferDescriptorInfo& descriptorInfo) {
+ bool isSupported(const BufferDescriptorInfo& descriptorInfo) {
bool ret = false;
- EXPECT_TRUE(mMapper->isSupported(descriptorInfo,
- [&](auto error, bool supported) {
- ASSERT_EQ(Error::NONE, error);
- ret = supported;
- })
- .isOk());
+ if (mIAllocatorVersion >= 2) {
+ EXPECT_TRUE(mAllocator->isSupported(descriptorInfo, &ret).isOk());
+ } else {
+ EXPECT_TRUE(mMapper4->isSupported(convert(descriptorInfo),
+ [&](auto error, bool supported) {
+ ASSERT_EQ(Error::NONE, error);
+ ret = supported;
+ })
+ .isOk());
+ }
return ret;
}
};
-class GraphicsAllocatorAidlTests
- : public GraphicsTestsBase,
- public ::testing::TestWithParam<std::tuple<std::string, std::string>> {
+BufferHandle::~BufferHandle() {
+ if (mRawHandle == nullptr) return;
+
+ if (mImported) {
+ if (mTestBase.mAIMapper) {
+ AIMapper_Error error = mTestBase.mAIMapper->v5.freeBuffer(mRawHandle);
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, error);
+ } else {
+ Error error = mTestBase.mMapper4->freeBuffer(mRawHandle);
+ EXPECT_EQ(Error::NONE, error) << "failed to free buffer " << mRawHandle;
+ }
+ } else {
+ native_handle_close(mRawHandle);
+ native_handle_delete(mRawHandle);
+ }
+}
+
+class GraphicsAllocatorAidlTests : public GraphicsTestsBase,
+ public ::testing::TestWithParam<std::string> {
public:
- void SetUp() override { Initialize(std::get<0>(GetParam()), std::get<1>(GetParam())); }
+ void SetUp() override { Initialize(GetParam()); }
void TearDown() override {}
};
@@ -191,22 +251,22 @@
class GraphicsFrontBufferTests
: public GraphicsTestsBase,
- public ::testing::TestWithParam<std::tuple<std::string, std::string, FlushMethod>> {
+ public ::testing::TestWithParam<std::tuple<std::string, FlushMethod>> {
private:
EglManager eglManager;
std::function<void(EglManager&)> flush;
public:
void SetUp() override {
- Initialize(std::get<0>(GetParam()), std::get<1>(GetParam()));
- flush = std::get<2>(GetParam()).func;
+ Initialize(std::get<0>(GetParam()));
+ flush = std::get<1>(GetParam()).func;
eglManager.initialize();
}
void TearDown() override { eglManager.destroy(); }
void fillWithGpu(AHardwareBuffer* buffer, float red, float green, float blue, float alpha) {
- const EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID(buffer);
+ EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID(buffer);
AutoEglImage eglImage(eglManager.eglDisplay(), clientBuffer);
AutoSkiaGlTexture glTexture;
AutoGLFramebuffer glFbo;
@@ -235,26 +295,14 @@
}
};
-TEST_P(GraphicsAllocatorAidlTests, CreateDescriptorBasic) {
- ASSERT_NO_FATAL_FAILURE(createDescriptor({
- .name = "CPU_8888",
- .width = 64,
- .height = 64,
- .layerCount = 1,
- .format = cast(PixelFormat::RGBA_8888),
- .usage = pack({BufferUsage::CPU_WRITE_OFTEN, BufferUsage::CPU_READ_OFTEN}),
- .reservedSize = 0,
- }));
-}
-
TEST_P(GraphicsAllocatorAidlTests, CanAllocate) {
auto buffer = allocate({
- .name = "CPU_8888",
+ .name = {"CPU_8888"},
.width = 64,
.height = 64,
.layerCount = 1,
- .format = cast(PixelFormat::RGBA_8888),
- .usage = pack({BufferUsage::CPU_WRITE_OFTEN, BufferUsage::CPU_READ_OFTEN}),
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
.reservedSize = 0,
});
ASSERT_NE(nullptr, buffer.get());
@@ -262,14 +310,14 @@
}
TEST_P(GraphicsFrontBufferTests, FrontBufferGpuToCpu) {
- IMapper::BufferDescriptorInfo info{
- .name = "CPU_8888",
+ BufferDescriptorInfo info{
+ .name = {"CPU_8888"},
.width = 64,
.height = 64,
.layerCount = 1,
- .format = cast(PixelFormat::RGBA_8888),
- .usage = pack({BufferUsage::GPU_RENDER_TARGET, BufferUsage::CPU_READ_OFTEN,
- BufferUsage::FRONT_BUFFER}),
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::GPU_RENDER_TARGET | BufferUsage::CPU_READ_OFTEN |
+ BufferUsage::FRONT_BUFFER,
.reservedSize = 0,
};
const bool supported = isSupported(info);
@@ -304,14 +352,14 @@
}
TEST_P(GraphicsFrontBufferTests, FrontBufferGpuToGpu) {
- IMapper::BufferDescriptorInfo info{
- .name = "CPU_8888",
+ BufferDescriptorInfo info{
+ .name = {"CPU_8888"},
.width = 64,
.height = 64,
.layerCount = 1,
- .format = cast(PixelFormat::RGBA_8888),
- .usage = pack({BufferUsage::GPU_RENDER_TARGET, BufferUsage::GPU_TEXTURE,
- BufferUsage::FRONT_BUFFER}),
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::GPU_RENDER_TARGET | BufferUsage::GPU_TEXTURE |
+ BufferUsage::FRONT_BUFFER,
.reservedSize = 0,
};
const bool supported = isSupported(info);
@@ -344,11 +392,9 @@
}
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GraphicsAllocatorAidlTests);
-INSTANTIATE_TEST_CASE_P(
- PerInstance, GraphicsAllocatorAidlTests,
- testing::Combine(testing::ValuesIn(getAidlHalInstanceNames(IAllocator::descriptor)),
- testing::ValuesIn(getAllHalInstanceNames(IMapper::descriptor))),
- PrintInstanceTupleNameToString<>);
+INSTANTIATE_TEST_CASE_P(PerInstance, GraphicsAllocatorAidlTests,
+ testing::ValuesIn(getAidlHalInstanceNames(IAllocator::descriptor)),
+ PrintInstanceNameToString);
const auto FlushMethodsValues = testing::Values(
FlushMethod{"glFinish", [](EglManager&) { glFinish(); }},
@@ -362,7 +408,7 @@
}},
FlushMethod{"eglClientWaitSync", [](EglManager& eglManager) {
EGLDisplay display = eglManager.eglDisplay();
- EGLSyncKHR fence = eglCreateSyncKHR(display, EGL_SYNC_FENCE_KHR, NULL);
+ EGLSyncKHR fence = eglCreateSyncKHR(display, EGL_SYNC_FENCE_KHR, nullptr);
eglClientWaitSyncKHR(display, fence, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
EGL_FOREVER_KHR);
eglDestroySyncKHR(display, fence);
@@ -371,9 +417,8 @@
INSTANTIATE_TEST_CASE_P(
PerInstance, GraphicsFrontBufferTests,
testing::Combine(testing::ValuesIn(getAidlHalInstanceNames(IAllocator::descriptor)),
- testing::ValuesIn(getAllHalInstanceNames(IMapper::descriptor)),
FlushMethodsValues),
[](auto info) -> std::string {
- std::string name = std::to_string(info.index) + "/" + std::get<2>(info.param).name;
+ std::string name = std::to_string(info.index) + "/" + std::get<1>(info.param).name;
return Sanitize(name);
- });
+ });
\ No newline at end of file
diff --git a/graphics/common/aidl/Android.bp b/graphics/common/aidl/Android.bp
index cb96663..84bc1af 100644
--- a/graphics/common/aidl/Android.bp
+++ b/graphics/common/aidl/Android.bp
@@ -40,6 +40,7 @@
min_sdk_version: "29",
},
},
+ frozen: false,
versions_with_info: [
{
version: "1",
diff --git a/graphics/common/aidl/android/hardware/graphics/common/StandardMetadataType.aidl b/graphics/common/aidl/android/hardware/graphics/common/StandardMetadataType.aidl
index 8126143..4bca795 100644
--- a/graphics/common/aidl/android/hardware/graphics/common/StandardMetadataType.aidl
+++ b/graphics/common/aidl/android/hardware/graphics/common/StandardMetadataType.aidl
@@ -22,9 +22,9 @@
* This is an enum that defines the common types of gralloc 4 buffer metadata. The comments for
* each enum include a description of the metadata that is associated with the type.
*
- * IMapper@4.x must support getting the following standard buffer metadata types, with the exception
- * of SMPTE 2094-10 metadata. IMapper@4.x may support setting these standard buffer metadata types
- * as well.
+ * IMapper@4.x & later must support getting the following standard buffer metadata types, with the
+ * exception of SMPTE 2094-10 and SMPTE 2094-40 metadata. IMapper@4.x & later may support setting
+ * these standard buffer metadata types as well.
*
* When encoding these StandardMetadataTypes into a byte stream, the associated MetadataType is
* is first encoded followed by the StandardMetadataType value. The MetadataType is encoded by
diff --git a/graphics/composer/aidl/Android.bp b/graphics/composer/aidl/Android.bp
index 0ba320d..1e08221 100644
--- a/graphics/composer/aidl/Android.bp
+++ b/graphics/composer/aidl/Android.bp
@@ -31,6 +31,8 @@
enabled: true,
support_system_process: true,
},
+ frozen: false,
+ vndk_use_version: "1",
srcs: [
"android/hardware/graphics/composer3/*.aidl",
],
diff --git a/graphics/mapper/stable-c/Android.bp b/graphics/mapper/stable-c/Android.bp
new file mode 100644
index 0000000..c03f67e
--- /dev/null
+++ b/graphics/mapper/stable-c/Android.bp
@@ -0,0 +1,104 @@
+/**
+ * Copyright (c) 2022, The Android Open Source Project
+ *
+ * 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.
+ */
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "hardware_interfaces_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_library_headers {
+ name: "libimapper_stablec",
+ export_include_dirs: ["include"],
+ vendor_available: true,
+ header_libs: [
+ "libarect_headers",
+ ],
+ export_header_lib_headers: [
+ "libarect_headers",
+ ],
+}
+
+cc_library_headers {
+ name: "libimapper_providerutils",
+ vendor_available: true,
+ export_include_dirs: ["implutils/include"],
+ header_libs: [
+ "libbase_headers",
+ "libimapper_stablec",
+ ],
+ export_header_lib_headers: [
+ "libbase_headers",
+ "libimapper_stablec",
+ ],
+}
+
+cc_test {
+ name: "libimapper_providerutils_tests",
+ defaults: [
+ "android.hardware.graphics.allocator-ndk_shared",
+ "android.hardware.graphics.common-ndk_shared",
+ ],
+ header_libs: [
+ "libimapper_providerutils",
+ ],
+ srcs: [
+ "implutils/impltests.cpp",
+ ],
+ visibility: [":__subpackages__"],
+ cpp_std: "experimental",
+}
+
+cc_test {
+ name: "VtsHalGraphicsMapperStableC_TargetTest",
+ cpp_std: "experimental",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ "android.hardware.graphics.allocator-ndk_shared",
+ "android.hardware.graphics.common-ndk_shared",
+ ],
+ srcs: [
+ "vts/VtsHalGraphicsMapperStableC_TargetTest.cpp",
+ ],
+
+ shared_libs: [
+ "libbinder_ndk",
+ "libbase",
+ "libsync",
+ "libvndksupport",
+ ],
+ static_libs: [
+ "libaidlcommonsupport",
+ "libgralloctypes",
+ "libgtest",
+ ],
+ header_libs: [
+ "libimapper_stablec",
+ "libimapper_providerutils",
+ ],
+ cflags: [
+ "-Wall",
+ "-Werror",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
diff --git a/graphics/mapper/stable-c/implutils/impltests.cpp b/graphics/mapper/stable-c/implutils/impltests.cpp
new file mode 100644
index 0000000..9c5d70b
--- /dev/null
+++ b/graphics/mapper/stable-c/implutils/impltests.cpp
@@ -0,0 +1,314 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <gtest/gtest.h>
+
+#include <android/hardware/graphics/mapper/utils/IMapperMetadataTypes.h>
+#include <android/hardware/graphics/mapper/utils/IMapperProvider.h>
+#include <vector>
+
+using namespace ::android::hardware::graphics::mapper;
+using namespace ::aidl::android::hardware::graphics::common;
+
+// These tests are primarily interested in hitting all the different *types* that can be
+// serialized/deserialized than in exhaustively testing all the StandardMetadataTypes.
+// Exhaustive testing of the actual metadata types is relegated for IMapper's VTS suite
+// where meaning & correctness of values are more narrowly defined (eg, read-only values)
+
+TEST(Metadata, setGetBufferId) {
+ using BufferId = StandardMetadata<StandardMetadataType::BUFFER_ID>::value;
+
+ std::vector<char> buffer;
+ buffer.resize(12, 0);
+ *reinterpret_cast<int64_t*>(buffer.data()) = 42;
+
+ EXPECT_EQ(8, BufferId::encode(18, buffer.data(), 0));
+ EXPECT_EQ(42, *reinterpret_cast<int64_t*>(buffer.data()));
+ EXPECT_EQ(8, BufferId::encode(18, buffer.data(), buffer.size()));
+ EXPECT_EQ(18, *reinterpret_cast<int64_t*>(buffer.data()));
+ EXPECT_FALSE(BufferId::decode(buffer.data(), 0));
+ auto read = BufferId::decode(buffer.data(), buffer.size());
+ EXPECT_TRUE(read.has_value());
+ EXPECT_EQ(18, read.value_or(0));
+}
+
+TEST(Metadata, setGetDataspace) {
+ using DataspaceValue = StandardMetadata<StandardMetadataType::DATASPACE>::value;
+ using intType = std::underlying_type_t<Dataspace>;
+ std::vector<char> buffer;
+ buffer.resize(12, 0);
+
+ EXPECT_EQ(4, DataspaceValue::encode(Dataspace::BT2020, buffer.data(), 0));
+ EXPECT_EQ(0, *reinterpret_cast<intType*>(buffer.data()));
+ EXPECT_EQ(4, DataspaceValue::encode(Dataspace::BT2020, buffer.data(), buffer.size()));
+ EXPECT_EQ(static_cast<intType>(Dataspace::BT2020), *reinterpret_cast<intType*>(buffer.data()));
+ EXPECT_FALSE(DataspaceValue::decode(buffer.data(), 0));
+ auto read = DataspaceValue::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ EXPECT_EQ(Dataspace::BT2020, *read);
+}
+
+TEST(Metadata, setGetValidName) {
+ using NameValue = StandardMetadata<StandardMetadataType::NAME>::value;
+
+ std::vector<char> buffer;
+ buffer.resize(100, 'a');
+ buffer[buffer.size() - 1] = '\0';
+
+ // len("Hello") + sizeof(int64)
+ constexpr int expectedSize = 5 + sizeof(int64_t);
+ EXPECT_EQ(expectedSize, NameValue::encode("Hello", buffer.data(), buffer.size()));
+ EXPECT_EQ(5, *reinterpret_cast<int64_t*>(buffer.data()));
+ // Verify didn't write past the end of the desired size
+ EXPECT_EQ('a', buffer[expectedSize]);
+
+ auto readValue = NameValue::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(readValue.has_value());
+ EXPECT_EQ(5, readValue->length());
+ EXPECT_EQ("Hello", *readValue);
+}
+
+TEST(Metadata, setGetInvalidName) {
+ using NameValue = StandardMetadata<StandardMetadataType::NAME>::value;
+
+ std::vector<char> buffer;
+ buffer.resize(12, 'a');
+ buffer[buffer.size() - 1] = '\0';
+
+ // len("This is a long string") + sizeof(int64)
+ constexpr int expectedSize = 21 + sizeof(int64_t);
+ EXPECT_EQ(expectedSize,
+ NameValue::encode("This is a long string", buffer.data(), buffer.size()));
+ EXPECT_EQ(21, *reinterpret_cast<int64_t*>(buffer.data()));
+ // Verify didn't write the too-long string
+ EXPECT_EQ('a', buffer[9]);
+ EXPECT_EQ('\0', buffer[buffer.size() - 1]);
+
+ auto readValue = NameValue::decode(buffer.data(), buffer.size());
+ EXPECT_FALSE(readValue.has_value());
+ readValue = NameValue::decode(buffer.data(), 0);
+ ASSERT_FALSE(readValue.has_value());
+}
+
+TEST(Metadata, wouldOverflowName) {
+ using NameValue = StandardMetadata<StandardMetadataType::NAME>::value;
+ std::vector<char> buffer(100, 0);
+
+ // int_max + sizeof(int64) overflows int32
+ std::string_view bad_string{"badbeef", std::numeric_limits<int32_t>::max()};
+ EXPECT_EQ(-AIMAPPER_ERROR_BAD_VALUE,
+ NameValue::encode(bad_string, buffer.data(), buffer.size()));
+
+ // check barely overflows
+ bad_string = std::string_view{"badbeef", std::numeric_limits<int32_t>::max() - 7};
+ EXPECT_EQ(-AIMAPPER_ERROR_BAD_VALUE,
+ NameValue::encode(bad_string, buffer.data(), buffer.size()));
+}
+
+TEST(Metadata, setGetCompression) {
+ using CompressionValue = StandardMetadata<StandardMetadataType::COMPRESSION>::value;
+ ExtendableType myCompression{"bestest_compression_ever", 42};
+ std::vector<char> buffer(100, '\0');
+ const int expectedSize = myCompression.name.length() + sizeof(int64_t) + sizeof(int64_t);
+ EXPECT_EQ(expectedSize, CompressionValue::encode(myCompression, buffer.data(), 0));
+ EXPECT_EQ(0, buffer[0]);
+ EXPECT_EQ(expectedSize, CompressionValue::encode(myCompression, buffer.data(), buffer.size()));
+ EXPECT_EQ(myCompression.name.length(), *reinterpret_cast<int64_t*>(buffer.data()));
+ EXPECT_FALSE(CompressionValue::decode(buffer.data(), 0).has_value());
+ auto read = CompressionValue::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ EXPECT_EQ(myCompression, read.value());
+}
+
+TEST(Metadata, setGetPlaneLayout) {
+ using PlaneLayoutValue = StandardMetadata<StandardMetadataType::PLANE_LAYOUTS>::value;
+ PlaneLayout myPlaneLayout;
+ myPlaneLayout.offsetInBytes = 10;
+ myPlaneLayout.sampleIncrementInBits = 11;
+ myPlaneLayout.strideInBytes = 12;
+ myPlaneLayout.widthInSamples = 13;
+ myPlaneLayout.heightInSamples = 14;
+ myPlaneLayout.totalSizeInBytes = 15;
+ myPlaneLayout.horizontalSubsampling = 16;
+ myPlaneLayout.verticalSubsampling = 17;
+
+ myPlaneLayout.components.resize(3);
+ for (int i = 0; i < myPlaneLayout.components.size(); i++) {
+ auto& it = myPlaneLayout.components[i];
+ it.type = ExtendableType{"Plane ID", 40 + i};
+ it.offsetInBits = 20 + i;
+ it.sizeInBits = 30 + i;
+ }
+
+ std::vector<PlaneLayout> layouts{myPlaneLayout, PlaneLayout{}};
+
+ std::vector<char> buffer(5000, '\0');
+ constexpr int componentSize = 8 + (4 * sizeof(int64_t));
+ constexpr int firstLayoutSize = (8 + 1) * sizeof(int64_t) + (3 * componentSize);
+ constexpr int secondLayoutSize = (8 + 1) * sizeof(int64_t);
+ constexpr int expectedSize = firstLayoutSize + secondLayoutSize + sizeof(int64_t);
+ EXPECT_EQ(expectedSize, PlaneLayoutValue::encode(layouts, buffer.data(), 0));
+ EXPECT_EQ(0, buffer[0]);
+ EXPECT_EQ(expectedSize, PlaneLayoutValue::encode(layouts, buffer.data(), buffer.size()));
+ EXPECT_EQ(3, reinterpret_cast<int64_t*>(buffer.data())[1]);
+ EXPECT_EQ(8, reinterpret_cast<int64_t*>(buffer.data())[2]);
+ EXPECT_EQ(40, reinterpret_cast<int64_t*>(buffer.data())[4]);
+ EXPECT_EQ(31, reinterpret_cast<int64_t*>(buffer.data())[11]);
+ EXPECT_EQ(22, reinterpret_cast<int64_t*>(buffer.data())[15]);
+ EXPECT_EQ(10, reinterpret_cast<int64_t*>(buffer.data())[17]);
+ EXPECT_EQ(11, reinterpret_cast<int64_t*>(buffer.data())[18]);
+ EXPECT_FALSE(PlaneLayoutValue::decode(buffer.data(), 0).has_value());
+ auto read = PlaneLayoutValue::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ EXPECT_EQ(layouts, *read);
+}
+
+TEST(Metadata, setGetRects) {
+ using RectsValue = StandardMetadata<StandardMetadataType::CROP>::value;
+ std::vector<uint8_t> buffer(500, 0);
+ std::vector<Rect> cropRects{2};
+ cropRects[0] = Rect{10, 11, 12, 13};
+ cropRects[1] = Rect{20, 21, 22, 23};
+
+ constexpr int expectedSize = sizeof(int64_t) + (8 * sizeof(int32_t));
+ EXPECT_EQ(expectedSize, RectsValue::encode(cropRects, buffer.data(), buffer.size()));
+ EXPECT_EQ(2, reinterpret_cast<int64_t*>(buffer.data())[0]);
+ EXPECT_EQ(10, reinterpret_cast<int32_t*>(buffer.data())[2]);
+ auto read = RectsValue::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ EXPECT_EQ(cropRects.size(), read->size());
+ EXPECT_EQ(cropRects, *read);
+}
+
+TEST(Metadata, setGetSmpte2086) {
+ using Smpte2086Value = StandardMetadata<StandardMetadataType::SMPTE2086>::value;
+ Smpte2086 source;
+ source.minLuminance = 12.335f;
+ source.maxLuminance = 452.889f;
+ source.whitePoint = XyColor{-6.f, -9.f};
+ source.primaryRed = XyColor{.1f, .2f};
+ source.primaryGreen = XyColor{.3f, .4f};
+ source.primaryBlue = XyColor{.5f, .6f};
+
+ constexpr int expectedSize = 10 * sizeof(float);
+ std::vector<uint8_t> buffer(500, 0);
+ EXPECT_EQ(expectedSize, Smpte2086Value::encode(source, buffer.data(), buffer.size()));
+ auto read = Smpte2086Value::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ ASSERT_TRUE(read->has_value());
+ EXPECT_EQ(source, read->value());
+
+ // A valid encoding of a nullopt
+ read = Smpte2086Value::decode(nullptr, 0);
+ ASSERT_TRUE(read.has_value());
+ EXPECT_FALSE(read->has_value());
+}
+
+TEST(Metadata, setGetCta861_3) {
+ using Cta861_3Value = StandardMetadata<StandardMetadataType::CTA861_3>::value;
+ Cta861_3 source;
+ source.maxFrameAverageLightLevel = 244.55f;
+ source.maxContentLightLevel = 202.202f;
+
+ constexpr int expectedSize = 2 * sizeof(float);
+ std::vector<uint8_t> buffer(500, 0);
+ EXPECT_EQ(expectedSize, Cta861_3Value::encode(source, buffer.data(), buffer.size()));
+ auto read = Cta861_3Value::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ ASSERT_TRUE(read->has_value());
+ EXPECT_EQ(source, read->value());
+
+ // A valid encoding of a nullopt
+ read = Cta861_3Value::decode(nullptr, 0);
+ ASSERT_TRUE(read.has_value());
+ EXPECT_FALSE(read->has_value());
+}
+
+TEST(Metadata, setGetSmpte2094_10) {
+ using SMPTE2094_10Value = StandardMetadata<StandardMetadataType::SMPTE2094_10>::value;
+
+ std::vector<uint8_t> buffer(500, 0);
+ EXPECT_EQ(0, SMPTE2094_10Value::encode(std::nullopt, buffer.data(), buffer.size()));
+ auto read = SMPTE2094_10Value::decode(buffer.data(), 0);
+ ASSERT_TRUE(read.has_value());
+ EXPECT_FALSE(read->has_value());
+
+ const std::vector<uint8_t> emptyBuffer;
+ EXPECT_EQ(sizeof(int64_t),
+ SMPTE2094_10Value::encode(emptyBuffer, buffer.data(), buffer.size()));
+ read = SMPTE2094_10Value::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ ASSERT_TRUE(read->has_value());
+ EXPECT_EQ(0, read->value().size());
+
+ const std::vector<uint8_t> simpleBuffer{0, 1, 2, 3, 4, 5};
+ EXPECT_EQ(sizeof(int64_t) + 6,
+ SMPTE2094_10Value::encode(simpleBuffer, buffer.data(), buffer.size()));
+ read = SMPTE2094_10Value::decode(buffer.data(), buffer.size());
+ ASSERT_TRUE(read.has_value());
+ ASSERT_TRUE(read->has_value());
+ EXPECT_EQ(6, read->value().size());
+ EXPECT_EQ(simpleBuffer, read->value());
+}
+
+TEST(MetadataProvider, bufferId) {
+ using BufferId = StandardMetadata<StandardMetadataType::BUFFER_ID>::value;
+ std::vector<uint8_t> buffer(500, 0);
+ int result = provideStandardMetadata(StandardMetadataType::BUFFER_ID, buffer.data(),
+ buffer.size(), []<StandardMetadataType T>(auto&& provide) {
+ if constexpr (T == StandardMetadataType::BUFFER_ID) {
+ return provide(42);
+ }
+ return 0;
+ });
+
+ EXPECT_EQ(8, result);
+ auto read = BufferId::decode(buffer.data(), buffer.size());
+ EXPECT_EQ(42, read.value_or(0));
+}
+
+TEST(MetadataProvider, allJumpsWork) {
+ const auto& values = ndk::internal::enum_values<StandardMetadataType>;
+ auto get = [](StandardMetadataType type) -> int {
+ return provideStandardMetadata(type, nullptr, 0, []<StandardMetadataType T>(auto&&) {
+ return static_cast<int>(T) + 100;
+ });
+ };
+
+ for (auto& type : values) {
+ const int expected = type == StandardMetadataType::INVALID ? -AIMAPPER_ERROR_UNSUPPORTED
+ : static_cast<int>(type) + 100;
+ EXPECT_EQ(expected, get(type));
+ }
+}
+
+TEST(MetadataProvider, invalid) {
+ int result = provideStandardMetadata(StandardMetadataType::INVALID, nullptr, 0,
+ []<StandardMetadataType T>(auto&&) { return 10; });
+
+ EXPECT_EQ(-AIMAPPER_ERROR_UNSUPPORTED, result);
+}
+
+TEST(MetadataProvider, outOfBounds) {
+ int result = provideStandardMetadata(static_cast<StandardMetadataType>(-1), nullptr, 0,
+ []<StandardMetadataType T>(auto&&) { return 10; });
+ EXPECT_EQ(-AIMAPPER_ERROR_UNSUPPORTED, result) << "-1 should have resulted in UNSUPPORTED";
+
+ result = provideStandardMetadata(static_cast<StandardMetadataType>(100), nullptr, 0,
+ []<StandardMetadataType T>(auto&&) { return 10; });
+ EXPECT_EQ(-AIMAPPER_ERROR_UNSUPPORTED, result)
+ << "100 (out of range) should have resulted in UNSUPPORTED";
+}
diff --git a/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperMetadataTypes.h b/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperMetadataTypes.h
new file mode 100644
index 0000000..7861af8
--- /dev/null
+++ b/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperMetadataTypes.h
@@ -0,0 +1,576 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/graphics/common/BlendMode.h>
+#include <aidl/android/hardware/graphics/common/BufferUsage.h>
+#include <aidl/android/hardware/graphics/common/Cta861_3.h>
+#include <aidl/android/hardware/graphics/common/Dataspace.h>
+#include <aidl/android/hardware/graphics/common/ExtendableType.h>
+#include <aidl/android/hardware/graphics/common/PixelFormat.h>
+#include <aidl/android/hardware/graphics/common/PlaneLayout.h>
+#include <aidl/android/hardware/graphics/common/PlaneLayoutComponent.h>
+#include <aidl/android/hardware/graphics/common/Rect.h>
+#include <aidl/android/hardware/graphics/common/Smpte2086.h>
+#include <aidl/android/hardware/graphics/common/StandardMetadataType.h>
+#include <aidl/android/hardware/graphics/common/XyColor.h>
+#include <android/hardware/graphics/mapper/IMapper.h>
+
+#include <cinttypes>
+#include <string_view>
+#include <type_traits>
+#include <vector>
+
+namespace android::hardware::graphics::mapper {
+
+using ::aidl::android::hardware::graphics::common::BlendMode;
+using ::aidl::android::hardware::graphics::common::BufferUsage;
+using ::aidl::android::hardware::graphics::common::Cta861_3;
+using ::aidl::android::hardware::graphics::common::Dataspace;
+using ::aidl::android::hardware::graphics::common::ExtendableType;
+using ::aidl::android::hardware::graphics::common::PixelFormat;
+using ::aidl::android::hardware::graphics::common::PlaneLayout;
+using ::aidl::android::hardware::graphics::common::PlaneLayoutComponent;
+using ::aidl::android::hardware::graphics::common::Rect;
+using ::aidl::android::hardware::graphics::common::Smpte2086;
+using ::aidl::android::hardware::graphics::common::StandardMetadataType;
+using ::aidl::android::hardware::graphics::common::XyColor;
+
+class MetadataWriter {
+ private:
+ uint8_t* _Nonnull mDest;
+ size_t mSizeRemaining = 0;
+ int32_t mDesiredSize = 0;
+
+ void* _Nullable reserve(size_t sizeToWrite) {
+ if (mDesiredSize < 0) {
+ // Error state
+ return nullptr;
+ }
+ if (__builtin_add_overflow(mDesiredSize, sizeToWrite, &mDesiredSize)) {
+ // Overflowed, abort writing any further data
+ mDesiredSize = -AIMAPPER_ERROR_BAD_VALUE;
+ mSizeRemaining = 0;
+ return nullptr;
+ }
+ if (sizeToWrite > mSizeRemaining) {
+ mSizeRemaining = 0;
+ return nullptr;
+ } else {
+ mSizeRemaining -= sizeToWrite;
+ uint8_t* whereToWrite = mDest;
+ mDest += sizeToWrite;
+ return whereToWrite;
+ }
+ }
+
+ public:
+ explicit MetadataWriter(void* _Nullable destBuffer, size_t destBufferSize)
+ : mDest(reinterpret_cast<uint8_t*>(destBuffer)), mSizeRemaining(destBufferSize) {}
+
+ int32_t desiredSize() const { return mDesiredSize; }
+
+ template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
+ MetadataWriter& write(T value) {
+ auto sizeToWrite = sizeof(T);
+ if (void* dest = reserve(sizeToWrite)) {
+ memcpy(dest, &value, sizeToWrite);
+ }
+ return *this;
+ }
+
+ MetadataWriter& write(float value) {
+ auto sizeToWrite = sizeof(float);
+ if (void* dest = reserve(sizeToWrite)) {
+ memcpy(dest, &value, sizeToWrite);
+ }
+ return *this;
+ }
+
+ MetadataWriter& write(const std::string_view& value) {
+ auto sizeToWrite = value.length();
+ write<int64_t>(sizeToWrite);
+ if (void* dest = reserve(sizeToWrite)) {
+ memcpy(dest, value.data(), sizeToWrite);
+ }
+ return *this;
+ }
+
+ MetadataWriter& write(const std::vector<uint8_t>& value) {
+ auto sizeToWrite = value.size();
+ write<int64_t>(sizeToWrite);
+ if (void* dest = reserve(sizeToWrite)) {
+ memcpy(dest, value.data(), sizeToWrite);
+ }
+ return *this;
+ }
+
+ MetadataWriter& write(const ExtendableType& value) {
+ return write(value.name).write(value.value);
+ }
+
+ MetadataWriter& write(const XyColor& value) { return write(value.x).write(value.y); }
+};
+
+class MetadataReader {
+ private:
+ const uint8_t* _Nonnull mSrc;
+ size_t mSizeRemaining = 0;
+ bool mOk = true;
+
+ const void* _Nullable advance(size_t size) {
+ if (mOk && mSizeRemaining >= size) {
+ const void* buf = mSrc;
+ mSrc += size;
+ mSizeRemaining -= size;
+ return buf;
+ }
+ mOk = false;
+ return nullptr;
+ }
+
+ public:
+ explicit MetadataReader(const void* _Nonnull metadata, size_t metadataSize)
+ : mSrc(reinterpret_cast<const uint8_t*>(metadata)), mSizeRemaining(metadataSize) {}
+
+ [[nodiscard]] size_t remaining() const { return mSizeRemaining; }
+ [[nodiscard]] bool ok() const { return mOk; }
+
+ template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
+ MetadataReader& read(T& dest) {
+ if (const void* src = advance(sizeof(T))) {
+ memcpy(&dest, src, sizeof(T));
+ }
+ return *this;
+ }
+
+ MetadataReader& read(float& dest) {
+ if (const void* src = advance(sizeof(float))) {
+ memcpy(&dest, src, sizeof(float));
+ }
+ return *this;
+ }
+
+ MetadataReader& read(std::string& dest) {
+ dest = readString();
+ return *this;
+ }
+
+ MetadataReader& read(ExtendableType& dest) {
+ dest.name = readString();
+ read(dest.value);
+ return *this;
+ }
+
+ MetadataReader& read(XyColor& dest) {
+ read(dest.x);
+ read(dest.y);
+ return *this;
+ }
+
+ template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
+ [[nodiscard]] std::optional<T> readInt() {
+ auto sizeToRead = sizeof(T);
+ if (const void* src = advance(sizeof(T))) {
+ T ret;
+ memcpy(&ret, src, sizeToRead);
+ return ret;
+ }
+ return std::nullopt;
+ }
+
+ [[nodiscard]] std::string_view readString() {
+ auto lengthOpt = readInt<int64_t>();
+ if (!lengthOpt) {
+ return std::string_view{};
+ }
+ size_t length = lengthOpt.value();
+ if (const void* src = advance(length)) {
+ return std::string_view{reinterpret_cast<const char*>(src), length};
+ }
+ return std::string_view{};
+ }
+
+ [[nodiscard]] std::optional<ExtendableType> readExtendable() {
+ ExtendableType ret;
+ ret.name = readString();
+ auto value = readInt<int64_t>();
+ if (value) {
+ ret.value = value.value();
+ return ret;
+ } else {
+ return std::nullopt;
+ }
+ }
+
+ [[nodiscard]] std::vector<uint8_t> readBuffer() {
+ std::vector<uint8_t> ret;
+ size_t length = readInt<int64_t>().value_or(0);
+ if (const void* src = advance(length)) {
+ ret.resize(length);
+ memcpy(ret.data(), src, length);
+ }
+ return ret;
+ }
+};
+
+template <typename T, class Enable = void>
+struct MetadataValue {};
+
+template <typename T>
+struct MetadataValue<T, std::enable_if_t<std::is_integral_v<T>>> {
+ [[nodiscard]] static int32_t encode(T value, void* _Nullable destBuffer,
+ size_t destBufferSize) {
+ return MetadataWriter{destBuffer, destBufferSize}.write(value).desiredSize();
+ }
+
+ [[nodiscard]] static std::optional<T> decode(const void* _Nonnull metadata,
+ size_t metadataSize) {
+ return MetadataReader{metadata, metadataSize}.readInt<T>();
+ }
+};
+
+template <typename T>
+struct MetadataValue<T, std::enable_if_t<std::is_enum_v<T>>> {
+ [[nodiscard]] static int32_t encode(T value, void* _Nullable destBuffer,
+ size_t destBufferSize) {
+ return MetadataWriter{destBuffer, destBufferSize}
+ .write(static_cast<std::underlying_type_t<T>>(value))
+ .desiredSize();
+ }
+
+ [[nodiscard]] static std::optional<T> decode(const void* _Nonnull metadata,
+ size_t metadataSize) {
+ std::underlying_type_t<T> temp;
+ return MetadataReader{metadata, metadataSize}.read(temp).ok()
+ ? std::optional<T>(static_cast<T>(temp))
+ : std::nullopt;
+ }
+};
+
+template <>
+struct MetadataValue<std::string> {
+ [[nodiscard]] static int32_t encode(const std::string_view& value, void* _Nullable destBuffer,
+ size_t destBufferSize) {
+ return MetadataWriter{destBuffer, destBufferSize}.write(value).desiredSize();
+ }
+
+ [[nodiscard]] static std::optional<std::string> decode(const void* _Nonnull metadata,
+ size_t metadataSize) {
+ auto reader = MetadataReader{metadata, metadataSize};
+ auto result = reader.readString();
+ return reader.ok() ? std::optional<std::string>{result} : std::nullopt;
+ }
+};
+
+template <>
+struct MetadataValue<ExtendableType> {
+ static_assert(sizeof(int64_t) == sizeof(ExtendableType::value));
+
+ [[nodiscard]] static int32_t encode(const ExtendableType& value, void* _Nullable destBuffer,
+ size_t destBufferSize) {
+ return MetadataWriter{destBuffer, destBufferSize}.write(value).desiredSize();
+ }
+
+ [[nodiscard]] static std::optional<ExtendableType> decode(const void* _Nonnull metadata,
+ size_t metadataSize) {
+ return MetadataReader{metadata, metadataSize}.readExtendable();
+ }
+};
+
+template <>
+struct MetadataValue<std::vector<PlaneLayout>> {
+ [[nodiscard]] static int32_t encode(const std::vector<PlaneLayout>& values,
+ void* _Nullable destBuffer, size_t destBufferSize) {
+ MetadataWriter writer{destBuffer, destBufferSize};
+ writer.write<int64_t>(values.size());
+ for (const auto& value : values) {
+ writer.write<int64_t>(value.components.size());
+ for (const auto& component : value.components) {
+ writer.write(component.type)
+ .write<int64_t>(component.offsetInBits)
+ .write<int64_t>(component.sizeInBits);
+ }
+ writer.write<int64_t>(value.offsetInBytes)
+ .write<int64_t>(value.sampleIncrementInBits)
+ .write<int64_t>(value.strideInBytes)
+ .write<int64_t>(value.widthInSamples)
+ .write<int64_t>(value.heightInSamples)
+ .write<int64_t>(value.totalSizeInBytes)
+ .write<int64_t>(value.horizontalSubsampling)
+ .write<int64_t>(value.verticalSubsampling);
+ }
+ return writer.desiredSize();
+ }
+
+ using DecodeResult = std::optional<std::vector<PlaneLayout>>;
+ [[nodiscard]] static DecodeResult decode(const void* _Nonnull metadata, size_t metadataSize) {
+ std::vector<PlaneLayout> values;
+ MetadataReader reader{metadata, metadataSize};
+ auto numPlanes = reader.readInt<int64_t>().value_or(0);
+ values.reserve(numPlanes);
+ for (int i = 0; i < numPlanes && reader.ok(); i++) {
+ PlaneLayout& value = values.emplace_back();
+ auto numPlaneComponents = reader.readInt<int64_t>().value_or(0);
+ value.components.reserve(numPlaneComponents);
+ for (int i = 0; i < numPlaneComponents && reader.ok(); i++) {
+ PlaneLayoutComponent& component = value.components.emplace_back();
+ reader.read(component.type)
+ .read<int64_t>(component.offsetInBits)
+ .read<int64_t>(component.sizeInBits);
+ }
+ reader.read<int64_t>(value.offsetInBytes)
+ .read<int64_t>(value.sampleIncrementInBits)
+ .read<int64_t>(value.strideInBytes)
+ .read<int64_t>(value.widthInSamples)
+ .read<int64_t>(value.heightInSamples)
+ .read<int64_t>(value.totalSizeInBytes)
+ .read<int64_t>(value.horizontalSubsampling)
+ .read<int64_t>(value.verticalSubsampling);
+ }
+ return reader.ok() ? DecodeResult{std::move(values)} : std::nullopt;
+ }
+};
+
+template <>
+struct MetadataValue<std::vector<Rect>> {
+ [[nodiscard]] static int32_t encode(const std::vector<Rect>& value, void* _Nullable destBuffer,
+ size_t destBufferSize) {
+ MetadataWriter writer{destBuffer, destBufferSize};
+ writer.write<int64_t>(value.size());
+ for (auto& rect : value) {
+ writer.write<int32_t>(rect.left)
+ .write<int32_t>(rect.top)
+ .write<int32_t>(rect.right)
+ .write<int32_t>(rect.bottom);
+ }
+ return writer.desiredSize();
+ }
+
+ using DecodeResult = std::optional<std::vector<Rect>>;
+ [[nodiscard]] static DecodeResult decode(const void* _Nonnull metadata, size_t metadataSize) {
+ MetadataReader reader{metadata, metadataSize};
+ std::vector<Rect> value;
+ auto numRects = reader.readInt<int64_t>().value_or(0);
+ value.reserve(numRects);
+ for (int i = 0; i < numRects && reader.ok(); i++) {
+ Rect& rect = value.emplace_back();
+ reader.read<int32_t>(rect.left)
+ .read<int32_t>(rect.top)
+ .read<int32_t>(rect.right)
+ .read<int32_t>(rect.bottom);
+ }
+ return reader.ok() ? DecodeResult{std::move(value)} : std::nullopt;
+ }
+};
+
+template <>
+struct MetadataValue<std::optional<Smpte2086>> {
+ [[nodiscard]] static int32_t encode(const std::optional<Smpte2086>& optValue,
+ void* _Nullable destBuffer, size_t destBufferSize) {
+ if (optValue.has_value()) {
+ const auto& value = *optValue;
+ return MetadataWriter{destBuffer, destBufferSize}
+ .write(value.primaryRed)
+ .write(value.primaryGreen)
+ .write(value.primaryBlue)
+ .write(value.whitePoint)
+ .write(value.maxLuminance)
+ .write(value.minLuminance)
+ .desiredSize();
+ } else {
+ return 0;
+ }
+ }
+
+ // Double optional because the value type itself is an optional<>
+ using DecodeResult = std::optional<std::optional<Smpte2086>>;
+ [[nodiscard]] static DecodeResult decode(const void* _Nullable metadata, size_t metadataSize) {
+ std::optional<Smpte2086> optValue{std::nullopt};
+ if (metadataSize > 0) {
+ Smpte2086 value;
+ MetadataReader reader{metadata, metadataSize};
+ reader.read(value.primaryRed)
+ .read(value.primaryGreen)
+ .read(value.primaryBlue)
+ .read(value.whitePoint)
+ .read(value.maxLuminance)
+ .read(value.minLuminance);
+ if (reader.ok()) {
+ optValue = std::move(value);
+ } else {
+ return std::nullopt;
+ }
+ }
+ return DecodeResult{std::move(optValue)};
+ }
+};
+
+template <>
+struct MetadataValue<std::optional<Cta861_3>> {
+ [[nodiscard]] static int32_t encode(const std::optional<Cta861_3>& optValue,
+ void* _Nullable destBuffer, size_t destBufferSize) {
+ if (optValue.has_value()) {
+ const auto& value = *optValue;
+ return MetadataWriter{destBuffer, destBufferSize}
+ .write(value.maxContentLightLevel)
+ .write(value.maxFrameAverageLightLevel)
+ .desiredSize();
+ } else {
+ return 0;
+ }
+ }
+
+ // Double optional because the value type itself is an optional<>
+ using DecodeResult = std::optional<std::optional<Cta861_3>>;
+ [[nodiscard]] static DecodeResult decode(const void* _Nullable metadata, size_t metadataSize) {
+ std::optional<Cta861_3> optValue{std::nullopt};
+ if (metadataSize > 0) {
+ MetadataReader reader{metadata, metadataSize};
+ Cta861_3 value;
+ reader.read(value.maxContentLightLevel).read(value.maxFrameAverageLightLevel);
+ if (reader.ok()) {
+ optValue = std::move(value);
+ } else {
+ return std::nullopt;
+ }
+ }
+ return DecodeResult{std::move(optValue)};
+ }
+};
+
+template <>
+struct MetadataValue<std::optional<std::vector<uint8_t>>> {
+ [[nodiscard]] static int32_t encode(const std::optional<std::vector<uint8_t>>& value,
+ void* _Nullable destBuffer, size_t destBufferSize) {
+ if (!value.has_value()) {
+ return 0;
+ }
+ return MetadataWriter{destBuffer, destBufferSize}.write(*value).desiredSize();
+ }
+
+ using DecodeResult = std::optional<std::optional<std::vector<uint8_t>>>;
+ [[nodiscard]] static DecodeResult decode(const void* _Nonnull metadata, size_t metadataSize) {
+ std::optional<std::vector<uint8_t>> optValue;
+ if (metadataSize > 0) {
+ MetadataReader reader{metadata, metadataSize};
+ auto value = reader.readBuffer();
+ if (reader.ok()) {
+ optValue = std::move(value);
+ } else {
+ return std::nullopt;
+ }
+ }
+ return DecodeResult{std::move(optValue)};
+ }
+};
+
+template <StandardMetadataType>
+struct StandardMetadata {};
+
+#define DEFINE_TYPE(name, typeArg) \
+ template <> \
+ struct StandardMetadata<StandardMetadataType::name> { \
+ using value_type = typeArg; \
+ using value = MetadataValue<value_type>; \
+ static_assert( \
+ StandardMetadataType::name == \
+ ndk::internal::enum_values<StandardMetadataType>[static_cast<size_t>( \
+ StandardMetadataType::name)], \
+ "StandardMetadataType must have equivalent value to index"); \
+ }
+
+DEFINE_TYPE(BUFFER_ID, uint64_t);
+DEFINE_TYPE(NAME, std::string);
+DEFINE_TYPE(WIDTH, uint64_t);
+DEFINE_TYPE(HEIGHT, uint64_t);
+DEFINE_TYPE(LAYER_COUNT, uint64_t);
+DEFINE_TYPE(PIXEL_FORMAT_REQUESTED, PixelFormat);
+DEFINE_TYPE(PIXEL_FORMAT_FOURCC, uint32_t);
+DEFINE_TYPE(PIXEL_FORMAT_MODIFIER, uint64_t);
+DEFINE_TYPE(USAGE, BufferUsage);
+DEFINE_TYPE(ALLOCATION_SIZE, uint64_t);
+DEFINE_TYPE(PROTECTED_CONTENT, uint64_t);
+DEFINE_TYPE(COMPRESSION, ExtendableType);
+DEFINE_TYPE(INTERLACED, ExtendableType);
+DEFINE_TYPE(CHROMA_SITING, ExtendableType);
+DEFINE_TYPE(PLANE_LAYOUTS, std::vector<PlaneLayout>);
+DEFINE_TYPE(CROP, std::vector<Rect>);
+DEFINE_TYPE(DATASPACE, Dataspace);
+DEFINE_TYPE(BLEND_MODE, BlendMode);
+DEFINE_TYPE(SMPTE2086, std::optional<Smpte2086>);
+DEFINE_TYPE(CTA861_3, std::optional<Cta861_3>);
+DEFINE_TYPE(SMPTE2094_10, std::optional<std::vector<uint8_t>>);
+DEFINE_TYPE(SMPTE2094_40, std::optional<std::vector<uint8_t>>);
+
+#undef DEFINE_TYPE
+
+template <typename F, std::size_t... I>
+void invokeWithStandardMetadata(F&& f, StandardMetadataType type, std::index_sequence<I...>) {
+ // Setup the jump table, mapping from each type to a springboard that invokes the template
+ // function with the appropriate concrete type
+ using F_PTR = decltype(&f);
+ using THUNK = void (*)(F_PTR);
+ static constexpr auto jump = std::array<THUNK, sizeof...(I)>{[](F_PTR fp) {
+ constexpr StandardMetadataType type = ndk::internal::enum_values<StandardMetadataType>[I];
+ if constexpr (type != StandardMetadataType::INVALID) {
+ (*fp)(StandardMetadata<type>{});
+ }
+ }...};
+
+ auto index = static_cast<size_t>(type);
+ if (index >= 0 && index < jump.size()) {
+ jump[index](&f);
+ }
+}
+
+template <typename F, typename StandardMetadataSequence = std::make_index_sequence<
+ ndk::internal::enum_values<StandardMetadataType>.size()>>
+int32_t provideStandardMetadata(StandardMetadataType type, void* _Nullable destBuffer,
+ size_t destBufferSize, F&& f) {
+ int32_t retVal = -AIMAPPER_ERROR_UNSUPPORTED;
+ invokeWithStandardMetadata(
+ [&]<StandardMetadataType T>(StandardMetadata<T>) {
+ retVal = f.template operator()<T>(
+ [&](const typename StandardMetadata<T>::value_type& value) -> int32_t {
+ return StandardMetadata<T>::value::encode(value, destBuffer,
+ destBufferSize);
+ });
+ },
+ type, StandardMetadataSequence{});
+ return retVal;
+}
+
+template <typename F, typename StandardMetadataSequence = std::make_index_sequence<
+ ndk::internal::enum_values<StandardMetadataType>.size()>>
+AIMapper_Error applyStandardMetadata(StandardMetadataType type, const void* _Nonnull metadata,
+ size_t metadataSize, F&& f) {
+ AIMapper_Error retVal = AIMAPPER_ERROR_UNSUPPORTED;
+ invokeWithStandardMetadata(
+ [&]<StandardMetadataType T>(StandardMetadata<T>) {
+ auto value = StandardMetadata<T>::value::decode(metadata, metadataSize);
+ if (value.has_value()) {
+ retVal = f.template operator()<T>(std::move(*value));
+ } else {
+ retVal = AIMAPPER_ERROR_BAD_VALUE;
+ }
+ },
+ type, StandardMetadataSequence{});
+ return retVal;
+}
+
+} // namespace android::hardware::graphics::mapper
\ No newline at end of file
diff --git a/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h b/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h
new file mode 100644
index 0000000..957fdc9
--- /dev/null
+++ b/graphics/mapper/stable-c/implutils/include/android/hardware/graphics/mapper/utils/IMapperProvider.h
@@ -0,0 +1,222 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <android-base/unique_fd.h>
+#include <android/hardware/graphics/mapper/IMapper.h>
+#include <log/log.h>
+
+#include <mutex>
+#include <optional>
+#include <type_traits>
+
+/**
+ * Helper utilities for providing an IMapper-StableC implementation.
+ */
+
+namespace vendor::mapper {
+
+/**
+ * Extend from this interface to provide Version 5 of the IMapper interface
+ */
+struct IMapperV5Impl {
+ static const auto version = AIMAPPER_VERSION_5;
+ virtual ~IMapperV5Impl() = default;
+
+ virtual AIMapper_Error importBuffer(const native_handle_t* _Nonnull handle,
+ buffer_handle_t _Nullable* _Nonnull outBufferHandle) = 0;
+
+ virtual AIMapper_Error freeBuffer(buffer_handle_t _Nonnull buffer) = 0;
+
+ virtual AIMapper_Error getTransportSize(buffer_handle_t _Nonnull buffer,
+ uint32_t* _Nonnull outNumFds,
+ uint32_t* _Nonnull outNumInts) = 0;
+
+ virtual AIMapper_Error lock(buffer_handle_t _Nonnull buffer, uint64_t cpuUsage,
+ ARect accessRegion, int acquireFence,
+ void* _Nullable* _Nonnull outData) = 0;
+
+ virtual AIMapper_Error unlock(buffer_handle_t _Nonnull buffer, int* _Nonnull releaseFence) = 0;
+
+ virtual AIMapper_Error flushLockedBuffer(buffer_handle_t _Nonnull buffer) = 0;
+
+ virtual AIMapper_Error rereadLockedBuffer(buffer_handle_t _Nonnull buffer) = 0;
+
+ virtual int32_t getMetadata(buffer_handle_t _Nonnull buffer, AIMapper_MetadataType metadataType,
+ void* _Nullable destBuffer, size_t destBufferSize) = 0;
+
+ virtual int32_t getStandardMetadata(buffer_handle_t _Nonnull buffer,
+ int64_t standardMetadataType, void* _Nullable destBuffer,
+ size_t destBufferSize) = 0;
+
+ virtual AIMapper_Error setMetadata(buffer_handle_t _Nonnull buffer,
+ AIMapper_MetadataType metadataType,
+ const void* _Nonnull metadata, size_t metadataSize) = 0;
+
+ virtual AIMapper_Error setStandardMetadata(buffer_handle_t _Nonnull buffer,
+ int64_t standardMetadataType,
+ const void* _Nonnull metadata,
+ size_t metadataSize) = 0;
+
+ virtual AIMapper_Error listSupportedMetadataTypes(
+ const AIMapper_MetadataTypeDescription* _Nullable* _Nonnull outDescriptionList,
+ size_t* _Nonnull outNumberOfDescriptions) = 0;
+
+ virtual AIMapper_Error dumpBuffer(buffer_handle_t _Nonnull bufferHandle,
+ AIMapper_DumpBufferCallback _Nonnull dumpBufferCallback,
+ void* _Null_unspecified context) = 0;
+
+ virtual AIMapper_Error dumpAllBuffers(
+ AIMapper_BeginDumpBufferCallback _Nonnull beginDumpBufferCallback,
+ AIMapper_DumpBufferCallback _Nonnull dumpBufferCallback,
+ void* _Null_unspecified context) = 0;
+
+ virtual AIMapper_Error getReservedRegion(buffer_handle_t _Nonnull buffer,
+ void* _Nullable* _Nonnull outReservedRegion,
+ uint64_t* _Nonnull outReservedSize) = 0;
+};
+
+namespace provider {
+#ifndef __cpp_inline_variables
+#error "Only C++17 & newer is supported; inline variables is missing"
+#endif
+
+inline void* _Nullable sIMapperInstance = nullptr;
+} // namespace provider
+
+template <typename IMPL>
+class IMapperProvider {
+ private:
+ static_assert(IMPL::version >= AIMAPPER_VERSION_5, "Must be at least AIMAPPER_VERSION_5");
+ static_assert(std::is_final_v<IMPL>, "Implementation must be final");
+ static_assert(std::is_constructible_v<IMPL>, "Implementation must have a no-args constructor");
+
+ std::once_flag mLoadOnceFlag;
+ std::optional<IMPL> mImpl;
+ AIMapper mMapper = {};
+
+ static IMPL& impl() {
+ return *reinterpret_cast<IMapperProvider<IMPL>*>(provider::sIMapperInstance)->mImpl;
+ }
+
+ void bindV5() {
+ mMapper.v5 = {
+ .importBuffer = [](const native_handle_t* _Nonnull handle,
+ buffer_handle_t _Nullable* _Nonnull outBufferHandle)
+ -> AIMapper_Error { return impl().importBuffer(handle, outBufferHandle); },
+
+ .freeBuffer = [](buffer_handle_t _Nonnull buffer) -> AIMapper_Error {
+ return impl().freeBuffer(buffer);
+ },
+
+ .getTransportSize = [](buffer_handle_t _Nonnull buffer,
+ uint32_t* _Nonnull outNumFds,
+ uint32_t* _Nonnull outNumInts) -> AIMapper_Error {
+ return impl().getTransportSize(buffer, outNumFds, outNumInts);
+ },
+
+ .lock = [](buffer_handle_t _Nonnull buffer, uint64_t cpuUsage, ARect accessRegion,
+ int acquireFence, void* _Nullable* _Nonnull outData) -> AIMapper_Error {
+ return impl().lock(buffer, cpuUsage, accessRegion, acquireFence, outData);
+ },
+
+ .unlock = [](buffer_handle_t _Nonnull buffer, int* _Nonnull releaseFence)
+ -> AIMapper_Error { return impl().unlock(buffer, releaseFence); },
+
+ .flushLockedBuffer = [](buffer_handle_t _Nonnull buffer) -> AIMapper_Error {
+ return impl().flushLockedBuffer(buffer);
+ },
+
+ .rereadLockedBuffer = [](buffer_handle_t _Nonnull buffer) -> AIMapper_Error {
+ return impl().rereadLockedBuffer(buffer);
+ },
+
+ .getMetadata = [](buffer_handle_t _Nonnull buffer,
+ AIMapper_MetadataType metadataType, void* _Nullable destBuffer,
+ size_t destBufferSize) -> int32_t {
+ return impl().getMetadata(buffer, metadataType, destBuffer, destBufferSize);
+ },
+
+ .getStandardMetadata = [](buffer_handle_t _Nonnull buffer,
+ int64_t standardMetadataType, void* _Nullable destBuffer,
+ size_t destBufferSize) -> int32_t {
+ return impl().getStandardMetadata(buffer, standardMetadataType, destBuffer,
+ destBufferSize);
+ },
+
+ .setMetadata = [](buffer_handle_t _Nonnull buffer,
+ AIMapper_MetadataType metadataType, const void* _Nonnull metadata,
+ size_t metadataSize) -> AIMapper_Error {
+ return impl().setMetadata(buffer, metadataType, metadata, metadataSize);
+ },
+
+ .setStandardMetadata =
+ [](buffer_handle_t _Nonnull buffer, int64_t standardMetadataType,
+ const void* _Nonnull metadata, size_t metadataSize) -> AIMapper_Error {
+ return impl().setStandardMetadata(buffer, standardMetadataType, metadata,
+ metadataSize);
+ },
+
+ .listSupportedMetadataTypes =
+ [](const AIMapper_MetadataTypeDescription* _Nullable* _Nonnull outDescriptionList,
+ size_t* _Nonnull outNumberOfDescriptions) -> AIMapper_Error {
+ return impl().listSupportedMetadataTypes(outDescriptionList,
+ outNumberOfDescriptions);
+ },
+
+ .dumpBuffer = [](buffer_handle_t _Nonnull bufferHandle,
+ AIMapper_DumpBufferCallback _Nonnull dumpBufferCallback,
+ void* _Null_unspecified context) -> AIMapper_Error {
+ return impl().dumpBuffer(bufferHandle, dumpBufferCallback, context);
+ },
+
+ .dumpAllBuffers =
+ [](AIMapper_BeginDumpBufferCallback _Nonnull beginDumpBufferCallback,
+ AIMapper_DumpBufferCallback _Nonnull dumpBufferCallback,
+ void* _Null_unspecified context) {
+ return impl().dumpAllBuffers(beginDumpBufferCallback,
+ dumpBufferCallback, context);
+ },
+
+ .getReservedRegion = [](buffer_handle_t _Nonnull buffer,
+ void* _Nullable* _Nonnull outReservedRegion,
+ uint64_t* _Nonnull outReservedSize) -> AIMapper_Error {
+ return impl().getReservedRegion(buffer, outReservedRegion, outReservedSize);
+ },
+ };
+ }
+
+ public:
+ explicit IMapperProvider() = default;
+
+ AIMapper_Error load(AIMapper* _Nullable* _Nonnull outImplementation) {
+ std::call_once(mLoadOnceFlag, [this] {
+ LOG_ALWAYS_FATAL_IF(provider::sIMapperInstance != nullptr,
+ "AIMapper implementation already loaded!");
+ provider::sIMapperInstance = this;
+ mImpl.emplace();
+ mMapper.version = IMPL::version;
+ if (IMPL::version >= AIMAPPER_VERSION_5) {
+ bindV5();
+ }
+ });
+ *outImplementation = &mMapper;
+ return AIMAPPER_ERROR_NONE;
+ }
+};
+
+} // namespace vendor::mapper
diff --git a/graphics/mapper/stable-c/include/android/hardware/graphics/mapper/IMapper.h b/graphics/mapper/stable-c/include/android/hardware/graphics/mapper/IMapper.h
new file mode 100644
index 0000000..0f6d146
--- /dev/null
+++ b/graphics/mapper/stable-c/include/android/hardware/graphics/mapper/IMapper.h
@@ -0,0 +1,691 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+/**
+ * IMapper Stable-C HAL interface
+ *
+ * This file represents the sphal interface between libui & the IMapper HAL implementation.
+ * A vendor implementation of this interface is retrieved by looking up the vendor imapper
+ * implementation library via the IAllocator AIDL interface.
+ *
+ * This interface is not intended for general use.
+ */
+
+#pragma once
+
+#include <sys/cdefs.h>
+#include <cinttypes>
+#include <cstddef>
+#include <type_traits>
+
+#include <android/rect.h>
+#include <cutils/native_handle.h>
+
+__BEGIN_DECLS
+
+/**
+ * AIMapper versioning
+ *
+ * IMapper versions 0-1 are pre-treble
+ * IMapper versions 2-4 are HIDL
+ * C-style AIMapper API starts at 5
+ */
+enum AIMapper_Version : uint32_t {
+ AIMAPPER_VERSION_5 = 5,
+};
+
+/**
+ * Possible AIMapper errors
+ * Values are the same as IMapper 4.0's Error type for simplicity
+ */
+enum AIMapper_Error : int32_t {
+ /**
+ * No error.
+ */
+ AIMAPPER_ERROR_NONE = 0,
+ /**
+ * Invalid BufferDescriptor.
+ */
+ AIMAPPER_ERROR_BAD_DESCRIPTOR = 1,
+ /**
+ * Invalid buffer handle.
+ */
+ AIMAPPER_ERROR_BAD_BUFFER = 2,
+ /**
+ * Invalid HardwareBufferDescription.
+ */
+ AIMAPPER_ERROR_BAD_VALUE = 3,
+ /**
+ * Resource unavailable.
+ */
+ AIMAPPER_ERROR_NO_RESOURCES = 5,
+ /**
+ * Permanent failure.
+ */
+ AIMAPPER_ERROR_UNSUPPORTED = 7,
+};
+
+/**
+ * MetadataType represents the different types of buffer metadata that could be
+ * associated with a buffer. It is used by IMapper to help get and set buffer metadata
+ * on the buffer's native handle.
+ *
+ * Standard buffer metadata will have the name field set to
+ * "android.hardware.graphics.common.StandardMetadataType" and will contain values
+ * from StandardMetadataType.aidl.
+ *
+ * Vendor-provided metadata should be prefixed with a "vendor.mycompanyname.*" namespace. It is
+ * recommended that the metadata follows the pattern of StandardMetadaType.aidl. That is, an
+ * aidl-defined enum with @VendorStability on it and the naming then matching that type such
+ * as "vendor.mycompanyname.graphics.common.MetadataType" with the value field then set to the
+ * aidl's enum value.
+ *
+ * Each company should create their own enum & namespace. The name
+ * field prevents values from different companies from colliding.
+ */
+typedef struct AIMapper_MetadataType {
+ const char* _Nonnull name;
+ int64_t value;
+} AIMapper_MetadataType;
+
+typedef struct AIMapper_MetadataTypeDescription {
+ /**
+ * The `name` of the metadataType must be valid for the lifetime of the process
+ */
+ AIMapper_MetadataType metadataType;
+ /**
+ * description should contain a string representation of the MetadataType.
+ *
+ * For example: "MyExampleMetadataType is a 64-bit timestamp in nanoseconds
+ * that indicates when a buffer is decoded. It is set by the media HAL after
+ * a buffer is decoded. It is used by the display HAL for hardware
+ * synchronization".
+ *
+ * This field is required for any non-StandardMetadataTypes. For StandardMetadataTypes this
+ * field may be null. The lifetime of this pointer must be valid for the duration of the
+ * process (that is, a static const char*).
+ */
+ const char* _Nullable description;
+ /**
+ * isGettable represents if the MetadataType can be get.
+ */
+ bool isGettable;
+ /**
+ * isSettable represents if the MetadataType can be set.
+ */
+ bool isSettable;
+
+ /** Reserved for future use; must be zero-initialized currently */
+ uint8_t reserved[32];
+} AIMapper_MetadataTypeDescription;
+
+/**
+ * Callback that is passed to dumpBuffer.
+ *
+ * @param context The caller-provided void* that was passed to dumpBuffer.
+ * @param metadataType The type of the metadata passed to the callback
+ * @param value A pointer to the value of the metadata. The lifetime of this pointer is only
+ * valid for the duration of the call
+ * @param valueSize The size of the value buffer.
+ */
+typedef void (*AIMapper_DumpBufferCallback)(void* _Null_unspecified context,
+ AIMapper_MetadataType metadataType,
+ const void* _Nonnull value, size_t valueSize);
+
+/**
+ * Callback that is passed to dumpAllBuffers.
+ *
+ * Indicates that a buffer is about to be dumped. Will be followed by N calls to
+ * AIMapper_DumpBufferCallback for all the metadata for this buffer.
+ *
+ * @param context The caller-provided void* that was passed to dumpAllBuffers.
+ */
+typedef void (*AIMapper_BeginDumpBufferCallback)(void* _Null_unspecified context);
+
+/**
+ * Implementation of AIMAPPER_VERSION_5
+ * All functions must not be null & must provide a valid implementation.
+ */
+typedef struct AIMapperV5 {
+ /**
+ * Imports a raw buffer handle to create an imported buffer handle for use
+ * with the rest of the mapper or with other in-process libraries.
+ *
+ * A buffer handle is considered raw when it is cloned (e.g., with
+ * `native_handle_clone()`) from another buffer handle locally, or when it
+ * is received from another HAL server/client or another process. A raw
+ * buffer handle must not be used to access the underlying graphic
+ * buffer. It must be imported to create an imported handle first.
+ *
+ * This function must at least validate the raw handle before creating the
+ * imported handle. It must also support importing the same raw handle
+ * multiple times to create multiple imported handles. The imported handle
+ * must be considered valid everywhere in the process, including in
+ * another instance of the mapper.
+ *
+ * Because of passthrough HALs, a raw buffer handle received from a HAL
+ * may actually have been imported in the process. importBuffer() must treat
+ * such a handle as if it is raw and must not return `BAD_BUFFER`. The
+ * returned handle is independent from the input handle as usual, and
+ * freeBuffer() must be called on it when it is no longer needed.
+ *
+ * @param handle Raw buffer handle to import.
+ * @param outBufferHandle The resulting imported buffer handle.
+ * @return Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `NO_RESOURCES` if the raw handle cannot be imported due to
+ * unavailability of resources.
+ */
+ AIMapper_Error (*_Nonnull importBuffer)(const native_handle_t* _Nonnull handle,
+ buffer_handle_t _Nullable* _Nonnull outBufferHandle);
+
+ /**
+ * Frees a buffer handle. Buffer handles returned by importBuffer() must be
+ * freed with this function when no longer needed.
+ *
+ * This function must free up all resources allocated by importBuffer() for
+ * the imported handle. For example, if the imported handle was created
+ * with `native_handle_create()`, this function must call
+ * `native_handle_close()` and `native_handle_delete()`.
+ *
+ * @param buffer Imported buffer handle.
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid.
+ */
+ AIMapper_Error (*_Nonnull freeBuffer)(buffer_handle_t _Nonnull buffer);
+
+ /**
+ * Calculates the transport size of a buffer. An imported buffer handle is a
+ * raw buffer handle with the process-local runtime data appended. This
+ * function, for example, allows a caller to omit the process-local runtime
+ * data at the tail when serializing the imported buffer handle.
+ *
+ * Note that a client might or might not omit the process-local runtime data
+ * when sending an imported buffer handle. The mapper must support both
+ * cases on the receiving end.
+ *
+ * @param buffer Buffer to get the transport size from.
+ * @param outNumFds The number of file descriptors needed for transport.
+ * @param outNumInts The number of integers needed for transport.
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid.
+ */
+ AIMapper_Error (*_Nonnull getTransportSize)(buffer_handle_t _Nonnull buffer,
+ uint32_t* _Nonnull outNumFds,
+ uint32_t* _Nonnull outNumInts);
+
+ /**
+ * Locks the given buffer for the specified CPU usage.
+ *
+ * Locking the same buffer simultaneously from multiple threads is
+ * permitted, but if any of the threads attempt to lock the buffer for
+ * writing, the behavior is undefined, except that it must not cause
+ * process termination or block the client indefinitely. Leaving the
+ * buffer content in an indeterminate state or returning an error are both
+ * acceptable.
+ *
+ * 1D buffers (width = size in bytes, height = 1, pixel_format = BLOB) must
+ * "lock in place". The buffers must be directly accessible via mapping.
+ *
+ * The client must not modify the content of the buffer outside of
+ * @p accessRegion, and the device need not guarantee that content outside
+ * of @p accessRegion is valid for reading. The result of reading or writing
+ * outside of @p accessRegion is undefined, except that it must not cause
+ * process termination.
+ *
+ * An accessRegion of all-zeros means the entire buffer. That is, it is
+ * equivalent to '(0,0)-(buffer width, buffer height)'.
+ *
+ * This function can lock both single-planar and multi-planar formats. The caller
+ * should use get() to get information about the buffer they are locking.
+ * get() can be used to get information about the planes, offsets, stride,
+ * etc.
+ *
+ * This function must also work on buffers with
+ * `AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_*` if supported by the device, as well
+ * as with any other formats requested by multimedia codecs when they are
+ * configured with a flexible-YUV-compatible color format.
+ *
+ * On success, @p data must be filled with a pointer to the locked buffer
+ * memory. This address will represent the top-left corner of the entire
+ * buffer, even if @p accessRegion does not begin at the top-left corner.
+ *
+ * The locked buffer must adhere to the format requested at allocation time
+ * in the BufferDescriptorInfo.
+ *
+ * @param buffer Buffer to lock.
+ * @param cpuUsage CPU usage flags to request. See BufferUsage.aidl for possible values.
+ * @param accessRegion Portion of the buffer that the client intends to
+ * access.
+ * @param acquireFence Handle containing a file descriptor referring to a
+ * sync fence object, which will be signaled when it is safe for the
+ * mapper to lock the buffer. @p acquireFence may be an empty fence (-1) if
+ * it is already safe to lock. Ownership is passed to the callee and it is the
+ * implementations responsibility to ensure it is closed even when an error
+ * occurs.
+ * @param outData CPU-accessible pointer to the buffer data.
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid or is incompatible with this
+ * function.
+ * - `BAD_VALUE` if @p cpuUsage is 0, contains non-CPU usage flags, or
+ * is incompatible with the buffer. Also if the @p accessRegion is
+ * outside the bounds of the buffer or the accessRegion is invalid.
+ * - `NO_RESOURCES` if the buffer cannot be locked at this time. Note
+ * that locking may succeed at a later time.
+ * @return data CPU-accessible pointer to the buffer data.
+ */
+ AIMapper_Error (*_Nonnull lock)(buffer_handle_t _Nonnull buffer, uint64_t cpuUsage,
+ ARect accessRegion, int acquireFence,
+ void* _Nullable* _Nonnull outData);
+
+ /**
+ * Unlocks a buffer to indicate all CPU accesses to the buffer have
+ * completed.
+ *
+ * @param buffer Buffer to unlock.
+ * @param releaseFence Handle containing a file descriptor referring to a
+ * sync fence object. The sync fence object will be signaled when the
+ * mapper has completed any pending work. @p releaseFence may be an
+ * empty fence (-1).
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid or not locked.
+ */
+ AIMapper_Error (*_Nonnull unlock)(buffer_handle_t _Nonnull buffer, int* _Nonnull releaseFence);
+
+ /**
+ * Flushes the contents of a locked buffer.
+ *
+ * This function flushes the CPUs caches for the range of all the buffer's
+ * planes and metadata. This should behave similarly to unlock() except the
+ * buffer should remain mapped to the CPU.
+ *
+ * The client is still responsible for calling unlock() when it is done
+ * with all CPU accesses to the buffer.
+ *
+ * If non-CPU blocks are simultaneously writing the buffer, the locked
+ * copy should still be flushed but what happens is undefined except that
+ * it should not cause any crashes.
+ *
+ * @param buffer Buffer to flush.
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid or not locked.
+ */
+ AIMapper_Error (*_Nonnull flushLockedBuffer)(buffer_handle_t _Nonnull buffer);
+
+ /**
+ * Rereads the contents of a locked buffer.
+ *
+ * This should fetch the most recent copy of the locked buffer.
+ *
+ * It may reread locked copies of the buffer in other processes.
+ *
+ * The client is still responsible for calling unlock() when it is done
+ * with all CPU accesses to the buffer.
+ *
+ * @param buffer Buffer to reread.
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid or not locked.
+ * - `NO_RESOURCES` if the buffer cannot be reread at this time. Note
+ * that rereading may succeed at a later time.
+ */
+ AIMapper_Error (*_Nonnull rereadLockedBuffer)(buffer_handle_t _Nonnull buffer);
+
+ /**
+ * Description for get(...), set(...) and getFromBufferDescriptorInfo(...)
+ *
+ * ------------ Overview -----------------------------------
+ * Gralloc 4 adds support for getting and setting buffer metadata on a buffer.
+ *
+ * To get buffer metadata, the client passes in a buffer handle and a token that
+ * represents the type of buffer metadata they would like to get. IMapper returns
+ * a byte stream that contains the buffer metadata. To set the buffer metadata, the
+ * client passes in a buffer handle and a token that represents the type of buffer
+ * metadata they would like to set and a byte stream that contains the buffer metadata
+ * they are setting.
+ *
+ * Buffer metadata is global for a buffer. When the metadata is set on the buffer
+ * in a process, the updated metadata should be available to all other processes.
+ * Please see "Storing and Propagating Metadata" below for more details.
+ *
+ * The getter and setter functions have been optimized for easy vendor extension.
+ * They do not require a formal extension to add support for getting and setting
+ * vendor defined buffer metadata. See "Buffer Metadata Token" and
+ * "Buffer Metadata Stream" below for more details.
+ *
+ * ------------ Storing and Propagating Metadata -----------
+ * Buffer metadata must be global. Any changes to the metadata must be propagated
+ * to all other processes immediately. Vendors may chose how they would like support
+ * this functionality.
+ *
+ * We recommend supporting this functionality by allocating an extra page of shared
+ * memory and storing it in the buffer's native_handle_t. The buffer metadata can
+ * be stored in the extra page of shared memory. Set operations are automatically
+ * propagated to all other processes.
+ *
+ * ------------ Buffer Metadata Synchronization ------------
+ * There are no explicit buffer metadata synchronization primitives. Many devices
+ * before gralloc 4 already support getting and setting of global buffer metadata
+ * with no explicit synchronization primitives. Adding synchronization primitives
+ * would just add unnecessary complexity.
+ *
+ * The general rule is if a process has permission to write to a buffer, they
+ * have permission to write to the buffer's writable metadata. If a process has permission
+ * to read from a buffer, they have permission to read the buffer's metadata.
+ *
+ * There is one exception to this rule. Fences CANNOT be used to protect a buffer's
+ * metadata. A process should finish writing to a buffer's metadata before
+ * sending the buffer to another process that will read or write to the buffer.
+ * This exception is needed because sometimes userspace needs to read the
+ * buffer's metadata before the buffer's contents are ready.
+ *
+ * As a simple example: an app renders to a buffer and then displays the buffer.
+ * In this example when the app renders to the buffer, both the buffer and its
+ * metadata need to be updated. The app's process queues up its work on the GPU
+ * and gets back an acquire fence. The app's process must update the buffer's
+ * metadata before enqueuing the buffer to SurfaceFlinger. The app process CANNOT
+ * update the buffer's metadata after enqueuing the buffer. When HardwareComposer
+ * receives the buffer, it is immediately safe to read the buffer's metadata
+ * and use it to program the display driver. To read the buffer's contents,
+ * display driver must still wait on the acquire fence.
+ *
+ * ------------ Buffer Metadata Token ----------------------
+ * In order to allow arbitrary vendor defined metadata, the token used to access
+ * metadata is defined defined as a struct that has a string representing
+ * the enum type and an int that represents the enum value. The string protects
+ * different enum values from colliding.
+ *
+ * The token struct (MetadataType) is defined as a C struct since it
+ * is passed into a C function. The standard buffer metadata types are NOT
+ * defined as a C enum but instead as an AIDL enum to allow for broader usage across
+ * other HALs and libraries. By putting the enum in the
+ * stable AIDL (hardware/interfaces/graphics/common/aidl/android/hardware/
+ * graphics/common/StandardMetadataType.aidl), vendors will be able to optionally
+ * choose to support future standard buffer metadata types without upgrading
+ * IMapper versions. For more information see the description of "struct MetadataType".
+ *
+ * ------------ Buffer Metadata Stream ---------------------
+ * The buffer metadata is get and set as a void* buffer. By getting
+ * and setting buffer metadata as a generic buffer, vendors can use the standard
+ * getters and setter functions defined here. Vendors do NOT need to add their own
+ * getters and setter functions for each new type of buffer metadata.
+ *
+ * Converting buffer metadata into a byte stream can be non-trivial. For the standard
+ * buffer metadata types defined in StandardMetadataType.aidl, there are also
+ * support functions that will encode the buffer metadata into a byte stream
+ * and decode the buffer metadata from a byte stream. We STRONGLY recommend using
+ * these support functions. The framework will use them when getting and setting
+ * metadata. The support functions are defined in
+ * frameworks/native/libs/gralloc/types/include/gralloctypes/Gralloc4.h.
+ */
+
+ /**
+ * Gets the buffer metadata for a given MetadataType.
+ *
+ * Buffer metadata can be changed after allocation so clients should avoid "caching"
+ * the buffer metadata. For example, if the video resolution changes and the buffers
+ * are not reallocated, several buffer metadata values may change without warning.
+ * Clients should not expect the values to be constant. They should requery them every
+ * frame. The only exception is buffer metadata that is determined at allocation
+ * time. For StandardMetadataType values, only BUFFER_ID, NAME, WIDTH,
+ * HEIGHT, LAYER_COUNT, PIXEL_FORMAT_REQUESTED and USAGE are safe to cache because
+ * they are determined at allocation time.
+ *
+ * @param buffer Buffer containing desired metadata
+ * @param metadataType MetadataType for the metadata value being queried
+ * @param destBuffer Pointer to a buffer in which to store the result of the get() call; if
+ * null, the computed output size or error must still be returned.
+ * @param destBufferSize How large the destBuffer buffer is. If destBuffer is null this must be
+ * 0.
+ * @return The number of bytes written to `destBuffer` or which would have been written
+ * if `destBufferSize` was large enough.
+ * A negative value indicates an error, which may be
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `UNSUPPORTED` when metadataType is unknown/unsupported.
+ * IMapper must support getting all StandardMetadataType.aidl values defined
+ * at the time the device first launches.
+ */
+ int32_t (*_Nonnull getMetadata)(buffer_handle_t _Nonnull buffer,
+ AIMapper_MetadataType metadataType, void* _Nullable destBuffer,
+ size_t destBufferSize);
+
+ /**
+ * Gets the buffer metadata for a StandardMetadataType.
+ *
+ * This is equivalent to `getMetadata` when passed an AIMapper_MetadataType with name
+ * set to "android.hardware.graphics.common.StandardMetadataType"
+ *
+ * Buffer metadata can be changed after allocation so clients should avoid "caching"
+ * the buffer metadata. For example, if the video resolution changes and the buffers
+ * are not reallocated, several buffer metadata values may change without warning.
+ * Clients should not expect the values to be constant. They should requery them every
+ * frame. The only exception is buffer metadata that is determined at allocation
+ * time. For StandardMetadataType values, only BUFFER_ID, NAME, WIDTH,
+ * HEIGHT, LAYER_COUNT, PIXEL_FORMAT_REQUESTED and USAGE are safe to cache because
+ * they are determined at allocation time.
+ *
+ * @param buffer Buffer containing desired metadata
+ * @param standardMetadataType StandardMetadataType for the metadata value being queried
+ * @param destBuffer Pointer to a buffer in which to store the result of the get() call; if
+ * null, the computed output size or error must still be returned.
+ * @param destBufferSize How large the destBuffer buffer is. If destBuffer is null this must be
+ * 0.
+ * @return The number of bytes written to `destBuffer` or which would have been written
+ * if `destBufferSize` was large enough.
+ * A negative value indicates an error, which may be
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `UNSUPPORTED` when metadataType is unknown/unsupported.
+ * IMapper must support getting all StandardMetadataType.aidl values defined
+ * at the time the device first launches.
+ */
+ int32_t (*_Nonnull getStandardMetadata)(buffer_handle_t _Nonnull buffer,
+ int64_t standardMetadataType,
+ void* _Nullable destBuffer, size_t destBufferSize);
+
+ /**
+ * Sets the global value for a given MetadataType.
+ *
+ * Metadata fields are not required to be settable. This function can
+ * return Error::UNSUPPORTED whenever it doesn't support setting a
+ * particular Metadata field.
+ *
+ * The framework will attempt to set the following StandardMetadataType
+ * values: DATASPACE, SMPTE2086, CTA861_3, and BLEND_MODE.
+ * We require everyone to support setting those fields. Framework will also attempt to set
+ * SMPTE2094_40 and SMPTE2094_10 if available, and it is required to support setting those
+ * if it is possible to get them. If a device's Composer implementation supports a field,
+ * it should be supported here. Over time these metadata fields will be moved out of
+ * Composer/BufferQueue/etc. and into the buffer's Metadata fields.
+ *
+ * @param buffer Buffer receiving desired metadata
+ * @param metadataType MetadataType for the metadata value being set
+ * @param metadata Pointer to a buffer of bytes representing the value associated with
+ * @param metadataSize The size of the metadata buffer
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `BAD_VALUE` when the field is constant and can never be set (such as
+ * BUFFER_ID, NAME, WIDTH, HEIGHT, LAYER_COUNT, PIXEL_FORMAT_REQUESTED and
+ * USAGE)
+ * - `NO_RESOURCES` if the set cannot be fulfilled due to unavailability of
+ * resources.
+ * - `UNSUPPORTED` when metadataType is unknown/unsupported or setting
+ * it is unsupported. Unsupported should also be returned if the metadata
+ * is malformed.
+ */
+ AIMapper_Error (*_Nonnull setMetadata)(buffer_handle_t _Nonnull buffer,
+ AIMapper_MetadataType metadataType,
+ const void* _Nonnull metadata, size_t metadataSize);
+
+ /**
+ * Sets the global value for a given MetadataType.
+ *
+ * This is equivalent to `setMetadata` when passed an AIMapper_MetadataType with name
+ * set to "android.hardware.graphics.common.StandardMetadataType"
+ *
+ * Metadata fields are not required to be settable. This function can
+ * return Error::UNSUPPORTED whenever it doesn't support setting a
+ * particular Metadata field.
+ *
+ * The framework will attempt to set the following StandardMetadataType
+ * values: DATASPACE, SMPTE2086, CTA861_3, and BLEND_MODE.
+ * We require everyone to support setting those fields. Framework will also attempt to set
+ * SMPTE2094_40 and SMPTE2094_10 if available, and it is required to support setting those
+ * if it is possible to get them. If a device's Composer implementation supports a field,
+ * it should be supported here. Over time these metadata fields will be moved out of
+ * Composer/BufferQueue/etc. and into the buffer's Metadata fields.
+ *
+ * @param buffer Buffer receiving desired metadata
+ * @param standardMetadataType StandardMetadataType for the metadata value being set
+ * @param metadata Pointer to a buffer of bytes representing the value associated with
+ * @param metadataSize The size of the metadata buffer
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `BAD_VALUE` when the field is constant and can never be set (such as
+ * BUFFER_ID, NAME, WIDTH, HEIGHT, LAYER_COUNT, PIXEL_FORMAT_REQUESTED and
+ * USAGE)
+ * - `NO_RESOURCES` if the set cannot be fulfilled due to unavailability of
+ * resources.
+ * - `UNSUPPORTED` when metadataType is unknown/unsupported or setting
+ * it is unsupported. Unsupported should also be returned if the metadata
+ * is malformed.
+ */
+ AIMapper_Error (*_Nonnull setStandardMetadata)(buffer_handle_t _Nonnull buffer,
+ int64_t standardMetadataType,
+ const void* _Nonnull metadata,
+ size_t metadataSize);
+
+ /**
+ * Lists all the MetadataTypes supported by IMapper as well as a description
+ * of each supported MetadataType. For StandardMetadataTypes, the description
+ * string can be left empty.
+ *
+ * This list is expected to be static & thus the returned array must be valid for the
+ * lifetime of the process.
+ *
+ * @param outDescriptionList The list of descriptions
+ * @param outNumberOfDescriptions How many descriptions are in `outDescriptionList`
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `UNSUPPORTED` if there's any error
+ */
+ AIMapper_Error (*_Nonnull listSupportedMetadataTypes)(
+ const AIMapper_MetadataTypeDescription* _Nullable* _Nonnull outDescriptionList,
+ size_t* _Nonnull outNumberOfDescriptions);
+
+ /**
+ * Dumps a buffer's metadata.
+ *
+ * @param buffer The buffer to dump the metadata for
+ * @param dumpBufferCallback Callback that will be invoked for each of the metadata fields
+ * @param context A caller-provided context to be passed to the dumpBufferCallback
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `NO_RESOURCES` if the get cannot be fulfilled due to unavailability of
+ * resources.
+ */
+ AIMapper_Error (*_Nonnull dumpBuffer)(buffer_handle_t _Nonnull buffer,
+ AIMapper_DumpBufferCallback _Nonnull dumpBufferCallback,
+ void* _Null_unspecified context);
+
+ /**
+ * Dump the metadata for all imported buffers in the current process
+ *
+ * The HAL implementation should invoke beginDumpCallback before dumping a buffer's metadata,
+ * followed by N calls to dumpBufferCallback for that buffer's metadata fields. The call
+ * sequence should follow this pseudocode:
+ *
+ * for (auto buffer : gListOfImportedBuffers) {
+ * beginDumpCallback(context);
+ * for (auto metadata : buffer->allMetadata()) {
+ * dumpBufferCallback(context, metadata...);
+ * }
+ * }
+ *
+ * @param beginDumpCallback Signals that a buffer is about to be dumped
+ * @param dumpBufferCallback Callback that will be invoked for each of the metadata fields
+ * @param context A caller-provided context to be passed to beginDumpCallback and
+ * dumpBufferCallback
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the raw handle is invalid.
+ * - `NO_RESOURCES` if the get cannot be fulfilled due to unavailability of
+ * resources.
+ */
+ AIMapper_Error (*_Nonnull dumpAllBuffers)(
+ AIMapper_BeginDumpBufferCallback _Nonnull beginDumpCallback,
+ AIMapper_DumpBufferCallback _Nonnull dumpBufferCallback,
+ void* _Null_unspecified context);
+
+ /**
+ * Returns the region of shared memory associated with the buffer that is
+ * reserved for client use.
+ *
+ * The shared memory may be allocated from any shared memory allocator.
+ * The shared memory must be CPU-accessible and virtually contiguous. The
+ * starting address must be word-aligned.
+ *
+ * This function may only be called after importBuffer() has been called by the
+ * client. The reserved region must remain accessible until freeBuffer() has
+ * been called. After freeBuffer() has been called, the client must not access
+ * the reserved region.
+ *
+ * This reserved memory may be used in future versions of Android to
+ * help clients implement backwards compatible features without requiring
+ * IAllocator/IMapper updates.
+ *
+ * @param buffer Imported buffer handle.
+ * @param outReservedRegion CPU-accessible pointer to the reserved region
+ * @param outReservedSize the size of the reservedRegion that was requested
+ * in the BufferDescriptorInfo.
+ * @return error Error status of the call, which may be
+ * - `NONE` upon success.
+ * - `BAD_BUFFER` if the buffer is invalid.
+ */
+ AIMapper_Error (*_Nonnull getReservedRegion)(buffer_handle_t _Nonnull buffer,
+ void* _Nullable* _Nonnull outReservedRegion,
+ uint64_t* _Nonnull outReservedSize);
+
+} AIMapperV5;
+
+/**
+ * Return value for AIMapper_loadIMapper
+ *
+ * Note: This struct's size is not fixed and callers must never store it by-value as a result.
+ * Only fields up to those covered by `version` are allowed to be accessed.
+ */
+typedef struct AIMapper {
+ alignas(alignof(max_align_t)) AIMapper_Version version;
+ AIMapperV5 v5;
+} AIMapper;
+
+/**
+ * Loads the vendor-provided implementation of AIMapper
+ * @return Error status of the call.
+ * - `NONE` upon success
+ * - `UNSUPPORTED` if no implementation is available
+ */
+AIMapper_Error AIMapper_loadIMapper(AIMapper* _Nullable* _Nonnull outImplementation);
+
+__END_DECLS
\ No newline at end of file
diff --git a/graphics/mapper/stable-c/vts/VtsHalGraphicsMapperStableC_TargetTest.cpp b/graphics/mapper/stable-c/vts/VtsHalGraphicsMapperStableC_TargetTest.cpp
new file mode 100644
index 0000000..326346c
--- /dev/null
+++ b/graphics/mapper/stable-c/vts/VtsHalGraphicsMapperStableC_TargetTest.cpp
@@ -0,0 +1,1763 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#undef LOG_TAG
+#define LOG_TAG "VtsHalGraphicsMapperStableC_TargetTest"
+
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/graphics/allocator/AllocationError.h>
+#include <aidl/android/hardware/graphics/allocator/AllocationResult.h>
+#include <aidl/android/hardware/graphics/allocator/IAllocator.h>
+#include <aidl/android/hardware/graphics/common/BufferUsage.h>
+#include <aidl/android/hardware/graphics/common/PixelFormat.h>
+#include <aidlcommonsupport/NativeHandle.h>
+#include <android/binder_enums.h>
+#include <android/binder_manager.h>
+#include <android/dlext.h>
+#include <android/hardware/graphics/mapper/IMapper.h>
+#include <android/hardware/graphics/mapper/utils/IMapperMetadataTypes.h>
+#include <gralloctypes/Gralloc4.h>
+#include <hidl/GtestPrinter.h>
+#include <system/graphics.h>
+
+#include <dlfcn.h>
+#include <drm/drm_fourcc.h>
+#include <gtest/gtest.h>
+#include <vndksupport/linker.h>
+#include <initializer_list>
+#include <optional>
+#include <string>
+#include <tuple>
+#include <vector>
+
+using namespace aidl::android::hardware::graphics::allocator;
+using namespace aidl::android::hardware::graphics::common;
+using namespace android;
+using namespace android::hardware;
+using namespace ::android::hardware::graphics::mapper;
+
+typedef AIMapper_Error (*AIMapper_loadIMapperFn)(AIMapper* _Nullable* _Nonnull outImplementation);
+
+inline constexpr BufferUsage operator|(BufferUsage lhs, BufferUsage rhs) {
+ using T = std::underlying_type_t<BufferUsage>;
+ return static_cast<BufferUsage>(static_cast<T>(lhs) | static_cast<T>(rhs));
+}
+
+inline BufferUsage& operator|=(BufferUsage& lhs, BufferUsage rhs) {
+ lhs = lhs | rhs;
+ return lhs;
+}
+
+struct YCbCr {
+ android_ycbcr yCbCr;
+ int64_t horizontalSubSampling;
+ int64_t verticalSubSampling;
+};
+
+constexpr const char* STANDARD_METADATA_NAME =
+ "android.hardware.graphics.common.StandardMetadataType";
+
+static bool isStandardMetadata(AIMapper_MetadataType metadataType) {
+ return strcmp(STANDARD_METADATA_NAME, metadataType.name) == 0;
+}
+
+static std::string toString(const std::vector<StandardMetadataType> types) {
+ std::stringstream buf;
+ buf << "[";
+ for (auto type : types) {
+ buf << toString(type) << ", ";
+ }
+ buf.seekp(-2, buf.cur);
+ buf << "]";
+ return buf.str();
+}
+
+class BufferHandle {
+ AIMapper* mIMapper;
+ buffer_handle_t mHandle = nullptr;
+
+ public:
+ explicit BufferHandle(AIMapper* mapper, native_handle_t* rawHandle) : mIMapper(mapper) {
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mIMapper->v5.importBuffer(rawHandle, &mHandle));
+ }
+
+ explicit BufferHandle(BufferHandle&& other) { *this = std::move(other); }
+
+ BufferHandle& operator=(BufferHandle&& other) noexcept {
+ reset();
+ mIMapper = other.mIMapper;
+ mHandle = other.mHandle;
+ other.mHandle = nullptr;
+ return *this;
+ }
+
+ ~BufferHandle() { reset(); }
+
+ constexpr explicit operator bool() const noexcept { return mHandle != nullptr; }
+
+ buffer_handle_t operator*() const noexcept { return mHandle; }
+
+ void reset() {
+ if (mHandle != nullptr) {
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mIMapper->v5.freeBuffer(mHandle));
+ mHandle = nullptr;
+ }
+ }
+};
+
+class BufferAllocation {
+ AIMapper* mIMapper;
+ native_handle_t* mRawHandle;
+ uint32_t mStride;
+ const BufferDescriptorInfo mInfo;
+
+ public:
+ BufferAllocation(const BufferAllocation&) = delete;
+ void operator=(const BufferAllocation&) = delete;
+
+ BufferAllocation(AIMapper* mapper, native_handle_t* handle, uint32_t stride,
+ const BufferDescriptorInfo& info)
+ : mIMapper(mapper), mRawHandle(handle), mStride(stride), mInfo(info) {}
+
+ ~BufferAllocation() {
+ if (mRawHandle == nullptr) return;
+
+ native_handle_close(mRawHandle);
+ native_handle_delete(mRawHandle);
+ }
+
+ uint32_t stride() const { return mStride; }
+ const BufferDescriptorInfo& info() const { return mInfo; }
+
+ BufferHandle import() { return BufferHandle{mIMapper, mRawHandle}; }
+
+ const native_handle_t* rawHandle() const { return mRawHandle; }
+};
+
+class GraphicsTestsBase {
+ private:
+ friend class BufferAllocation;
+ int32_t mIAllocatorVersion = 1;
+ std::shared_ptr<IAllocator> mAllocator;
+ AIMapper* mIMapper = nullptr;
+ AIMapper_loadIMapperFn mIMapperLoader;
+
+ protected:
+ void Initialize(std::shared_ptr<IAllocator> allocator) {
+ mAllocator = allocator;
+ ASSERT_NE(nullptr, mAllocator.get()) << "failed to get allocator service";
+ ASSERT_TRUE(mAllocator->getInterfaceVersion(&mIAllocatorVersion).isOk());
+ ASSERT_GE(mIAllocatorVersion, 2);
+ std::string mapperSuffix;
+ auto status = mAllocator->getIMapperLibrarySuffix(&mapperSuffix);
+ ASSERT_TRUE(status.isOk()) << "Failed to get IMapper library suffix";
+ std::string lib_name = "mapper." + mapperSuffix + ".so";
+ void* so = android_load_sphal_library(lib_name.c_str(), RTLD_LOCAL | RTLD_NOW);
+ ASSERT_NE(nullptr, so) << "Failed to load " << lib_name;
+ mIMapperLoader = (AIMapper_loadIMapperFn)dlsym(so, "AIMapper_loadIMapper");
+ ASSERT_NE(nullptr, mIMapperLoader) << "AIMapper_locaIMapper missing from " << lib_name;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mIMapperLoader(&mIMapper));
+ ASSERT_NE(mIMapper, nullptr);
+ }
+
+ public:
+ AIMapper_loadIMapperFn getIMapperLoader() const { return mIMapperLoader; }
+
+ std::unique_ptr<BufferAllocation> allocate(const BufferDescriptorInfo& descriptorInfo) {
+ AllocationResult result;
+ ::ndk::ScopedAStatus status = mAllocator->allocate2(descriptorInfo, 1, &result);
+ if (!status.isOk()) {
+ status_t error = status.getExceptionCode();
+ if (error == EX_SERVICE_SPECIFIC) {
+ error = status.getServiceSpecificError();
+ EXPECT_NE(OK, error) << "Failed to set error properly";
+ } else {
+ EXPECT_EQ(OK, error) << "Allocation transport failure";
+ }
+ return nullptr;
+ } else {
+ return std::make_unique<BufferAllocation>(mIMapper, dupFromAidl(result.buffers[0]),
+ result.stride, descriptorInfo);
+ }
+ }
+
+ std::unique_ptr<BufferAllocation> allocateGeneric() {
+ return allocate({
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ }
+
+ bool isSupported(const BufferDescriptorInfo& descriptorInfo) {
+ bool ret = false;
+ EXPECT_TRUE(mAllocator->isSupported(descriptorInfo, &ret).isOk());
+ return ret;
+ }
+
+ AIMapper* mapper() const { return mIMapper; }
+
+ template <StandardMetadataType T>
+ auto getStandardMetadata(buffer_handle_t bufferHandle)
+ -> decltype(StandardMetadata<T>::value::decode(nullptr, 0)) {
+ using Value = typename StandardMetadata<T>::value;
+ std::vector<uint8_t> buffer;
+ // Initial guess
+ buffer.resize(512);
+ int32_t sizeRequired = mapper()->v5.getStandardMetadata(
+ bufferHandle, static_cast<int64_t>(T), buffer.data(), buffer.size());
+ if (sizeRequired < 0) {
+ EXPECT_EQ(-AIMAPPER_ERROR_UNSUPPORTED, sizeRequired)
+ << "Received something other than UNSUPPORTED from valid getStandardMetadata "
+ "call";
+ return std::nullopt;
+ }
+ if (sizeRequired > buffer.size()) {
+ buffer.resize(sizeRequired);
+ sizeRequired = mapper()->v5.getStandardMetadata(bufferHandle, static_cast<int64_t>(T),
+ buffer.data(), buffer.size());
+ }
+ if (sizeRequired < 0 || sizeRequired >= buffer.size()) {
+ ADD_FAILURE() << "getStandardMetadata failed, received " << sizeRequired
+ << " with buffer size " << buffer.size();
+ // Generate a fail type
+ return std::nullopt;
+ }
+ return Value::decode(buffer.data(), sizeRequired);
+ }
+
+ template <StandardMetadataType T>
+ AIMapper_Error setStandardMetadata(buffer_handle_t bufferHandle,
+ const typename StandardMetadata<T>::value_type& value) {
+ using Value = typename StandardMetadata<T>::value;
+ int32_t sizeRequired = Value::encode(value, nullptr, 0);
+ if (sizeRequired < 0) {
+ EXPECT_GE(sizeRequired, 0) << "Failed to calculate required size";
+ return static_cast<AIMapper_Error>(-sizeRequired);
+ }
+ std::vector<uint8_t> buffer;
+ buffer.resize(sizeRequired);
+ sizeRequired = Value::encode(value, buffer.data(), buffer.size());
+ if (sizeRequired < 0 || sizeRequired > buffer.size()) {
+ ADD_FAILURE() << "Failed to encode with calculated size " << sizeRequired
+ << "; buffer size" << buffer.size();
+ return static_cast<AIMapper_Error>(-sizeRequired);
+ }
+ return mapper()->v5.setStandardMetadata(bufferHandle, static_cast<int64_t>(T),
+ buffer.data(), sizeRequired);
+ }
+
+ void verifyRGBA8888PlaneLayouts(const std::vector<PlaneLayout>& planeLayouts) {
+ ASSERT_EQ(1, planeLayouts.size());
+
+ const auto& planeLayout = planeLayouts.front();
+
+ ASSERT_EQ(4, planeLayout.components.size());
+
+ int64_t offsetInBitsR = -1;
+ int64_t offsetInBitsG = -1;
+ int64_t offsetInBitsB = -1;
+ int64_t offsetInBitsA = -1;
+
+ for (const auto& component : planeLayout.components) {
+ if (!gralloc4::isStandardPlaneLayoutComponentType(component.type)) {
+ continue;
+ }
+ EXPECT_EQ(8, component.sizeInBits);
+ if (component.type.value == gralloc4::PlaneLayoutComponentType_R.value) {
+ offsetInBitsR = component.offsetInBits;
+ }
+ if (component.type.value == gralloc4::PlaneLayoutComponentType_G.value) {
+ offsetInBitsG = component.offsetInBits;
+ }
+ if (component.type.value == gralloc4::PlaneLayoutComponentType_B.value) {
+ offsetInBitsB = component.offsetInBits;
+ }
+ if (component.type.value == gralloc4::PlaneLayoutComponentType_A.value) {
+ offsetInBitsA = component.offsetInBits;
+ }
+ }
+
+ EXPECT_EQ(0, offsetInBitsR);
+ EXPECT_EQ(8, offsetInBitsG);
+ EXPECT_EQ(16, offsetInBitsB);
+ EXPECT_EQ(24, offsetInBitsA);
+
+ EXPECT_EQ(0, planeLayout.offsetInBytes);
+ EXPECT_EQ(32, planeLayout.sampleIncrementInBits);
+ // Skip testing stride because any stride is valid
+ EXPECT_LE(planeLayout.widthInSamples * planeLayout.heightInSamples * 4,
+ planeLayout.totalSizeInBytes);
+ EXPECT_EQ(1, planeLayout.horizontalSubsampling);
+ EXPECT_EQ(1, planeLayout.verticalSubsampling);
+ }
+
+ void fillRGBA8888(uint8_t* data, uint32_t height, size_t strideInBytes, size_t widthInBytes) {
+ for (uint32_t y = 0; y < height; y++) {
+ memset(data, y, widthInBytes);
+ data += strideInBytes;
+ }
+ }
+
+ void verifyRGBA8888(const buffer_handle_t bufferHandle, const uint8_t* data, uint32_t height,
+ size_t strideInBytes, size_t widthInBytes) {
+ auto decodeResult = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(bufferHandle);
+ ASSERT_TRUE(decodeResult.has_value());
+ const auto& planeLayouts = *decodeResult;
+ ASSERT_TRUE(planeLayouts.size() > 0);
+
+ verifyRGBA8888PlaneLayouts(planeLayouts);
+
+ for (uint32_t y = 0; y < height; y++) {
+ for (size_t i = 0; i < widthInBytes; i++) {
+ EXPECT_EQ(static_cast<uint8_t>(y), data[i]);
+ }
+ data += strideInBytes;
+ }
+ }
+
+ void traverseYCbCrData(const android_ycbcr& yCbCr, int32_t width, int32_t height,
+ int64_t hSubsampling, int64_t vSubsampling,
+ std::function<void(uint8_t*, uint8_t)> traverseFuncion) {
+ auto yData = static_cast<uint8_t*>(yCbCr.y);
+ auto cbData = static_cast<uint8_t*>(yCbCr.cb);
+ auto crData = static_cast<uint8_t*>(yCbCr.cr);
+ auto yStride = yCbCr.ystride;
+ auto cStride = yCbCr.cstride;
+ auto chromaStep = yCbCr.chroma_step;
+
+ for (uint32_t y = 0; y < height; y++) {
+ for (uint32_t x = 0; x < width; x++) {
+ auto val = static_cast<uint8_t>(height * y + x);
+
+ traverseFuncion(yData + yStride * y + x, val);
+
+ if (y % vSubsampling == 0 && x % hSubsampling == 0) {
+ uint32_t subSampleX = x / hSubsampling;
+ uint32_t subSampleY = y / vSubsampling;
+ const auto subSampleOffset = cStride * subSampleY + chromaStep * subSampleX;
+ const auto subSampleVal =
+ static_cast<uint8_t>(height * subSampleY + subSampleX);
+
+ traverseFuncion(cbData + subSampleOffset, subSampleVal);
+ traverseFuncion(crData + subSampleOffset, subSampleVal + 1);
+ }
+ }
+ }
+ }
+
+ void fillYCbCrData(const android_ycbcr& yCbCr, int32_t width, int32_t height,
+ int64_t hSubsampling, int64_t vSubsampling) {
+ traverseYCbCrData(yCbCr, width, height, hSubsampling, vSubsampling,
+ [](auto address, auto fillingData) { *address = fillingData; });
+ }
+
+ void verifyYCbCrData(const android_ycbcr& yCbCr, int32_t width, int32_t height,
+ int64_t hSubsampling, int64_t vSubsampling) {
+ traverseYCbCrData(
+ yCbCr, width, height, hSubsampling, vSubsampling,
+ [](auto address, auto expectedData) { EXPECT_EQ(*address, expectedData); });
+ }
+
+ constexpr uint64_t bitsToBytes(int64_t bits) { return bits / 8; }
+ constexpr uint64_t bytesToBits(int64_t bytes) { return bytes * 8; }
+
+ void getAndroidYCbCr(buffer_handle_t bufferHandle, uint8_t* data, android_ycbcr* outYCbCr,
+ int64_t* hSubsampling, int64_t* vSubsampling) {
+ auto decodeResult = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(bufferHandle);
+ ASSERT_TRUE(decodeResult.has_value());
+ const auto& planeLayouts = *decodeResult;
+ ASSERT_TRUE(planeLayouts.size() > 0);
+
+ outYCbCr->y = nullptr;
+ outYCbCr->cb = nullptr;
+ outYCbCr->cr = nullptr;
+ outYCbCr->ystride = 0;
+ outYCbCr->cstride = 0;
+ outYCbCr->chroma_step = 0;
+
+ for (const auto& planeLayout : planeLayouts) {
+ for (const auto& planeLayoutComponent : planeLayout.components) {
+ if (!gralloc4::isStandardPlaneLayoutComponentType(planeLayoutComponent.type)) {
+ continue;
+ }
+ ASSERT_EQ(0, planeLayoutComponent.offsetInBits % 8);
+
+ uint8_t* tmpData = data + planeLayout.offsetInBytes +
+ bitsToBytes(planeLayoutComponent.offsetInBits);
+ uint64_t sampleIncrementInBytes;
+
+ auto type = static_cast<PlaneLayoutComponentType>(planeLayoutComponent.type.value);
+ switch (type) {
+ case PlaneLayoutComponentType::Y:
+ ASSERT_EQ(nullptr, outYCbCr->y);
+ ASSERT_EQ(8, planeLayoutComponent.sizeInBits);
+ ASSERT_EQ(8, planeLayout.sampleIncrementInBits);
+ outYCbCr->y = tmpData;
+ outYCbCr->ystride = planeLayout.strideInBytes;
+ break;
+
+ case PlaneLayoutComponentType::CB:
+ case PlaneLayoutComponentType::CR:
+ ASSERT_EQ(0, planeLayout.sampleIncrementInBits % 8);
+
+ sampleIncrementInBytes = planeLayout.sampleIncrementInBits / 8;
+ ASSERT_TRUE(sampleIncrementInBytes == 1 || sampleIncrementInBytes == 2);
+
+ if (outYCbCr->cstride == 0 && outYCbCr->chroma_step == 0) {
+ outYCbCr->cstride = planeLayout.strideInBytes;
+ outYCbCr->chroma_step = sampleIncrementInBytes;
+ } else {
+ ASSERT_EQ(outYCbCr->cstride, planeLayout.strideInBytes);
+ ASSERT_EQ(outYCbCr->chroma_step, sampleIncrementInBytes);
+ }
+
+ if (*hSubsampling == 0 && *vSubsampling == 0) {
+ *hSubsampling = planeLayout.horizontalSubsampling;
+ *vSubsampling = planeLayout.verticalSubsampling;
+ } else {
+ ASSERT_EQ(*hSubsampling, planeLayout.horizontalSubsampling);
+ ASSERT_EQ(*vSubsampling, planeLayout.verticalSubsampling);
+ }
+
+ if (type == PlaneLayoutComponentType::CB) {
+ ASSERT_EQ(nullptr, outYCbCr->cb);
+ outYCbCr->cb = tmpData;
+ } else {
+ ASSERT_EQ(nullptr, outYCbCr->cr);
+ outYCbCr->cr = tmpData;
+ }
+ break;
+ default:
+ break;
+ };
+ }
+ }
+
+ ASSERT_NE(nullptr, outYCbCr->y);
+ ASSERT_NE(nullptr, outYCbCr->cb);
+ ASSERT_NE(nullptr, outYCbCr->cr);
+ }
+
+ YCbCr getAndroidYCbCr_P010(const native_handle_t* bufferHandle, uint8_t* data) {
+ YCbCr yCbCr_P010;
+ auto decodeResult = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(bufferHandle);
+ if (!decodeResult.has_value()) {
+ ADD_FAILURE() << "failed to get plane layout";
+ return YCbCr{};
+ }
+ const auto& planeLayouts = *decodeResult;
+ EXPECT_EQ(2, planeLayouts.size());
+ EXPECT_EQ(1, planeLayouts[0].components.size());
+ EXPECT_EQ(2, planeLayouts[1].components.size());
+
+ yCbCr_P010.yCbCr.y = nullptr;
+ yCbCr_P010.yCbCr.cb = nullptr;
+ yCbCr_P010.yCbCr.cr = nullptr;
+ yCbCr_P010.yCbCr.ystride = 0;
+ yCbCr_P010.yCbCr.cstride = 0;
+ yCbCr_P010.yCbCr.chroma_step = 0;
+ int64_t cb_offset = 0;
+ int64_t cr_offset = 0;
+
+ for (const auto& planeLayout : planeLayouts) {
+ for (const auto& planeLayoutComponent : planeLayout.components) {
+ if (!gralloc4::isStandardPlaneLayoutComponentType(planeLayoutComponent.type)) {
+ continue;
+ }
+
+ uint8_t* tmpData = data + planeLayout.offsetInBytes +
+ bitsToBytes(planeLayoutComponent.offsetInBits);
+ uint64_t sampleIncrementInBytes = 0;
+ auto type = static_cast<PlaneLayoutComponentType>(planeLayoutComponent.type.value);
+ switch (type) {
+ case PlaneLayoutComponentType::Y:
+ // For specs refer:
+ // https://docs.microsoft.com/en-us/windows/win32/medfound/10-bit-and-16-bit-yuv-video-formats
+ EXPECT_EQ(6, planeLayoutComponent.offsetInBits);
+ EXPECT_EQ(nullptr, yCbCr_P010.yCbCr.y);
+ EXPECT_EQ(10, planeLayoutComponent.sizeInBits);
+ EXPECT_EQ(16, planeLayout.sampleIncrementInBits);
+
+ yCbCr_P010.yCbCr.y = tmpData;
+ yCbCr_P010.yCbCr.ystride = planeLayout.strideInBytes;
+ break;
+
+ case PlaneLayoutComponentType::CB:
+ case PlaneLayoutComponentType::CR:
+ sampleIncrementInBytes = bitsToBytes(planeLayout.sampleIncrementInBits);
+ EXPECT_EQ(4, sampleIncrementInBytes);
+
+ if (yCbCr_P010.yCbCr.cstride == 0 && yCbCr_P010.yCbCr.chroma_step == 0) {
+ yCbCr_P010.yCbCr.cstride = planeLayout.strideInBytes;
+ yCbCr_P010.yCbCr.chroma_step = sampleIncrementInBytes;
+ } else {
+ EXPECT_EQ(yCbCr_P010.yCbCr.cstride, planeLayout.strideInBytes);
+ EXPECT_EQ(yCbCr_P010.yCbCr.chroma_step, sampleIncrementInBytes);
+ }
+
+ if (yCbCr_P010.horizontalSubSampling == 0 &&
+ yCbCr_P010.verticalSubSampling == 0) {
+ yCbCr_P010.horizontalSubSampling = planeLayout.horizontalSubsampling;
+ yCbCr_P010.verticalSubSampling = planeLayout.verticalSubsampling;
+ } else {
+ EXPECT_EQ(yCbCr_P010.horizontalSubSampling,
+ planeLayout.horizontalSubsampling);
+ EXPECT_EQ(yCbCr_P010.verticalSubSampling,
+ planeLayout.verticalSubsampling);
+ }
+
+ if (type == PlaneLayoutComponentType::CB) {
+ EXPECT_EQ(nullptr, yCbCr_P010.yCbCr.cb);
+ yCbCr_P010.yCbCr.cb = tmpData;
+ cb_offset = planeLayoutComponent.offsetInBits;
+ } else {
+ EXPECT_EQ(nullptr, yCbCr_P010.yCbCr.cr);
+ yCbCr_P010.yCbCr.cr = tmpData;
+ cr_offset = planeLayoutComponent.offsetInBits;
+ }
+ break;
+ default:
+ break;
+ };
+ }
+ }
+
+ EXPECT_EQ(cb_offset + bytesToBits(2), cr_offset);
+ EXPECT_NE(nullptr, yCbCr_P010.yCbCr.y);
+ EXPECT_NE(nullptr, yCbCr_P010.yCbCr.cb);
+ EXPECT_NE(nullptr, yCbCr_P010.yCbCr.cr);
+ return yCbCr_P010;
+ }
+};
+
+class GraphicsMapperStableCTests
+ : public GraphicsTestsBase,
+ public ::testing::TestWithParam<std::tuple<std::string, std::shared_ptr<IAllocator>>> {
+ public:
+ void SetUp() override { Initialize(std::get<1>(GetParam())); }
+
+ void TearDown() override {}
+};
+
+TEST_P(GraphicsMapperStableCTests, AllV5CallbacksDefined) {
+ ASSERT_GE(mapper()->version, AIMAPPER_VERSION_5);
+
+ EXPECT_TRUE(mapper()->v5.importBuffer);
+ EXPECT_TRUE(mapper()->v5.freeBuffer);
+ EXPECT_TRUE(mapper()->v5.getTransportSize);
+ EXPECT_TRUE(mapper()->v5.lock);
+ EXPECT_TRUE(mapper()->v5.unlock);
+ EXPECT_TRUE(mapper()->v5.flushLockedBuffer);
+ EXPECT_TRUE(mapper()->v5.rereadLockedBuffer);
+ EXPECT_TRUE(mapper()->v5.getMetadata);
+ EXPECT_TRUE(mapper()->v5.getStandardMetadata);
+ EXPECT_TRUE(mapper()->v5.setMetadata);
+ EXPECT_TRUE(mapper()->v5.setStandardMetadata);
+ EXPECT_TRUE(mapper()->v5.listSupportedMetadataTypes);
+ EXPECT_TRUE(mapper()->v5.dumpBuffer);
+ EXPECT_TRUE(mapper()->v5.getReservedRegion);
+}
+
+TEST_P(GraphicsMapperStableCTests, DualLoadIsIdentical) {
+ ASSERT_GE(mapper()->version, AIMAPPER_VERSION_5);
+ AIMapper* secondMapper;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, getIMapperLoader()(&secondMapper));
+
+ EXPECT_EQ(secondMapper->v5.importBuffer, mapper()->v5.importBuffer);
+ EXPECT_EQ(secondMapper->v5.freeBuffer, mapper()->v5.freeBuffer);
+ EXPECT_EQ(secondMapper->v5.getTransportSize, mapper()->v5.getTransportSize);
+ EXPECT_EQ(secondMapper->v5.lock, mapper()->v5.lock);
+ EXPECT_EQ(secondMapper->v5.unlock, mapper()->v5.unlock);
+ EXPECT_EQ(secondMapper->v5.flushLockedBuffer, mapper()->v5.flushLockedBuffer);
+ EXPECT_EQ(secondMapper->v5.rereadLockedBuffer, mapper()->v5.rereadLockedBuffer);
+ EXPECT_EQ(secondMapper->v5.getMetadata, mapper()->v5.getMetadata);
+ EXPECT_EQ(secondMapper->v5.getStandardMetadata, mapper()->v5.getStandardMetadata);
+ EXPECT_EQ(secondMapper->v5.setMetadata, mapper()->v5.setMetadata);
+ EXPECT_EQ(secondMapper->v5.setStandardMetadata, mapper()->v5.setStandardMetadata);
+ EXPECT_EQ(secondMapper->v5.listSupportedMetadataTypes, mapper()->v5.listSupportedMetadataTypes);
+ EXPECT_EQ(secondMapper->v5.dumpBuffer, mapper()->v5.dumpBuffer);
+ EXPECT_EQ(secondMapper->v5.getReservedRegion, mapper()->v5.getReservedRegion);
+}
+
+TEST_P(GraphicsMapperStableCTests, CanAllocate) {
+ auto buffer = allocate({
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ ASSERT_NE(nullptr, buffer.get());
+ EXPECT_GE(buffer->stride(), 64);
+}
+
+TEST_P(GraphicsMapperStableCTests, ImportFreeBuffer) {
+ auto buffer = allocate({
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ ASSERT_NE(nullptr, buffer.get());
+ EXPECT_GE(buffer->stride(), 64);
+
+ {
+ auto import1 = buffer->import();
+ auto import2 = buffer->import();
+ EXPECT_TRUE(import1);
+ EXPECT_TRUE(import2);
+ EXPECT_NE(*import1, *import2);
+ }
+}
+
+/**
+ * Test IMapper::importBuffer and IMapper::freeBuffer cross mapper instances.
+ */
+TEST_P(GraphicsMapperStableCTests, ImportFreeBufferSingleton) {
+ auto buffer = allocate({
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ ASSERT_NE(nullptr, buffer.get());
+ EXPECT_GE(buffer->stride(), 64);
+
+ buffer_handle_t bufferHandle = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.importBuffer(buffer->rawHandle(), &bufferHandle));
+ ASSERT_NE(nullptr, bufferHandle);
+
+ AIMapper* secondMapper;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, getIMapperLoader()(&secondMapper));
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, secondMapper->v5.freeBuffer(bufferHandle));
+}
+
+/**
+ * Test IMapper::importBuffer with invalid buffers.
+ */
+TEST_P(GraphicsMapperStableCTests, ImportBufferNegative) {
+ native_handle_t* invalidHandle = nullptr;
+ buffer_handle_t bufferHandle = nullptr;
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.importBuffer(invalidHandle, &bufferHandle))
+ << "importBuffer with nullptr did not fail with BAD_BUFFER";
+
+ invalidHandle = native_handle_create(0, 0);
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.importBuffer(invalidHandle, &bufferHandle))
+ << "importBuffer with invalid handle did not fail with BAD_BUFFER";
+ native_handle_delete(invalidHandle);
+}
+
+/**
+ * Test IMapper::freeBuffer with invalid buffers.
+ */
+TEST_P(GraphicsMapperStableCTests, FreeBufferNegative) {
+ native_handle_t* bufferHandle = nullptr;
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.freeBuffer(bufferHandle))
+ << "freeBuffer with nullptr did not fail with BAD_BUFFER";
+
+ bufferHandle = native_handle_create(0, 0);
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.freeBuffer(bufferHandle))
+ << "freeBuffer with invalid handle did not fail with BAD_BUFFER";
+ native_handle_delete(bufferHandle);
+
+ auto buffer = allocateGeneric();
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.freeBuffer(buffer->rawHandle()))
+ << "freeBuffer with un-imported handle did not fail with BAD_BUFFER";
+}
+
+/**
+ * Test IMapper::lock and IMapper::unlock.
+ */
+TEST_P(GraphicsMapperStableCTests, LockUnlockBasic) {
+ constexpr auto usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN;
+ auto buffer = allocate({
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = usage,
+ .reservedSize = 0,
+ });
+ ASSERT_NE(nullptr, buffer.get());
+
+ // lock buffer for writing
+ const auto& info = buffer->info();
+ const auto stride = buffer->stride();
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.lock(*handle, static_cast<int64_t>(usage), region, -1, (void**)&data));
+
+ // RGBA_8888
+ fillRGBA8888(data, info.height, stride * 4, info.width * 4);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+
+ // lock again for reading
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(usage), region,
+ releaseFence, (void**)&data));
+ releaseFence = -1;
+
+ ASSERT_NO_FATAL_FAILURE(verifyRGBA8888(*handle, data, info.height, stride * 4, info.width * 4));
+
+ releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+/**
+ * Test multiple operations associated with different color formats
+ */
+TEST_P(GraphicsMapperStableCTests, Lock_YCRCB_420_SP) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::YCRCB_420_SP,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ if (!buffer) {
+ ASSERT_FALSE(isSupported(info));
+ GTEST_SUCCEED() << "YCRCB_420_SP format is unsupported";
+ return;
+ }
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ android_ycbcr yCbCr;
+ int64_t hSubsampling = 0;
+ int64_t vSubsampling = 0;
+ ASSERT_NO_FATAL_FAILURE(getAndroidYCbCr(*handle, data, &yCbCr, &hSubsampling, &vSubsampling));
+
+ constexpr uint32_t kCbCrSubSampleFactor = 2;
+ ASSERT_EQ(kCbCrSubSampleFactor, hSubsampling);
+ ASSERT_EQ(kCbCrSubSampleFactor, vSubsampling);
+
+ auto cbData = static_cast<uint8_t*>(yCbCr.cb);
+ auto crData = static_cast<uint8_t*>(yCbCr.cr);
+ ASSERT_EQ(crData + 1, cbData);
+ ASSERT_EQ(2, yCbCr.chroma_step);
+
+ fillYCbCrData(yCbCr, info.width, info.height, hSubsampling, vSubsampling);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+
+ // lock again for reading
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, releaseFence, (void**)&data));
+ releaseFence = -1;
+
+ ASSERT_NO_FATAL_FAILURE(getAndroidYCbCr(*handle, data, &yCbCr, &hSubsampling, &vSubsampling));
+
+ verifyYCbCrData(yCbCr, info.width, info.height, hSubsampling, vSubsampling);
+
+ releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, YV12SubsampleMetadata) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::YV12,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ ASSERT_NE(nullptr, buffer.get());
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ auto decodeResult = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(*handle);
+ ASSERT_TRUE(decodeResult.has_value());
+ const auto& planeLayouts = *decodeResult;
+
+ ASSERT_EQ(3, planeLayouts.size());
+
+ auto yPlane = planeLayouts[0];
+ auto crPlane = planeLayouts[1];
+ auto cbPlane = planeLayouts[2];
+
+ constexpr uint32_t kCbCrSubSampleFactor = 2;
+ EXPECT_EQ(kCbCrSubSampleFactor, crPlane.horizontalSubsampling);
+ EXPECT_EQ(kCbCrSubSampleFactor, crPlane.verticalSubsampling);
+
+ EXPECT_EQ(kCbCrSubSampleFactor, cbPlane.horizontalSubsampling);
+ EXPECT_EQ(kCbCrSubSampleFactor, cbPlane.verticalSubsampling);
+
+ const long chromaSampleWidth = info.width / kCbCrSubSampleFactor;
+ const long chromaSampleHeight = info.height / kCbCrSubSampleFactor;
+
+ EXPECT_EQ(info.width, yPlane.widthInSamples);
+ EXPECT_EQ(info.height, yPlane.heightInSamples);
+
+ EXPECT_EQ(chromaSampleWidth, crPlane.widthInSamples);
+ EXPECT_EQ(chromaSampleHeight, crPlane.heightInSamples);
+
+ EXPECT_EQ(chromaSampleWidth, cbPlane.widthInSamples);
+ EXPECT_EQ(chromaSampleHeight, cbPlane.heightInSamples);
+
+ EXPECT_LE(crPlane.widthInSamples, crPlane.strideInBytes);
+ EXPECT_LE(cbPlane.widthInSamples, cbPlane.strideInBytes);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, Lock_YV12) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::YV12,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ ASSERT_NE(nullptr, buffer.get());
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ android_ycbcr yCbCr;
+ int64_t hSubsampling = 0;
+ int64_t vSubsampling = 0;
+ ASSERT_NO_FATAL_FAILURE(getAndroidYCbCr(*handle, data, &yCbCr, &hSubsampling, &vSubsampling));
+
+ constexpr uint32_t kCbCrSubSampleFactor = 2;
+ ASSERT_EQ(kCbCrSubSampleFactor, hSubsampling);
+ ASSERT_EQ(kCbCrSubSampleFactor, vSubsampling);
+
+ auto cbData = static_cast<uint8_t*>(yCbCr.cb);
+ auto crData = static_cast<uint8_t*>(yCbCr.cr);
+ ASSERT_EQ(crData + yCbCr.cstride * info.height / vSubsampling, cbData);
+ ASSERT_EQ(1, yCbCr.chroma_step);
+
+ fillYCbCrData(yCbCr, info.width, info.height, hSubsampling, vSubsampling);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+
+ // lock again for reading
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, releaseFence, (void**)&data));
+ releaseFence = -1;
+
+ ASSERT_NO_FATAL_FAILURE(getAndroidYCbCr(*handle, data, &yCbCr, &hSubsampling, &vSubsampling));
+
+ verifyYCbCrData(yCbCr, info.width, info.height, hSubsampling, vSubsampling);
+
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, Lock_YCBCR_420_888) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::YCBCR_420_888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ ASSERT_NE(nullptr, buffer.get());
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ android_ycbcr yCbCr;
+ int64_t hSubsampling = 0;
+ int64_t vSubsampling = 0;
+ ASSERT_NO_FATAL_FAILURE(getAndroidYCbCr(*handle, data, &yCbCr, &hSubsampling, &vSubsampling));
+
+ constexpr uint32_t kCbCrSubSampleFactor = 2;
+ ASSERT_EQ(kCbCrSubSampleFactor, hSubsampling);
+ ASSERT_EQ(kCbCrSubSampleFactor, vSubsampling);
+
+ fillYCbCrData(yCbCr, info.width, info.height, hSubsampling, vSubsampling);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+
+ // lock again for reading
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, releaseFence, (void**)&data));
+ releaseFence = -1;
+
+ ASSERT_NO_FATAL_FAILURE(getAndroidYCbCr(*handle, data, &yCbCr, &hSubsampling, &vSubsampling));
+
+ verifyYCbCrData(yCbCr, info.width, info.height, hSubsampling, vSubsampling);
+
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, Lock_RAW10) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RAW10,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ if (!buffer) {
+ ASSERT_FALSE(isSupported(info));
+ GTEST_SUCCEED() << "RAW10 format is unsupported";
+ return;
+ }
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ auto decodeResult = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(*handle);
+ ASSERT_TRUE(decodeResult.has_value());
+ const auto& planeLayouts = *decodeResult;
+
+ ASSERT_EQ(1, planeLayouts.size());
+ auto planeLayout = planeLayouts[0];
+
+ EXPECT_EQ(0, planeLayout.sampleIncrementInBits);
+ EXPECT_EQ(1, planeLayout.horizontalSubsampling);
+ EXPECT_EQ(1, planeLayout.verticalSubsampling);
+
+ ASSERT_EQ(1, planeLayout.components.size());
+ auto planeLayoutComponent = planeLayout.components[0];
+
+ EXPECT_EQ(PlaneLayoutComponentType::RAW,
+ static_cast<PlaneLayoutComponentType>(planeLayoutComponent.type.value));
+ EXPECT_EQ(0, planeLayoutComponent.offsetInBits % 8);
+ EXPECT_EQ(-1, planeLayoutComponent.sizeInBits);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, Lock_RAW12) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RAW12,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ if (!buffer) {
+ ASSERT_FALSE(isSupported(info));
+ GTEST_SUCCEED() << "RAW12 format is unsupported";
+ return;
+ }
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ auto decodeResult = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(*handle);
+ ASSERT_TRUE(decodeResult.has_value());
+ const auto& planeLayouts = *decodeResult;
+
+ ASSERT_EQ(1, planeLayouts.size());
+ auto planeLayout = planeLayouts[0];
+
+ EXPECT_EQ(0, planeLayout.sampleIncrementInBits);
+ EXPECT_EQ(1, planeLayout.horizontalSubsampling);
+ EXPECT_EQ(1, planeLayout.verticalSubsampling);
+
+ ASSERT_EQ(1, planeLayout.components.size());
+ auto planeLayoutComponent = planeLayout.components[0];
+
+ EXPECT_EQ(PlaneLayoutComponentType::RAW,
+ static_cast<PlaneLayoutComponentType>(planeLayoutComponent.type.value));
+ EXPECT_EQ(0, planeLayoutComponent.offsetInBits % 8);
+ EXPECT_EQ(-1, planeLayoutComponent.sizeInBits);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, Lock_YCBCR_P010) {
+ BufferDescriptorInfo info{
+ .name = {"VTS_TEMP"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::YCBCR_P010,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ if (!buffer) {
+ ASSERT_FALSE(isSupported(info));
+ GTEST_SUCCEED() << "YCBCR_P010 format is unsupported";
+ return;
+ }
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width, info.height};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+
+ YCbCr yCbCr;
+ ASSERT_NO_FATAL_FAILURE(yCbCr = getAndroidYCbCr_P010(*handle, data));
+
+ constexpr uint32_t kCbCrSubSampleFactor = 2;
+ ASSERT_EQ(kCbCrSubSampleFactor, yCbCr.horizontalSubSampling);
+ ASSERT_EQ(kCbCrSubSampleFactor, yCbCr.verticalSubSampling);
+
+ ASSERT_EQ(0, info.height % 2);
+
+ // fill the data
+ fillYCbCrData(yCbCr.yCbCr, info.width, info.height, yCbCr.horizontalSubSampling,
+ yCbCr.verticalSubSampling);
+ // verify the YCbCr data
+ verifyYCbCrData(yCbCr.yCbCr, info.width, info.height, yCbCr.horizontalSubSampling,
+ yCbCr.verticalSubSampling);
+
+ int releaseFence = -1;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, LockBadAccessRegion) {
+ auto buffer = allocateGeneric();
+ ASSERT_NE(nullptr, buffer);
+ const auto& info = buffer->info();
+
+ // lock buffer for writing
+ const ARect region{0, 0, info.width * 2, info.height * 2};
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_VALUE, mapper()->v5.lock(*handle, static_cast<int64_t>(info.usage),
+ region, -1, (void**)&data));
+}
+
+TEST_P(GraphicsMapperStableCTests, UnlockNegative) {
+ native_handle_t* invalidHandle = nullptr;
+ int releaseFence = -1;
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.unlock(invalidHandle, &releaseFence))
+ << "unlock with nullptr did not fail with BAD_BUFFER";
+
+ invalidHandle = native_handle_create(0, 0);
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.unlock(invalidHandle, &releaseFence))
+ << "unlock with invalid handle did not fail with BAD_BUFFER";
+ native_handle_delete(invalidHandle);
+
+ auto buffer = allocateGeneric();
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.unlock(buffer->rawHandle(), &releaseFence))
+ << "unlock with un-imported handle did not fail with BAD_BUFFER";
+}
+
+TEST_P(GraphicsMapperStableCTests, UnlockNotImported) {
+ int releaseFence = -1;
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.unlock(buffer->rawHandle(), &releaseFence))
+ << "unlock with un-imported handle did not fail with BAD_BUFFER";
+}
+
+TEST_P(GraphicsMapperStableCTests, UnlockNotLocked) {
+ int releaseFence = -1;
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.unlock(*bufferHandle, &releaseFence))
+ << "unlock with unlocked handle did not fail with BAD_BUFFER";
+}
+
+TEST_P(GraphicsMapperStableCTests, LockUnlockNested) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ const ARect region{0, 0, buffer->info().width, buffer->info().height};
+ auto usage = static_cast<int64_t>(buffer->info().usage);
+ auto handle = buffer->import();
+ uint8_t* data = nullptr;
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, usage, region, -1, (void**)&data));
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.lock(*handle, usage, region, -1, (void**)&data))
+ << "Second lock failed";
+ int releaseFence = -1;
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ releaseFence = -1;
+ }
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*handle, &releaseFence))
+ << "Second unlock failed";
+ if (releaseFence != -1) {
+ close(releaseFence);
+ releaseFence = -1;
+ }
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.unlock(*handle, &releaseFence))
+ << "Third, unmatched, unlock should have failed with BAD_BUFFER";
+}
+
+TEST_P(GraphicsMapperStableCTests, FlushRereadBasic) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ const auto& info = buffer->info();
+ const auto stride = buffer->stride();
+ const ARect region{0, 0, buffer->info().width, buffer->info().height};
+
+ auto writeHandle = buffer->import();
+ auto readHandle = buffer->import();
+ ASSERT_TRUE(writeHandle && readHandle);
+
+ // lock buffer for writing
+
+ uint8_t* writeData;
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.lock(*writeHandle, static_cast<uint64_t>(BufferUsage::CPU_WRITE_OFTEN),
+ region, -1, (void**)&writeData));
+
+ uint8_t* readData;
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.lock(*readHandle, static_cast<uint64_t>(BufferUsage::CPU_READ_OFTEN),
+ region, -1, (void**)&readData));
+
+ fillRGBA8888(writeData, info.height, stride * 4, info.width * 4);
+
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.flushLockedBuffer(*writeHandle));
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.rereadLockedBuffer(*readHandle));
+
+ ASSERT_NO_FATAL_FAILURE(
+ verifyRGBA8888(*readHandle, readData, info.height, stride * 4, info.width * 4));
+
+ int releaseFence = -1;
+
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*readHandle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ releaseFence = -1;
+ }
+
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, mapper()->v5.unlock(*writeHandle, &releaseFence));
+ if (releaseFence != -1) {
+ close(releaseFence);
+ releaseFence = -1;
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, FlushLockedBufferBadBuffer) {
+ // Amazingly this is enough to make the compiler happy even though flushLockedBuffer
+ // is _Nonnull :shrug:
+ buffer_handle_t badBuffer = nullptr;
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.flushLockedBuffer(badBuffer));
+}
+
+TEST_P(GraphicsMapperStableCTests, RereadLockedBufferBadBuffer) {
+ buffer_handle_t badBuffer = nullptr;
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, mapper()->v5.rereadLockedBuffer(badBuffer));
+}
+
+TEST_P(GraphicsMapperStableCTests, GetBufferId) {
+ auto buffer = allocateGeneric();
+ auto bufferHandle = buffer->import();
+ auto bufferId = getStandardMetadata<StandardMetadataType::BUFFER_ID>(*bufferHandle);
+ ASSERT_TRUE(bufferId.has_value());
+
+ auto buffer2 = allocateGeneric();
+ auto bufferHandle2 = buffer2->import();
+ auto bufferId2 = getStandardMetadata<StandardMetadataType::BUFFER_ID>(*bufferHandle2);
+ ASSERT_TRUE(bufferId2.has_value());
+
+ EXPECT_NE(*bufferId, *bufferId2);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetName) {
+ auto buffer = allocate({
+ .name = {"Hello, World!"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ auto bufferHandle = buffer->import();
+ auto name = getStandardMetadata<StandardMetadataType::NAME>(*bufferHandle);
+ ASSERT_TRUE(name.has_value());
+ EXPECT_EQ(*name, "Hello, World!");
+}
+
+TEST_P(GraphicsMapperStableCTests, GetWidthHeight) {
+ auto buffer = allocate({
+ .name = {"Hello, World!"},
+ .width = 64,
+ .height = 128,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::WIDTH>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, 64);
+ value = getStandardMetadata<StandardMetadataType::HEIGHT>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, 128);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetLayerCount) {
+ auto buffer = allocateGeneric();
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::LAYER_COUNT>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, buffer->info().layerCount);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetPixelFormatRequested) {
+ auto buffer = allocateGeneric();
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_REQUESTED>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, buffer->info().format);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetPixelFormatFourCC) {
+ auto buffer = allocate({
+ .name = {"Hello, World!"},
+ .width = 64,
+ .height = 128,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ {
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_FOURCC>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, DRM_FORMAT_ABGR8888);
+ }
+
+ buffer = allocate({
+ .name = {"yv12"},
+ .width = 64,
+ .height = 128,
+ .layerCount = 1,
+ .format = PixelFormat::YV12,
+ .usage = BufferUsage::CPU_WRITE_OFTEN | BufferUsage::CPU_READ_OFTEN,
+ .reservedSize = 0,
+ });
+ {
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_FOURCC>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, DRM_FORMAT_YVU420);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, GetPixelFormatModifier) {
+ auto buffer = allocateGeneric();
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::PIXEL_FORMAT_MODIFIER>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ // Only the upper 8-bits are defined and is just the vendor ID, the lower 56 bits are
+ // then vendor specific. So there's not anything useful to assert here beyond just that
+ // we successfully queried a value
+}
+
+TEST_P(GraphicsMapperStableCTests, GetUsage) {
+ auto buffer = allocateGeneric();
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::USAGE>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(buffer->info().usage, *value);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetAllocationSize) {
+ auto buffer = allocateGeneric();
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::ALLOCATION_SIZE>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ const auto estimatedSize = buffer->stride() * buffer->info().height * 4;
+ // This buffer has CPU usage, so we expect at least stride * height * 4 since it should be
+ // generally linear uncompressed.
+ EXPECT_GE(*value, estimatedSize)
+ << "Expected allocation size to be at least stride * height * 4bpp";
+ // Might need refining, but hopefully this a generous-enough upper-bound?
+ EXPECT_LT(*value, estimatedSize * 2)
+ << "Expected allocation size to less than double stride * height * 4bpp";
+}
+
+TEST_P(GraphicsMapperStableCTests, GetProtectedContent) {
+ const BufferDescriptorInfo info{
+ .name = {"prot8888"},
+ .width = 64,
+ .height = 64,
+ .layerCount = 1,
+ .format = PixelFormat::RGBA_8888,
+ .usage = BufferUsage::PROTECTED | BufferUsage::COMPOSER_OVERLAY,
+ .reservedSize = 0,
+ };
+ auto buffer = allocate(info);
+ if (!buffer) {
+ ASSERT_FALSE(isSupported(info))
+ << "Allocation of trivial sized buffer failed, so isSupported() must be false";
+ GTEST_SUCCEED() << "PROTECTED RGBA_8888 is unsupported";
+ return;
+ }
+ auto bufferHandle = buffer->import();
+ auto value = getStandardMetadata<StandardMetadataType::PROTECTED_CONTENT>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(*value, 1);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetCompression) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::COMPRESSION>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(gralloc4::Compression_None.name, value->name);
+ EXPECT_EQ(gralloc4::Compression_None.value, value->value);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetInterlaced) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::INTERLACED>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(gralloc4::Interlaced_None.name, value->name);
+ EXPECT_EQ(gralloc4::Interlaced_None.value, value->value);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetChromaSiting) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::CHROMA_SITING>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(gralloc4::ChromaSiting_None.name, value->name);
+ EXPECT_EQ(gralloc4::ChromaSiting_None.value, value->value);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetPlaneLayouts) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::PLANE_LAYOUTS>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ ASSERT_NO_FATAL_FAILURE(verifyRGBA8888PlaneLayouts(*value));
+}
+
+TEST_P(GraphicsMapperStableCTests, GetCrop) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::CROP>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(1, value->size());
+ const Rect expected{0, 0, buffer->info().width, buffer->info().height};
+ EXPECT_EQ(expected, value->at(0));
+}
+
+TEST_P(GraphicsMapperStableCTests, GetSetDataspace) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::DATASPACE>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(Dataspace::UNKNOWN, *value);
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, setStandardMetadata<StandardMetadataType::DATASPACE>(
+ *bufferHandle, Dataspace::DISPLAY_P3));
+ value = getStandardMetadata<StandardMetadataType::DATASPACE>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(Dataspace::DISPLAY_P3, *value);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetSetBlendMode) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::BLEND_MODE>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(BlendMode::INVALID, *value);
+ EXPECT_EQ(AIMAPPER_ERROR_NONE, setStandardMetadata<StandardMetadataType::BLEND_MODE>(
+ *bufferHandle, BlendMode::COVERAGE));
+ value = getStandardMetadata<StandardMetadataType::BLEND_MODE>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_EQ(BlendMode::COVERAGE, *value);
+}
+
+TEST_P(GraphicsMapperStableCTests, GetSetSmpte2086) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::SMPTE2086>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_FALSE(value->has_value());
+
+ // TODO: Maybe use something resembling real values, but validation isn't supposed to happen
+ // here anyway so :shrug:
+ const Smpte2086 awesomeHdr{
+ XyColor{1.f, 1.f}, XyColor{2.f, 2.f}, XyColor{3.f, 3.f},
+ XyColor{400.f, 1000.f}, 100000.0f, 0.0001f,
+ };
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ setStandardMetadata<StandardMetadataType::SMPTE2086>(*bufferHandle, awesomeHdr));
+ value = getStandardMetadata<StandardMetadataType::SMPTE2086>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ ASSERT_TRUE(value->has_value());
+ EXPECT_EQ(awesomeHdr, *value);
+
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ setStandardMetadata<StandardMetadataType::SMPTE2086>(*bufferHandle, std::nullopt));
+ value = getStandardMetadata<StandardMetadataType::SMPTE2086>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_FALSE(value->has_value());
+}
+
+TEST_P(GraphicsMapperStableCTests, GetCta861_3) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::CTA861_3>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_FALSE(value->has_value());
+
+ const Cta861_3 genericHlgish{1000.f, 140.f};
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ setStandardMetadata<StandardMetadataType::CTA861_3>(*bufferHandle, genericHlgish));
+ value = getStandardMetadata<StandardMetadataType::CTA861_3>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ ASSERT_TRUE(value->has_value());
+ EXPECT_EQ(genericHlgish, *value);
+
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ setStandardMetadata<StandardMetadataType::CTA861_3>(*bufferHandle, std::nullopt));
+ value = getStandardMetadata<StandardMetadataType::CTA861_3>(*bufferHandle);
+ ASSERT_TRUE(value.has_value());
+ EXPECT_FALSE(value->has_value());
+}
+
+TEST_P(GraphicsMapperStableCTests, GetSmpte2094_10) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::SMPTE2094_10>(*bufferHandle);
+ if (value.has_value()) {
+ EXPECT_FALSE(value->has_value());
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, GetSmpte2094_40) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ auto value = getStandardMetadata<StandardMetadataType::SMPTE2094_40>(*bufferHandle);
+ if (value.has_value()) {
+ EXPECT_FALSE(value->has_value());
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, SupportsRequiredGettersSetters) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ const AIMapper_MetadataTypeDescription* descriptions = nullptr;
+ size_t descriptionCount = 0;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.listSupportedMetadataTypes(&descriptions, &descriptionCount));
+ std::vector<StandardMetadataType> requiredGetters = {
+ StandardMetadataType::BUFFER_ID,
+ StandardMetadataType::NAME,
+ StandardMetadataType::WIDTH,
+ StandardMetadataType::HEIGHT,
+ StandardMetadataType::LAYER_COUNT,
+ StandardMetadataType::PIXEL_FORMAT_REQUESTED,
+ StandardMetadataType::PIXEL_FORMAT_FOURCC,
+ StandardMetadataType::PIXEL_FORMAT_MODIFIER,
+ StandardMetadataType::USAGE,
+ StandardMetadataType::ALLOCATION_SIZE,
+ StandardMetadataType::PROTECTED_CONTENT,
+ StandardMetadataType::COMPRESSION,
+ StandardMetadataType::INTERLACED,
+ StandardMetadataType::CHROMA_SITING,
+ StandardMetadataType::PLANE_LAYOUTS,
+ StandardMetadataType::CROP,
+ StandardMetadataType::DATASPACE,
+ StandardMetadataType::BLEND_MODE,
+ StandardMetadataType::SMPTE2086,
+ StandardMetadataType::CTA861_3,
+ };
+
+ std::vector<StandardMetadataType> requiredSetters = {
+ StandardMetadataType::DATASPACE,
+ StandardMetadataType::BLEND_MODE,
+ StandardMetadataType::SMPTE2086,
+ StandardMetadataType::CTA861_3,
+ };
+
+ for (int i = 0; i < descriptionCount; i++) {
+ const auto& it = descriptions[i];
+ if (isStandardMetadata(it.metadataType)) {
+ EXPECT_GT(it.metadataType.value, static_cast<int64_t>(StandardMetadataType::INVALID));
+ EXPECT_LT(it.metadataType.value,
+ ndk::internal::enum_values<StandardMetadataType>.size());
+
+ if (it.isGettable) {
+ std::erase(requiredGetters,
+ static_cast<StandardMetadataType>(it.metadataType.value));
+ }
+ if (it.isSettable) {
+ std::erase(requiredSetters,
+ static_cast<StandardMetadataType>(it.metadataType.value));
+ }
+ } else {
+ EXPECT_NE(nullptr, it.description) << "Non-standard metadata must have a description";
+ int len = strlen(it.description);
+ EXPECT_GE(len, 0) << "Non-standard metadata must have a description";
+ }
+ }
+
+ EXPECT_EQ(0, requiredGetters.size()) << "Missing required getters" << toString(requiredGetters);
+ EXPECT_EQ(0, requiredSetters.size()) << "Missing required setters" << toString(requiredSetters);
+}
+
+/*
+ * Test that verifies that if the optional StandardMetadataTypes have getters, they have
+ * the required setters as well
+ */
+TEST_P(GraphicsMapperStableCTests, CheckRequiredSettersIfHasGetters) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ const AIMapper_MetadataTypeDescription* descriptions = nullptr;
+ size_t descriptionCount = 0;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.listSupportedMetadataTypes(&descriptions, &descriptionCount));
+
+ for (int i = 0; i < descriptionCount; i++) {
+ const auto& it = descriptions[i];
+ if (isStandardMetadata(it.metadataType)) {
+ const auto type = static_cast<StandardMetadataType>(it.metadataType.value);
+ switch (type) {
+ case StandardMetadataType::SMPTE2094_10:
+ case StandardMetadataType::SMPTE2094_40:
+ if (it.isGettable) {
+ EXPECT_TRUE(it.isSettable)
+ << "Type " << toString(type) << " must be settable if gettable";
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, ListSupportedWorks) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+ const AIMapper_MetadataTypeDescription* descriptions = nullptr;
+ size_t descriptionCount = 0;
+ ASSERT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.listSupportedMetadataTypes(&descriptions, &descriptionCount));
+
+ std::vector<uint8_t> metadataBuffer;
+ auto get = [&](AIMapper_MetadataType metadataType) -> int32_t {
+ int32_t size = mapper()->v5.getMetadata(*bufferHandle, metadataType, nullptr, 0);
+ if (size >= 0) {
+ metadataBuffer.resize(size);
+ size = mapper()->v5.getMetadata(*bufferHandle, metadataType, metadataBuffer.data(),
+ metadataBuffer.size());
+ EXPECT_EQ(size, metadataBuffer.size());
+ }
+ return size;
+ };
+
+ for (int i = 0; i < descriptionCount; i++) {
+ const auto& it = descriptions[i];
+ if (!isStandardMetadata(it.metadataType)) {
+ continue;
+ }
+ if (!it.isGettable) {
+ EXPECT_FALSE(it.isSettable)
+ << "StandardMetadata that isn't gettable must not be settable";
+ continue;
+ }
+ EXPECT_GE(get(it.metadataType), 0)
+ << "Get failed for claimed supported getter of "
+ << toString(static_cast<StandardMetadataType>(it.metadataType.value));
+ if (it.isSettable) {
+ EXPECT_EQ(AIMAPPER_ERROR_NONE,
+ mapper()->v5.setMetadata(*bufferHandle, it.metadataType,
+ metadataBuffer.data(), metadataBuffer.size()))
+ << "Failed to set metadata for "
+ << toString(static_cast<StandardMetadataType>(it.metadataType.value));
+ }
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, GetMetadataBadValue) {
+ auto get = [this](StandardMetadataType type) -> AIMapper_Error {
+ // This is a _Nonnull parameter, but this is enough obfuscation to fool the linter
+ buffer_handle_t buffer = nullptr;
+ int32_t ret =
+ mapper()->v5.getStandardMetadata(buffer, static_cast<int64_t>(type), nullptr, 0);
+ return (ret < 0) ? (AIMapper_Error)-ret : AIMAPPER_ERROR_NONE;
+ };
+
+ for (auto type : ndk::enum_range<StandardMetadataType>()) {
+ if (type == StandardMetadataType::INVALID) {
+ continue;
+ }
+ EXPECT_EQ(AIMAPPER_ERROR_BAD_BUFFER, get(type)) << "Wrong error for " << toString(type);
+ }
+}
+
+TEST_P(GraphicsMapperStableCTests, GetUnsupportedMetadata) {
+ auto buffer = allocateGeneric();
+ ASSERT_TRUE(buffer);
+ auto bufferHandle = buffer->import();
+ ASSERT_TRUE(bufferHandle);
+
+ int result = mapper()->v5.getMetadata(*bufferHandle, {"Fake", 1}, nullptr, 0);
+ EXPECT_EQ(AIMAPPER_ERROR_UNSUPPORTED, -result);
+
+ result = mapper()->v5.getStandardMetadata(
+ *bufferHandle, static_cast<int64_t>(StandardMetadataType::INVALID), nullptr, 0);
+ EXPECT_EQ(AIMAPPER_ERROR_UNSUPPORTED, -result);
+
+ constexpr int64_t unknownStandardType = ndk::internal::enum_values<StandardMetadataType>.size();
+ result = mapper()->v5.getStandardMetadata(*bufferHandle, unknownStandardType, nullptr, 0);
+ EXPECT_EQ(AIMAPPER_ERROR_UNSUPPORTED, -result);
+}
+
+std::vector<std::tuple<std::string, std::shared_ptr<IAllocator>>> getIAllocatorsAtLeastVersion(
+ int32_t minVersion) {
+ auto instanceNames = getAidlHalInstanceNames(IAllocator::descriptor);
+ std::vector<std::tuple<std::string, std::shared_ptr<IAllocator>>> filteredInstances;
+ filteredInstances.reserve(instanceNames.size());
+ for (const auto& name : instanceNames) {
+ auto allocator =
+ IAllocator::fromBinder(ndk::SpAIBinder(AServiceManager_checkService(name.c_str())));
+ int32_t version = 0;
+ if (allocator->getInterfaceVersion(&version).isOk()) {
+ if (version >= minVersion) {
+ filteredInstances.emplace_back(name, std::move(allocator));
+ }
+ }
+ }
+ return filteredInstances;
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GraphicsMapperStableCTests);
+INSTANTIATE_TEST_CASE_P(PerInstance, GraphicsMapperStableCTests,
+ testing::ValuesIn(getIAllocatorsAtLeastVersion(2)),
+ [](auto info) -> std::string {
+ std::string name =
+ std::to_string(info.index) + "/" + std::get<0>(info.param);
+ return Sanitize(name);
+ });
\ No newline at end of file
diff --git a/identity/aidl/default/EicOpsImpl.cc b/identity/aidl/default/EicOpsImpl.cc
index b6d324f..803df64 100644
--- a/identity/aidl/default/EicOpsImpl.cc
+++ b/identity/aidl/default/EicOpsImpl.cc
@@ -489,7 +489,7 @@
}
bool eicOpsEcdh(const uint8_t publicKey[EIC_P256_PUB_KEY_SIZE],
- const uint8_t privateKey[EIC_P256_PUB_KEY_SIZE],
+ const uint8_t privateKey[EIC_P256_PRIV_KEY_SIZE],
uint8_t sharedSecret[EIC_P256_COORDINATE_SIZE]) {
vector<uint8_t> pubKeyVec(EIC_P256_PUB_KEY_SIZE + 1);
pubKeyVec[0] = 0x04;
diff --git a/media/c2/aidl/Android.bp b/media/c2/aidl/Android.bp
new file mode 100644
index 0000000..10867c0
--- /dev/null
+++ b/media/c2/aidl/Android.bp
@@ -0,0 +1,29 @@
+// This is the expected build file, but it may not be right in all cases
+
+aidl_interface {
+ name: "android.hardware.media.c2",
+ vendor_available: true,
+ srcs: ["android/hardware/media/c2/*.aidl"],
+ include_dirs: [
+ "frameworks/native/aidl/gui",
+ ],
+ imports: [
+ "android.hardware.common-V2",
+ "android.hardware.media.bufferpool2-V1",
+ ],
+ stability: "vintf",
+ backend: {
+ cpp: {
+ enabled: false,
+ },
+ java: {
+ enabled: false,
+ },
+ ndk: {
+ enabled: true,
+ additional_shared_libraries: [
+ "libnativewindow",
+ ],
+ },
+ },
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl
new file mode 100644
index 0000000..460ff97
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/BaseBlock.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+union BaseBlock {
+ android.hardware.common.NativeHandle nativeBlock;
+ android.hardware.media.bufferpool2.BufferStatusMessage pooledBlock;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Block.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Block.aidl
new file mode 100644
index 0000000..7b3005e
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Block.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable Block {
+ int index;
+ android.hardware.media.c2.Params meta;
+ android.hardware.common.NativeHandle fence;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Buffer.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Buffer.aidl
new file mode 100644
index 0000000..b632932
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Buffer.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable Buffer {
+ android.hardware.media.c2.Params info;
+ android.hardware.media.c2.Block[] blocks;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldDescriptor.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldDescriptor.aidl
new file mode 100644
index 0000000..d0e4cbf
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldDescriptor.aidl
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable FieldDescriptor {
+ android.hardware.media.c2.FieldId fieldId;
+ android.hardware.media.c2.FieldDescriptor.Type type;
+ int structIndex;
+ int extent;
+ String name;
+ android.hardware.media.c2.FieldDescriptor.NamedValue[] namedValues;
+ @Backing(type="int") @VintfStability
+ enum Type {
+ NO_INIT = 0,
+ INT32 = 1,
+ UINT32 = 2,
+ CNTR32 = 3,
+ INT64 = 4,
+ UINT64 = 5,
+ CNTR64 = 6,
+ FLOAT = 7,
+ STRING = 256,
+ BLOB = 257,
+ STRUCT = 131072,
+ }
+ @VintfStability
+ parcelable NamedValue {
+ String name;
+ long value;
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldId.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldId.aidl
new file mode 100644
index 0000000..935b85d
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldId.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable FieldId {
+ int offset;
+ int sizeBytes;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValues.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValues.aidl
new file mode 100644
index 0000000..69060be
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValues.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+union FieldSupportedValues {
+ boolean empty;
+ android.hardware.media.c2.ValueRange range;
+ long[] values;
+ long[] flags;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValuesQuery.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValuesQuery.aidl
new file mode 100644
index 0000000..22f7c84
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValuesQuery.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable FieldSupportedValuesQuery {
+ android.hardware.media.c2.ParamField field;
+ android.hardware.media.c2.FieldSupportedValuesQuery.Type type;
+ @Backing(type="int") @VintfStability
+ enum Type {
+ POSSIBLE = 0,
+ CURRENT = 1,
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValuesQueryResult.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValuesQueryResult.aidl
new file mode 100644
index 0000000..187e3eb
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FieldSupportedValuesQueryResult.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable FieldSupportedValuesQueryResult {
+ android.hardware.media.c2.Status status;
+ android.hardware.media.c2.FieldSupportedValues values;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FrameData.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FrameData.aidl
new file mode 100644
index 0000000..e73b05e
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/FrameData.aidl
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable FrameData {
+ int flags;
+ android.hardware.media.c2.WorkOrdinal ordinal;
+ android.hardware.media.c2.Buffer[] buffers;
+ android.hardware.media.c2.Params configUpdate;
+ android.hardware.media.c2.InfoBuffer[] infoBuffers;
+ const int DROP_FRAME = 1;
+ const int END_OF_STREAM = 2;
+ const int DISCARD_FRAME = 4;
+ const int FLAG_INCOMPLETE = 8;
+ const int CODEC_CONFIG = -2147483648;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl
new file mode 100644
index 0000000..7ed09af
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponent.aidl
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IComponent {
+ android.hardware.common.NativeHandle configureVideoTunnel(in int avSyncHwId);
+ android.hardware.media.c2.IComponent.BlockPool createBlockPool(in int allocatorId);
+ void destroyBlockPool(in long blockPoolId);
+ void drain(in boolean withEos);
+ android.hardware.media.c2.WorkBundle flush();
+ android.hardware.media.c2.IComponentInterface getInterface();
+ void queue(in android.hardware.media.c2.WorkBundle workBundle);
+ void release();
+ void reset();
+ void setOutputSurface(in long blockPoolId, in android.view.Surface surface, in android.hardware.media.c2.SurfaceSyncObj syncObject);
+ void start();
+ void stop();
+ parcelable BlockPool {
+ long blockPoolId;
+ android.hardware.media.c2.IConfigurable configurable;
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentInterface.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentInterface.aidl
new file mode 100644
index 0000000..2350dae
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentInterface.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IComponentInterface {
+ android.hardware.media.c2.IConfigurable getConfigurable();
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentListener.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentListener.aidl
new file mode 100644
index 0000000..f6f2a63
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentListener.aidl
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IComponentListener {
+ oneway void onError(in android.hardware.media.c2.Status status, in int errorCode);
+ oneway void onFramesRendered(in android.hardware.media.c2.IComponentListener.RenderedFrame[] renderedFrames);
+ oneway void onInputBuffersReleased(in android.hardware.media.c2.IComponentListener.InputBuffer[] inputBuffers);
+ oneway void onTripped(in android.hardware.media.c2.SettingResult[] settingResults);
+ oneway void onWorkDone(in android.hardware.media.c2.WorkBundle workBundle);
+ @VintfStability
+ parcelable InputBuffer {
+ long frameIndex;
+ int arrayIndex;
+ }
+ @VintfStability
+ parcelable RenderedFrame {
+ long bufferQueueId;
+ int slotId;
+ long timestampNs;
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl
new file mode 100644
index 0000000..35532be
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IComponentStore.aidl
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IComponentStore {
+ void copyBuffer(in android.hardware.media.c2.Buffer src, in android.hardware.media.c2.Buffer dst);
+ android.hardware.media.c2.IComponent createComponent(in String name, in android.hardware.media.c2.IComponentListener listener, in android.hardware.media.bufferpool2.IClientManager pool);
+ android.hardware.media.c2.IComponentInterface createInterface(in String name);
+ android.hardware.media.c2.IConfigurable getConfigurable();
+ android.hardware.media.bufferpool2.IClientManager getPoolClientManager();
+ android.hardware.media.c2.StructDescriptor[] getStructDescriptors(in int[] indices);
+ android.hardware.media.c2.IComponentStore.ComponentTraits[] listComponents();
+ @VintfStability
+ parcelable ComponentTraits {
+ String name;
+ android.hardware.media.c2.IComponentStore.ComponentTraits.Domain domain;
+ android.hardware.media.c2.IComponentStore.ComponentTraits.Kind kind;
+ int rank;
+ String mediaType;
+ String[] aliases;
+ @Backing(type="int") @VintfStability
+ enum Kind {
+ OTHER = 0,
+ DECODER = 1,
+ ENCODER = 2,
+ }
+ @Backing(type="int") @VintfStability
+ enum Domain {
+ OTHER = 0,
+ VIDEO = 1,
+ AUDIO = 2,
+ IMAGE = 3,
+ }
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IConfigurable.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IConfigurable.aidl
new file mode 100644
index 0000000..32f5abd
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/IConfigurable.aidl
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+interface IConfigurable {
+ android.hardware.media.c2.IConfigurable.ConfigResult config(in android.hardware.media.c2.Params inParams, in boolean mayBlock);
+ int getId();
+ String getName();
+ android.hardware.media.c2.Params query(in int[] indices, in boolean mayBlock);
+ android.hardware.media.c2.ParamDescriptor[] querySupportedParams(in int start, in int count);
+ android.hardware.media.c2.FieldSupportedValuesQueryResult[] querySupportedValues(in android.hardware.media.c2.FieldSupportedValuesQuery[] inFields, in boolean mayBlock);
+ @VintfStability
+ parcelable ConfigResult {
+ android.hardware.media.c2.Params params;
+ android.hardware.media.c2.SettingResult[] failures;
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/InfoBuffer.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/InfoBuffer.aidl
new file mode 100644
index 0000000..94cd77d
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/InfoBuffer.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable InfoBuffer {
+ int index;
+ android.hardware.media.c2.Buffer buffer;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamDescriptor.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamDescriptor.aidl
new file mode 100644
index 0000000..04c869c
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamDescriptor.aidl
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable ParamDescriptor {
+ int index;
+ int attrib;
+ String name;
+ int[] dependencies;
+ const int ATTRIBUTE_REQUIRED = 1;
+ const int ATTRIBUTE_PERSISTENT = 2;
+ const int ATTRIBUTE_STRICT = 4;
+ const int ATTRIBUTE_READ_ONLY = 8;
+ const int ATTRIBUTE_HIDDEN = 16;
+ const int ATTRIBUTE_INTERNAL = 32;
+ const int ATTRIBUTE_CONST = 64;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamField.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamField.aidl
new file mode 100644
index 0000000..13d2522
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamField.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable ParamField {
+ int index;
+ android.hardware.media.c2.FieldId fieldId;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamFieldValues.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamFieldValues.aidl
new file mode 100644
index 0000000..5a2821c
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ParamFieldValues.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable ParamFieldValues {
+ android.hardware.media.c2.ParamField paramOrField;
+ android.hardware.media.c2.FieldSupportedValues[] values;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Params.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Params.aidl
new file mode 100644
index 0000000..7d363c0
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Params.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable Params {
+ byte[] params;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/SettingResult.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/SettingResult.aidl
new file mode 100644
index 0000000..f9e6a93
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/SettingResult.aidl
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable SettingResult {
+ android.hardware.media.c2.SettingResult.Failure failure;
+ android.hardware.media.c2.ParamFieldValues field;
+ android.hardware.media.c2.ParamFieldValues[] conflicts;
+ @Backing(type="int") @VintfStability
+ enum Failure {
+ BAD_TYPE = 0,
+ BAD_PORT = 1,
+ BAD_INDEX = 2,
+ READ_ONLY = 3,
+ MISMATCH = 4,
+ BAD_VALUE = 5,
+ CONFLICT = 6,
+ UNSUPPORTED = 7,
+ INFO_BAD_VALUE = 8,
+ INFO_CONFLICT = 9,
+ }
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Status.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Status.aidl
new file mode 100644
index 0000000..ad07677
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Status.aidl
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable Status {
+ int status;
+ const int OK = 0;
+ const int BAD_VALUE = -22;
+ const int BAD_INDEX = -75;
+ const int CANNOT_DO = -2147483646;
+ const int DUPLICATE = -17;
+ const int NOT_FOUND = -2;
+ const int BAD_STATE = -38;
+ const int BLOCKING = -9930;
+ const int NO_MEMORY = -12;
+ const int REFUSED = -1;
+ const int TIMED_OUT = -110;
+ const int OMITTED = -74;
+ const int CORRUPTED = -2147483648;
+ const int NO_INIT = -19;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/StructDescriptor.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/StructDescriptor.aidl
new file mode 100644
index 0000000..58268e0
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/StructDescriptor.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable StructDescriptor {
+ int type;
+ android.hardware.media.c2.FieldDescriptor[] fields;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/SurfaceSyncObj.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/SurfaceSyncObj.aidl
new file mode 100644
index 0000000..1c9bf8d
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/SurfaceSyncObj.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable SurfaceSyncObj {
+ android.hardware.common.NativeHandle syncMemory;
+ long bqId;
+ int generationId;
+ long consumerUsage;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ValueRange.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ValueRange.aidl
new file mode 100644
index 0000000..db71ce0
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/ValueRange.aidl
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable ValueRange {
+ long min;
+ long max;
+ long step;
+ long num;
+ long denom;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Work.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Work.aidl
new file mode 100644
index 0000000..a534348
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Work.aidl
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable Work {
+ byte[] chainInfo;
+ android.hardware.media.c2.FrameData input;
+ android.hardware.media.c2.Worklet[] worklets;
+ int workletsProcessed;
+ android.hardware.media.c2.Status result;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/WorkBundle.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/WorkBundle.aidl
new file mode 100644
index 0000000..84708a8
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/WorkBundle.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable WorkBundle {
+ android.hardware.media.c2.Work[] works;
+ android.hardware.media.c2.BaseBlock[] baseBlocks;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/WorkOrdinal.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/WorkOrdinal.aidl
new file mode 100644
index 0000000..2833df3
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/WorkOrdinal.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable WorkOrdinal {
+ long timestampUs;
+ long frameIndex;
+ long customOrdinal;
+}
diff --git a/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Worklet.aidl b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Worklet.aidl
new file mode 100644
index 0000000..a79abf2
--- /dev/null
+++ b/media/c2/aidl/aidl_api/android.hardware.media.c2/current/android/hardware/media/c2/Worklet.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.media.c2;
+@VintfStability
+parcelable Worklet {
+ int componentId;
+ byte[] tunings;
+ android.hardware.media.c2.SettingResult[] failures;
+ android.hardware.media.c2.FrameData output;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl b/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl
new file mode 100644
index 0000000..8b8b8e0
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/BaseBlock.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.common.NativeHandle;
+
+/**
+ * Storage type for `BaseBlock`.
+ *
+ * A `BaseBlock` is a representation of a codec memory block. Coded data,
+ * decoded data, codec-specific data, and other codec-related data are all sent
+ * in the form of BaseBlocks.
+ */
+@VintfStability
+union BaseBlock {
+ /**
+ * #nativeBlock is the opaque representation of a buffer.
+ */
+ NativeHandle nativeBlock;
+ /**
+ * #pooledBlock is a reference to a buffer handled by a BufferPool.
+ */
+ android.hardware.media.bufferpool2.BufferStatusMessage pooledBlock;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/Block.aidl b/media/c2/aidl/android/hardware/media/c2/Block.aidl
new file mode 100644
index 0000000..34aa7b1
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/Block.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.common.NativeHandle;
+import android.hardware.media.c2.Params;
+
+/**
+ * Reference to a @ref BaseBlock within a @ref WorkBundle.
+ *
+ * `Block` contains additional attributes that `BaseBlock` does not. These
+ * attributes may differ among `Block` objects that refer to the same
+ * `BaseBlock` in the same `WorkBundle`.
+ */
+@VintfStability
+parcelable Block {
+ /**
+ * Identity of a `BaseBlock` within a `WorkBundle`. This is an index into
+ * #WorkBundle.baseBlocks.
+ */
+ int index;
+ /**
+ * Metadata associated with this `Block`.
+ */
+ Params meta;
+ /**
+ * Fence for synchronizing `Block` access.
+ */
+ NativeHandle fence;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/Buffer.aidl b/media/c2/aidl/android/hardware/media/c2/Buffer.aidl
new file mode 100644
index 0000000..d2dcf2d
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/Buffer.aidl
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.Block;
+import android.hardware.media.c2.Params;
+
+/**
+ * A codec buffer, which is a collection of @ref Block objects and metadata.
+ *
+ * This is a part of @ref FrameData.
+ */
+@VintfStability
+parcelable Buffer {
+ /**
+ * Metadata associated with the buffer.
+ */
+ Params info;
+ /**
+ * Blocks contained in the buffer.
+ */
+ Block[] blocks;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/FieldDescriptor.aidl b/media/c2/aidl/android/hardware/media/c2/FieldDescriptor.aidl
new file mode 100644
index 0000000..a2774ec
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/FieldDescriptor.aidl
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FieldId;
+
+/**
+ * Description of a field inside a C2Param structure.
+ */
+@VintfStability
+parcelable FieldDescriptor {
+ /**
+ * Possible types of the field.
+ */
+ @VintfStability
+ @Backing(type="int")
+ enum Type {
+ NO_INIT = 0,
+ INT32,
+ UINT32,
+ CNTR32,
+ INT64,
+ UINT64,
+ CNTR64,
+ FLOAT,
+ /**
+ * Fixed-size string (POD).
+ */
+ STRING = 0x100,
+ /**
+ * A blob has no sub-elements and can be thought of as an array of
+ * bytes. However, bytes cannot be individually addressed by clients.
+ */
+ BLOB,
+ /**
+ * The field is a structure that may contain other fields.
+ */
+ STRUCT = 0x20000,
+ }
+ /**
+ * Named value type. This is used for defining an enum value for a numeric
+ * type.
+ */
+ @VintfStability
+ parcelable NamedValue {
+ /**
+ * Name of the enum value. This must be unique for each enum value in
+ * the same field.
+ */
+ String name;
+ /**
+ * Underlying value of the enum value. Multiple enum names may have the
+ * same underlying value.
+ */
+ long value;
+ }
+ /**
+ * Location of the field in the C2Param structure
+ */
+ FieldId fieldId;
+ /**
+ * Type of the field.
+ */
+ Type type;
+ /**
+ * If #type is #Type.STRUCT, #structIndex is the C2Param structure index;
+ * otherwise, #structIndex is not used.
+ */
+ int structIndex;
+ /**
+ * Extent of the field.
+ * - For a non-array field, #extent is 1.
+ * - For a fixed-length array field, #extent is the length. An array field
+ * of length 1 is indistinguishable from a non-array field.
+ * - For a variable-length array field, #extent is 0. This can only occur as
+ * the last member of a C2Param structure.
+ */
+ int extent;
+ /**
+ * Name of the field. This must be unique for each field in the same
+ * structure.
+ */
+ String name;
+ /**
+ * List of enum values. This is not used when #type is not one of the
+ * numeric types.
+ */
+ NamedValue[] namedValues;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/FieldId.aidl b/media/c2/aidl/android/hardware/media/c2/FieldId.aidl
new file mode 100644
index 0000000..68bf058
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/FieldId.aidl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Identifying information of a field relative to a known C2Param structure.
+ *
+ * Within a given C2Param structure, each field is uniquely identified by @ref
+ * FieldId.
+ */
+@VintfStability
+parcelable FieldId {
+ /**
+ * Offset of the field in bytes.
+ */
+ int offset;
+ /**
+ * Size of the field in bytes.
+ */
+ int sizeBytes;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/FieldSupportedValues.aidl b/media/c2/aidl/android/hardware/media/c2/FieldSupportedValues.aidl
new file mode 100644
index 0000000..6c2033b
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/FieldSupportedValues.aidl
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.ValueRange;
+
+/*
+ * Description of supported values for a field of C2Param.
+ *
+ * This can be a continuous range or a discrete set of values.
+ *
+ * The intended type of values must be made clear in the context where
+ * `FieldSupportedValues` is used.
+ */
+@VintfStability
+union FieldSupportedValues {
+ /**
+ * No supported values
+ */
+ boolean empty;
+ /**
+ * Numeric range, described in a #ValueRange structure
+ */
+ ValueRange range;
+ /**
+ * List of values
+ */
+ long[] values;
+ /**
+ * List of flags that can be OR-ed.
+ *
+ * The list contains { min-mask, flag1, flag2... }. Basically, the first
+ * value is the required set of flags to be set, and the rest of the values are flags that can
+ * be set independently. FLAGS is only supported for integral types. Supported flags should
+ * not overlap, as it can make validation non-deterministic. The standard validation method
+ * is that starting from the original value, if each flag is removed when fully present (the
+ * min-mask must be fully present), we shall arrive at 0.
+ */
+ long[] flags;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/FieldSupportedValuesQuery.aidl b/media/c2/aidl/android/hardware/media/c2/FieldSupportedValuesQuery.aidl
new file mode 100644
index 0000000..bdaaef6
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/FieldSupportedValuesQuery.aidl
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.ParamField;
+
+/**
+ * Query information for supported values of a field. This is used as input to
+ * IConfigurable::querySupportedValues().
+ */
+@VintfStability
+parcelable FieldSupportedValuesQuery {
+ @VintfStability
+ @Backing(type="int")
+ enum Type {
+ /**
+ * Query all possible values regardless of other settings.
+ */
+ POSSIBLE = 0,
+ /**
+ * Query currently possible values given dependent settings.
+ */
+ CURRENT,
+ }
+ /**
+ * Identity of the field to query.
+ */
+ ParamField field;
+ /**
+ * Type of the query. See #Type for more information.
+ */
+ Type type;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/FieldSupportedValuesQueryResult.aidl b/media/c2/aidl/android/hardware/media/c2/FieldSupportedValuesQueryResult.aidl
new file mode 100644
index 0000000..b5c28c6
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/FieldSupportedValuesQueryResult.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FieldSupportedValues;
+import android.hardware.media.c2.Status;
+
+/**
+ * This structure is used to hold the result from
+ * IConfigurable::querySupportedValues().
+ */
+@VintfStability
+parcelable FieldSupportedValuesQueryResult {
+ /**
+ * Result of the query. Possible values are
+ * - `Status::OK`: The query was successful.
+ * - `Status::BAD_STATE`: The query was requested when the `IConfigurable` instance
+ * was in a bad state.
+ * - `Status::BAD_INDEX`: The requested field was not recognized.
+ * - `Status::TIMED_OUT`: The query could not be completed in a timely manner.
+ * - `Status::BLOCKING`: The query must block, but the parameter `mayBlock` in the
+ * call to `querySupportedValues()` was `false`.
+ * - `Status::CORRUPTED`: Some unknown error occurred.
+ */
+ Status status;
+ /**
+ * Supported values. This is meaningful only when #status is `OK`.
+ */
+ FieldSupportedValues values;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/FrameData.aidl b/media/c2/aidl/android/hardware/media/c2/FrameData.aidl
new file mode 100644
index 0000000..15c1b6d
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/FrameData.aidl
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.Buffer;
+import android.hardware.media.c2.InfoBuffer;
+import android.hardware.media.c2.Params;
+import android.hardware.media.c2.WorkOrdinal;
+
+/**
+ * Data for an input frame or an output frame.
+ *
+ * This structure represents a @e frame with its metadata. A @e frame consists
+ * of an ordered set of buffers, configuration changes, and info buffers along
+ * with some non-configuration metadata.
+ *
+ * @note `FrameData` is the HIDL counterpart of `C2FrameData` in the Codec 2.0
+ * standard.
+ */
+@VintfStability
+parcelable FrameData {
+ /** List of frame flags */
+ /**
+ * For input frames: no output frame shall be generated when processing
+ * this frame, but metadata must still be processed.
+ *
+ * For output frames: this frame must be discarded but metadata is still
+ * valid.
+ */
+ const int DROP_FRAME = (1 << 0);
+ /**
+ * This frame is the last frame of the current stream. Further frames
+ * are part of a new stream.
+ */
+ const int END_OF_STREAM = (1 << 1);
+ /**
+ * This frame must be discarded with its metadata.
+ *
+ * This flag is only set by components, e.g. as a response to the flush
+ * command.
+ */
+ const int DISCARD_FRAME = (1 << 2);
+ /**
+ * This frame is not the last frame produced for the input.
+ *
+ * This flag is normally set by the component - e.g. when an input frame
+ * results in multiple output frames, this flag is set on all but the
+ * last output frame.
+ *
+ * Also, when components are chained, this flag should be propagated
+ * down the work chain. That is, if set on an earlier frame of a
+ * work-chain, it should be propagated to all later frames in that
+ * chain. Additionally, components down the chain could set this flag
+ * even if not set earlier, e.g. if multiple output frames are generated
+ * at that component for the input frame.
+ */
+ const int FLAG_INCOMPLETE = (1 << 3);
+ /**
+ * This frame contains only codec-specific configuration data, and no
+ * actual access unit.
+ */
+ const int CODEC_CONFIG = (1 << 31);
+ /**
+ * Frame flags, as described above.
+ */
+ int flags;
+ /**
+ * @ref WorkOrdinal of the frame.
+ */
+ WorkOrdinal ordinal;
+ /**
+ * List of frame buffers.
+ */
+ Buffer[] buffers;
+ /**
+ * List of configuration updates.
+ */
+ Params configUpdate;
+ /**
+ * List of info buffers.
+ */
+ InfoBuffer[] infoBuffers;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IComponent.aidl b/media/c2/aidl/android/hardware/media/c2/IComponent.aidl
new file mode 100644
index 0000000..b3390c3
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IComponent.aidl
@@ -0,0 +1,304 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.common.NativeHandle;
+import android.view.Surface;
+
+import android.hardware.media.c2.IComponentInterface;
+import android.hardware.media.c2.IConfigurable;
+import android.hardware.media.c2.WorkBundle;
+import android.hardware.media.c2.SurfaceSyncObj;
+
+/**
+ * Interface for an AIDL Codec2 component.
+ * Components have two states: stopped and running. The running state has three
+ * sub-states: executing, tripped and error.
+ *
+ * All methods in `IComponent` must not block. If a method call cannot be
+ * completed in a timely manner, it must throw `Status::TIMED_OUT`.
+ */
+@VintfStability
+interface IComponent {
+ /**
+ * The reference object from framwork to HAL C2BlockPool.
+ *
+ * The object will be returned when C2BlockPool is created by a framework
+ * request. The object also can be destroyed using blockPoolId.
+ * Using configurable framework can query/config the object in HAL(IComponent).
+ */
+ parcelable BlockPool {
+ long blockPoolId;
+ IConfigurable configurable;
+ }
+ /**
+ * Configures a component for a tunneled playback mode.
+ *
+ * A successful call to this method puts the component in the *tunneled*
+ * mode. In this mode, the output `Worklet`s returned in
+ * IComponentListener::onWorkDone() may not contain any buffers. The output
+ * buffers are passed directly to the consumer end of a buffer queue whose
+ * producer side is configured with the returned @p sidebandStream passed
+ * to IGraphicBufferProducer::setSidebandStream().
+ *
+ * The component is initially in the non-tunneled mode by default. The
+ * tunneled mode can be toggled on only before the component starts
+ * processing. Once the component is put into the tunneled mode, it shall
+ * stay in the tunneled mode until and only until reset() is called.
+ *
+ * @param avSyncHwId A resource ID for hardware sync. The generator of sync
+ * IDs must ensure that this number is unique among all services at any
+ * given time. For example, if both the audio HAL and the tuner HAL
+ * support this feature, sync IDs from the audio HAL must not clash
+ * with sync IDs from the tuner HAL.
+ * @return Codec-allocated sideband stream NativeHandle. This can
+ * be passed to IGraphicBufferProducer::setSidebandStream() to
+ * establish a direct channel to the consumer.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::OMITTED` - The component does not support video tunneling.
+ * - `Status::BAD_STATE` - The component is already running.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ NativeHandle configureVideoTunnel(in int avSyncHwId);
+
+ /**
+ * Creates a local `C2BlockPool` backed by the given allocator and returns
+ * its id.
+ *
+ * The returned @p blockPoolId is the only way the client can refer to a
+ * `C2BlockPool` object in the component. The id can be passed to
+ * setOutputSurface() or used in some C2Param objects later.
+ *
+ * The created `C2BlockPool` object can be destroyed by calling
+ * destroyBlockPool(), reset() or release(). reset() and release() must
+ * destroy all `C2BlockPool` objects that have been created.
+ *
+ * @param allocatorId Id of a `C2Allocator`.
+ * @param out configurable Configuration interface for the created pool. This
+ * must not be null.
+ * @return Created block pool information. This could be used to config/query and
+ * also be used in setOutputSurface() if the allocator
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NO_MEMORY` - Not enough memory to create the pool.
+ * - `Status::BAD_VALUE` - @p allocatorId is not recognized.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ BlockPool createBlockPool(in int allocatorId);
+
+ /**
+ * Destroys a local block pool previously created by createBlockPool().
+ *
+ * @param blockPoolId Id of a `C2BlockPool` that was previously returned by
+ * createBlockPool().
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NOT_FOUND` - The supplied blockPoolId is not valid.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void destroyBlockPool(in long blockPoolId);
+
+ /**
+ * Drains the component, and optionally downstream components. This is a
+ * signalling method; as such it does not wait for any work completion.
+ *
+ * The last `Work` item is marked as "drain-till-here", so the component is
+ * notified not to wait for further `Work` before it processes what is
+ * already queued. This method can also be used to set the end-of-stream
+ * flag after `Work` has been queued. Client can continue to queue further
+ * `Work` immediately after this method returns.
+ *
+ * This method must be supported in running (including tripped) states.
+ *
+ * `Work` that is completed must be returned via
+ * IComponentListener::onWorkDone().
+ *
+ * @param withEos Whether to drain the component with marking end-of-stream.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void drain(in boolean withEos);
+
+ /**
+ * Discards and abandons any pending `Work` items for the component.
+ *
+ * This method must be supported in running (including tripped) states.
+ *
+ * `Work` that could be immediately abandoned/discarded must be returned in
+ * @p flushedWorkBundle. The order in which queued `Work` items are
+ * discarded can be arbitrary.
+ *
+ * `Work` that could not be abandoned or discarded immediately must be
+ * marked to be discarded at the earliest opportunity, and must be returned
+ * via IComponentListener::onWorkDone(). This must be completed within
+ * 500ms.
+ *
+ * @return `WorkBundle` object containing flushed `Work` items.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ WorkBundle flush();
+
+ /**
+ * Returns the @ref IComponentInterface instance associated to this
+ * component.
+ *
+ * An @ref IConfigurable instance for the component can be obtained by calling
+ * IComponentInterface::getConfigurable() on the returned @p intf.
+ *
+ * @return `IComponentInterface` instance. This must not be null.
+ */
+ IComponentInterface getInterface();
+
+ /**
+ * Queues up work for the component.
+ *
+ * This method must be supported in running (including tripped) states.
+ *
+ * It is acceptable for this method to return `OK` and return an error value
+ * using the IComponentListener::onWorkDone() callback.
+ *
+ * @param workBundle `WorkBundle` object containing a list of `Work` objects
+ * to queue to the component.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::BAD_INDEX` - Some component id in some `Worklet` is not valid.
+ * - `Status::CANNOT_DO` - The components are not tunneled but some `Work` object
+ * contains tunneling information.
+ * - `Status::NO_MEMORY` - Not enough memory to queue @p workBundle.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void queue(in WorkBundle workBundle);
+
+ /**
+ * Releases the component.
+ *
+ * This method must be supported in stopped state.
+ *
+ * This method destroys the component. Upon return, if @p status is `OK` or
+ * `DUPLICATE`, all resources must have been released.
+ *
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::BAD_STATE` - The component is running.
+ * - `Status::DUPLICATE` - The component is already released.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void release();
+
+ /**
+ * Resets the component.
+ *
+ * This method must be supported in all (including tripped) states other
+ * than released.
+ *
+ * This method must be supported during any other blocking call.
+ *
+ * This method must return within 500ms.
+ *
+ * When this call returns, if @p status is `OK`, all `Work` items must
+ * have been abandoned, and all resources (including `C2BlockPool` objects
+ * previously created by createBlockPool()) must have been released.
+ *
+ * If the return value is `BAD_STATE` or `DUPLICATE`, no state change is
+ * expected as a response to this call. For all other return values, the
+ * component must be in the stopped state.
+ *
+ * This brings settings back to their default, "guaranteeing" no tripped
+ * state.
+ *
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::BAD_STATE` - Component is in released state.
+ * - `Status::DUPLICATE` - When called during another reset call from another
+ * thread.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void reset();
+
+ /**
+ * Starts using a surface for output with a synchronization object
+ *
+ * This method must not block.
+ *
+ * @param blockPoolId Id of the `C2BlockPool` to be associated with the
+ * output surface.
+ * @param surface Output surface.
+ * @param syncObject synchronization object for buffer allocation between
+ * Framework and Component.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::CANNOT_DO` - The component does not support an output surface.
+ * - `Status::REFUSED` - The output surface cannot be accessed.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void setOutputSurface(in long blockPoolId, in Surface surface,
+ in SurfaceSyncObj syncObject);
+
+ /**
+ * Starts the component.
+ *
+ * This method must be supported in stopped state as well as tripped state.
+ *
+ * If the return value is `OK`, the component must be in the running state.
+ * If the return value is `BAD_STATE` or `DUPLICATE`, no state change is
+ * expected as a response to this call. Otherwise, the component must be in
+ * the stopped state.
+ *
+ * If a component is in the tripped state and start() is called while the
+ * component configuration still results in a trip, start() must succeed and
+ * a new onTripped() callback must be used to communicate the configuration
+ * conflict that results in the new trip.
+ *
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::BAD_STATE` - Component is not in stopped or tripped state.
+ * - `Status::DUPLICATE` - When called during another start call from another
+ * thread.
+ * - `Status::NO_MEMORY` - Not enough memory to start the component.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void start();
+
+ /**
+ * Stops the component.
+ *
+ * This method must be supported in running (including tripped) state.
+ *
+ * This method must return within 500ms.
+ *
+ * Upon this call, all pending `Work` must be abandoned.
+ *
+ * If the return value is `BAD_STATE` or `DUPLICATE`, no state change is
+ * expected as a response to this call. For all other return values, the
+ * component must be in the stopped state.
+ *
+ * This does not alter any settings and tunings that may have resulted in a
+ * tripped state.
+ *
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::BAD_STATE` - Component is not in running state.
+ * - `Status::DUPLICATE` - When called during another stop call from another
+ * thread.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void stop();
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IComponentInterface.aidl b/media/c2/aidl/android/hardware/media/c2/IComponentInterface.aidl
new file mode 100644
index 0000000..9db81e6
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IComponentInterface.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.IConfigurable;
+
+/**
+ * Component interface object. This object contains all of the configurations of
+ * a potential or actual component. It can be created and used independently of
+ * an actual Codec2 component to query supported parameters for various
+ * component settings, and configurations for a potential component.
+ *
+ * An actual component exposes this interface via IComponent::getInterface().
+ */
+@VintfStability
+interface IComponentInterface {
+ /**
+ * Returns the @ref IConfigurable instance associated to this component
+ * interface.
+ *
+ * @return `IConfigurable` instance. This must not be null.
+ */
+ IConfigurable getConfigurable();
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IComponentListener.aidl b/media/c2/aidl/android/hardware/media/c2/IComponentListener.aidl
new file mode 100644
index 0000000..75500b7
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IComponentListener.aidl
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.SettingResult;
+import android.hardware.media.c2.Status;
+import android.hardware.media.c2.WorkBundle;
+
+/**
+ * Callback interface for handling notifications from @ref IComponent.
+ */
+@VintfStability
+oneway interface IComponentListener {
+ /**
+ * Identifying information for an input buffer previously queued to the
+ * component via IComponent::queue().
+ */
+ @VintfStability
+ parcelable InputBuffer {
+ /**
+ * This value comes from `Work::input.ordinal.frameIndex` in a `Work`
+ * object that was previously queued.
+ */
+ long frameIndex;
+ /**
+ * This value is an index into `Work::input.buffers` (which is an array)
+ * in a `Work` object that was previously queued.
+ */
+ int arrayIndex;
+ }
+ /**
+ * Information about rendering of a frame to a `Surface`.
+ */
+ @VintfStability
+ parcelable RenderedFrame {
+ /**
+ * Id of the `BufferQueue` containing the rendered buffer.
+ *
+ * This value must have been obtained by an earlier call to
+ * IGraphicBufferProducer::getUniqueId().
+ */
+ long bufferQueueId;
+ /**
+ * Id of the slot of the rendered buffer.
+ *
+ * This value must have been obtained by an earlier call to
+ * IGraphicBufferProducer::dequeueBuffer() or
+ * IGraphicBufferProducer::attachBuffer().
+ */
+ int slotId;
+ /**
+ * Timestamp the rendering happened.
+ *
+ * The reference point for the timestamp is determined by the
+ * `BufferQueue` that performed the rendering.
+ */
+ long timestampNs;
+ }
+ /**
+ * Notify the listener of an error.
+ *
+ * @param status Error type. @p status may be `OK`, which means that an
+ * error has occurred, but the error type does not fit into the type
+ * `Status`. In this case, additional information is provided by
+ * @p errorCode.
+ * @param errorCode Additional error information. The framework may not
+ * recognize the meaning of this value.
+ */
+ void onError(in Status status, in int errorCode);
+
+ /**
+ * Notify the listener that frames have been rendered.
+ *
+ * @param renderedFrames List of @ref RenderedFrame objects.
+ */
+ void onFramesRendered(in RenderedFrame[] renderedFrames);
+
+ /**
+ * Notify the listener that some input buffers are no longer needed by the
+ * component, and hence can be released or reused by the client.
+ *
+ * Input buffers that are contained in a `Work` object returned by an
+ * earlier onWorkDone() call are assumed released, so they must not appear
+ * in any onInputBuffersReleased() calls. That means
+ * onInputBuffersReleased() must only report input buffers that are released
+ * before the output in the same `Work` item is produced. However, it is
+ * possible for an input buffer to be returned by onWorkDone() after it has
+ * been reported by onInputBuffersReleased().
+ *
+ * @note onWorkDone() and onInputBuffersReleased() both notify the client
+ * that input buffers are no longer needed. However, in order to minimize
+ * IPC calls, onInputBuffersReleased() should be called only when
+ * onWorkDone() cannot be called, e.g., the component needs more input
+ * before an output can be produced.
+ *
+ * @param inputBuffers List of `InputBuffer` objects, identifying input
+ * buffers that are no longer needed by the component.
+ */
+ void onInputBuffersReleased(in InputBuffer[] inputBuffers);
+
+ /**
+ * Notify the listener that the component is tripped.
+ *
+ * @param settingResults List of failures.
+ */
+ void onTripped(in SettingResult[] settingResults);
+
+ /**
+ * Notify the listener that some `Work` items have been completed.
+ *
+ * All the input buffers in the returned `Work` objects must not be used by
+ * the component after onWorkDone() is called.
+ *
+ * @param workBundle List of completed `Work` objects.
+ */
+ void onWorkDone(in WorkBundle workBundle);
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl b/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl
new file mode 100644
index 0000000..1435a7e
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IComponentStore.aidl
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.Buffer;
+import android.hardware.media.c2.IComponent;
+import android.hardware.media.c2.IComponentInterface;
+import android.hardware.media.c2.IComponentListener;
+import android.hardware.media.c2.IConfigurable;
+import android.hardware.media.c2.StructDescriptor;
+
+/**
+ * Entry point for Codec2 HAL.
+ *
+ * All methods in `IComponentStore` must not block. If a method call cannot be
+ * completed in a timely manner, it must throw `Status::TIMED_OUT`. The only
+ * exceptions are getPoolClientManager() and getConfigurable(), which must
+ * always return immediately.
+ *
+ * @note This is an extension of version 1.1 of `IComponentStore`. The purpose
+ * of the extension is to add support for blocking output buffer allocator.
+ */
+@VintfStability
+interface IComponentStore {
+ /**
+ * Component traits.
+ */
+ @VintfStability
+ parcelable ComponentTraits {
+ @VintfStability
+ @Backing(type="int")
+ enum Kind {
+ OTHER = 0,
+ DECODER,
+ ENCODER,
+ }
+ @VintfStability
+ @Backing(type="int")
+ enum Domain {
+ OTHER = 0,
+ VIDEO,
+ AUDIO,
+ IMAGE,
+ }
+ /**
+ * Name of the component. This must be unique for each component.
+ *
+ * This name is use to identify the component to create in
+ * createComponent() and createComponentInterface().
+ */
+ String name;
+ /**
+ * Component domain.
+ */
+ Domain domain;
+ /**
+ * Component kind.
+ */
+ Kind kind;
+ /**
+ * Rank used by `MediaCodecList` to determine component ordering. Lower
+ * value means higher priority.
+ */
+ int rank;
+ /**
+ * MIME type.
+ */
+ String mediaType;
+ /**
+ * Aliases for component name for backward compatibility.
+ *
+ * Multiple components can have the same alias (but not the same
+ * component name) as long as their media types differ.
+ */
+ String[] aliases;
+ }
+
+ /**
+ * Copies the contents of @p src into @p dst without changing the format of
+ * @p dst.
+ *
+ * @param src Source buffer.
+ * @param dst Destination buffer.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::CANNOT_DO` - @p src and @p dst are not compatible.
+ * - `Status::REFUSED` - No permission to copy.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ void copyBuffer(in Buffer src, in Buffer dst);
+
+ /**
+ * Creates a component by name.
+ *
+ * @param name Name of the component to create. This must match one of the
+ * names returned by listComponents().
+ * @param listener Callback receiver.
+ * @param pool `IClientManager` object of the BufferPool in the client
+ * process. This may be null if the client does not own a BufferPool.
+ * @return The created component.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NOT_FOUND` - There is no component with the given name.
+ * - `Status::NO_MEMORY` - Not enough memory to create the component.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ *
+ * @sa IComponentListener.
+ */
+ IComponent createComponent(in String name, in IComponentListener listener,
+ in android.hardware.media.bufferpool2.IClientManager pool);
+
+ /**
+ * Creates a component interface by name.
+ *
+ * @param name Name of the component interface to create. This should match
+ * one of the names returned by listComponents().
+ * @return The created component interface.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NOT_FOUND` - There is no component interface with the given name.
+ * - `Status::NO_MEMORY` - Not enough memory to create the component interface.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ IComponentInterface createInterface(in String name);
+
+ /**
+ * Returns the @ref IConfigurable instance associated to this component
+ * store.
+ *
+ * @return `IConfigurable` instance. This must not be null.
+ */
+ IConfigurable getConfigurable();
+
+ /**
+ * Returns the `IClientManager` object for the component's BufferPool.
+ *
+ * @return If the component store supports receiving buffers via
+ * BufferPool API, @p pool must be a valid `IClientManager` instance.
+ * Otherwise, @p pool must be null.
+ */
+ android.hardware.media.bufferpool2.IClientManager getPoolClientManager();
+
+ /**
+ * Returns a list of `StructDescriptor` objects for a set of requested
+ * C2Param structure indices that this store is aware of.
+ *
+ * This operation must be performed at best effort, e.g. the component
+ * store must simply ignore all struct indices that it is not aware of.
+ *
+ * @param indices Indices of C2Param structures to describe.
+ * @return List of `StructDescriptor` objects.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NOT_FOUND` - Some indices were not known.
+ * - `Status::NO_MEMORY` - Not enough memory to complete this method.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ StructDescriptor[] getStructDescriptors(in int[] indices);
+
+ /**
+ * Returns the list of components supported by this component store.
+ *
+ * @return traits List of component traits for all components supported by
+ * this store (in no particular order).
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NO_MEMORY` - Not enough memory to complete this method.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ ComponentTraits[] listComponents();
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/IConfigurable.aidl b/media/c2/aidl/android/hardware/media/c2/IConfigurable.aidl
new file mode 100644
index 0000000..7fdb825
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/IConfigurable.aidl
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FieldSupportedValuesQuery;
+import android.hardware.media.c2.FieldSupportedValuesQueryResult;
+import android.hardware.media.c2.ParamDescriptor;
+import android.hardware.media.c2.Params;
+import android.hardware.media.c2.SettingResult;
+
+/**
+ * Generic configuration interface presented by all configurable Codec2 objects.
+ *
+ * This interface must be supported in all states of the owning object, and must
+ * not change the state of the owning object.
+ */
+@VintfStability
+interface IConfigurable {
+ /**
+ * Return parcelable for config() interface.
+ *
+ * This includes the successful config settings along with the failure reasons of
+ * the specified setting.
+ */
+ @VintfStability
+ parcelable ConfigResult {
+ Params params;
+ SettingResult[] failures;
+ }
+
+ /**
+ * Sets a set of parameters for the object.
+ *
+ * Tuning is performed at best effort: the object must update all supported
+ * configurations at best effort and skip unsupported parameters. Any errors
+ * are communicated in the return value along with the failures.
+ *
+ * A non-strict parameter update with an unsupported value shall cause an
+ * update to the closest supported value. A strict parameter update with an
+ * unsupported value shall be skipped and a failure shall be returned.
+ *
+ * If @p mayBlock is false, this method must not block. An update that
+ * requires blocking shall be skipped and a failure shall be returned.
+ *
+ * If @p mayBlock is true, an update may block, but the whole method call
+ * has to complete in a timely manner, or `Status::TIMED_OUT` is thrown.
+ *
+ * The final values for all parameters set are propagated back to the caller
+ * in @p params.
+ *
+ * \par For IComponent
+ *
+ * When the object type is @ref IComponent, this method must be supported in
+ * any state except released.
+ *
+ * The blocking behavior of this method differs among states:
+ * - In the stopped state, this must be non-blocking. @p mayBlock is
+ * ignored. (The method operates as if @p mayBlock was false.)
+ * - In any of the running states, this method may block momentarily if
+ * @p mayBlock is true. However, if the call cannot be completed in a
+ * timely manner, `Status::TIMED_OUT` is thrown.
+ *
+ * @note Parameter tuning @e does depend on the order of the tuning
+ * parameters, e.g., some parameter update may enable some subsequent
+ * parameter update.
+ *
+ * @param inParams Requested parameter updates.
+ * @param mayBlock Whether this call may block or not.
+ * @return result of config. Params in the result should be in same order
+ * with @p inParams.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NO_MEMORY` - Some supported parameters could not be updated
+ * successfully because they contained unsupported values.
+ * These are returned in @p failures.
+ * - `Status::BLOCKING` - Setting some parameters requires blocking, but
+ * @p mayBlock is false.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ ConfigResult config(in Params inParams, in boolean mayBlock);
+
+ /**
+ * Returns the id of the object. This must be unique among all objects of
+ * the same type hosted by the same store.
+ *
+ * @return Id of the object.
+ */
+ int getId();
+
+ /**
+ * Returns the name of the object.
+ *
+ * This must match the name that was supplied during the creation of the
+ * object.
+ *
+ * @return Name of the object.
+ */
+ String getName();
+
+ /**
+ * Queries a set of parameters from the object.
+ *
+ * Querying is performed at best effort: the object must query all supported
+ * parameters and skip unsupported ones (which may include parameters that
+ * could not be allocated).
+ *
+ * If @p mayBlock is true, a query may block, but the whole method call
+ * has to complete in a timely manner, or `Status::TIMED_OUT` is thrown.
+ *
+ * If @p mayBlock is false, this method must not block(All parameter queries
+ * that require blocking must be skipped). Otherwise, this
+ * method is allowed to block for a certain period of time before completing
+ * the operation. If the operation is not completed in a timely manner,
+ * `Status::TIMED_OUT` is thrown.
+ *
+ * @note Since unsupported parameters will be skipped, the returned results
+ * does not have every settings from @p indices, but the result will preserve
+ * the original order from @p indices though unsupported settings are skipped.
+ *
+ * \par For IComponent
+ *
+ * When the object type is @ref IComponent, this method must be supported in
+ * any state except released. This call must not change the state nor the
+ * internal configuration of the component.
+ *
+ * The blocking behavior of this method differs among states:
+ * - In the stopped state, this must be non-blocking. @p mayBlock is
+ * ignored. (The method operates as if @p mayBlock was false.)
+ * - In any of the running states, this method may block momentarily if
+ * @p mayBlock is true. However, if the call cannot be completed in a
+ * timely manner, `Status::status` is thrown.
+ *
+ * @param indices List of C2Param structure indices to query.
+ * @param mayBlock Whether this call may block or not.
+ * @return Flattened representation of std::vector<C2Param> object.
+ * Unsupported settings are skipped in the results. The order in @p indices
+ * still be preserved except skipped settings.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NO_MEMORY` - Could not allocate memory for a supported parameter.
+ * - `Status::BLOCKING` - Querying some parameters requires blocking, but
+ * @p mayBlock is false.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ Params query(in int[] indices, in boolean mayBlock);
+
+ /**
+ * Returns a list of supported parameters within a selected range of C2Param
+ * structure indices.
+ *
+ * @param start The first index of the selected range.
+ * @param count The length of the selected range.
+ * @return List of supported parameters in the selected range. This
+ * list may have fewer than @p count elements if some indices in the
+ * range are not supported.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::NO_MEMORY` - Not enough memory to complete this method.
+ *
+ */
+ ParamDescriptor[] querySupportedParams(in int start, in int count);
+
+ /**
+ * Retrieves the supported values for the queried fields.
+ *
+ * The object must process all fields queried even if some queries fail.
+ *
+ * If @p mayBlock is false, this method must not block. Otherwise, this
+ * method is allowed to block for a certain period of time before completing
+ * the operation. If the operation cannot be completed in a timely manner,
+ * `Status::TIMED_OUT` is thrown.
+ *
+ * \par For IComponent
+ *
+ * When the object type is @ref IComponent, this method must be supported in
+ * any state except released.
+ *
+ * The blocking behavior of this method differs among states:
+ * - In the stopped state, this must be non-blocking. @p mayBlock is
+ * ignored. (The method operates as if @p mayBlock was false.)
+ * - In any of the running states, this method may block momentarily if
+ * @p mayBlock is true. However, if the call cannot be completed in a
+ * timely manner, `Status::TIMED_OUT` is thrown.
+ *
+ * @param inFields List of field queries.
+ * @param mayBlock Whether this call may block or not.
+ * @return List of supported values and results for the
+ * supplied queries.
+ * @throws ServiceSpecificException with one of the following values:
+ * - `Status::BLOCKING` - Querying some parameters requires blocking, but
+ * @p mayBlock is false.
+ * - `Status::NO_MEMORY` - Not enough memory to complete this method.
+ * - `Status::BLOCKING` - Querying some fields requires blocking, but @p mayblock
+ * is false.
+ * - `Status::TIMED_OUT` - The operation cannot be finished in a timely manner.
+ * - `Status::CORRUPTED` - Some unknown error occurred.
+ */
+ FieldSupportedValuesQueryResult[] querySupportedValues(
+ in FieldSupportedValuesQuery[] inFields, in boolean mayBlock);
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/InfoBuffer.aidl b/media/c2/aidl/android/hardware/media/c2/InfoBuffer.aidl
new file mode 100644
index 0000000..207c4d0
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/InfoBuffer.aidl
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.Buffer;
+
+/**
+ * An extension of @ref Buffer that also contains a C2Param structure index.
+ *
+ * This is a part of @ref FrameData.
+ */
+@VintfStability
+parcelable InfoBuffer {
+ /**
+ * A C2Param structure index.
+ */
+ int index;
+ /**
+ * Associated @ref Buffer object.
+ */
+ Buffer buffer;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/ParamDescriptor.aidl b/media/c2/aidl/android/hardware/media/c2/ParamDescriptor.aidl
new file mode 100644
index 0000000..84c6acc
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/ParamDescriptor.aidl
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Usage description of a C2Param structure.
+ *
+ * @ref ParamDescriptor is returned by IConfigurable::querySupportedParams().
+ */
+@VintfStability
+parcelable ParamDescriptor {
+ /** The list of bit flags for attrib */
+ /**
+ * The parameter is required to be specified.
+ */
+ const int ATTRIBUTE_REQUIRED = 1 << 0;
+ /**
+ * The parameter retains its value.
+ */
+ const int ATTRIBUTE_PERSISTENT = 1 << 1;
+ /**
+ * The parameter is strict.
+ */
+ const int ATTRIBUTE_STRICT = 1 << 2;
+ /**
+ * The parameter is publicly read-only.
+ */
+ const int ATTRIBUTE_READ_ONLY = 1 << 3;
+ /**
+ * The parameter must not be visible to clients.
+ */
+ const int ATTRIBUTE_HIDDEN = 1 << 4;
+ /**
+ * The parameter must not be used by framework (other than testing).
+ */
+ const int ATTRIBUTE_INTERNAL = 1 << 5;
+ /**
+ * The parameter is publicly constant (hence read-only).
+ */
+ const int ATTRIBUTE_CONST = 1 << 6;
+
+ /**
+ * Index of the C2Param structure being described.
+ */
+ int index;
+ /**
+ * bit flag for attribute defined in the above.
+ */
+ int attrib;
+ /**
+ * Name of the structure. This must be unique for each structure.
+ */
+ String name;
+ /**
+ * Indices of other C2Param structures that this C2Param structure depends
+ * on.
+ */
+ int[] dependencies;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/ParamField.aidl b/media/c2/aidl/android/hardware/media/c2/ParamField.aidl
new file mode 100644
index 0000000..64a46bb
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/ParamField.aidl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FieldId;
+
+/**
+ * Reference to a field in a C2Param structure.
+ */
+@VintfStability
+parcelable ParamField {
+ /**
+ * Index of the C2Param structure.
+ */
+ int index;
+ /**
+ * Identifier of the field inside the C2Param structure.
+ */
+ FieldId fieldId;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/ParamFieldValues.aidl b/media/c2/aidl/android/hardware/media/c2/ParamFieldValues.aidl
new file mode 100644
index 0000000..7b74c0e
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/ParamFieldValues.aidl
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FieldSupportedValues;
+import android.hardware.media.c2.ParamField;
+
+/**
+ * Supported values for a field.
+ *
+ * This is a pair of the field specifier together with an optional supported
+ * values object. This structure is used when reporting parameter configuration
+ * failures and conflicts.
+ */
+@VintfStability
+parcelable ParamFieldValues {
+ /**
+ * Reference to a field or a C2Param structure.
+ */
+ ParamField paramOrField;
+ /**
+ * Optional supported values for the field if #paramOrField specifies an
+ * actual field that is numeric (non struct, blob or string). Supported
+ * values for arrays (including string and blobs) describe the supported
+ * values for each element (character for string, and bytes for blobs). It
+ * is optional for read-only strings and blobs.
+ */
+ FieldSupportedValues[] values;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/Params.aidl b/media/c2/aidl/android/hardware/media/c2/Params.aidl
new file mode 100644
index 0000000..53b512c
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/Params.aidl
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Flattened representation of std::vector<C2Param> object.
+ *
+ * The `Params` type is an array of bytes made up by concatenating a list of
+ * C2Param objects. The start index (offset into @ref Params) of each C2Param
+ * object in the list is divisible by 8. Up to 7 padding bytes may be added
+ * after each C2Param object to achieve this 64-bit alignment.
+ *
+ * Each C2Param object has the following layout:
+ * - 4 bytes: C2Param structure index (of type @ref ParamIndex) identifying the
+ * type of the C2Param object.
+ * - 4 bytes: size of the C2Param object (unsigned 4-byte integer).
+ * - (size - 8) bytes: data of the C2Param object.
+ */
+@VintfStability
+parcelable Params {
+ byte[] params;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/SettingResult.aidl b/media/c2/aidl/android/hardware/media/c2/SettingResult.aidl
new file mode 100644
index 0000000..c2b9574
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/SettingResult.aidl
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.ParamFieldValues;
+
+/**
+ * Information describing the reason the parameter settings may fail, or may be
+ * overridden.
+ */
+@VintfStability
+parcelable SettingResult {
+ /**
+ * Failure code
+ */
+ @VintfStability
+ @Backing(type="int")
+ enum Failure {
+ /**
+ * Parameter is not supported.
+ */
+ BAD_TYPE,
+ /**
+ * Parameter is not supported on the specific port.
+ */
+ BAD_PORT,
+ /**
+ * Parameter is not supported on the specific stream.
+ */
+ BAD_INDEX,
+ /**
+ * Parameter is read-only and cannot be set.
+ */
+ READ_ONLY,
+ /**
+ * Parameter mismatches input data.
+ */
+ MISMATCH,
+ /**
+ * Strict parameter does not accept value for the field at all.
+ */
+ BAD_VALUE,
+ /**
+ * Strict parameter field value is in conflict with an/other
+ * setting(s).
+ */
+ CONFLICT,
+ /**
+ * Parameter field is out of range due to other settings. (This failure
+ * mode can only be used for strict calculated parameters.)
+ */
+ UNSUPPORTED,
+ /**
+ * Field does not access the requested parameter value at all. It has
+ * been corrected to the closest supported value. This failure mode is
+ * provided to give guidance as to what are the currently supported
+ * values for this field (which may be a subset of the at-all-potential
+ * values).
+ */
+ INFO_BAD_VALUE,
+ /**
+ * Requested parameter value is in conflict with an/other setting(s)
+ * and has been corrected to the closest supported value. This failure
+ * mode is given to provide guidance as to what are the currently
+ * supported values as well as to optionally provide suggestion to the
+ * client as to how to enable the requested parameter value.
+ */
+ INFO_CONFLICT,
+ }
+ Failure failure;
+ /**
+ * Failing (or corrected) field or parameter and optionally, currently
+ * supported values for the field. Values must only be set for field
+ * failures other than `BAD_VALUE`, and only if they are different from the
+ * globally supported values (e.g. due to restrictions by another parameter
+ * or input data).
+ */
+ ParamFieldValues field;
+ /**
+ * Conflicting parameters or fields with (optional) suggested values for any
+ * conflicting fields to avoid the conflict. Values must only be set for
+ * `CONFLICT`, `UNSUPPORTED` or `INFO_CONFLICT` failure code.
+ */
+ ParamFieldValues[] conflicts;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/Status.aidl b/media/c2/aidl/android/hardware/media/c2/Status.aidl
new file mode 100644
index 0000000..58a2404
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/Status.aidl
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Common return values for Codec2 operations.
+ */
+@VintfStability
+parcelable Status {
+ /**
+ * Operation completed successfully.
+ */
+ const int OK = 0;
+ /**
+ * Argument has invalid value (user error).
+ */
+ const int BAD_VALUE = -22;
+ /**
+ * Argument uses invalid index (user error).
+ */
+ const int BAD_INDEX = -75;
+ /**
+ * Argument/Index is valid but not possible.
+ */
+ const int CANNOT_DO = -2147483646;
+ /**
+ * Object already exists.
+ */
+ const int DUPLICATE = -17;
+ /**
+ * Object not found.
+ */
+ const int NOT_FOUND = -2;
+ /**
+ * Operation is not permitted in the current state.
+ */
+ const int BAD_STATE = -38;
+ /**
+ * Operation would block but blocking is not permitted.
+ */
+ const int BLOCKING = -9930;
+ /**
+ * Not enough memory to complete operation.
+ */
+ const int NO_MEMORY = -12;
+ /**
+ * Missing permission to complete operation.
+ */
+ const int REFUSED = -1;
+ /**
+ * Operation did not complete within timeout.
+ */
+ const int TIMED_OUT = -110;
+ /**
+ * Operation is not implemented/supported (optional only).
+ */
+ const int OMITTED = -74;
+ /**
+ * Some unexpected error prevented the operation.
+ */
+ const int CORRUPTED = -2147483648;
+ /**
+ * Status has not been initialized.
+ */
+ const int NO_INIT = -19;
+
+ int status;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/StructDescriptor.aidl b/media/c2/aidl/android/hardware/media/c2/StructDescriptor.aidl
new file mode 100644
index 0000000..00359041
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/StructDescriptor.aidl
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FieldDescriptor;
+
+/**
+ * Description of a C2Param structure. It consists of an index and a list of
+ * `FieldDescriptor`s.
+ */
+@VintfStability
+parcelable StructDescriptor {
+ /**
+ * Index of the structure.
+ *
+ * Actually C2Param::CoreIndex
+ * Core index is the underlying parameter type for a parameter. It is used to describe the
+ * layout of the parameter structure regardless of the component or parameter kind/scope.
+ *
+ * It is used to identify and distinguish global parameters, and also parameters on a given
+ * port or stream. They must be unique for the set of global parameters, as well as for the
+ * set of parameters on each port or each stream, but the same core index can be used for
+ * parameters on different streams or ports, as well as for global parameters and port/stream
+ * parameters.
+ */
+ int type;
+ /**
+ * List of fields in the structure.
+ *
+ * Fields are ordered by their offsets. A field that is a structure is
+ * ordered before its members.
+ */
+ FieldDescriptor[] fields;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/SurfaceSyncObj.aidl b/media/c2/aidl/android/hardware/media/c2/SurfaceSyncObj.aidl
new file mode 100644
index 0000000..d20e102
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/SurfaceSyncObj.aidl
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.common.NativeHandle;
+/**
+ * Surface(BufferQueue/IGBP) synchronization object regarding # of dequeued
+ * output buffers. This keeps # of dequeued buffers from Surface less than
+ * configured max # of dequeued buffers all the time.
+ */
+@VintfStability
+parcelable SurfaceSyncObj {
+ /**
+ * ASharedMemory for synchronization data. Layout is below
+ *
+ * |lock(futex) 4bytes|
+ * |conditional_variable(futex) 4bytes|
+ * |# of max dequeable buffer 4bytes|
+ * |# of dequeued buffer 4bytes|
+ * |Status of the surface 4bytes|
+ * INIT = 0, Configuring surface is not finished.
+ * ACTIVE = 1, Surface is ready to allocate(dequeue).
+ * SWITCHING = 2, Switching to the new surface. It is blocked
+ * to allocate(dequeue) a buffer until switching
+ * completes.
+ */
+ NativeHandle syncMemory;
+ /**
+ * BufferQueue id.
+ */
+ long bqId;
+ /**
+ * Generation id.
+ */
+ int generationId;
+ /**
+ * Consumer usage flags. See +ndk
+ * libnativewindow#AHardwareBuffer_UsageFlags for possible values.
+ */
+ long consumerUsage;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/ValueRange.aidl b/media/c2/aidl/android/hardware/media/c2/ValueRange.aidl
new file mode 100644
index 0000000..9abcb7d
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/ValueRange.aidl
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Description of a set of values.
+ *
+ * If the `step` member is 0, and `num` and `denom` are both 1, the `Range`
+ * structure represents a closed interval bounded by `min` and `max`.
+ *
+ * Otherwise, the #ValueRange structure represents a finite sequence of numbers
+ * produced from the following recurrence relation:
+ *
+ * @code
+ * v[0] = min
+ * v[i] = v[i - 1] * num / denom + step ; i >= 1
+ * @endcode
+ *
+ * Both the ratio `num / denom` and the value `step` must be positive. The
+ * last number in the sequence described by this #Range structure is the
+ * largest number in the sequence that is smaller than or equal to `max`.
+ *
+ * @note
+ * The division in the formula may truncate the result if the data type of
+ * these values is an integral type.
+ */
+@VintfStability
+parcelable ValueRange {
+ /**
+ * Lower end of the range (inclusive).
+ */
+ long min;
+ /**
+ * Upper end of the range (inclusive).
+ */
+ long max;
+ /**
+ * The non-homogeneous term in the recurrence relation.
+ */
+ long step;
+ /**
+ * The numerator of the scale coefficient in the recurrence relation.
+ */
+ long num;
+ /**
+ * The denominator of the scale coefficient in the recurrence relation.
+ */
+ long denom;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/Work.aidl b/media/c2/aidl/android/hardware/media/c2/Work.aidl
new file mode 100644
index 0000000..4b8d696
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/Work.aidl
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FrameData;
+import android.hardware.media.c2.Status;
+import android.hardware.media.c2.Worklet;
+
+/**
+ * A collection of input data to and output data from the component.
+ *
+ * A `Work` object holds information about a single work item. It is created by
+ * the client and passed to the component via IComponent::queue(). The component
+ * has two ways of returning a `Work` object to the client:
+ * 1. If the queued `Work` object has been successfully processed,
+ * IComponentListener::onWorkDone() shall be called to notify the listener,
+ * and the output shall be included in the returned `Work` object.
+ * 2. If the client calls IComponent::flush(), a `Work` object that has not
+ * been processed shall be returned.
+ *
+ * `Work` is a part of @ref WorkBundle.
+ */
+@VintfStability
+parcelable Work {
+ /**
+ * Additional work chain info not part of this work.
+ */
+ byte[] chainInfo;
+ /**
+ * @ref FrameData for the input.
+ */
+ FrameData input;
+ /**
+ * The chain of `Worklet`s.
+ *
+ * The length of #worklets is 1 when tunneling is not enabled.
+ *
+ * If #worklets has more than a single element, the tunnels between
+ * successive components of the work chain must have been successfully
+ * pre-registered at the time that the `Work` is submitted. Allocating the
+ * output buffers in the `Worklet`s is the responsibility of each component
+ * in the chain.
+ *
+ * Upon `Work` submission, #worklets must be an appropriately sized vector
+ * containing `Worklet`s with @ref Worklet.hasOutput set to `false`. After a
+ * successful processing, all but the final `Worklet` in the returned
+ * #worklets must have @ref Worklet.hasOutput set to `false`.
+ */
+ Worklet[] worklets;
+ /**
+ * The number of `Worklet`s successfully processed in this chain.
+ *
+ * This must be initialized to 0 by the client when the `Work` is submitted,
+ * and it must contain the number of `Worklet`s that were successfully
+ * processed when the `Work` is returned to the client.
+ *
+ * #workletsProcessed cannot exceed the length of #worklets. If
+ * #workletsProcessed is smaller than the length of #worklets, #result
+ * cannot be `OK`.
+ */
+ int workletsProcessed;
+ /**
+ * The final outcome of the `Work` (corresponding to #workletsProcessed).
+ *
+ * The value of @ref Status.OK implies that all `Worklet`s have been
+ * successfully processed.
+ */
+ Status result;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/WorkBundle.aidl b/media/c2/aidl/android/hardware/media/c2/WorkBundle.aidl
new file mode 100644
index 0000000..2125fda
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/WorkBundle.aidl
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.BaseBlock;
+import android.hardware.media.c2.Work;
+
+/**
+ * List of `Work` objects.
+ *
+ * `WorkBundle` is used in IComponent::queue(), IComponent::flush() and
+ * IComponentListener::onWorkDone(). A `WorkBundle` object consists of a list of
+ * `Work` objects and a list of `BaseBlock` objects. Bundling multiple `Work`
+ * objects together provides two benefits:
+ * 1. Batching of `Work` objects can reduce the number of IPC calls.
+ * 2. If multiple `Work` objects contain `Block`s that refer to the same
+ * `BaseBlock`, the number of `BaseBlock`s that is sent between processes
+ * is also reduced.
+ *
+ * @note `WorkBundle` is the AIDL counterpart of the vector of `C2Work` in the
+ * Codec 2.0 standard. The presence of #baseBlocks helps with minimizing the
+ * data transferred over an IPC.
+ */
+@VintfStability
+parcelable WorkBundle {
+ /**
+ * A list of Work items.
+ */
+ Work[] works;
+ /**
+ * A list of blocks indexed by elements of #works.
+ */
+ BaseBlock[] baseBlocks;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/WorkOrdinal.aidl b/media/c2/aidl/android/hardware/media/c2/WorkOrdinal.aidl
new file mode 100644
index 0000000..5708a90
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/WorkOrdinal.aidl
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+/**
+ * Ordering information of @ref FrameData objects. Each member is used for
+ * comparing urgency: a smaller difference from a reference value indicates that
+ * the associated Work object is more urgent. The reference value for each
+ * member is initialized the first time it is communicated between the client
+ * and the codec, and it may be updated to later values that are communicated.
+ *
+ * Each member of `WorkOrdinal` is stored as an unsigned integer, but the actual
+ * order it represents is derived by subtracting the reference value, then
+ * interpreting the result as a signed number with the same storage size (using
+ * two's complement).
+ *
+ * @note `WorkOrdinal` is the HIDL counterpart of `C2WorkOrdinalStruct` in the
+ * Codec 2.0 standard.
+ */
+@VintfStability
+parcelable WorkOrdinal {
+ /**
+ * Timestamp in microseconds.
+ */
+ long timestampUs;
+ /**
+ * Frame index.
+ */
+ long frameIndex;
+ /**
+ * Component specific frame ordinal.
+ */
+ long customOrdinal;
+}
diff --git a/media/c2/aidl/android/hardware/media/c2/Worklet.aidl b/media/c2/aidl/android/hardware/media/c2/Worklet.aidl
new file mode 100644
index 0000000..6b3ceac
--- /dev/null
+++ b/media/c2/aidl/android/hardware/media/c2/Worklet.aidl
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.media.c2;
+
+import android.hardware.media.c2.FrameData;
+import android.hardware.media.c2.SettingResult;
+
+/**
+ * In/out structure containing some instructions for and results from output
+ * processing.
+ *
+ * This is a part of @ref Work. One `Worklet` corresponds to one output
+ * @ref FrameData. The client must construct an original `Worklet` object inside
+ * a @ref Work object for each expected output before calling
+ * IComponent::queue().
+ */
+@VintfStability
+parcelable Worklet {
+ /**
+ * Component id. (Input)
+ *
+ * This is used only when tunneling is enabled.
+ *
+ * When used, this must match the return value from IConfigurable::getId().
+ */
+ int componentId;
+ /**
+ * List of C2Param objects describing tunings to be applied before
+ * processing this `Worklet`. (Input)
+ */
+ byte[] tunings;
+ /**
+ * List of failures. (Output)
+ */
+ SettingResult[] failures;
+ /**
+ * Output frame data. (Output)
+ */
+ FrameData output;
+}
diff --git a/memtrack/aidl/Android.bp b/memtrack/aidl/Android.bp
index 79effcb..0d1c241 100644
--- a/memtrack/aidl/Android.bp
+++ b/memtrack/aidl/Android.bp
@@ -39,5 +39,6 @@
},
},
},
+ frozen: true,
versions: ["1"],
}
diff --git a/neuralnetworks/1.0/vts/functional/Android.bp b/neuralnetworks/1.0/vts/functional/Android.bp
index a41f37f..8048e62 100644
--- a/neuralnetworks/1.0/vts/functional/Android.bp
+++ b/neuralnetworks/1.0/vts/functional/Android.bp
@@ -27,7 +27,6 @@
name: "neuralnetworks_vts_functional_defaults",
defaults: [
"VtsHalTargetTestDefaults",
- "neuralnetworks_float16",
],
}
diff --git a/radio/aidl/Android.bp b/radio/aidl/Android.bp
index 8911aea..9dbe09a 100644
--- a/radio/aidl/Android.bp
+++ b/radio/aidl/Android.bp
@@ -36,7 +36,7 @@
host_supported: true,
srcs: ["android/hardware/radio/config/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: true,
@@ -60,7 +60,7 @@
host_supported: true,
srcs: ["android/hardware/radio/data/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: true,
@@ -84,7 +84,7 @@
host_supported: true,
srcs: ["android/hardware/radio/messaging/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: true,
@@ -108,7 +108,7 @@
host_supported: true,
srcs: ["android/hardware/radio/modem/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: true,
@@ -132,7 +132,7 @@
host_supported: true,
srcs: ["android/hardware/radio/network/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: true,
@@ -157,8 +157,8 @@
srcs: ["android/hardware/radio/sim/*.aidl"],
stability: "vintf",
imports: [
- "android.hardware.radio-V1",
- "android.hardware.radio.config",
+ "android.hardware.radio-V2",
+ "android.hardware.radio.config-V2",
],
backend: {
cpp: {
@@ -186,7 +186,7 @@
host_supported: true,
srcs: ["android/hardware/radio/voice/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: true,
@@ -209,8 +209,10 @@
vendor_available: true,
srcs: ["android/hardware/radio/ims/media/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1",
- "android.hardware.radio.data-V1"],
+ imports: [
+ "android.hardware.radio-V2",
+ "android.hardware.radio.data-V2",
+ ],
backend: {
cpp: {
enabled: false,
@@ -226,7 +228,7 @@
vendor_available: true,
srcs: ["android/hardware/radio/ims/*.aidl"],
stability: "vintf",
- imports: ["android.hardware.radio-V1"],
+ imports: ["android.hardware.radio-V2"],
backend: {
cpp: {
enabled: false,
@@ -236,4 +238,3 @@
},
},
}
-
diff --git a/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/MultipleEnabledProfilesMode.aidl b/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/MultipleEnabledProfilesMode.aidl
new file mode 100644
index 0000000..fad767c
--- /dev/null
+++ b/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/MultipleEnabledProfilesMode.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.radio.config;
+@Backing(type="int") @JavaDerive(toString=true) @VintfStability
+enum MultipleEnabledProfilesMode {
+ NONE = 0,
+ MEP_A1 = 1,
+ MEP_A2 = 2,
+ MEP_B = 3,
+}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/SimSlotStatus.aidl b/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/SimSlotStatus.aidl
index be4c080..da894cd 100644
--- a/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/SimSlotStatus.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio.config/current/android/hardware/radio/config/SimSlotStatus.aidl
@@ -38,4 +38,5 @@
String atr;
String eid;
android.hardware.radio.config.SimPortInfo[] portInfo;
+ android.hardware.radio.config.MultipleEnabledProfilesMode supportedMepMode;
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.data/current/android/hardware/radio/data/NrQos.aidl b/radio/aidl/aidl_api/android.hardware.radio.data/current/android/hardware/radio/data/NrQos.aidl
index 62f6204..a0792c3 100644
--- a/radio/aidl/aidl_api/android.hardware.radio.data/current/android/hardware/radio/data/NrQos.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio.data/current/android/hardware/radio/data/NrQos.aidl
@@ -37,8 +37,12 @@
int fiveQi;
android.hardware.radio.data.QosBandwidth downlink;
android.hardware.radio.data.QosBandwidth uplink;
+ /**
+ * @deprecated use qosFlowIdentifier.
+ */
byte qfi;
char averagingWindowMs;
+ int qosFlowIdentifier;
const byte FLOW_ID_RANGE_MIN = 1;
const byte FLOW_ID_RANGE_MAX = 63;
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetwork.aidl b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetwork.aidl
index 9761900..5aed024 100644
--- a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetwork.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetwork.aidl
@@ -80,4 +80,6 @@
oneway void setNullCipherAndIntegrityEnabled(in int serial, in boolean enabled);
oneway void isN1ModeEnabled(in int serial);
oneway void setN1ModeEnabled(in int serial, boolean enable);
+ oneway void setLocationPrivacySetting(in int serial, in boolean shareLocation);
+ oneway void getLocationPrivacySetting(in int serial);
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkIndication.aidl b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkIndication.aidl
index 0f017ea..229f3e2 100644
--- a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkIndication.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkIndication.aidl
@@ -49,4 +49,5 @@
oneway void suppSvcNotify(in android.hardware.radio.RadioIndicationType type, in android.hardware.radio.network.SuppSvcNotification suppSvc);
oneway void voiceRadioTechChanged(in android.hardware.radio.RadioIndicationType type, in android.hardware.radio.RadioTechnology rat);
oneway void emergencyNetworkScanResult(in android.hardware.radio.RadioIndicationType type, in android.hardware.radio.network.EmergencyRegResult result);
+ oneway void onNetworkInitiatedLocationResult(in android.hardware.radio.RadioIndicationType type, in android.hardware.radio.network.LocationResponseType locationResponseType);
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkResponse.aidl b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkResponse.aidl
index c228bc1..ccdfde6 100644
--- a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkResponse.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/IRadioNetworkResponse.aidl
@@ -79,4 +79,6 @@
oneway void setNullCipherAndIntegrityEnabledResponse(in android.hardware.radio.RadioResponseInfo info);
oneway void isN1ModeEnabledResponse(in android.hardware.radio.RadioResponseInfo info, boolean isEnabled);
oneway void setN1ModeEnabledResponse(in android.hardware.radio.RadioResponseInfo info);
+ oneway void setLocationPrivacySettingResponse(in android.hardware.radio.RadioResponseInfo info);
+ oneway void getLocationPrivacySettingResponse(in android.hardware.radio.RadioResponseInfo info, boolean shareLocation);
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/LocationResponseType.aidl b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/LocationResponseType.aidl
new file mode 100644
index 0000000..e89a40f
--- /dev/null
+++ b/radio/aidl/aidl_api/android.hardware.radio.network/current/android/hardware/radio/network/LocationResponseType.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.radio.network;
+@Backing(type="int") @JavaDerive(toString=true) @VintfStability
+enum LocationResponseType {
+ REJECTED = 0,
+ ACCEPTED_NO_LOCATION_PROVIDED = 1,
+ ACCEPTED_LOCATION_PROVIDED = 2,
+}
diff --git a/radio/aidl/aidl_api/android.hardware.radio.sim/current/android/hardware/radio/sim/SimApdu.aidl b/radio/aidl/aidl_api/android.hardware.radio.sim/current/android/hardware/radio/sim/SimApdu.aidl
index 2201345..2f2e07b 100644
--- a/radio/aidl/aidl_api/android.hardware.radio.sim/current/android/hardware/radio/sim/SimApdu.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio.sim/current/android/hardware/radio/sim/SimApdu.aidl
@@ -41,4 +41,5 @@
int p2;
int p3;
String data;
+ boolean isEs10;
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioAccessFamily.aidl b/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioAccessFamily.aidl
index ecc2a9b..afc4f4e 100644
--- a/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioAccessFamily.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioAccessFamily.aidl
@@ -53,6 +53,9 @@
GSM = 65536,
TD_SCDMA = 131072,
IWLAN = 262144,
+ /**
+ * @deprecated use LTE instead.
+ */
LTE_CA = 524288,
NR = 1048576,
}
diff --git a/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioTechnology.aidl b/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioTechnology.aidl
index 9dad0a4..7060469 100644
--- a/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioTechnology.aidl
+++ b/radio/aidl/aidl_api/android.hardware.radio/current/android/hardware/radio/RadioTechnology.aidl
@@ -53,6 +53,9 @@
GSM = 16,
TD_SCDMA = 17,
IWLAN = 18,
+ /**
+ * @deprecated use LTE instead and indicate carrier aggregation through multiple physical channel configurations in IRadioNetwork::currentPhysicalChannelConfigs.
+ */
LTE_CA = 19,
NR = 20,
}
diff --git a/radio/aidl/android/hardware/radio/RadioAccessFamily.aidl b/radio/aidl/android/hardware/radio/RadioAccessFamily.aidl
index 6cd0a95..edf33ba 100644
--- a/radio/aidl/android/hardware/radio/RadioAccessFamily.aidl
+++ b/radio/aidl/android/hardware/radio/RadioAccessFamily.aidl
@@ -41,6 +41,7 @@
GSM = 1 << RadioTechnology.GSM,
TD_SCDMA = 1 << RadioTechnology.TD_SCDMA,
IWLAN = 1 << RadioTechnology.IWLAN,
+ /** @deprecated use LTE instead. */
LTE_CA = 1 << RadioTechnology.LTE_CA,
/**
* 5G NR. This is only use in 5G Standalone mode.
diff --git a/radio/aidl/android/hardware/radio/RadioTechnology.aidl b/radio/aidl/android/hardware/radio/RadioTechnology.aidl
index 917cb16..4b51152 100644
--- a/radio/aidl/android/hardware/radio/RadioTechnology.aidl
+++ b/radio/aidl/android/hardware/radio/RadioTechnology.aidl
@@ -45,6 +45,10 @@
GSM,
TD_SCDMA,
IWLAN,
+ /**
+ * @deprecated use LTE instead and indicate carrier aggregation through multiple
+ * physical channel configurations in IRadioNetwork::currentPhysicalChannelConfigs.
+ */
LTE_CA,
/**
* 5G NR. This is only used in 5G Standalone mode.
diff --git a/radio/aidl/android/hardware/radio/config/MultipleEnabledProfilesMode.aidl b/radio/aidl/android/hardware/radio/config/MultipleEnabledProfilesMode.aidl
new file mode 100644
index 0000000..b18ea0e
--- /dev/null
+++ b/radio/aidl/android/hardware/radio/config/MultipleEnabledProfilesMode.aidl
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.radio.config;
+
+/**
+ * Multiple Enabled Profiles(MEP) mode is the jointly supported MEP mode. As per section 3.4.1.1 of
+ * GSMA spec SGP.22 v3.0,there are 3 supported MEP modes: MEP-A1, MEP-A2 and MEP-B.
+ * If there is no jointly supported MEP mode, supported MEP mode is set to NONE.
+ */
+@VintfStability
+@Backing(type="int")
+@JavaDerive(toString=true)
+enum MultipleEnabledProfilesMode {
+ /**
+ * If there is no jointly supported MEP mode, set supported MEP mode to NONE.
+ */
+ NONE,
+ /**
+ * In case of MEP-A1, the ISD-R is selected on eSIM port 0 only and profiles are selected on
+ * eSIM ports 1 and higher, with the eSIM port being assigned by the LPA or platform.
+ */
+ MEP_A1,
+ /**
+ * In case of MEP-A2, the ISD-R is selected on eSIM port 0 only and profiles are selected on
+ * eSIM ports 1 and higher, with the eSIM port being assigned by the eUICC.
+ */
+ MEP_A2,
+ /**
+ * In case of MEP-B, profiles are selected on eSIM ports 0 and higher, with the ISD-R being
+ * selectable on any of these eSIM ports.
+ */
+ MEP_B,
+}
diff --git a/radio/aidl/android/hardware/radio/config/SimSlotStatus.aidl b/radio/aidl/android/hardware/radio/config/SimSlotStatus.aidl
index 748660f..73f2954 100644
--- a/radio/aidl/android/hardware/radio/config/SimSlotStatus.aidl
+++ b/radio/aidl/android/hardware/radio/config/SimSlotStatus.aidl
@@ -16,6 +16,7 @@
package android.hardware.radio.config;
+import android.hardware.radio.config.MultipleEnabledProfilesMode;
import android.hardware.radio.config.SimPortInfo;
@VintfStability
@@ -52,4 +53,8 @@
* active port in the slot mapping.
*/
SimPortInfo[] portInfo;
+ /**
+ * Jointly supported Multiple Enabled Profiles(MEP) mode as per SGP.22 V3.0
+ */
+ MultipleEnabledProfilesMode supportedMepMode;
}
diff --git a/radio/aidl/android/hardware/radio/data/NrQos.aidl b/radio/aidl/android/hardware/radio/data/NrQos.aidl
index af8ab83..28b4a7f 100644
--- a/radio/aidl/android/hardware/radio/data/NrQos.aidl
+++ b/radio/aidl/android/hardware/radio/data/NrQos.aidl
@@ -36,9 +36,13 @@
QosBandwidth downlink;
QosBandwidth uplink;
/**
- * QOS flow identifier of the QOS flow description in the range
- * (FLOW_ID_RANGE_MIN, FLOW_ID_RANGE_MAX)
+ * @deprecated use qosFlowIdentifier.
*/
byte qfi;
char averagingWindowMs;
+ /**
+ * QOS flow identifier of the QOS flow description in the range
+ * (FLOW_ID_RANGE_MIN, FLOW_ID_RANGE_MAX).
+ **/
+ int qosFlowIdentifier;
}
diff --git a/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl b/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl
index 4d35742..70427f8 100644
--- a/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl
+++ b/radio/aidl/android/hardware/radio/network/IRadioNetwork.aidl
@@ -488,7 +488,11 @@
/**
* Set if null encryption and integrity modes are enabled. If the value of enabled is false
* the modem must not allow any network communications with null ciphering or null integrity
- * modes. In case of an emergency call, the modem must bypass this setting.
+ * modes.
+ *
+ * In the case when enabled is false, integrity protection for user data is optional, but
+ * ciphering for user data is required. In case of an emergency call, the modem must bypass
+ * this setting.
*
* Null ciphering and integrity modes include (but are not limited to):
* 2G: A5/0
@@ -530,4 +534,30 @@
* Response function is IRadioNetworkResponse.setN1ModeEnabledResponse()
*/
void setN1ModeEnabled(in int serial, boolean enable);
+
+ /**
+ * This API updates the current user setting of sharing the location data. This value must be
+ * used by radio before honoring a network initiated location request for non emergency use
+ * cases. The radio shall ignore this setting during emergency call, emergency SMS or emergency
+ * call back modes and continue to provide the location information to the network initiated
+ * location requests.
+ *
+ * @param serial Serial number of request.
+ * @param shareLocation Whether to share location data to the network or not. true means the
+ * radio is allowed to provide location data for any network initiated locations
+ * request. false means the radio must not share location data for any network initiated
+ * location requests for non-emergency use cases.
+ *
+ * Response function is IRadioNetworkResponse.setLocationPrivacySettingResponse()
+ */
+ void setLocationPrivacySetting(in int serial, in boolean shareLocation);
+
+ /**
+ * Request the current setting of sharing the location data.
+ *
+ * @param serial Serial number of request.
+ *
+ * Response function is IRadioNetworkResponse.getLocationPrivacySettingResponse()
+ */
+ void getLocationPrivacySetting(in int serial);
}
diff --git a/radio/aidl/android/hardware/radio/network/IRadioNetworkIndication.aidl b/radio/aidl/android/hardware/radio/network/IRadioNetworkIndication.aidl
index 47d932d..2891496 100644
--- a/radio/aidl/android/hardware/radio/network/IRadioNetworkIndication.aidl
+++ b/radio/aidl/android/hardware/radio/network/IRadioNetworkIndication.aidl
@@ -21,13 +21,14 @@
import android.hardware.radio.network.BarringInfo;
import android.hardware.radio.network.CellIdentity;
import android.hardware.radio.network.CellInfo;
+import android.hardware.radio.network.EmergencyRegResult;
import android.hardware.radio.network.LinkCapacityEstimate;
+import android.hardware.radio.network.LocationResponseType;
import android.hardware.radio.network.NetworkScanResult;
import android.hardware.radio.network.PhoneRestrictedState;
import android.hardware.radio.network.PhysicalChannelConfig;
import android.hardware.radio.network.SignalStrength;
import android.hardware.radio.network.SuppSvcNotification;
-import android.hardware.radio.network.EmergencyRegResult;
/**
* Interface declaring unsolicited radio indications for network APIs.
@@ -199,4 +200,13 @@
* @param result the result of the Emergency Network Scan
*/
void emergencyNetworkScanResult(in RadioIndicationType type, in EmergencyRegResult result);
+
+ /**
+ * Reports the result of the network initiated location request.
+ *
+ * @param type Type of radio indication
+ * @param locationResponseType result of the network initiated location request.
+ */
+ void onNetworkInitiatedLocationResult(
+ in RadioIndicationType type, in LocationResponseType locationResponseType);
}
diff --git a/radio/aidl/android/hardware/radio/network/IRadioNetworkResponse.aidl b/radio/aidl/android/hardware/radio/network/IRadioNetworkResponse.aidl
index 3802bd6..3fa6521 100644
--- a/radio/aidl/android/hardware/radio/network/IRadioNetworkResponse.aidl
+++ b/radio/aidl/android/hardware/radio/network/IRadioNetworkResponse.aidl
@@ -654,4 +654,26 @@
* RadioError:INVALID_STATE
*/
void setN1ModeEnabledResponse(in RadioResponseInfo info);
+
+ /**
+ * @param info Response info struct containing response type, serial no. and error
+ *
+ * Valid errors returned:
+ * RadioError:NONE
+ * RadioError:RADIO_NOT_AVAILABLE
+ * RadioError:INTERNAL_ERR
+ */
+ void setLocationPrivacySettingResponse(in RadioResponseInfo info);
+
+ /**
+ * @param info Response info struct containing response type, serial no. and error
+ * @param shareLocation Indicates whether the location sharing is allowed or not, True if
+ * allowed else false.
+ *
+ * Valid errors returned:
+ * RadioError:NONE
+ * RadioError:RADIO_NOT_AVAILABLE
+ * RadioError:INTERNAL_ERR
+ */
+ void getLocationPrivacySettingResponse(in RadioResponseInfo info, boolean shareLocation);
}
diff --git a/radio/aidl/android/hardware/radio/network/LocationResponseType.aidl b/radio/aidl/android/hardware/radio/network/LocationResponseType.aidl
new file mode 100644
index 0000000..0c502d0
--- /dev/null
+++ b/radio/aidl/android/hardware/radio/network/LocationResponseType.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.radio.network;
+
+@VintfStability
+@Backing(type="int")
+@JavaDerive(toString=true)
+enum LocationResponseType {
+ /**
+ * Network initiated Location request rejected by modem because the user has not given
+ * permission for this use case
+ */
+ REJECTED = 0,
+ /**
+ * Network initiated Location request is accepted by modem however no location information has
+ * been shared to network due to a failure
+ */
+ ACCEPTED_NO_LOCATION_PROVIDED = 1,
+ /**
+ * Network initiated Location request is accepted and location information is provided to the
+ * network by modem
+ */
+ ACCEPTED_LOCATION_PROVIDED = 2,
+}
diff --git a/radio/aidl/android/hardware/radio/network/RegStateResult.aidl b/radio/aidl/android/hardware/radio/network/RegStateResult.aidl
index 3d96b8c..f1d2972 100644
--- a/radio/aidl/android/hardware/radio/network/RegStateResult.aidl
+++ b/radio/aidl/android/hardware/radio/network/RegStateResult.aidl
@@ -33,9 +33,9 @@
*/
RegState regState;
/**
- * Indicates the radio technology (except LTE_CA, which is no longer a valid value), which
- * must not be UNKNOWN if regState is REG_HOME, REG_ROAMING, NOT_REG_MT_NOT_SEARCHING_OP_EM,
- * NOT_REG_MT_SEARCHING_OP_EM, REG_DENIED_EM, or UNKNOWN_EM.
+ * Indicates the radio technology, which must not be UNKNOWN if regState is REG_HOME,
+ * REG_ROAMING, NOT_REG_MT_NOT_SEARCHING_OP_EM, NOT_REG_MT_SEARCHING_OP_EM, REG_DENIED_EM,
+ * or UNKNOWN_EM.
* When the device is on carrier aggregation, vendor RIL service must properly report multiple
* PhysicalChannelConfig elements through IRadioNetwork::currentPhysicalChannelConfigs.
*/
diff --git a/radio/aidl/android/hardware/radio/sim/SimApdu.aidl b/radio/aidl/android/hardware/radio/sim/SimApdu.aidl
index 43adbbc..4759e2e 100644
--- a/radio/aidl/android/hardware/radio/sim/SimApdu.aidl
+++ b/radio/aidl/android/hardware/radio/sim/SimApdu.aidl
@@ -49,4 +49,9 @@
* In hex string format ([a-fA-F0-9]*)
*/
String data;
+ /**
+ * isEs10 indicates that the current streaming APDU contains an ES10 command or it is a regular
+ * APDU. (As per spec SGP.22 V3.0, ES10 commands needs to be sent over command port of MEP-A1)
+ */
+ boolean isEs10;
}
diff --git a/radio/aidl/compat/libradiocompat/Android.bp b/radio/aidl/compat/libradiocompat/Android.bp
index 557e461..c40ca30 100644
--- a/radio/aidl/compat/libradiocompat/Android.bp
+++ b/radio/aidl/compat/libradiocompat/Android.bp
@@ -31,18 +31,18 @@
"-DANDROID_UTILS_REF_BASE_DISABLE_IMPLICIT_CONSTRUCTION",
],
shared_libs: [
- "android.hardware.radio.config-V1-ndk",
+ "android.hardware.radio.config-V2-ndk",
"android.hardware.radio.config@1.0",
"android.hardware.radio.config@1.1",
"android.hardware.radio.config@1.2",
"android.hardware.radio.config@1.3",
- "android.hardware.radio.data-V1-ndk",
+ "android.hardware.radio.data-V2-ndk",
"android.hardware.radio.ims-V1-ndk",
- "android.hardware.radio.messaging-V1-ndk",
+ "android.hardware.radio.messaging-V2-ndk",
"android.hardware.radio.modem-V2-ndk",
"android.hardware.radio.network-V2-ndk",
- "android.hardware.radio.sim-V1-ndk",
- "android.hardware.radio.voice-V1-ndk",
+ "android.hardware.radio.sim-V2-ndk",
+ "android.hardware.radio.voice-V2-ndk",
"android.hardware.radio@1.0",
"android.hardware.radio@1.1",
"android.hardware.radio@1.2",
diff --git a/radio/aidl/compat/libradiocompat/data/structs.cpp b/radio/aidl/compat/libradiocompat/data/structs.cpp
index cc6dcbc..22cde6b 100644
--- a/radio/aidl/compat/libradiocompat/data/structs.cpp
+++ b/radio/aidl/compat/libradiocompat/data/structs.cpp
@@ -136,7 +136,7 @@
.fiveQi = qos.fiveQi,
.downlink = toAidl(qos.downlink),
.uplink = toAidl(qos.uplink),
- .qfi = static_cast<int8_t>(qos.qfi),
+ .qosFlowIdentifier = static_cast<int8_t>(qos.qfi),
.averagingWindowMs = qos.averagingWindowMs,
};
}
diff --git a/radio/aidl/compat/libradiocompat/include/libradiocompat/RadioNetwork.h b/radio/aidl/compat/libradiocompat/include/libradiocompat/RadioNetwork.h
index f9f3c6c..b446103 100644
--- a/radio/aidl/compat/libradiocompat/include/libradiocompat/RadioNetwork.h
+++ b/radio/aidl/compat/libradiocompat/include/libradiocompat/RadioNetwork.h
@@ -104,6 +104,9 @@
::ndk::ScopedAStatus setNullCipherAndIntegrityEnabled(int32_t serial, bool enabled) override;
+ ::ndk::ScopedAStatus setLocationPrivacySetting(int32_t serial, bool shareLocation) override;
+ ::ndk::ScopedAStatus getLocationPrivacySetting(int32_t serial) override;
+
protected:
std::shared_ptr<::aidl::android::hardware::radio::network::IRadioNetworkResponse> respond();
diff --git a/radio/aidl/compat/libradiocompat/network/RadioNetwork.cpp b/radio/aidl/compat/libradiocompat/network/RadioNetwork.cpp
index 005deae..730b5dd 100644
--- a/radio/aidl/compat/libradiocompat/network/RadioNetwork.cpp
+++ b/radio/aidl/compat/libradiocompat/network/RadioNetwork.cpp
@@ -360,4 +360,18 @@
respond()->setN1ModeEnabledResponse(notSupported(serial));
return ok();
}
+
+ScopedAStatus RadioNetwork::setLocationPrivacySetting(int32_t serial, bool /*shareLocation*/) {
+ LOG_CALL << serial;
+ LOG(ERROR) << " setLocationPrivacySetting is unsupported by HIDL HALs";
+ respond()->setLocationPrivacySettingResponse(notSupported(serial));
+ return ok();
+}
+
+ScopedAStatus RadioNetwork::getLocationPrivacySetting(int32_t serial) {
+ LOG_CALL << serial;
+ LOG(ERROR) << " getLocationPrivacySetting is unsupported by HIDL HALs";
+ respond()->getLocationPrivacySettingResponse(notSupported(serial), false);
+ return ok();
+}
} // namespace android::hardware::radio::compat
diff --git a/radio/aidl/compat/service/Android.bp b/radio/aidl/compat/service/Android.bp
index 692f15a..7a48da2 100644
--- a/radio/aidl/compat/service/Android.bp
+++ b/radio/aidl/compat/service/Android.bp
@@ -34,18 +34,18 @@
],
shared_libs: [
"android.hardware.radio-library.compat",
- "android.hardware.radio.config-V1-ndk",
+ "android.hardware.radio.config-V2-ndk",
"android.hardware.radio.config@1.0",
"android.hardware.radio.config@1.1",
"android.hardware.radio.config@1.2",
"android.hardware.radio.config@1.3",
- "android.hardware.radio.data-V1-ndk",
+ "android.hardware.radio.data-V2-ndk",
"android.hardware.radio.ims-V1-ndk",
- "android.hardware.radio.messaging-V1-ndk",
+ "android.hardware.radio.messaging-V2-ndk",
"android.hardware.radio.modem-V2-ndk",
"android.hardware.radio.network-V2-ndk",
- "android.hardware.radio.sim-V1-ndk",
- "android.hardware.radio.voice-V1-ndk",
+ "android.hardware.radio.sim-V2-ndk",
+ "android.hardware.radio.voice-V2-ndk",
"android.hardware.radio@1.0",
"android.hardware.radio@1.1",
"android.hardware.radio@1.2",
diff --git a/radio/aidl/vts/Android.bp b/radio/aidl/vts/Android.bp
index 4df54f7..5a0dbd0 100644
--- a/radio/aidl/vts/Android.bp
+++ b/radio/aidl/vts/Android.bp
@@ -66,15 +66,15 @@
"libvintf",
],
static_libs: [
- "android.hardware.radio-V1-ndk",
- "android.hardware.radio.config-V1-ndk",
- "android.hardware.radio.data-V1-ndk",
+ "android.hardware.radio-V2-ndk",
+ "android.hardware.radio.config-V2-ndk",
+ "android.hardware.radio.data-V2-ndk",
"android.hardware.radio.ims-V1-ndk",
- "android.hardware.radio.messaging-V1-ndk",
+ "android.hardware.radio.messaging-V2-ndk",
"android.hardware.radio.modem-V2-ndk",
"android.hardware.radio.network-V2-ndk",
- "android.hardware.radio.sim-V1-ndk",
- "android.hardware.radio.voice-V1-ndk",
+ "android.hardware.radio.sim-V2-ndk",
+ "android.hardware.radio.voice-V2-ndk",
],
test_suites: [
"general-tests",
diff --git a/radio/aidl/vts/radio_network_indication.cpp b/radio/aidl/vts/radio_network_indication.cpp
index ae3bd4b..7178982 100644
--- a/radio/aidl/vts/radio_network_indication.cpp
+++ b/radio/aidl/vts/radio_network_indication.cpp
@@ -97,3 +97,8 @@
RadioIndicationType /*type*/, const EmergencyRegResult& /*result*/) {
return ndk::ScopedAStatus::ok();
}
+
+ndk::ScopedAStatus RadioNetworkIndication::onNetworkInitiatedLocationResult(
+ RadioIndicationType /*type*/, LocationResponseType /*locationResponseType*/) {
+ return ndk::ScopedAStatus::ok();
+}
diff --git a/radio/aidl/vts/radio_network_response.cpp b/radio/aidl/vts/radio_network_response.cpp
index c890df0..4f0e4f3 100644
--- a/radio/aidl/vts/radio_network_response.cpp
+++ b/radio/aidl/vts/radio_network_response.cpp
@@ -313,3 +313,17 @@
parent_network.notify(info.serial);
return ndk::ScopedAStatus::ok();
}
+
+ndk::ScopedAStatus RadioNetworkResponse::setLocationPrivacySettingResponse(
+ const RadioResponseInfo& info) {
+ rspInfo = info;
+ parent_network.notify(info.serial);
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus RadioNetworkResponse::getLocationPrivacySettingResponse(
+ const RadioResponseInfo& info, bool /*shareLocation*/) {
+ rspInfo = info;
+ parent_network.notify(info.serial);
+ return ndk::ScopedAStatus::ok();
+}
diff --git a/radio/aidl/vts/radio_network_test.cpp b/radio/aidl/vts/radio_network_test.cpp
index c15899a..e7a48bc 100644
--- a/radio/aidl/vts/radio_network_test.cpp
+++ b/radio/aidl/vts/radio_network_test.cpp
@@ -1501,7 +1501,7 @@
RadioTechnology rat = radioRsp_network->dataRegResp.rat;
// TODO: add logic for cdmaInfo
- if (rat == RadioTechnology::LTE || rat == RadioTechnology::LTE_CA) {
+ if (rat == RadioTechnology::LTE) {
ASSERT_EQ(info.getTag(), AccessTechnologySpecificInfo::eutranInfo);
} else if (rat == RadioTechnology::NR) {
ASSERT_TRUE(info.getTag() == AccessTechnologySpecificInfo::ngranNrVopsInfo);
diff --git a/radio/aidl/vts/radio_network_utils.h b/radio/aidl/vts/radio_network_utils.h
index e6a320b..92dcb1f 100644
--- a/radio/aidl/vts/radio_network_utils.h
+++ b/radio/aidl/vts/radio_network_utils.h
@@ -166,6 +166,12 @@
const RadioResponseInfo& info, bool isEnabled) override;
virtual ndk::ScopedAStatus setN1ModeEnabledResponse(const RadioResponseInfo& info) override;
+
+ virtual ndk::ScopedAStatus setLocationPrivacySettingResponse(
+ const RadioResponseInfo& info) override;
+
+ virtual ndk::ScopedAStatus getLocationPrivacySettingResponse(const RadioResponseInfo& info,
+ bool shareLocation) override;
};
/* Callback class for radio network indication */
@@ -223,6 +229,9 @@
virtual ndk::ScopedAStatus emergencyNetworkScanResult(
RadioIndicationType type, const EmergencyRegResult& result) override;
+
+ virtual ndk::ScopedAStatus onNetworkInitiatedLocationResult(
+ RadioIndicationType type, LocationResponseType locationResponseType) override;
};
// The main test class for Radio AIDL Network.
diff --git a/secure_element/aidl/Android.bp b/secure_element/aidl/Android.bp
new file mode 100644
index 0000000..5a529a4
--- /dev/null
+++ b/secure_element/aidl/Android.bp
@@ -0,0 +1,35 @@
+aidl_interface {
+ name: "android.hardware.secure_element",
+ vendor_available: true,
+ host_supported: true,
+ srcs: ["android/hardware/secure_element/*.aidl"],
+ stability: "vintf",
+ backend: {
+ cpp: {
+ enabled: false,
+ },
+ java: {
+ sdk_version: "system_current",
+ },
+ },
+}
+
+cc_test {
+ name: "VtsHalSecureElementTargetTest",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ ],
+ srcs: ["vts/VtsHalSecureElementTargetTest.cpp"],
+ shared_libs: [
+ "libbinder_ndk",
+ ],
+ static_libs: [
+ "android.hardware.secure_element-V1-ndk",
+ "libgmock",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
diff --git a/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/ISecureElement.aidl b/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/ISecureElement.aidl
new file mode 100644
index 0000000..fba29ab
--- /dev/null
+++ b/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/ISecureElement.aidl
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.secure_element;
+@VintfStability
+interface ISecureElement {
+ void closeChannel(in byte channelNumber);
+ byte[] getAtr();
+ void init(in android.hardware.secure_element.ISecureElementCallback clientCallback);
+ boolean isCardPresent();
+ byte[] openBasicChannel(in byte[] aid, in byte p2);
+ android.hardware.secure_element.LogicalChannelResponse openLogicalChannel(in byte[] aid, in byte p2);
+ void reset();
+ byte[] transmit(in byte[] data);
+ const int FAILED = 1;
+ const int CHANNEL_NOT_AVAILABLE = 2;
+ const int NO_SUCH_ELEMENT_ERROR = 3;
+ const int UNSUPPORTED_OPERATION = 4;
+ const int IOERROR = 5;
+}
diff --git a/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/ISecureElementCallback.aidl b/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/ISecureElementCallback.aidl
new file mode 100644
index 0000000..6c2be2a
--- /dev/null
+++ b/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/ISecureElementCallback.aidl
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.secure_element;
+@VintfStability
+interface ISecureElementCallback {
+ void onStateChange(in boolean connected, in String debugReason);
+}
diff --git a/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/LogicalChannelResponse.aidl b/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/LogicalChannelResponse.aidl
new file mode 100644
index 0000000..f2e7f04
--- /dev/null
+++ b/secure_element/aidl/aidl_api/android.hardware.secure_element/current/android/hardware/secure_element/LogicalChannelResponse.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.secure_element;
+@VintfStability
+parcelable LogicalChannelResponse {
+ byte channelNumber;
+ byte[] selectResponse;
+}
diff --git a/secure_element/aidl/android/hardware/secure_element/ISecureElement.aidl b/secure_element/aidl/android/hardware/secure_element/ISecureElement.aidl
new file mode 100644
index 0000000..7c5a704
--- /dev/null
+++ b/secure_element/aidl/android/hardware/secure_element/ISecureElement.aidl
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.secure_element;
+
+import android.hardware.secure_element.ISecureElementCallback;
+import android.hardware.secure_element.LogicalChannelResponse;
+
+@VintfStability
+interface ISecureElement {
+ const int FAILED = 1;
+ const int CHANNEL_NOT_AVAILABLE = 2;
+ const int NO_SUCH_ELEMENT_ERROR = 3;
+ const int UNSUPPORTED_OPERATION = 4;
+ const int IOERROR = 5;
+
+ /**
+ * Closes the channel indicated by the channelNumber.
+ *
+ * @throws ServiceSpecificException Closing a channel must return
+ * FAILED on an error or if a basic channel (i.e. channel 0)
+ * is used.
+ *
+ * @param channelNumber to be closed
+ */
+ void closeChannel(in byte channelNumber);
+
+ /**
+ * Returns Answer to Reset as per ISO/IEC 7816
+ *
+ * @return containing the response. Empty vector if Secure Element
+ * doesn't support ATR.
+ */
+ byte[] getAtr();
+
+ /**
+ * Initializes the Secure Element. This may include updating the applet
+ * and/or vendor-specific initialization.
+ *
+ * HAL service must send onStateChange() with connected equal to true
+ * after all the initialization has been successfully completed.
+ * Clients must wait for a onStateChange(true) before opening channels.
+ *
+ * @param clientCallback callback used to sent status of the SE back to the
+ * client
+ */
+ void init(in ISecureElementCallback clientCallback);
+
+ /**
+ * Returns the current state of the card.
+ *
+ * This is useful for removable Secure Elements like UICC,
+ * Secure Elements on SD cards etc.
+ *
+ * @return true if present, false otherwise
+ */
+ boolean isCardPresent();
+
+ /**
+ * Opens a basic channel with the Secure Element, selecting the applet
+ * represented by the Application ID (AID). A basic channel has channel
+ * number 0.
+ *
+ * @throws ServiceSpecificException with codes
+ * - CHANNEL_NOT_AVAILABLE if secure element has reached the maximum
+ * limit on the number of channels it can support.
+ * - NO_SUCH_ELEMENT_ERROR if AID provided doesn't match any applet
+ * on the secure element.
+ * - UNSUPPORTED_OPERATION if operation provided by the P2 parameter
+ * is not permitted by the applet.
+ * - IOERROR if there was an error communicating with the Secure Element.
+ *
+ * @param aid AID to uniquely identify the applet on the Secure Element
+ * @param p2 P2 parameter of SELECT APDU as per ISO 7816-4
+ *
+ * @return On success, response to SELECT command.
+ */
+ byte[] openBasicChannel(in byte[] aid, in byte p2);
+
+ /**
+ * Opens a logical channel with the Secure Element, selecting the applet
+ * represented by the Application ID (AID).
+ *
+ * @param aid AID to uniquely identify the applet on the Secure Element
+ * @param p2 P2 parameter of SELECT APDU as per ISO 7816-4
+ * @throws ServiceSpecificException on error with the following code:
+ * - CHANNEL_NOT_AVAILABLE if secure element has reached the maximum
+ * limit on the number of channels it can support.
+ * - NO_SUCH_ELEMENT_ERROR if AID provided doesn't match any applet
+ * on the secure element.
+ * - UNSUPPORTED_OPERATION if operation provided by the P2 parameter
+ * is not permitted by the applet.
+ * - IOERROR if there was an error communicating with the Secure Element.
+ *
+ * @return On success, response to SELECT command
+ */
+ LogicalChannelResponse openLogicalChannel(in byte[] aid, in byte p2);
+
+ /**
+ * Reset the Secure Element.
+ *
+ * HAL should trigger reset to the secure element. It could hardware power cycle or
+ * a soft reset depends on the hardware design.
+ * HAL service must send onStateChange() with connected equal to true
+ * after resetting and all the re-initialization has been successfully completed.
+ */
+ void reset();
+
+ /**
+ * Transmits an APDU command (as per ISO/IEC 7816) to the SE.
+ *
+ * @param data APDU command to be sent
+ * @return response to the command
+ */
+ byte[] transmit(in byte[] data);
+}
diff --git a/secure_element/aidl/android/hardware/secure_element/ISecureElementCallback.aidl b/secure_element/aidl/android/hardware/secure_element/ISecureElementCallback.aidl
new file mode 100644
index 0000000..d15a7fb
--- /dev/null
+++ b/secure_element/aidl/android/hardware/secure_element/ISecureElementCallback.aidl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.secure_element;
+
+@VintfStability
+interface ISecureElementCallback {
+ /**
+ * Used to inform the client about changes in the state of the Secure
+ * Element.
+ *
+ * @param connected indicates the current state of the SE
+ * @param reason provides additional data why there was a change in state
+ * ex. initialization error, SE removed etc
+ * This is used only for debugging purpose to understand
+ * in-field issues.
+ */
+ void onStateChange(in boolean connected, in String debugReason);
+}
diff --git a/secure_element/aidl/android/hardware/secure_element/LogicalChannelResponse.aidl b/secure_element/aidl/android/hardware/secure_element/LogicalChannelResponse.aidl
new file mode 100644
index 0000000..65ea71e
--- /dev/null
+++ b/secure_element/aidl/android/hardware/secure_element/LogicalChannelResponse.aidl
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.secure_element;
+
+@VintfStability
+parcelable LogicalChannelResponse {
+ /**
+ * Channel number to uniquely identify the channel
+ */
+ byte channelNumber;
+ /**
+ * Response to SELECT command as per ISO/IEC 7816
+ */
+ byte[] selectResponse;
+}
diff --git a/secure_element/aidl/default/Android.bp b/secure_element/aidl/default/Android.bp
new file mode 100644
index 0000000..c604b68
--- /dev/null
+++ b/secure_element/aidl/default/Android.bp
@@ -0,0 +1,15 @@
+cc_binary {
+ name: "android.hardware.secure_element-service.example",
+ relative_install_path: "hw",
+ vendor: true,
+ init_rc: ["secure_element.rc"],
+ vintf_fragments: ["secure_element.xml"],
+ shared_libs: [
+ "libbase",
+ "libbinder_ndk",
+ "android.hardware.secure_element-V1-ndk",
+ ],
+ srcs: [
+ "main.cpp",
+ ],
+}
diff --git a/secure_element/aidl/default/main.cpp b/secure_element/aidl/default/main.cpp
new file mode 100644
index 0000000..16b8236
--- /dev/null
+++ b/secure_element/aidl/default/main.cpp
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <aidl/android/hardware/secure_element/BnSecureElement.h>
+
+#include <android-base/hex.h>
+#include <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+
+using aidl::android::hardware::secure_element::BnSecureElement;
+using aidl::android::hardware::secure_element::ISecureElementCallback;
+using aidl::android::hardware::secure_element::LogicalChannelResponse;
+using android::base::HexString;
+using ndk::ScopedAStatus;
+
+static const std::vector<uint8_t> kAndroidTestAid = {0xA0, 0x00, 0x00, 0x04, 0x76, 0x41,
+ 0x6E, 0x64, 0x72, 0x6F, 0x69, 0x64,
+ 0x43, 0x54, 0x53, 0x31};
+static const std::vector<uint8_t> kLongAndroidTestAid = {0xA0, 0x00, 0x00, 0x04, 0x76, 0x41,
+ 0x6E, 0x64, 0x72, 0x6F, 0x69, 0x64,
+ 0x43, 0x54, 0x53, 0x32};
+
+class MySecureElement : public BnSecureElement {
+ public:
+ ScopedAStatus closeChannel(int8_t channelNumber) override {
+ LOG(INFO) << __func__ << " channel number: " << channelNumber;
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus getAtr(std::vector<uint8_t>* _aidl_return) override {
+ LOG(INFO) << __func__;
+ _aidl_return->clear();
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus init(const std::shared_ptr<ISecureElementCallback>& clientCallback) override {
+ LOG(INFO) << __func__ << " callback: " << clientCallback.get();
+ if (!clientCallback) {
+ return ScopedAStatus::fromExceptionCode(EX_NULL_POINTER);
+ }
+ mCb = clientCallback;
+ mCb->onStateChange(true, "");
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus isCardPresent(bool* _aidl_return) override {
+ LOG(INFO) << __func__;
+ *_aidl_return = true;
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus openBasicChannel(const std::vector<uint8_t>& aid, int8_t p2,
+ std::vector<uint8_t>* _aidl_return) override {
+ LOG(INFO) << __func__ << " aid: " << HexString(aid.data(), aid.size()) << " (" << aid.size()
+ << ") p2 " << p2;
+
+ // TODO(b/123254068) - this is not an implementation of the OMAPI protocol or APDU.
+ // The functionality here is enough to exercise the framework, but actual
+ // calls to the secure element will fail. This implementation does not model
+ // channel isolation or any other aspects important to implementing secure element.
+ *_aidl_return = {0x90, 0x00, 0x00}; // DO NOT COPY
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus openLogicalChannel(
+ const std::vector<uint8_t>& aid, int8_t p2,
+ ::aidl::android::hardware::secure_element::LogicalChannelResponse* _aidl_return)
+ override {
+ LOG(INFO) << __func__ << " aid: " << HexString(aid.data(), aid.size()) << " (" << aid.size()
+ << ") p2 " << p2;
+
+ if (aid != kAndroidTestAid && aid != kLongAndroidTestAid) {
+ return ScopedAStatus::fromServiceSpecificError(NO_SUCH_ELEMENT_ERROR);
+ }
+
+ *_aidl_return = LogicalChannelResponse{.channelNumber = 1, .selectResponse = {}};
+
+ // TODO(b/123254068) - this is not an implementation of the OMAPI protocol or APDU.
+ // The functionality here is enough to exercise the framework, but actual
+ // calls to the secure element will fail. This implementation does not model
+ // channel isolation or any other aspects important to implementing secure element.
+ if (aid == kAndroidTestAid) { // DO NOT COPY
+ size_t size = 2050; // DO NOT COPY
+ _aidl_return->selectResponse.resize(size); // DO NOT COPY
+ _aidl_return->selectResponse[size - 1] = 0x00; // DO NOT COPY
+ _aidl_return->selectResponse[size - 2] = 0x90; // DO NOT COPY
+ } else { // DO NOT COPY
+ _aidl_return->selectResponse = {0x00, 0x00, 0x90, 0x00}; // DO NOT COPY
+ } // DO NOT COPY
+
+ LOG(INFO) << __func__ << " sending response: "
+ << HexString(_aidl_return->selectResponse.data(),
+ _aidl_return->selectResponse.size());
+
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus reset() override {
+ LOG(INFO) << __func__;
+ mCb->onStateChange(false, "reset");
+ mCb->onStateChange(true, "reset");
+ return ScopedAStatus::ok();
+ }
+ ScopedAStatus transmit(const std::vector<uint8_t>& data,
+ std::vector<uint8_t>* _aidl_return) override {
+ LOG(INFO) << __func__ << " data: " << HexString(data.data(), data.size()) << " ("
+ << data.size() << ")";
+
+ // TODO(b/123254068) - this is not an implementation of the OMAPI protocol or APDU.
+ // The functionality here is enough to exercise the framework, but actual
+ // calls to the secure element will fail. This implementation does not model
+ // channel isolation or any other aspects important to implementing secure element.
+
+ std::string hex = HexString(data.data(), data.size()); // DO NOT COPY
+ if (hex == "01a4040210a000000476416e64726f696443545331") { // DO NOT COPY
+ *_aidl_return = {0x00, 0x6A, 0x00}; // DO NOT COPY
+ } else if (data == std::vector<uint8_t>{0x00, 0xF4, 0x00, 0x00, 0x00}) { // DO NOT COPY
+ // CHECK_SELECT_P2_APDU w/ channel 1 // DO NOT COPY
+ *_aidl_return = {0x00, 0x90, 0x00}; // DO NOT COPY
+ } else if (data == std::vector<uint8_t>{0x01, 0xF4, 0x00, 0x00, 0x00}) { // DO NOT COPY
+ // CHECK_SELECT_P2_APDU w/ channel 1 // DO NOT COPY
+ *_aidl_return = {0x00, 0x90, 0x00}; // DO NOT COPY
+ } else if (data.size() == 5 || data.size() == 8) { // DO NOT COPY
+ // SEGMENTED_RESP_APDU - happens to use length 5 and 8 // DO NOT COPY
+ size_t size = (data[2] << 8 | data[3]) + 2; // DO NOT COPY
+ _aidl_return->resize(size); // DO NOT COPY
+ (*_aidl_return)[size - 1] = 0x00; // DO NOT COPY
+ (*_aidl_return)[size - 2] = 0x90; // DO NOT COPY
+ if (size >= 3) (*_aidl_return)[size - 3] = 0xFF; // DO NOT COPY
+ } else { // DO NOT COPY
+ *_aidl_return = {0x90, 0x00, 0x00}; // DO NOT COPY
+ } // DO NOT COPY
+
+ return ScopedAStatus::ok();
+ }
+
+ private:
+ std::shared_ptr<ISecureElementCallback> mCb;
+};
+
+int main() {
+ ABinderProcess_setThreadPoolMaxThreadCount(0);
+
+ auto se = ndk::SharedRefBase::make<MySecureElement>();
+ const std::string name = std::string() + BnSecureElement::descriptor + "/eSE1";
+ binder_status_t status = AServiceManager_addService(se->asBinder().get(), name.c_str());
+ CHECK_EQ(status, STATUS_OK);
+
+ ABinderProcess_joinThreadPool();
+ return EXIT_FAILURE; // should not reach
+}
diff --git a/secure_element/aidl/default/secure_element.rc b/secure_element/aidl/default/secure_element.rc
new file mode 100644
index 0000000..7d21666
--- /dev/null
+++ b/secure_element/aidl/default/secure_element.rc
@@ -0,0 +1,4 @@
+service vendor.secure_element /vendor/bin/hw/android.hardware.secure_element-service.example
+ class hal
+ user nobody
+ group nobody
diff --git a/secure_element/aidl/default/secure_element.xml b/secure_element/aidl/default/secure_element.xml
new file mode 100644
index 0000000..96ab2e7
--- /dev/null
+++ b/secure_element/aidl/default/secure_element.xml
@@ -0,0 +1,7 @@
+<manifest version="1.0" type="device">
+ <hal format="aidl">
+ <name>android.hardware.secure_element</name>
+ <version>1</version>
+ <fqname>ISecureElement/eSE1</fqname>
+ </hal>
+</manifest>
diff --git a/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp b/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp
new file mode 100644
index 0000000..a85a8bc
--- /dev/null
+++ b/secure_element/aidl/vts/VtsHalSecureElementTargetTest.cpp
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/secure_element/BnSecureElementCallback.h>
+#include <aidl/android/hardware/secure_element/ISecureElement.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+
+using namespace std::chrono_literals;
+
+using aidl::android::hardware::secure_element::BnSecureElementCallback;
+using aidl::android::hardware::secure_element::ISecureElement;
+using aidl::android::hardware::secure_element::LogicalChannelResponse;
+using ndk::ScopedAStatus;
+using ndk::SharedRefBase;
+using ndk::SpAIBinder;
+using testing::ElementsAre;
+using testing::ElementsAreArray;
+
+#define EXPECT_OK(status) \
+ do { \
+ auto status_impl = (status); \
+ EXPECT_TRUE(status_impl.isOk()) << status_impl.getDescription(); \
+ } while (false)
+
+static const std::vector<uint8_t> kDataApdu = {0x00, 0x08, 0x00, 0x00, 0x00};
+static const std::vector<uint8_t> kAndroidTestAid = {0xA0, 0x00, 0x00, 0x04, 0x76, 0x41,
+ 0x6E, 0x64, 0x72, 0x6F, 0x69, 0x64,
+ 0x43, 0x54, 0x53, 0x31};
+
+class MySecureElementCallback : public BnSecureElementCallback {
+ public:
+ ScopedAStatus onStateChange(bool state, const std::string& debugReason) override {
+ {
+ std::unique_lock<std::mutex> l(m);
+ (void)debugReason;
+ history.push_back(state);
+ }
+ cv.notify_one();
+ return ScopedAStatus::ok();
+ };
+
+ void expectCallbackHistory(std::vector<bool>&& want) {
+ std::unique_lock<std::mutex> l(m);
+ cv.wait_for(l, 2s, [&]() { return history.size() >= want.size(); });
+ EXPECT_THAT(history, ElementsAreArray(want));
+ }
+
+ private:
+ std::mutex m; // guards history
+ std::condition_variable cv;
+ std::vector<bool> history;
+};
+
+class SecureElementAidl : public ::testing::TestWithParam<std::string> {
+ public:
+ virtual void SetUp() override {
+ SpAIBinder binder = SpAIBinder(AServiceManager_waitForService(GetParam().c_str()));
+ se = ISecureElement::fromBinder(binder);
+ ASSERT_NE(se, nullptr);
+
+ cb = SharedRefBase::make<MySecureElementCallback>();
+ EXPECT_OK(se->init(cb));
+
+ cb->expectCallbackHistory({true});
+ }
+
+ std::shared_ptr<ISecureElement> se;
+ std::shared_ptr<MySecureElementCallback> cb;
+};
+
+TEST_P(SecureElementAidl, isCardPresent) {
+ bool res = false;
+ EXPECT_OK(se->isCardPresent(&res));
+ EXPECT_TRUE(res);
+}
+
+TEST_P(SecureElementAidl, transmit) {
+ LogicalChannelResponse response;
+ EXPECT_OK(se->openLogicalChannel(kAndroidTestAid, 0x00, &response));
+
+ EXPECT_GE(response.selectResponse.size(), 2u);
+ EXPECT_GE(response.channelNumber, 1);
+
+ std::vector<uint8_t> command = kDataApdu;
+ command[0] |= response.channelNumber;
+
+ std::vector<uint8_t> transmitResponse;
+ EXPECT_OK(se->transmit(command, &transmitResponse));
+
+ EXPECT_LE(transmitResponse.size(), 3);
+ EXPECT_GE(transmitResponse.size(), 2);
+ EXPECT_EQ(transmitResponse[transmitResponse.size() - 1], 0x00);
+ EXPECT_EQ(transmitResponse[transmitResponse.size() - 2], 0x90);
+
+ EXPECT_OK(se->closeChannel(response.channelNumber));
+}
+
+TEST_P(SecureElementAidl, openBasicChannel) {
+ std::vector<uint8_t> response;
+ auto status = se->openBasicChannel(kAndroidTestAid, 0x00, &response);
+
+ if (!status.isOk()) {
+ EXPECT_EQ(status.getServiceSpecificError(), ISecureElement::CHANNEL_NOT_AVAILABLE)
+ << status.getDescription();
+ return;
+ }
+
+ EXPECT_GE(response.size(), 2u);
+ EXPECT_OK(se->closeChannel(0));
+}
+
+TEST_P(SecureElementAidl, getAtr) {
+ std::vector<uint8_t> atr;
+ EXPECT_OK(se->getAtr(&atr));
+ if (atr.size() == 0) {
+ return;
+ }
+ EXPECT_LE(atr.size(), 32u);
+ EXPECT_GE(atr.size(), 1u);
+}
+
+TEST_P(SecureElementAidl, openCloseLogicalChannel) {
+ LogicalChannelResponse response;
+ EXPECT_OK(se->openLogicalChannel(kAndroidTestAid, 0x00, &response));
+ EXPECT_GE(response.selectResponse.size(), 2u);
+ EXPECT_GE(response.channelNumber, 1);
+ EXPECT_OK(se->closeChannel(response.channelNumber));
+}
+
+TEST_P(SecureElementAidl, openInvalidAid) {
+ LogicalChannelResponse response;
+ auto status = se->openLogicalChannel({0x42}, 0x00, &response);
+ EXPECT_EQ(status.getServiceSpecificError(), ISecureElement::NO_SUCH_ELEMENT_ERROR)
+ << status.getDescription();
+}
+
+TEST_P(SecureElementAidl, Reset) {
+ cb->expectCallbackHistory({true});
+ EXPECT_OK(se->reset());
+ cb->expectCallbackHistory({true, false, true});
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SecureElementAidl);
+INSTANTIATE_TEST_SUITE_P(
+ SecureElement, SecureElementAidl,
+ testing::ValuesIn(android::getAidlHalInstanceNames(ISecureElement::descriptor)),
+ android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ ABinderProcess_setThreadPoolMaxThreadCount(1);
+ ABinderProcess_startThreadPool();
+ return RUN_ALL_TESTS();
+}
diff --git a/security/keymint/aidl/android/hardware/security/keymint/KeyCreationResult.aidl b/security/keymint/aidl/android/hardware/security/keymint/KeyCreationResult.aidl
index 4c2be89..294c205 100644
--- a/security/keymint/aidl/android/hardware/security/keymint/KeyCreationResult.aidl
+++ b/security/keymint/aidl/android/hardware/security/keymint/KeyCreationResult.aidl
@@ -125,9 +125,9 @@
* straightforward translation of the KeyMint tag/value parameter lists to ASN.1.
*
* KeyDescription ::= SEQUENCE {
- * attestationVersion INTEGER, # Value 200
+ * attestationVersion INTEGER, # Value 300
* attestationSecurityLevel SecurityLevel, # See below
- * keyMintVersion INTEGER, # Value 200
+ * keyMintVersion INTEGER, # Value 300
* keymintSecurityLevel SecurityLevel, # See below
* attestationChallenge OCTET_STRING, # Tag::ATTESTATION_CHALLENGE from attestParams
* uniqueId OCTET_STRING, # Empty unless key has Tag::INCLUDE_UNIQUE_ID
@@ -209,6 +209,7 @@
* vendorPatchLevel [718] EXPLICIT INTEGER OPTIONAL,
* bootPatchLevel [719] EXPLICIT INTEGER OPTIONAL,
* deviceUniqueAttestation [720] EXPLICIT NULL OPTIONAL,
+ * attestationIdSecondImei [723] EXPLICIT OCTET_STRING OPTIONAL,
* }
*/
Certificate[] certificateChain;
diff --git a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
index f4c0095..ea4ba18 100644
--- a/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
+++ b/security/keymint/aidl/vts/functional/AttestKeyTest.cpp
@@ -892,6 +892,7 @@
ASSERT_TRUE(result == ErrorCode::CANNOT_ATTEST_IDS || result == ErrorCode::INVALID_TAG)
<< "result = " << result;
+ device_id_attestation_vsr_check(result);
}
CheckedDeleteKey(&attest_key.keyBlob);
}
diff --git a/security/keymint/aidl/vts/functional/DeviceUniqueAttestationTest.cpp b/security/keymint/aidl/vts/functional/DeviceUniqueAttestationTest.cpp
index cd140c8..26dc3f5 100644
--- a/security/keymint/aidl/vts/functional/DeviceUniqueAttestationTest.cpp
+++ b/security/keymint/aidl/vts/functional/DeviceUniqueAttestationTest.cpp
@@ -348,8 +348,8 @@
// Add the tag that doesn't match the local device's real ID.
builder.push_back(invalid_tag);
auto result = GenerateKey(builder, &key_blob, &key_characteristics);
-
ASSERT_TRUE(result == ErrorCode::CANNOT_ATTEST_IDS || result == ErrorCode::INVALID_TAG);
+ device_id_attestation_vsr_check(result);
}
}
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
index 80abd92..43ad30a 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.cpp
@@ -2031,6 +2031,16 @@
*signingKey = std::move(pubKey);
}
+void device_id_attestation_vsr_check(const ErrorCode& result) {
+ if (get_vsr_api_level() >= 34) {
+ ASSERT_FALSE(result == ErrorCode::INVALID_TAG)
+ << "It is a specification violation for INVALID_TAG to be returned due to ID "
+ << "mismatch in a Device ID Attestation call. INVALID_TAG is only intended to "
+ << "be used for a case where updateAad() is called after update(). As of "
+ << "VSR-14, this is now enforced as an error.";
+ }
+}
+
} // namespace test
} // namespace aidl::android::hardware::security::keymint
diff --git a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
index 67e8b21..5b09ca5 100644
--- a/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
+++ b/security/keymint/aidl/vts/functional/KeyMintAidlTestBase.h
@@ -395,6 +395,7 @@
void check_maced_pubkey(const MacedPublicKey& macedPubKey, bool testMode,
vector<uint8_t>* payload_value);
void p256_pub_key(const vector<uint8_t>& coseKeyData, EVP_PKEY_Ptr* signingKey);
+void device_id_attestation_vsr_check(const ErrorCode& result);
AuthorizationSet HwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics);
AuthorizationSet SwEnforcedAuthorizations(const vector<KeyCharacteristics>& key_characteristics);
diff --git a/security/rkp/CHANGELOG.md b/security/rkp/CHANGELOG.md
index 29b1a1c..c3e3609 100644
--- a/security/rkp/CHANGELOG.md
+++ b/security/rkp/CHANGELOG.md
@@ -27,7 +27,7 @@
`"android.hardward.security.keymint"`).
* ProtectedData has been removed.
* DeviceInfo
- * `version` has moved to a top-level field within the CSR generated by the HAL
+ * `version` has moved to a top-level field within the CSR generated by the HAL.
* IRemotelyProvisionedComponent
* The need for an EEK has been removed. There is no longer an encrypted portion of the CSR.
* Test mode has been removed.
@@ -36,5 +36,10 @@
* the chain of signing, MACing, and encryption operations has been replaced with a single
COSE_Sign1 object.
* CertificateType has been added to identify the type of certificate being requested.
+ * The structure has been composed to enable a clear split between what is required to validate a
+ payload and the implementation-defined payload itself. This is done by creating a typed
+ `AuthenticatedRequest<T>` object representing the top level data required to authenticate
+ the data provided in the payload, `T`.
* RpcHardwareInfo
* `supportedNumKeysInCsr` added to report the maximum number of keys supported in a CSR.
+ * `supportedEekCurve` is no longer used, due to the removal of the EEK from the scheme.
diff --git a/security/rkp/aidl/Android.bp b/security/rkp/aidl/Android.bp
index 4c479f4..5285477 100644
--- a/security/rkp/aidl/Android.bp
+++ b/security/rkp/aidl/Android.bp
@@ -21,6 +21,10 @@
backend: {
java: {
min_sdk_version: "33",
+ apex_available: [
+ "//apex_available:platform",
+ "com.android.rkpd",
+ ],
},
rust: {
enabled: true,
diff --git a/security/rkp/aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.aidl b/security/rkp/aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.aidl
index 78969d1..2fc780c 100644
--- a/security/rkp/aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.aidl
+++ b/security/rkp/aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.aidl
@@ -345,20 +345,20 @@
* ]
*
* ; COSE_Sign1 (untagged)
- * SignedData<T> = [
+ * SignedData<Data> = [
* protected: bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 },
* unprotected: {},
- * payload: bstr .cbor T / nil,
- * signature: bstr ; PureEd25519(CDI_Leaf_Priv, bstr .cbor SignedDataSigStruct<T>) /
- * ; ECDSA(CDI_Leaf_Priv, bstr .cbor SignedDataSigStruct<T>)
+ * payload: bstr .cbor Data / nil,
+ * signature: bstr ; PureEd25519(CDI_Leaf_Priv, bstr .cbor SignedDataSigStruct<Data>) /
+ * ; ECDSA(CDI_Leaf_Priv, bstr .cbor SignedDataSigStruct<Data>)
* ]
*
* ; Sig_structure for SignedData
- * SignedDataSigStruct<T> = [
+ * SignedDataSigStruct<Data> = [
* context: "Signature1",
* protected: bstr .cbor { 1 : AlgorithmEdDSA / AlgorithmES256 },
* external_aad: bstr .size 0,
- * payload: bstr .cbor T
+ * payload: bstr .cbor Data / nil,
* ]
*
* ; UdsCerts allows the platform to provide additional certifications for the UDS_Pub. For
diff --git a/security/rkp/aidl/android/hardware/security/keymint/RpcHardwareInfo.aidl b/security/rkp/aidl/android/hardware/security/keymint/RpcHardwareInfo.aidl
index 5fe5b00..d0b059d 100644
--- a/security/rkp/aidl/android/hardware/security/keymint/RpcHardwareInfo.aidl
+++ b/security/rkp/aidl/android/hardware/security/keymint/RpcHardwareInfo.aidl
@@ -29,9 +29,9 @@
const int CURVE_25519 = 2;
/**
- * Implementation version of the remotely provisioned component hardware. The version number is
- * implementation defined, and not necessarily globally meaningful. The version is used to
- * distinguish between different versions of a given implementation.
+ * Implementation version of the remotely provisioned component hardware. The version provided
+ * here must match the version reported in the CsrPayload produced by the HAL interface. This
+ * field primarily acts as a convenience for the system components interacting with the HALs.
*/
int versionNumber;
@@ -43,6 +43,9 @@
@utf8InCpp String rpcAuthorName;
/**
+ * NOTE: This field is no longer used as of version 3 of the HAL interface. This is because the
+ * Endpoint Encryption Key is no longer used in the provisioning scheme.
+ *
* supportedEekCurve returns an int representing which curve is supported for validating
* signatures over the Endpoint Encryption Key certificate chain and for using the corresponding
* signed encryption key in ECDH. Only one curve should be supported, with preference for 25519
diff --git a/sensors/aidl/Android.bp b/sensors/aidl/Android.bp
index d04017c..9673190 100644
--- a/sensors/aidl/Android.bp
+++ b/sensors/aidl/Android.bp
@@ -11,6 +11,7 @@
name: "android.hardware.sensors",
vendor_available: true,
srcs: ["android/hardware/sensors/*.aidl"],
+ host_supported: true,
imports: [
"android.hardware.common-V2",
"android.hardware.common.fmq-V1",
diff --git a/audio/aidl/default/reverb/Android.bp b/sensors/aidl/convert/Android.bp
similarity index 68%
copy from audio/aidl/default/reverb/Android.bp
copy to sensors/aidl/convert/Android.bp
index 955038c..d47de8e 100644
--- a/audio/aidl/default/reverb/Android.bp
+++ b/sensors/aidl/convert/Android.bp
@@ -23,18 +23,22 @@
default_applicable_licenses: ["hardware_interfaces_license"],
}
-cc_library_shared {
- name: "libreverbsw",
- defaults: [
- "aidlaudioeffectservice_defaults",
- "latest_android_media_audio_common_types_ndk_shared",
- "latest_android_hardware_audio_effect_ndk_shared",
+cc_library_static {
+ name: "android.hardware.sensors-V1-convert",
+ vendor_available: true,
+ host_supported: true,
+ srcs: ["convert.cpp"],
+ export_include_dirs: ["include"],
+ shared_libs: [
+ "liblog",
+ "libcutils",
+ "libhardware",
+ "libbase",
+ "libutils",
+ "android.hardware.sensors-V1-ndk",
],
- srcs: [
- "ReverbSw.cpp",
- ":effectCommonFile",
- ],
- visibility: [
- "//hardware/interfaces/audio/aidl/default",
+ local_include_dirs: ["include/aidl/sensors"],
+ export_shared_lib_headers: [
+ "libhardware",
],
}
diff --git a/sensors/aidl/convert/convert.cpp b/sensors/aidl/convert/convert.cpp
new file mode 100644
index 0000000..415f435
--- /dev/null
+++ b/sensors/aidl/convert/convert.cpp
@@ -0,0 +1,496 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "aidl/sensors/convert.h"
+#include "android-base/logging.h"
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace implementation {
+
+using aidl::android::hardware::sensors::AdditionalInfo;
+using aidl::android::hardware::sensors::DynamicSensorInfo;
+using aidl::android::hardware::sensors::Event;
+using aidl::android::hardware::sensors::ISensors;
+using aidl::android::hardware::sensors::SensorInfo;
+using aidl::android::hardware::sensors::SensorStatus;
+using aidl::android::hardware::sensors::SensorType;
+
+status_t convertToStatus(ndk::ScopedAStatus status) {
+ if (status.isOk()) {
+ return OK;
+ } else {
+ switch (status.getExceptionCode()) {
+ case EX_ILLEGAL_ARGUMENT: {
+ return BAD_VALUE;
+ }
+ case EX_SECURITY: {
+ return PERMISSION_DENIED;
+ }
+ case EX_UNSUPPORTED_OPERATION: {
+ return INVALID_OPERATION;
+ }
+ case EX_SERVICE_SPECIFIC: {
+ switch (status.getServiceSpecificError()) {
+ case ISensors::ERROR_BAD_VALUE: {
+ return BAD_VALUE;
+ }
+ case ISensors::ERROR_NO_MEMORY: {
+ return NO_MEMORY;
+ }
+ default: {
+ return UNKNOWN_ERROR;
+ }
+ }
+ }
+ default: {
+ return UNKNOWN_ERROR;
+ }
+ }
+ }
+}
+
+void convertToSensor(const SensorInfo& src, sensor_t* dst) {
+ dst->name = strdup(src.name.c_str());
+ dst->vendor = strdup(src.vendor.c_str());
+ dst->version = src.version;
+ dst->handle = src.sensorHandle;
+ dst->type = (int)src.type;
+ dst->maxRange = src.maxRange;
+ dst->resolution = src.resolution;
+ dst->power = src.power;
+ dst->minDelay = src.minDelayUs;
+ dst->fifoReservedEventCount = src.fifoReservedEventCount;
+ dst->fifoMaxEventCount = src.fifoMaxEventCount;
+ dst->stringType = strdup(src.typeAsString.c_str());
+ dst->requiredPermission = strdup(src.requiredPermission.c_str());
+ dst->maxDelay = src.maxDelayUs;
+ dst->flags = src.flags;
+ dst->reserved[0] = dst->reserved[1] = 0;
+}
+
+void convertToSensorEvent(const Event& src, sensors_event_t* dst) {
+ *dst = {.version = sizeof(sensors_event_t),
+ .sensor = src.sensorHandle,
+ .type = (int32_t)src.sensorType,
+ .reserved0 = 0,
+ .timestamp = src.timestamp};
+
+ switch (src.sensorType) {
+ case SensorType::META_DATA: {
+ // Legacy HALs expect the handle reference in the meta data field.
+ // Copy it over from the handle of the event.
+ dst->meta_data.what = (int32_t)src.payload.get<Event::EventPayload::meta>().what;
+ dst->meta_data.sensor = src.sensorHandle;
+ // Set the sensor handle to 0 to maintain compatibility.
+ dst->sensor = 0;
+ break;
+ }
+
+ case SensorType::ACCELEROMETER:
+ case SensorType::MAGNETIC_FIELD:
+ case SensorType::ORIENTATION:
+ case SensorType::GYROSCOPE:
+ case SensorType::GRAVITY:
+ case SensorType::LINEAR_ACCELERATION: {
+ dst->acceleration.x = src.payload.get<Event::EventPayload::vec3>().x;
+ dst->acceleration.y = src.payload.get<Event::EventPayload::vec3>().y;
+ dst->acceleration.z = src.payload.get<Event::EventPayload::vec3>().z;
+ dst->acceleration.status = (int32_t)src.payload.get<Event::EventPayload::vec3>().status;
+ break;
+ }
+
+ case SensorType::GAME_ROTATION_VECTOR: {
+ dst->data[0] = src.payload.get<Event::EventPayload::vec4>().x;
+ dst->data[1] = src.payload.get<Event::EventPayload::vec4>().y;
+ dst->data[2] = src.payload.get<Event::EventPayload::vec4>().z;
+ dst->data[3] = src.payload.get<Event::EventPayload::vec4>().w;
+ break;
+ }
+
+ case SensorType::ROTATION_VECTOR:
+ case SensorType::GEOMAGNETIC_ROTATION_VECTOR: {
+ dst->data[0] = src.payload.get<Event::EventPayload::data>().values[0];
+ dst->data[1] = src.payload.get<Event::EventPayload::data>().values[1];
+ dst->data[2] = src.payload.get<Event::EventPayload::data>().values[2];
+ dst->data[3] = src.payload.get<Event::EventPayload::data>().values[3];
+ dst->data[4] = src.payload.get<Event::EventPayload::data>().values[4];
+ break;
+ }
+
+ case SensorType::MAGNETIC_FIELD_UNCALIBRATED:
+ case SensorType::GYROSCOPE_UNCALIBRATED:
+ case SensorType::ACCELEROMETER_UNCALIBRATED: {
+ dst->uncalibrated_gyro.x_uncalib = src.payload.get<Event::EventPayload::uncal>().x;
+ dst->uncalibrated_gyro.y_uncalib = src.payload.get<Event::EventPayload::uncal>().y;
+ dst->uncalibrated_gyro.z_uncalib = src.payload.get<Event::EventPayload::uncal>().z;
+ dst->uncalibrated_gyro.x_bias = src.payload.get<Event::EventPayload::uncal>().xBias;
+ dst->uncalibrated_gyro.y_bias = src.payload.get<Event::EventPayload::uncal>().yBias;
+ dst->uncalibrated_gyro.z_bias = src.payload.get<Event::EventPayload::uncal>().zBias;
+ break;
+ }
+
+ case SensorType::HINGE_ANGLE:
+ case SensorType::DEVICE_ORIENTATION:
+ case SensorType::LIGHT:
+ case SensorType::PRESSURE:
+ case SensorType::PROXIMITY:
+ case SensorType::RELATIVE_HUMIDITY:
+ case SensorType::AMBIENT_TEMPERATURE:
+ case SensorType::SIGNIFICANT_MOTION:
+ case SensorType::STEP_DETECTOR:
+ case SensorType::TILT_DETECTOR:
+ case SensorType::WAKE_GESTURE:
+ case SensorType::GLANCE_GESTURE:
+ case SensorType::PICK_UP_GESTURE:
+ case SensorType::WRIST_TILT_GESTURE:
+ case SensorType::STATIONARY_DETECT:
+ case SensorType::MOTION_DETECT:
+ case SensorType::HEART_BEAT:
+ case SensorType::LOW_LATENCY_OFFBODY_DETECT: {
+ dst->data[0] = src.payload.get<Event::EventPayload::scalar>();
+ break;
+ }
+
+ case SensorType::STEP_COUNTER: {
+ dst->u64.step_counter = src.payload.get<Event::EventPayload::stepCount>();
+ break;
+ }
+
+ case SensorType::HEART_RATE: {
+ dst->heart_rate.bpm = src.payload.get<Event::EventPayload::heartRate>().bpm;
+ dst->heart_rate.status =
+ (int8_t)src.payload.get<Event::EventPayload::heartRate>().status;
+ break;
+ }
+
+ case SensorType::POSE_6DOF: { // 15 floats
+ for (size_t i = 0; i < 15; ++i) {
+ dst->data[i] = src.payload.get<Event::EventPayload::pose6DOF>().values[i];
+ }
+ break;
+ }
+
+ case SensorType::DYNAMIC_SENSOR_META: {
+ dst->dynamic_sensor_meta.connected =
+ src.payload.get<Event::EventPayload::dynamic>().connected;
+ dst->dynamic_sensor_meta.handle =
+ src.payload.get<Event::EventPayload::dynamic>().sensorHandle;
+ dst->dynamic_sensor_meta.sensor = NULL; // to be filled in later
+
+ memcpy(dst->dynamic_sensor_meta.uuid,
+ src.payload.get<Event::EventPayload::dynamic>().uuid.values.data(), 16);
+
+ break;
+ }
+
+ case SensorType::ADDITIONAL_INFO: {
+ const AdditionalInfo& srcInfo = src.payload.get<Event::EventPayload::additional>();
+
+ additional_info_event_t* dstInfo = &dst->additional_info;
+ dstInfo->type = (int32_t)srcInfo.type;
+ dstInfo->serial = srcInfo.serial;
+
+ switch (srcInfo.payload.getTag()) {
+ case AdditionalInfo::AdditionalInfoPayload::Tag::dataInt32: {
+ const auto& values =
+ srcInfo.payload.get<AdditionalInfo::AdditionalInfoPayload::dataInt32>()
+ .values;
+ CHECK_EQ(values.size() * sizeof(int32_t), sizeof(dstInfo->data_int32));
+ memcpy(dstInfo->data_int32, values.data(), sizeof(dstInfo->data_int32));
+ break;
+ }
+ case AdditionalInfo::AdditionalInfoPayload::Tag::dataFloat: {
+ const auto& values =
+ srcInfo.payload.get<AdditionalInfo::AdditionalInfoPayload::dataFloat>()
+ .values;
+ CHECK_EQ(values.size() * sizeof(float), sizeof(dstInfo->data_float));
+ memcpy(dstInfo->data_float, values.data(), sizeof(dstInfo->data_float));
+ break;
+ }
+ default: {
+ LOG(ERROR) << "Invalid sensor additional info tag: ",
+ (int)srcInfo.payload.getTag();
+ }
+ }
+ break;
+ }
+
+ case SensorType::HEAD_TRACKER: {
+ const auto& ht = src.payload.get<Event::EventPayload::headTracker>();
+ dst->head_tracker.rx = ht.rx;
+ dst->head_tracker.ry = ht.ry;
+ dst->head_tracker.rz = ht.rz;
+ dst->head_tracker.vx = ht.vx;
+ dst->head_tracker.vy = ht.vy;
+ dst->head_tracker.vz = ht.vz;
+ dst->head_tracker.discontinuity_count = ht.discontinuityCount;
+ break;
+ }
+
+ case SensorType::ACCELEROMETER_LIMITED_AXES:
+ case SensorType::GYROSCOPE_LIMITED_AXES:
+ dst->limited_axes_imu.x = src.payload.get<Event::EventPayload::limitedAxesImu>().x;
+ dst->limited_axes_imu.y = src.payload.get<Event::EventPayload::limitedAxesImu>().y;
+ dst->limited_axes_imu.z = src.payload.get<Event::EventPayload::limitedAxesImu>().z;
+ dst->limited_axes_imu.x_supported =
+ src.payload.get<Event::EventPayload::limitedAxesImu>().xSupported;
+ dst->limited_axes_imu.y_supported =
+ src.payload.get<Event::EventPayload::limitedAxesImu>().ySupported;
+ dst->limited_axes_imu.z_supported =
+ src.payload.get<Event::EventPayload::limitedAxesImu>().zSupported;
+ break;
+
+ case SensorType::ACCELEROMETER_LIMITED_AXES_UNCALIBRATED:
+ case SensorType::GYROSCOPE_LIMITED_AXES_UNCALIBRATED:
+ dst->limited_axes_imu_uncalibrated.x_uncalib =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().x;
+ dst->limited_axes_imu_uncalibrated.y_uncalib =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().y;
+ dst->limited_axes_imu_uncalibrated.z_uncalib =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().z;
+ dst->limited_axes_imu_uncalibrated.x_bias =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().xBias;
+ dst->limited_axes_imu_uncalibrated.y_bias =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().yBias;
+ dst->limited_axes_imu_uncalibrated.z_bias =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().zBias;
+ dst->limited_axes_imu_uncalibrated.x_supported =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().xSupported;
+ dst->limited_axes_imu_uncalibrated.y_supported =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().ySupported;
+ dst->limited_axes_imu_uncalibrated.z_supported =
+ src.payload.get<Event::EventPayload::limitedAxesImuUncal>().zSupported;
+ break;
+
+ case SensorType::HEADING:
+ dst->heading.heading = src.payload.get<Event::EventPayload::heading>().heading;
+ dst->heading.accuracy = src.payload.get<Event::EventPayload::heading>().accuracy;
+ break;
+
+ default: {
+ CHECK_GE((int32_t)src.sensorType, (int32_t)SensorType::DEVICE_PRIVATE_BASE);
+
+ memcpy(dst->data, src.payload.get<Event::EventPayload::data>().values.data(),
+ 16 * sizeof(float));
+ break;
+ }
+ }
+}
+
+void convertFromSensorEvent(const sensors_event_t& src, Event* dst) {
+ *dst = {
+ .timestamp = src.timestamp,
+ .sensorHandle = src.sensor,
+ .sensorType = (SensorType)src.type,
+ };
+
+ switch (dst->sensorType) {
+ case SensorType::META_DATA: {
+ Event::EventPayload::MetaData meta;
+ meta.what = (Event::EventPayload::MetaData::MetaDataEventType)src.meta_data.what;
+ // Legacy HALs contain the handle reference in the meta data field.
+ // Copy that over to the handle of the event. In legacy HALs this
+ // field was expected to be 0.
+ dst->sensorHandle = src.meta_data.sensor;
+ dst->payload.set<Event::EventPayload::Tag::meta>(meta);
+ break;
+ }
+
+ case SensorType::ACCELEROMETER:
+ case SensorType::MAGNETIC_FIELD:
+ case SensorType::ORIENTATION:
+ case SensorType::GYROSCOPE:
+ case SensorType::GRAVITY:
+ case SensorType::LINEAR_ACCELERATION: {
+ Event::EventPayload::Vec3 vec3;
+ vec3.x = src.acceleration.x;
+ vec3.y = src.acceleration.y;
+ vec3.z = src.acceleration.z;
+ vec3.status = (SensorStatus)src.acceleration.status;
+ dst->payload.set<Event::EventPayload::Tag::vec3>(vec3);
+ break;
+ }
+
+ case SensorType::GAME_ROTATION_VECTOR: {
+ Event::EventPayload::Vec4 vec4;
+ vec4.x = src.data[0];
+ vec4.y = src.data[1];
+ vec4.z = src.data[2];
+ vec4.w = src.data[3];
+ dst->payload.set<Event::EventPayload::Tag::vec4>(vec4);
+ break;
+ }
+
+ case SensorType::ROTATION_VECTOR:
+ case SensorType::GEOMAGNETIC_ROTATION_VECTOR: {
+ Event::EventPayload::Data data;
+ memcpy(data.values.data(), src.data, 5 * sizeof(float));
+ dst->payload.set<Event::EventPayload::Tag::data>(data);
+ break;
+ }
+
+ case SensorType::MAGNETIC_FIELD_UNCALIBRATED:
+ case SensorType::GYROSCOPE_UNCALIBRATED:
+ case SensorType::ACCELEROMETER_UNCALIBRATED: {
+ Event::EventPayload::Uncal uncal;
+ uncal.x = src.uncalibrated_gyro.x_uncalib;
+ uncal.y = src.uncalibrated_gyro.y_uncalib;
+ uncal.z = src.uncalibrated_gyro.z_uncalib;
+ uncal.xBias = src.uncalibrated_gyro.x_bias;
+ uncal.yBias = src.uncalibrated_gyro.y_bias;
+ uncal.zBias = src.uncalibrated_gyro.z_bias;
+ dst->payload.set<Event::EventPayload::Tag::uncal>(uncal);
+ break;
+ }
+
+ case SensorType::DEVICE_ORIENTATION:
+ case SensorType::LIGHT:
+ case SensorType::PRESSURE:
+ case SensorType::PROXIMITY:
+ case SensorType::RELATIVE_HUMIDITY:
+ case SensorType::AMBIENT_TEMPERATURE:
+ case SensorType::SIGNIFICANT_MOTION:
+ case SensorType::STEP_DETECTOR:
+ case SensorType::TILT_DETECTOR:
+ case SensorType::WAKE_GESTURE:
+ case SensorType::GLANCE_GESTURE:
+ case SensorType::PICK_UP_GESTURE:
+ case SensorType::WRIST_TILT_GESTURE:
+ case SensorType::STATIONARY_DETECT:
+ case SensorType::MOTION_DETECT:
+ case SensorType::HEART_BEAT:
+ case SensorType::LOW_LATENCY_OFFBODY_DETECT:
+ case SensorType::HINGE_ANGLE: {
+ dst->payload.set<Event::EventPayload::Tag::scalar>((float)src.data[0]);
+ break;
+ }
+
+ case SensorType::STEP_COUNTER: {
+ dst->payload.set<Event::EventPayload::Tag::stepCount>(src.u64.step_counter);
+ break;
+ }
+
+ case SensorType::HEART_RATE: {
+ Event::EventPayload::HeartRate heartRate;
+ heartRate.bpm = src.heart_rate.bpm;
+ heartRate.status = (SensorStatus)src.heart_rate.status;
+ dst->payload.set<Event::EventPayload::Tag::heartRate>(heartRate);
+ break;
+ }
+
+ case SensorType::POSE_6DOF: { // 15 floats
+ Event::EventPayload::Pose6Dof pose6DOF;
+ for (size_t i = 0; i < 15; ++i) {
+ pose6DOF.values[i] = src.data[i];
+ }
+ dst->payload.set<Event::EventPayload::Tag::pose6DOF>(pose6DOF);
+ break;
+ }
+
+ case SensorType::DYNAMIC_SENSOR_META: {
+ DynamicSensorInfo dynamic;
+ dynamic.connected = src.dynamic_sensor_meta.connected;
+ dynamic.sensorHandle = src.dynamic_sensor_meta.handle;
+
+ memcpy(dynamic.uuid.values.data(), src.dynamic_sensor_meta.uuid, 16);
+ dst->payload.set<Event::EventPayload::Tag::dynamic>(dynamic);
+ break;
+ }
+
+ case SensorType::ADDITIONAL_INFO: {
+ AdditionalInfo info;
+ const additional_info_event_t& srcInfo = src.additional_info;
+ info.type = (AdditionalInfo::AdditionalInfoType)srcInfo.type;
+ info.serial = srcInfo.serial;
+
+ AdditionalInfo::AdditionalInfoPayload::Int32Values data;
+ CHECK_EQ(data.values.size() * sizeof(int32_t), sizeof(srcInfo.data_int32));
+ memcpy(data.values.data(), srcInfo.data_int32, sizeof(srcInfo.data_int32));
+ info.payload.set<AdditionalInfo::AdditionalInfoPayload::Tag::dataInt32>(data);
+
+ dst->payload.set<Event::EventPayload::Tag::additional>(info);
+ break;
+ }
+
+ case SensorType::HEAD_TRACKER: {
+ Event::EventPayload::HeadTracker headTracker;
+ headTracker.rx = src.head_tracker.rx;
+ headTracker.ry = src.head_tracker.ry;
+ headTracker.rz = src.head_tracker.rz;
+ headTracker.vx = src.head_tracker.vx;
+ headTracker.vy = src.head_tracker.vy;
+ headTracker.vz = src.head_tracker.vz;
+ headTracker.discontinuityCount = src.head_tracker.discontinuity_count;
+
+ dst->payload.set<Event::EventPayload::Tag::headTracker>(headTracker);
+ break;
+ }
+
+ case SensorType::ACCELEROMETER_LIMITED_AXES:
+ case SensorType::GYROSCOPE_LIMITED_AXES: {
+ Event::EventPayload::LimitedAxesImu limitedAxesImu;
+ limitedAxesImu.x = src.limited_axes_imu.x;
+ limitedAxesImu.y = src.limited_axes_imu.y;
+ limitedAxesImu.z = src.limited_axes_imu.z;
+ limitedAxesImu.xSupported = src.limited_axes_imu.x_supported;
+ limitedAxesImu.ySupported = src.limited_axes_imu.y_supported;
+ limitedAxesImu.zSupported = src.limited_axes_imu.z_supported;
+ dst->payload.set<Event::EventPayload::Tag::limitedAxesImu>(limitedAxesImu);
+ break;
+ }
+
+ case SensorType::ACCELEROMETER_LIMITED_AXES_UNCALIBRATED:
+ case SensorType::GYROSCOPE_LIMITED_AXES_UNCALIBRATED: {
+ Event::EventPayload::LimitedAxesImuUncal limitedAxesImuUncal;
+ limitedAxesImuUncal.x = src.limited_axes_imu_uncalibrated.x_uncalib;
+ limitedAxesImuUncal.y = src.limited_axes_imu_uncalibrated.y_uncalib;
+ limitedAxesImuUncal.z = src.limited_axes_imu_uncalibrated.z_uncalib;
+ limitedAxesImuUncal.xBias = src.limited_axes_imu_uncalibrated.x_bias;
+ limitedAxesImuUncal.yBias = src.limited_axes_imu_uncalibrated.y_bias;
+ limitedAxesImuUncal.yBias = src.limited_axes_imu_uncalibrated.y_bias;
+ limitedAxesImuUncal.zBias = src.limited_axes_imu_uncalibrated.z_bias;
+ limitedAxesImuUncal.xSupported = src.limited_axes_imu_uncalibrated.x_supported;
+ limitedAxesImuUncal.ySupported = src.limited_axes_imu_uncalibrated.y_supported;
+ limitedAxesImuUncal.zSupported = src.limited_axes_imu_uncalibrated.z_supported;
+ dst->payload.set<Event::EventPayload::Tag::limitedAxesImuUncal>(limitedAxesImuUncal);
+ break;
+ }
+
+ case SensorType::HEADING: {
+ Event::EventPayload::Heading heading;
+ heading.heading = src.heading.heading;
+ heading.accuracy = src.heading.accuracy;
+ dst->payload.set<Event::EventPayload::heading>(heading);
+ break;
+ }
+
+ default: {
+ CHECK_GE((int32_t)dst->sensorType, (int32_t)SensorType::DEVICE_PRIVATE_BASE);
+
+ Event::EventPayload::Data data;
+ memcpy(data.values.data(), src.data, 16 * sizeof(float));
+ dst->payload.set<Event::EventPayload::Tag::data>(data);
+ break;
+ }
+ }
+}
+
+} // namespace implementation
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/aidl/convert/include/aidl/sensors/convert.h b/sensors/aidl/convert/include/aidl/sensors/convert.h
new file mode 100644
index 0000000..702b226
--- /dev/null
+++ b/sensors/aidl/convert/include/aidl/sensors/convert.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/sensors/ISensors.h>
+#include <hardware/sensors.h>
+
+namespace android {
+namespace hardware {
+namespace sensors {
+namespace implementation {
+
+status_t convertToStatus(ndk::ScopedAStatus status);
+void convertToSensor(const aidl::android::hardware::sensors::SensorInfo& src, sensor_t* dst);
+void convertToSensorEvent(const aidl::android::hardware::sensors::Event& src, sensors_event_t* dst);
+void convertFromSensorEvent(const sensors_event_t& src,
+ aidl::android::hardware::sensors::Event* dst);
+
+} // namespace implementation
+} // namespace sensors
+} // namespace hardware
+} // namespace android
diff --git a/sensors/aidl/default/Sensor.cpp b/sensors/aidl/default/Sensor.cpp
index 62193d6..3bdd8b6 100644
--- a/sensors/aidl/default/Sensor.cpp
+++ b/sensors/aidl/default/Sensor.cpp
@@ -223,7 +223,7 @@
EventPayload::Vec3 vec3 = {
.x = 0,
.y = 0,
- .z = -9.8,
+ .z = 9.8,
.status = SensorStatus::ACCURACY_HIGH,
};
payload.set<EventPayload::Tag::vec3>(vec3);
diff --git a/sensors/common/default/2.X/Sensor.cpp b/sensors/common/default/2.X/Sensor.cpp
index fd701fd..2c1cdfb 100644
--- a/sensors/common/default/2.X/Sensor.cpp
+++ b/sensors/common/default/2.X/Sensor.cpp
@@ -218,7 +218,7 @@
void AccelSensor::readEventPayload(EventPayload& payload) {
payload.vec3.x = 0;
payload.vec3.y = 0;
- payload.vec3.z = -9.8;
+ payload.vec3.z = 9.8;
payload.vec3.status = SensorStatus::ACCURACY_HIGH;
}
diff --git a/sensors/common/default/2.X/multihal/tests/fake_subhal/Sensor.cpp b/sensors/common/default/2.X/multihal/tests/fake_subhal/Sensor.cpp
index f5745c5..a0bb67a 100644
--- a/sensors/common/default/2.X/multihal/tests/fake_subhal/Sensor.cpp
+++ b/sensors/common/default/2.X/multihal/tests/fake_subhal/Sensor.cpp
@@ -237,7 +237,7 @@
event.timestamp = ::android::elapsedRealtimeNano();
event.u.vec3.x = 0;
event.u.vec3.y = 0;
- event.u.vec3.z = -9.815;
+ event.u.vec3.z = 9.815;
event.u.vec3.status = SensorStatus::ACCURACY_HIGH;
events.push_back(event);
return events;
diff --git a/tv/hdmi/aidl/aidl_api/android.hardware.tv.hdmi/current/android/hardware/tv/hdmi/HdmiPortInfo.aidl b/tv/hdmi/aidl/aidl_api/android.hardware.tv.hdmi/current/android/hardware/tv/hdmi/HdmiPortInfo.aidl
index a5e3a2a..25c3be1 100644
--- a/tv/hdmi/aidl/aidl_api/android.hardware.tv.hdmi/current/android/hardware/tv/hdmi/HdmiPortInfo.aidl
+++ b/tv/hdmi/aidl/aidl_api/android.hardware.tv.hdmi/current/android/hardware/tv/hdmi/HdmiPortInfo.aidl
@@ -38,5 +38,6 @@
int portId;
boolean cecSupported;
boolean arcSupported;
+ boolean eArcSupported;
int physicalAddress;
}
diff --git a/tv/hdmi/aidl/android/hardware/tv/hdmi/HdmiPortInfo.aidl b/tv/hdmi/aidl/android/hardware/tv/hdmi/HdmiPortInfo.aidl
index 1d6f27d..2e2c858 100644
--- a/tv/hdmi/aidl/android/hardware/tv/hdmi/HdmiPortInfo.aidl
+++ b/tv/hdmi/aidl/android/hardware/tv/hdmi/HdmiPortInfo.aidl
@@ -27,6 +27,7 @@
int portId; // Should start from 1 which corresponds to HDMI "port 1".
boolean cecSupported;
boolean arcSupported;
+ boolean eArcSupported;
// The physical address of the device connected to this port, valid range is 0x0000 to 0xFFFF
// (ref Sec 8.7.2 of HDMI 1.4b).
int physicalAddress;
diff --git a/tv/hdmi/aidl/default/HdmiMock.cpp b/tv/hdmi/aidl/default/HdmiMock.cpp
index 0cf5118..bbc4705 100644
--- a/tv/hdmi/aidl/default/HdmiMock.cpp
+++ b/tv/hdmi/aidl/default/HdmiMock.cpp
@@ -166,6 +166,7 @@
.portId = static_cast<uint32_t>(1),
.cecSupported = true,
.arcSupported = false,
+ .eArcSupported = false,
.physicalAddress = mPhysicalAddress};
mPortConnectionStatus[0] = false;
mDeathRecipient = ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new(serviceDied));
diff --git a/tv/tuner/OWNERS b/tv/tuner/OWNERS
new file mode 100644
index 0000000..83e090d
--- /dev/null
+++ b/tv/tuner/OWNERS
@@ -0,0 +1,6 @@
+# Bug component: 136752
+
+quxiangfang@google.com
+shubang@google.com
+hgchen@google.com
+raychin@google.com
diff --git a/tv/tuner/aidl/aidl_api/android.hardware.tv.tuner/current/android/hardware/tv/tuner/ITuner.aidl b/tv/tuner/aidl/aidl_api/android.hardware.tv.tuner/current/android/hardware/tv/tuner/ITuner.aidl
index 0ff2da9..5d1d215 100644
--- a/tv/tuner/aidl/aidl_api/android.hardware.tv.tuner/current/android/hardware/tv/tuner/ITuner.aidl
+++ b/tv/tuner/aidl/aidl_api/android.hardware.tv.tuner/current/android/hardware/tv/tuner/ITuner.aidl
@@ -47,4 +47,5 @@
void setLna(in boolean bEnable);
void setMaxNumberOfFrontends(in android.hardware.tv.tuner.FrontendType frontendType, in int maxNumber);
int getMaxNumberOfFrontends(in android.hardware.tv.tuner.FrontendType frontendType);
+ boolean isLnaSupported();
}
diff --git a/tv/tuner/aidl/android/hardware/tv/tuner/ITuner.aidl b/tv/tuner/aidl/android/hardware/tv/tuner/ITuner.aidl
index 03def33..4a0b7a2 100644
--- a/tv/tuner/aidl/android/hardware/tv/tuner/ITuner.aidl
+++ b/tv/tuner/aidl/android/hardware/tv/tuner/ITuner.aidl
@@ -125,6 +125,9 @@
/**
* Enable or Disable Low Noise Amplifier (LNA).
*
+ * If the device doesn't support LNA, the HAL implement should set {@link Result#UNAVAILABLE}
+ * to EX_SERVICE_SPECIFIC as the service specific error.
+ *
* @param bEnable true if activate LNA module; false if deactivate LNA
*/
void setLna(in boolean bEnable);
@@ -148,4 +151,11 @@
* @return the maximum usable number of the queried frontend type.
*/
int getMaxNumberOfFrontends(in FrontendType frontendType);
+
+ /**
+ * Is Low Noise Amplifier (LNA) supported.
+ *
+ * @return true if supported, otherwise false
+ */
+ boolean isLnaSupported();
}
diff --git a/tv/tuner/aidl/default/Tuner.cpp b/tv/tuner/aidl/default/Tuner.cpp
index 591f936..8c715a0 100644
--- a/tv/tuner/aidl/default/Tuner.cpp
+++ b/tv/tuner/aidl/default/Tuner.cpp
@@ -204,6 +204,13 @@
return ::ndk::ScopedAStatus::ok();
}
+::ndk::ScopedAStatus Tuner::isLnaSupported(bool* _aidl_return) {
+ ALOGV("%s", __FUNCTION__);
+
+ *_aidl_return = true;
+ return ::ndk::ScopedAStatus::ok();
+}
+
binder_status_t Tuner::dump(int fd, const char** args, uint32_t numArgs) {
ALOGV("%s", __FUNCTION__);
{
diff --git a/tv/tuner/aidl/default/Tuner.h b/tv/tuner/aidl/default/Tuner.h
index ad73003..a77c930 100644
--- a/tv/tuner/aidl/default/Tuner.h
+++ b/tv/tuner/aidl/default/Tuner.h
@@ -61,6 +61,7 @@
int32_t in_maxNumber) override;
::ndk::ScopedAStatus getMaxNumberOfFrontends(FrontendType in_frontendType,
int32_t* _aidl_return) override;
+ ::ndk::ScopedAStatus isLnaSupported(bool* _aidl_return) override;
binder_status_t dump(int fd, const char** args, uint32_t numArgs) override;
diff --git a/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/ComplianceWarning.aidl b/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/ComplianceWarning.aidl
new file mode 100644
index 0000000..8b67070
--- /dev/null
+++ b/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/ComplianceWarning.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.usb;
+@Backing(type="int") @VintfStability
+enum ComplianceWarning {
+ OTHER = 1,
+ DEBUG_ACCESSORY = 2,
+ BC_1_2 = 3,
+ MISSING_RP = 4,
+}
diff --git a/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/IUsb.aidl b/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/IUsb.aidl
index f866c1e..859f526 100644
--- a/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/IUsb.aidl
+++ b/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/IUsb.aidl
@@ -41,5 +41,5 @@
oneway void setCallback(in android.hardware.usb.IUsbCallback callback);
oneway void switchRole(in String portName, in android.hardware.usb.PortRole role, long transactionId);
oneway void limitPowerTransfer(in String portName, boolean limit, long transactionId);
- oneway void resetUsbPort(in String portName,long transactionId);
+ oneway void resetUsbPort(in String portName, long transactionId);
}
diff --git a/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/PortStatus.aidl b/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/PortStatus.aidl
index dfd99fb..b0b7552 100644
--- a/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/PortStatus.aidl
+++ b/usb/aidl/aidl_api/android.hardware.usb/current/android/hardware/usb/PortStatus.aidl
@@ -50,4 +50,6 @@
android.hardware.usb.UsbDataStatus[] usbDataStatus;
boolean powerTransferLimited;
android.hardware.usb.PowerBrickStatus powerBrickStatus;
+ boolean supportsComplianceWarnings = false;
+ android.hardware.usb.ComplianceWarning[] complianceWarnings = {};
}
diff --git a/usb/aidl/android/hardware/usb/ComplianceWarning.aidl b/usb/aidl/android/hardware/usb/ComplianceWarning.aidl
new file mode 100644
index 0000000..4c18a31
--- /dev/null
+++ b/usb/aidl/android/hardware/usb/ComplianceWarning.aidl
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.usb;
+
+@VintfStability
+@Backing(type="int")
+/**
+ * Indicates the potential non-compliance reasons for the
+ * connected USB Type-C port partner which could be a power
+ * source, accessory or cable. Applicable for USB-C receptacles
+ * in Android devices.
+ */
+enum ComplianceWarning {
+ /**
+ * Used to indicate Type-C sources/cables/accessories/ports
+ * whose issue is not listed below but do not meet
+ * specification requirements from including but not limited to
+ * USB Type-C Cable and Connector Specification, Universal Serial Bus
+ * Power Delivery Specification, and Universal Serial Bus
+ * 1.x/2.0/3.x/4.0.
+ */
+ OTHER = 1,
+ /**
+ * Used to indicate Type-C port partner
+ * (cable/accessory/source) that identifies itself as debug
+ * accessory source as defined in USB Type-C Cable and
+ * Connector Specification. However, the specification
+ * states that this is meant for debug only and shall not
+ * be used for with commercial products.
+ */
+ DEBUG_ACCESSORY = 2,
+ /**
+ * Used to indicate Type-C port partner that does not
+ * identify itself as one of the charging port types
+ * (SDP/CDP/DCP etc) as defined by Battery Charging v1.2
+ * Specification.
+ */
+ BC_1_2 = 3,
+ /**
+ * Used to indicate Type-C sources/cables that are missing
+ * pull up resistors on the CC pins as required by USB
+ * Type-C Cable and Connector Specification.
+ */
+ MISSING_RP = 4,
+}
diff --git a/usb/aidl/android/hardware/usb/PortStatus.aidl b/usb/aidl/android/hardware/usb/PortStatus.aidl
index 51bee71..d7e61ec 100644
--- a/usb/aidl/android/hardware/usb/PortStatus.aidl
+++ b/usb/aidl/android/hardware/usb/PortStatus.aidl
@@ -19,6 +19,7 @@
import android.hardware.usb.ContaminantDetectionStatus;
import android.hardware.usb.ContaminantProtectionMode;
import android.hardware.usb.ContaminantProtectionStatus;
+import android.hardware.usb.ComplianceWarning;
import android.hardware.usb.PortDataRole;
import android.hardware.usb.PortMode;
import android.hardware.usb.PortPowerRole;
@@ -115,4 +116,15 @@
* Denotes whether Power brick is connected.
*/
PowerBrickStatus powerBrickStatus;
+ /**
+ * True if the hal implementation can support identifying
+ * non compliant USB power source/cable/accessory. False other
+ * otherwise.
+ */
+ boolean supportsComplianceWarnings = false;
+ /**
+ * List of reasons as to why the attached USB
+ * power source/cable/accessory is non compliant.
+ */
+ ComplianceWarning[] complianceWarnings = {};
}
diff --git a/usb/aidl/default/Android.bp b/usb/aidl/default/Android.bp
index ad331f9..472e732 100644
--- a/usb/aidl/default/Android.bp
+++ b/usb/aidl/default/Android.bp
@@ -34,7 +34,7 @@
"Usb.cpp",
],
shared_libs: [
- "android.hardware.usb-V1-ndk",
+ "android.hardware.usb-V2-ndk",
"libbase",
"libbinder_ndk",
"libcutils",
diff --git a/usb/aidl/default/Usb.cpp b/usb/aidl/default/Usb.cpp
index 7e738c4..dd12da0 100644
--- a/usb/aidl/default/Usb.cpp
+++ b/usb/aidl/default/Usb.cpp
@@ -123,6 +123,15 @@
return Status::SUCCESS;
}
+Status queryNonCompliantChargerStatus(std::vector<PortStatus> *currentPortStatus) {
+ string reasons, path;
+
+ for (int i = 0; i < currentPortStatus->size(); i++) {
+ (*currentPortStatus)[i].supportsComplianceWarnings = false;
+ }
+ return Status::SUCCESS;
+}
+
string appendRoleNodeHelper(const string &portName, PortRole::Tag tag) {
string node(kTypecPath + portName);
@@ -527,6 +536,7 @@
pthread_mutex_lock(&usb->mLock);
status = getPortStatusHelper(currentPortStatus);
queryMoistureDetectionStatus(currentPortStatus);
+ queryNonCompliantChargerStatus(currentPortStatus);
if (usb->mCallback != NULL) {
ScopedAStatus ret = usb->mCallback->notifyPortStatusChange(*currentPortStatus,
status);
diff --git a/usb/aidl/default/android.hardware.usb-service.example.xml b/usb/aidl/default/android.hardware.usb-service.example.xml
index 6088194..c3f07f5 100644
--- a/usb/aidl/default/android.hardware.usb-service.example.xml
+++ b/usb/aidl/default/android.hardware.usb-service.example.xml
@@ -1,7 +1,7 @@
<manifest version="1.0" type="device">
<hal format="aidl">
<name>android.hardware.usb</name>
- <version>1</version>
+ <version>2</version>
<interface>
<name>IUsb</name>
<instance>default</instance>
diff --git a/usb/aidl/vts/Android.bp b/usb/aidl/vts/Android.bp
index 00a7c93..d0e0eec 100644
--- a/usb/aidl/vts/Android.bp
+++ b/usb/aidl/vts/Android.bp
@@ -34,7 +34,7 @@
"libbinder_ndk",
],
static_libs: [
- "android.hardware.usb-V1-ndk",
+ "android.hardware.usb-V2-ndk",
],
test_suites: [
"general-tests",
diff --git a/usb/aidl/vts/VtsAidlUsbTargetTest.cpp b/usb/aidl/vts/VtsAidlUsbTargetTest.cpp
index ea2f985..c4ec8a4 100644
--- a/usb/aidl/vts/VtsAidlUsbTargetTest.cpp
+++ b/usb/aidl/vts/VtsAidlUsbTargetTest.cpp
@@ -43,6 +43,7 @@
#define TIMEOUT_PERIOD 10
using ::aidl::android::hardware::usb::BnUsbCallback;
+using ::aidl::android::hardware::usb::ComplianceWarning;
using ::aidl::android::hardware::usb::IUsb;
using ::aidl::android::hardware::usb::IUsbCallback;
using ::aidl::android::hardware::usb::PortDataRole;
@@ -560,6 +561,53 @@
ALOGI("UsbAidlTest resetUsbPort end");
}
+/*
+ * Test charger compliance warning
+ * The test asserts that complianceWarnings is
+ * empty when the feature is not supported. i.e.
+ * supportsComplianceWarning is false.
+ */
+TEST_P(UsbAidlTest, nonCompliantChargerStatus) {
+ ALOGI("UsbAidlTest nonCompliantChargerStatus start");
+ int64_t transactionId = rand() % 10000;
+ const auto& ret = usb->queryPortStatus(transactionId);
+ ASSERT_TRUE(ret.isOk());
+ EXPECT_EQ(std::cv_status::no_timeout, wait());
+ EXPECT_EQ(2, usb_last_cookie);
+ EXPECT_EQ(transactionId, last_transactionId);
+
+ if (!usb_last_port_status.supportsComplianceWarnings) {
+ EXPECT_TRUE(usb_last_port_status.complianceWarnings.empty());
+ }
+
+ ALOGI("UsbAidlTest nonCompliantChargerStatus end");
+}
+
+/*
+ * Test charger compliance warning values
+ * The test asserts that complianceWarning values
+ * are valid.
+ */
+TEST_P(UsbAidlTest, nonCompliantChargerValues) {
+ ALOGI("UsbAidlTest nonCompliantChargerValues start");
+ int64_t transactionId = rand() % 10000;
+ const auto& ret = usb->queryPortStatus(transactionId);
+ ASSERT_TRUE(ret.isOk());
+ EXPECT_EQ(std::cv_status::no_timeout, wait());
+ EXPECT_EQ(2, usb_last_cookie);
+ EXPECT_EQ(transactionId, last_transactionId);
+
+ // Current compliance values range from [1, 4]
+ if (usb_last_port_status.supportsComplianceWarnings) {
+ for (auto warning : usb_last_port_status.complianceWarnings) {
+ EXPECT_TRUE((int)warning >= (int)ComplianceWarning::OTHER);
+ EXPECT_TRUE((int)warning <= (int)ComplianceWarning::MISSING_RP);
+ }
+ }
+
+ ALOGI("UsbAidlTest nonCompliantChargerValues end");
+}
+
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(UsbAidlTest);
INSTANTIATE_TEST_SUITE_P(
PerInstance, UsbAidlTest,
diff --git a/usb/gadget/aidl/Android.bp b/usb/gadget/aidl/Android.bp
new file mode 100644
index 0000000..cb8560a
--- /dev/null
+++ b/usb/gadget/aidl/Android.bp
@@ -0,0 +1,37 @@
+// Copyright (C) 2022 The Android Open Source Project
+//
+// 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.
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "hardware_interfaces_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+aidl_interface {
+ name: "android.hardware.usb.gadget",
+ vendor_available: true,
+ srcs: ["android/hardware/usb/gadget/*.aidl"],
+ stability: "vintf",
+ backend: {
+ cpp: {
+ enabled: false,
+ },
+ java: {
+ sdk_version: "module_current",
+ },
+ },
+}
diff --git a/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/GadgetFunction.aidl b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/GadgetFunction.aidl
new file mode 100644
index 0000000..c3f26d5
--- /dev/null
+++ b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/GadgetFunction.aidl
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.usb.gadget;
+@VintfStability
+parcelable GadgetFunction {
+ const long NONE = 0;
+ const long ADB = 1;
+ const long ACCESSORY = 2;
+ const long MTP = 4;
+ const long MIDI = 8;
+ const long PTP = 16;
+ const long RNDIS = 32;
+ const long AUDIO_SOURCE = 64;
+ const long NCM = 1024;
+}
diff --git a/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/IUsbGadget.aidl b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/IUsbGadget.aidl
new file mode 100644
index 0000000..ef45f8b
--- /dev/null
+++ b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/IUsbGadget.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.usb.gadget;
+@VintfStability
+interface IUsbGadget {
+ oneway void setCurrentUsbFunctions(in long functions, in android.hardware.usb.gadget.IUsbGadgetCallback callback, in long timeoutMs, long transactionId);
+ oneway void getCurrentUsbFunctions(in android.hardware.usb.gadget.IUsbGadgetCallback callback, long transactionId);
+ oneway void getUsbSpeed(in android.hardware.usb.gadget.IUsbGadgetCallback callback, long transactionId);
+ oneway void reset();
+}
diff --git a/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/IUsbGadgetCallback.aidl b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/IUsbGadgetCallback.aidl
new file mode 100644
index 0000000..8672a0c
--- /dev/null
+++ b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/IUsbGadgetCallback.aidl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.usb.gadget;
+@VintfStability
+interface IUsbGadgetCallback {
+ oneway void getCurrentUsbFunctionsCb(in long functions, in android.hardware.usb.gadget.Status status, long transactionId);
+ oneway void getUsbSpeedCb(in android.hardware.usb.gadget.UsbSpeed speed, long transactionId);
+ oneway void setCurrentUsbFunctionsCb(in long functions, in android.hardware.usb.gadget.Status status, long transactionId);
+}
diff --git a/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/Status.aidl b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/Status.aidl
new file mode 100644
index 0000000..bdcf685
--- /dev/null
+++ b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/Status.aidl
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.usb.gadget;
+@Backing(type="int") @VintfStability
+enum Status {
+ SUCCESS = 0,
+ ERROR = 1,
+ FUNCTIONS_APPLIED = 2,
+ FUNCTIONS_NOT_APPLIED = 3,
+ CONFIGURATION_NOT_SUPPORTED = 4,
+}
diff --git a/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/UsbSpeed.aidl b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/UsbSpeed.aidl
new file mode 100644
index 0000000..0f54ee5
--- /dev/null
+++ b/usb/gadget/aidl/aidl_api/android.hardware.usb.gadget/current/android/hardware/usb/gadget/UsbSpeed.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.usb.gadget;
+@Backing(type="int") @VintfStability
+enum UsbSpeed {
+ UNKNOWN = 0,
+ LOWSPEED = 1,
+ FULLSPEED = 2,
+ HIGHSPEED = 3,
+ SUPERSPEED = 4,
+ SUPERSPEED_10Gb = 5,
+ SUPERSPEED_20Gb = 6,
+}
diff --git a/usb/gadget/aidl/android/hardware/usb/gadget/GadgetFunction.aidl b/usb/gadget/aidl/android/hardware/usb/gadget/GadgetFunction.aidl
new file mode 100644
index 0000000..18b31b8
--- /dev/null
+++ b/usb/gadget/aidl/android/hardware/usb/gadget/GadgetFunction.aidl
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.usb.gadget;
+
+@VintfStability
+parcelable GadgetFunction {
+ /**
+ * Removes all the functions and pulls down the gadget.
+ */
+ const long NONE = 0;
+ /**
+ * Android Debug Bridge function.
+ */
+ const long ADB = 1;
+ /**
+ * Android open accessory protocol function.
+ */
+ const long ACCESSORY = 2;
+ /**
+ * Media Transfer protocol function.
+ */
+ const long MTP = 4;
+ /**
+ * Peripheral mode USB Midi function.
+ */
+ const long MIDI = 8;
+ /**
+ * Picture transfer protocol function.
+ */
+ const long PTP = 16;
+ /**
+ * Tethering function.
+ */
+ const long RNDIS = 32;
+ /**
+ * AOAv2.0 - Audio Source function.
+ */
+ const long AUDIO_SOURCE = 64;
+ /**
+ * NCM - NCM function.
+ */
+ const long NCM = 1024;
+}
diff --git a/usb/gadget/aidl/android/hardware/usb/gadget/IUsbGadget.aidl b/usb/gadget/aidl/android/hardware/usb/gadget/IUsbGadget.aidl
new file mode 100644
index 0000000..d187993
--- /dev/null
+++ b/usb/gadget/aidl/android/hardware/usb/gadget/IUsbGadget.aidl
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.usb.gadget;
+
+import android.hardware.usb.gadget.GadgetFunction;
+import android.hardware.usb.gadget.IUsbGadgetCallback;
+
+@VintfStability
+oneway interface IUsbGadget {
+ /**
+ * This function is used to set the current USB gadget configuration.
+ * Usb gadget needs to teared down if an USB configuration is already
+ * active.
+ *
+ * @param functions The GadgetFunction bitmap. See GadgetFunction for
+ * the value of each bit.
+ * @param callback IUsbGadgetCallback::setCurrentUsbFunctionsCb used to
+ * propagate back the status.
+ * @param timeoutMs The maximum time (in milliseconds) within which the
+ * IUsbGadgetCallback needs to be returned.
+ * @param transactionId ID to be used when invoking the callback.
+ *
+ */
+ void setCurrentUsbFunctions(in long functions, in IUsbGadgetCallback callback,
+ in long timeoutMs, long transactionId);
+
+ /**
+ * This function is used to query the USB functions included in the
+ * current USB configuration.
+ *
+ * @param callback IUsbGadgetCallback::getCurrentUsbFunctionsCb used to
+ * propagate the current functions list.
+ * @param transactionId ID to be used when invoking the callback.
+ */
+ void getCurrentUsbFunctions(in IUsbGadgetCallback callback, long transactionId);
+
+ /**
+ * The function is used to query current USB speed.
+ *
+ * @param callback IUsbGadgetCallback::getUsbSpeedCb used to propagate
+ * current USB speed.
+ * @param transactionId ID to be used when invoking the callback.
+ */
+ void getUsbSpeed(in IUsbGadgetCallback callback, long transactionId);
+
+ /**
+ * This function is used to reset USB gadget driver.
+ * Performs USB data connection reset. The connection will disconnect and
+ * reconnect.
+ */
+ void reset();
+}
diff --git a/usb/gadget/aidl/android/hardware/usb/gadget/IUsbGadgetCallback.aidl b/usb/gadget/aidl/android/hardware/usb/gadget/IUsbGadgetCallback.aidl
new file mode 100644
index 0000000..75ff02b
--- /dev/null
+++ b/usb/gadget/aidl/android/hardware/usb/gadget/IUsbGadgetCallback.aidl
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.usb.gadget;
+
+import android.hardware.usb.gadget.GadgetFunction;
+import android.hardware.usb.gadget.Status;
+import android.hardware.usb.gadget.UsbSpeed;
+
+@VintfStability
+oneway interface IUsbGadgetCallback {
+ /**
+ * Callback function used to propagate the current USB gadget
+ * configuration.
+ * @param functions The GadgetFunction bitmap. See GadgetFunction for
+ * the value of each bit.
+ * @param status FUNCTIONS_APPLIED when list of functions have been
+ * applied.
+ * FUNCTIONS_NOT_APPLIED when the functions have not
+ * been applied.
+ * ERROR otherwise.
+ * @param transactionId ID to be used when invoking the callback.
+ */
+ void getCurrentUsbFunctionsCb(in long functions, in Status status, long transactionId);
+
+ /**
+ * Used to convey the current USB speed to the caller.
+ * Must be called either when USB state changes due to USB enumeration or
+ * when caller requested for USB speed through getUsbSpeed.
+ *
+ * @param speed USB Speed defined by UsbSpeed showed current USB
+ * connection speed.
+ * @param transactionId ID to be used when invoking the callback.
+ */
+ void getUsbSpeedCb(in UsbSpeed speed, long transactionId);
+
+ /**
+ * Callback function used to propagate the status of configuration
+ * switch to the caller.
+ *
+ * @param functions list of functions defined by GadgetFunction
+ * included in the current USB gadget composition.
+ * @param status SUCCESS when the functions are applied.
+ * FUNCTIONS_NOT_SUPPORTED when the configuration is
+ * not supported.
+ * ERROR otherwise.
+ * @param transactionId ID to be used when invoking the callback.
+ */
+ void setCurrentUsbFunctionsCb(in long functions, in Status status, long transactionId);
+}
diff --git a/usb/gadget/aidl/android/hardware/usb/gadget/Status.aidl b/usb/gadget/aidl/android/hardware/usb/gadget/Status.aidl
new file mode 100644
index 0000000..8d8c3e3
--- /dev/null
+++ b/usb/gadget/aidl/android/hardware/usb/gadget/Status.aidl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.usb.gadget;
+
+@VintfStability
+@Backing(type="int")
+enum Status {
+ SUCCESS = 0,
+ /**
+ * Error value when the HAL operation fails for reasons not listed here.
+ */
+ ERROR = 1,
+ /**
+ * USB configuration applied successfully.
+ */
+ FUNCTIONS_APPLIED = 2,
+ /**
+ * USB confgiuration failed to apply.
+ */
+ FUNCTIONS_NOT_APPLIED = 3,
+ /**
+ * USB configuration not supported.
+ */
+ CONFIGURATION_NOT_SUPPORTED = 4,
+}
diff --git a/usb/gadget/aidl/android/hardware/usb/gadget/UsbSpeed.aidl b/usb/gadget/aidl/android/hardware/usb/gadget/UsbSpeed.aidl
new file mode 100644
index 0000000..0492757
--- /dev/null
+++ b/usb/gadget/aidl/android/hardware/usb/gadget/UsbSpeed.aidl
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.usb.gadget;
+
+@VintfStability
+@Backing(type="int")
+enum UsbSpeed {
+ /**
+ * UNKNOWN - Not Connected or Unsupported Speed
+ */
+ UNKNOWN = 0,
+ /**
+ * USB Low Speed
+ */
+ LOWSPEED = 1,
+ /**
+ * USB Full Speed
+ */
+ FULLSPEED = 2,
+ /**
+ * USB High Speed
+ */
+ HIGHSPEED = 3,
+ /**
+ * USB Super Speed
+ */
+ SUPERSPEED = 4,
+ /**
+ * USB Super Speed 10Gbps
+ */
+ SUPERSPEED_10Gb = 5,
+ /**
+ * USB Super Speed 20Gbps
+ */
+ SUPERSPEED_20Gb = 6,
+}
diff --git a/usb/gadget/aidl/default/Android.bp b/usb/gadget/aidl/default/Android.bp
new file mode 100644
index 0000000..2ea0e12
--- /dev/null
+++ b/usb/gadget/aidl/default/Android.bp
@@ -0,0 +1,47 @@
+//
+// Copyright (C) 2022 The Android Open Source Project
+//
+// 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.
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "hardware_interfaces_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: [
+ "hardware_interfaces_license",
+ ],
+}
+cc_binary {
+ name: "android.hardware.usb.gadget-service.example",
+ relative_install_path: "hw",
+ init_rc: ["android.hardware.usb.gadget-service.example.rc"],
+ vintf_fragments: [
+ "android.hardware.usb.gadget-service.example.xml",
+ ],
+ vendor: true,
+ srcs: ["service_gadget.cpp", "UsbGadget.cpp"],
+ cflags: ["-Wall", "-Werror"],
+ shared_libs: [
+ "libbase",
+ "libbinder",
+ "libhidlbase",
+ "liblog",
+ "libutils",
+ "libhardware",
+ "android.hardware.usb.gadget-V1-ndk",
+ "android.frameworks.stats-V1-ndk",
+ "libcutils",
+ "libbinder_ndk",
+ ],
+}
diff --git a/usb/gadget/aidl/default/UsbGadget.cpp b/usb/gadget/aidl/default/UsbGadget.cpp
new file mode 100644
index 0000000..1f1dc74
--- /dev/null
+++ b/usb/gadget/aidl/default/UsbGadget.cpp
@@ -0,0 +1,299 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#define LOG_TAG "android.hardware.usb.gadget.aidl-service"
+
+#include "UsbGadget.h"
+#include <dirent.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <sys/inotify.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <aidl/android/frameworks/stats/IStats.h>
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace usb {
+namespace gadget {
+
+string enabledPath;
+constexpr char kHsi2cPath[] = "/sys/devices/platform/10d50000.hsi2c";
+constexpr char kI2CPath[] = "/sys/devices/platform/10d50000.hsi2c/i2c-";
+constexpr char kAccessoryLimitCurrent[] = "i2c-max77759tcpc/usb_limit_accessory_current";
+constexpr char kAccessoryLimitCurrentEnable[] = "i2c-max77759tcpc/usb_limit_accessory_enable";
+
+UsbGadget::UsbGadget() : mGadgetIrqPath("") {
+}
+
+Status UsbGadget::getUsbGadgetIrqPath() {
+ std::string irqs;
+ size_t read_pos = 0;
+ size_t found_pos = 0;
+
+ if (!ReadFileToString(kProcInterruptsPath, &irqs)) {
+ ALOGE("cannot read all interrupts");
+ return Status::ERROR;
+ }
+
+ while (true) {
+ found_pos = irqs.find_first_of("\n", read_pos);
+ if (found_pos == std::string::npos) {
+ ALOGI("the string of all interrupts is unexpected");
+ return Status::ERROR;
+ }
+
+ std::string single_irq = irqs.substr(read_pos, found_pos - read_pos);
+
+ if (single_irq.find("dwc3", 0) != std::string::npos) {
+ unsigned int dwc3_irq_number;
+ size_t dwc3_pos = single_irq.find_first_of(":");
+ if (!ParseUint(single_irq.substr(0, dwc3_pos), &dwc3_irq_number)) {
+ ALOGI("unknown IRQ strings");
+ return Status::ERROR;
+ }
+
+ mGadgetIrqPath = kProcIrqPath + single_irq.substr(0, dwc3_pos) + kSmpAffinityList;
+ break;
+ }
+
+ if (found_pos == irqs.npos) {
+ ALOGI("USB gadget doesn't start");
+ return Status::ERROR;
+ }
+
+ read_pos = found_pos + 1;
+ }
+
+ return Status::SUCCESS;
+}
+
+void currentFunctionsAppliedCallback(bool functionsApplied, void *payload) {
+ UsbGadget *gadget = (UsbGadget *)payload;
+ gadget->mCurrentUsbFunctionsApplied = functionsApplied;
+}
+
+ScopedAStatus UsbGadget::getCurrentUsbFunctions(const shared_ptr<IUsbGadgetCallback> &callback,
+ int64_t in_transactionId) {
+ ScopedAStatus ret = callback->getCurrentUsbFunctionsCb(
+ mCurrentUsbFunctions,
+ mCurrentUsbFunctionsApplied ? Status::FUNCTIONS_APPLIED : Status::FUNCTIONS_NOT_APPLIED,
+ in_transactionId);
+ if (!ret.isOk())
+ ALOGE("Call to getCurrentUsbFunctionsCb failed %s", ret.getDescription().c_str());
+
+ return ScopedAStatus::ok();
+}
+
+ScopedAStatus UsbGadget::getUsbSpeed(const shared_ptr<IUsbGadgetCallback> &callback,
+ int64_t in_transactionId) {
+ std::string current_speed;
+ if (ReadFileToString(SPEED_PATH, ¤t_speed)) {
+ current_speed = Trim(current_speed);
+ ALOGI("current USB speed is %s", current_speed.c_str());
+ if (current_speed == "low-speed")
+ mUsbSpeed = UsbSpeed::LOWSPEED;
+ else if (current_speed == "full-speed")
+ mUsbSpeed = UsbSpeed::FULLSPEED;
+ else if (current_speed == "high-speed")
+ mUsbSpeed = UsbSpeed::HIGHSPEED;
+ else if (current_speed == "super-speed")
+ mUsbSpeed = UsbSpeed::SUPERSPEED;
+ else if (current_speed == "super-speed-plus")
+ mUsbSpeed = UsbSpeed::SUPERSPEED_10Gb;
+ else if (current_speed == "UNKNOWN")
+ mUsbSpeed = UsbSpeed::UNKNOWN;
+ else
+ mUsbSpeed = UsbSpeed::UNKNOWN;
+ } else {
+ ALOGE("Fail to read current speed");
+ mUsbSpeed = UsbSpeed::UNKNOWN;
+ }
+
+ if (callback) {
+ ScopedAStatus ret = callback->getUsbSpeedCb(mUsbSpeed, in_transactionId);
+
+ if (!ret.isOk())
+ ALOGE("Call to getUsbSpeedCb failed %s", ret.getDescription().c_str());
+ }
+
+ return ScopedAStatus::ok();
+}
+
+Status UsbGadget::tearDownGadget() {
+ return Status::SUCCESS;
+}
+
+ScopedAStatus UsbGadget::reset() {
+ return ScopedAStatus::ok();
+}
+
+Status UsbGadget::setupFunctions(long functions,
+ const shared_ptr<IUsbGadgetCallback> &callback, uint64_t timeout,
+ int64_t in_transactionId) {
+ bool ffsEnabled = false;
+ ALOGI("functions: %ld, timeout: %ld", functions, timeout);
+
+ if ((functions & GadgetFunction::ADB) != 0) {
+ ffsEnabled = true;
+ }
+
+ if ((functions & GadgetFunction::NCM) != 0) {
+ ALOGI("setCurrentUsbFunctions ncm");
+ }
+
+ // Pull up the gadget right away when there are no ffs functions.
+ if (!ffsEnabled) {
+ mCurrentUsbFunctionsApplied = true;
+ if (callback)
+ callback->setCurrentUsbFunctionsCb(functions, Status::SUCCESS, in_transactionId);
+ return Status::SUCCESS;
+ }
+
+ return Status::SUCCESS;
+}
+
+Status getI2cBusHelper(string *name) {
+ DIR *dp;
+
+ dp = opendir(kHsi2cPath);
+ if (dp != NULL) {
+ struct dirent *ep;
+
+ while ((ep = readdir(dp))) {
+ if (ep->d_type == DT_DIR) {
+ if (string::npos != string(ep->d_name).find("i2c-")) {
+ std::strtok(ep->d_name, "-");
+ *name = std::strtok(NULL, "-");
+ }
+ }
+ }
+ closedir(dp);
+ return Status::SUCCESS;
+ }
+
+ ALOGE("Failed to open %s", kHsi2cPath);
+ return Status::ERROR;
+}
+
+ScopedAStatus UsbGadget::setCurrentUsbFunctions(long functions,
+ const shared_ptr<IUsbGadgetCallback> &callback,
+ int64_t timeout,
+ int64_t in_transactionId) {
+ std::unique_lock<std::mutex> lk(mLockSetCurrentFunction);
+ std::string current_usb_power_operation_mode, current_usb_type;
+ std::string usb_limit_sink_enable;
+
+ string accessoryCurrentLimitEnablePath, accessoryCurrentLimitPath, path;
+
+ ALOGI("enter setCurrentUsbFunctions, in_transactionId=%ld , %ld", in_transactionId , timeout);
+ mCurrentUsbFunctions = functions;
+ mCurrentUsbFunctionsApplied = false;
+
+ getI2cBusHelper(&path);
+ accessoryCurrentLimitPath = kI2CPath + path + "/" + kAccessoryLimitCurrent;
+ accessoryCurrentLimitEnablePath = kI2CPath + path + "/" + kAccessoryLimitCurrentEnable;
+
+ // Get the gadget IRQ number before tearDownGadget()
+ if (mGadgetIrqPath.empty())
+ getUsbGadgetIrqPath();
+
+ // Unlink the gadget and stop the monitor if running.
+ Status status = tearDownGadget();
+ if (status != Status::SUCCESS) {
+ goto error;
+ }
+
+ ALOGI("Returned from tearDown gadget");
+
+ // Leave the gadget pulled down to give time for the host to sense disconnect.
+ //usleep(kDisconnectWaitUs);
+
+ if (functions == GadgetFunction::NONE) {
+ if (callback == NULL)
+ return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+ -1, "callback == NULL");
+ ScopedAStatus ret = callback->setCurrentUsbFunctionsCb(functions, Status::SUCCESS, in_transactionId);
+ if (!ret.isOk())
+ ALOGE("Error while calling setCurrentUsbFunctionsCb %s", ret.getDescription().c_str());
+ return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+ -1, "Error while calling setCurrentUsbFunctionsCb");
+ }
+
+ status = setupFunctions(functions, callback, timeout, in_transactionId);
+ if (status != Status::SUCCESS) {
+ goto error;
+ }
+
+ if (functions & GadgetFunction::NCM) {
+ if (!mGadgetIrqPath.empty()) {
+ if (!WriteStringToFile(BIG_CORE, mGadgetIrqPath))
+ ALOGI("Cannot move gadget IRQ to big core, path:%s", mGadgetIrqPath.c_str());
+ }
+ } else {
+ if (!mGadgetIrqPath.empty()) {
+ if (!WriteStringToFile(MEDIUM_CORE, mGadgetIrqPath))
+ ALOGI("Cannot move gadget IRQ to medium core, path:%s", mGadgetIrqPath.c_str());
+ }
+ }
+
+ if (ReadFileToString(CURRENT_USB_TYPE_PATH, ¤t_usb_type))
+ current_usb_type = Trim(current_usb_type);
+
+ if (ReadFileToString(CURRENT_USB_POWER_OPERATION_MODE_PATH, ¤t_usb_power_operation_mode))
+ current_usb_power_operation_mode = Trim(current_usb_power_operation_mode);
+
+ if (functions & GadgetFunction::ACCESSORY &&
+ current_usb_type == "Unknown SDP [CDP] DCP" &&
+ (current_usb_power_operation_mode == "default" ||
+ current_usb_power_operation_mode == "1.5A")) {
+ if (!WriteStringToFile("1300000", accessoryCurrentLimitPath)) {
+ ALOGI("Write 1.3A to limit current fail");
+ } else {
+ if (!WriteStringToFile("1", accessoryCurrentLimitEnablePath)) {
+ ALOGI("Enable limit current fail");
+ }
+ }
+ } else {
+ if (!WriteStringToFile("0", accessoryCurrentLimitEnablePath))
+ ALOGI("unvote accessory limit current failed");
+ }
+
+ ALOGI("Usb Gadget setcurrent functions called successfully");
+ return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+ -1, "Usb Gadget setcurrent functions called successfully");
+
+
+error:
+ ALOGI("Usb Gadget setcurrent functions failed");
+ if (callback == NULL)
+ return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+ -1, "Usb Gadget setcurrent functions failed");
+ ScopedAStatus ret = callback->setCurrentUsbFunctionsCb(functions, status, in_transactionId);
+ if (!ret.isOk())
+ ALOGE("Error while calling setCurrentUsbFunctionsCb %s", ret.getDescription().c_str());
+ return ScopedAStatus::fromServiceSpecificErrorWithMessage(
+ -1, "Error while calling setCurrentUsbFunctionsCb");
+}
+} // namespace gadget
+} // namespace usb
+} // namespace hardware
+} // namespace android
+} // aidl
diff --git a/usb/gadget/aidl/default/UsbGadget.h b/usb/gadget/aidl/default/UsbGadget.h
new file mode 100644
index 0000000..e119419
--- /dev/null
+++ b/usb/gadget/aidl/default/UsbGadget.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <android-base/file.h>
+#include <android-base/properties.h>
+#include <android-base/unique_fd.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
+#include <aidl/android/hardware/usb/gadget/BnUsbGadget.h>
+#include <aidl/android/hardware/usb/gadget/BnUsbGadgetCallback.h>
+#include <aidl/android/hardware/usb/gadget/GadgetFunction.h>
+#include <aidl/android/hardware/usb/gadget/IUsbGadget.h>
+#include <aidl/android/hardware/usb/gadget/IUsbGadgetCallback.h>
+#include <sched.h>
+#include <sys/epoll.h>
+#include <sys/eventfd.h>
+#include <utils/Log.h>
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+#include <string>
+#include <thread>
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace usb {
+namespace gadget {
+
+using ::aidl::android::hardware::usb::gadget::GadgetFunction;
+using ::aidl::android::hardware::usb::gadget::IUsbGadgetCallback;
+using ::aidl::android::hardware::usb::gadget::IUsbGadget;
+using ::aidl::android::hardware::usb::gadget::Status;
+using ::aidl::android::hardware::usb::gadget::UsbSpeed;
+using ::android::base::GetProperty;
+using ::android::base::SetProperty;
+using ::android::base::ParseUint;
+using ::android::base::unique_fd;
+using ::android::base::ReadFileToString;
+using ::android::base::Trim;
+using ::android::base::WriteStringToFile;
+using ::ndk::ScopedAStatus;
+using ::std::shared_ptr;
+using ::std::string;
+
+constexpr char kGadgetName[] = "11110000.dwc3";
+constexpr char kProcInterruptsPath[] = "/proc/interrupts";
+constexpr char kProcIrqPath[] = "/proc/irq/";
+constexpr char kSmpAffinityList[] = "/smp_affinity_list";
+#ifndef UDC_PATH
+#define UDC_PATH "/sys/class/udc/11110000.dwc3/"
+#endif
+//static MonitorFfs monitorFfs(kGadgetName);
+
+#define SPEED_PATH UDC_PATH "current_speed"
+
+#define BIG_CORE "6"
+#define MEDIUM_CORE "4"
+
+#define POWER_SUPPLY_PATH "/sys/class/power_supply/usb/"
+#define USB_PORT0_PATH "/sys/class/typec/port0/"
+
+#define CURRENT_MAX_PATH POWER_SUPPLY_PATH "current_max"
+#define CURRENT_USB_TYPE_PATH POWER_SUPPLY_PATH "usb_type"
+#define CURRENT_USB_POWER_OPERATION_MODE_PATH USB_PORT0_PATH "power_operation_mode"
+
+struct UsbGadget : public BnUsbGadget {
+ UsbGadget();
+
+ // Makes sure that only one request is processed at a time.
+ std::mutex mLockSetCurrentFunction;
+ std::string mGadgetIrqPath;
+ long mCurrentUsbFunctions;
+ bool mCurrentUsbFunctionsApplied;
+ UsbSpeed mUsbSpeed;
+
+ ScopedAStatus setCurrentUsbFunctions(long functions,
+ const shared_ptr<IUsbGadgetCallback> &callback,
+ int64_t timeout, int64_t in_transactionId) override;
+
+ ScopedAStatus getCurrentUsbFunctions(const shared_ptr<IUsbGadgetCallback> &callback,
+ int64_t in_transactionId) override;
+
+ ScopedAStatus reset() override;
+
+ ScopedAStatus getUsbSpeed(const shared_ptr<IUsbGadgetCallback> &callback,
+ int64_t in_transactionId) override;
+
+ private:
+ Status tearDownGadget();
+ Status getUsbGadgetIrqPath();
+ Status setupFunctions(long functions, const shared_ptr<IUsbGadgetCallback> &callback,
+ uint64_t timeout, int64_t in_transactionId);
+};
+
+} // namespace gadget
+} // namespace usb
+} // namespace hardware
+} // namespace android
+} // aidl
diff --git a/usb/gadget/aidl/default/android.hardware.usb.gadget-service.example.rc b/usb/gadget/aidl/default/android.hardware.usb.gadget-service.example.rc
new file mode 100644
index 0000000..b2a8cc0
--- /dev/null
+++ b/usb/gadget/aidl/default/android.hardware.usb.gadget-service.example.rc
@@ -0,0 +1,4 @@
+service vendor.usb_gadget_default /vendor/bin/hw/android.hardware.usb.gadget-service.example
+ class hal
+ user system
+ group system
diff --git a/usb/gadget/aidl/default/android.hardware.usb.gadget-service.example.xml b/usb/gadget/aidl/default/android.hardware.usb.gadget-service.example.xml
new file mode 100644
index 0000000..e7eebc3
--- /dev/null
+++ b/usb/gadget/aidl/default/android.hardware.usb.gadget-service.example.xml
@@ -0,0 +1,10 @@
+<manifest version="1.0" type="device">
+ <hal format="aidl">
+ <name>android.hardware.usb.gadget</name>
+ <version>1</version>
+ <interface>
+ <name>IUsbGadget</name>
+ <instance>default</instance>
+ </interface>
+ </hal>
+</manifest>
diff --git a/usb/gadget/aidl/default/service_gadget.cpp b/usb/gadget/aidl/default/service_gadget.cpp
new file mode 100644
index 0000000..3cc5718
--- /dev/null
+++ b/usb/gadget/aidl/default/service_gadget.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include "UsbGadget.h"
+/*using android::OK;
+using android::hardware::configureRpcThreadpool;
+using android::hardware::joinRpcThreadpool;
+using android::sp;
+using android::status_t;*/
+using ::aidl::android::hardware::usb::gadget::UsbGadget;
+int main() {
+ ABinderProcess_setThreadPoolMaxThreadCount(0);
+ std::shared_ptr<UsbGadget> usbgadget = ndk::SharedRefBase::make<UsbGadget>();
+ const std::string instance = std::string() + UsbGadget::descriptor + "/default";
+ binder_status_t status = AServiceManager_addService(usbgadget->asBinder().get(), instance.c_str());
+ CHECK(status == STATUS_OK);
+ ABinderProcess_joinThreadPool();
+ return -1;
+}
diff --git a/vibrator/aidl/Android.bp b/vibrator/aidl/Android.bp
index 86ef027..c5936e3 100644
--- a/vibrator/aidl/Android.bp
+++ b/vibrator/aidl/Android.bp
@@ -17,7 +17,7 @@
stability: "vintf",
backend: {
java: {
- sdk_version: "module_current",
+ sdk_version: "system_current",
},
},
versions: [
diff --git a/vibrator/aidl/default/example_vendor_java_client/Android.bp b/vibrator/aidl/default/example_vendor_java_client/Android.bp
new file mode 100644
index 0000000..f615cb1
--- /dev/null
+++ b/vibrator/aidl/default/example_vendor_java_client/Android.bp
@@ -0,0 +1,34 @@
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "hardware_interfaces_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_library {
+ name: "libexample_vib_getter",
+ srcs: ["getter.cpp"],
+ vendor: true,
+ shared_libs: [
+ "liblog",
+ "libbinder_ndk",
+ ],
+ header_libs: ["jni_headers"],
+ stl: "c++_shared",
+ visibility: [":__subpackages__"],
+}
+
+android_app {
+ name: "ExampleVibratorJavaVendorClient",
+ privileged: true,
+ vendor: true,
+ static_libs: ["android.hardware.vibrator-V1-java"],
+ jni_libs: ["libexample_vib_getter"],
+ jarjar_rules: "jarjar.txt",
+ stl: "c++_shared",
+ srcs: ["example/vib/MyActivity.java"],
+ sdk_version: "system_current",
+ visibility: [":__subpackages__"],
+}
diff --git a/vibrator/aidl/default/example_vendor_java_client/AndroidManifest.xml b/vibrator/aidl/default/example_vendor_java_client/AndroidManifest.xml
new file mode 100644
index 0000000..0561066
--- /dev/null
+++ b/vibrator/aidl/default/example_vendor_java_client/AndroidManifest.xml
@@ -0,0 +1,7 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ package="example.vib">
+ <application>
+ <activity android:name=".MyActivity"/>
+ </application>
+</manifest>
diff --git a/vibrator/aidl/default/example_vendor_java_client/example/vib/MyActivity.java b/vibrator/aidl/default/example_vendor_java_client/example/vib/MyActivity.java
new file mode 100644
index 0000000..aadce8e
--- /dev/null
+++ b/vibrator/aidl/default/example_vendor_java_client/example/vib/MyActivity.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package example.vib;
+
+import android.app.Activity;
+import android.hardware.vibrator.IVibrator;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+
+public class MyActivity extends Activity {
+ private static native IBinder gimme(String name);
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ System.loadLibrary("example_vib_getter");
+
+ // There is no API to get ahold of a Stable AIDL service from a vendor app
+ // in Java. This is because this is not the recommended way to get ahold
+ // of functionality in Android. The Android API Council recommendation is to
+ // implement uses-library APIs in the system/system_ext partition which add
+ // new APIs. AIDL as an API in Java is not recommended or supported way to
+ // communicate by apps - the recommendation is to use Java APIs. However,
+ // there also exists a large number of vendor apps which are coupled with
+ // hardware-specific code, and are therefore on the vendor partition. A
+ // large number of these use HIDL, and this is how they can continue to
+ // use that structure with AIDL.
+ IVibrator v =
+ IVibrator.Stub.asInterface(gimme("android.hardware.vibrator.IVibrator/default"));
+
+ try {
+ v.on(100 /*ms*/, null /*cb*/);
+ } catch (RemoteException e) {
+ throw new RuntimeException(e);
+ }
+
+ finish();
+ }
+}
diff --git a/vibrator/aidl/default/example_vendor_java_client/getter.cpp b/vibrator/aidl/default/example_vendor_java_client/getter.cpp
new file mode 100644
index 0000000..6115445
--- /dev/null
+++ b/vibrator/aidl/default/example_vendor_java_client/getter.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <android/binder_auto_utils.h>
+#include <android/binder_ibinder_jni.h>
+#include <android/binder_manager.h>
+#include <jni.h>
+#include <log/log.h>
+
+extern "C" JNIEXPORT jobject JNICALL
+Java_example_vib_MyActivity_gimme__Ljava_lang_String_2(JNIEnv* env, jclass /**/, jstring str) {
+ ALOGI("%s", __func__);
+
+ // Best practice is probably libnativehelper ScopedUtfChars or
+ // libbase ScopeGuard (for platform code), but this is with minimal
+ // dependencies.
+ const char* name = env->GetStringUTFChars(str, nullptr);
+
+ ALOGI("example vib gimme %s", name);
+
+ jobject jbinder = nullptr;
+
+ // Java does not have vendor variants. It's only safe to pass a service when
+ // 'vendor: true' if it is @VintfStability.
+ if (AServiceManager_isDeclared(name)) {
+ ndk::SpAIBinder binder = ndk::SpAIBinder(AServiceManager_waitForService(name));
+ jbinder = AIBinder_toJavaBinder(env, binder.get());
+ } else {
+ ALOGI("not declared");
+ }
+
+ env->ReleaseStringUTFChars(str, name);
+
+ return jbinder;
+}
diff --git a/vibrator/aidl/default/example_vendor_java_client/jarjar.txt b/vibrator/aidl/default/example_vendor_java_client/jarjar.txt
new file mode 100644
index 0000000..e7613a0
--- /dev/null
+++ b/vibrator/aidl/default/example_vendor_java_client/jarjar.txt
@@ -0,0 +1,2 @@
+rule android.hardware.** example.vib.ah.@1
+
diff --git a/wifi/1.6/default/android.hardware.wifi@1.0-service-lazy.rc b/wifi/1.6/default/android.hardware.wifi@1.0-service-lazy.rc
deleted file mode 100644
index ee8c818..0000000
--- a/wifi/1.6/default/android.hardware.wifi@1.0-service-lazy.rc
+++ /dev/null
@@ -1,14 +0,0 @@
-service vendor.wifi_hal_legacy /vendor/bin/hw/android.hardware.wifi@1.0-service-lazy
- interface android.hardware.wifi@1.0::IWifi default
- interface android.hardware.wifi@1.1::IWifi default
- interface android.hardware.wifi@1.2::IWifi default
- interface android.hardware.wifi@1.3::IWifi default
- interface android.hardware.wifi@1.4::IWifi default
- interface android.hardware.wifi@1.5::IWifi default
- interface android.hardware.wifi@1.6::IWifi default
- oneshot
- disabled
- class hal
- capabilities NET_ADMIN NET_RAW SYS_MODULE
- user wifi
- group wifi gps
diff --git a/wifi/1.6/default/android.hardware.wifi@1.0-service.rc b/wifi/1.6/default/android.hardware.wifi@1.0-service.rc
deleted file mode 100644
index 18f40d0..0000000
--- a/wifi/1.6/default/android.hardware.wifi@1.0-service.rc
+++ /dev/null
@@ -1,12 +0,0 @@
-service vendor.wifi_hal_legacy /vendor/bin/hw/android.hardware.wifi@1.0-service
- interface android.hardware.wifi@1.0::IWifi default
- interface android.hardware.wifi@1.1::IWifi default
- interface android.hardware.wifi@1.2::IWifi default
- interface android.hardware.wifi@1.3::IWifi default
- interface android.hardware.wifi@1.4::IWifi default
- interface android.hardware.wifi@1.5::IWifi default
- interface android.hardware.wifi@1.6::IWifi default
- class hal
- capabilities NET_ADMIN NET_RAW SYS_MODULE
- user wifi
- group wifi gps
diff --git a/wifi/1.6/default/android.hardware.wifi@1.0-service.xml b/wifi/1.6/default/android.hardware.wifi@1.0-service.xml
deleted file mode 100644
index 771fbaa..0000000
--- a/wifi/1.6/default/android.hardware.wifi@1.0-service.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<manifest version="1.0" type="device">
- <hal format="hidl">
- <name>android.hardware.wifi</name>
- <transport>hwbinder</transport>
- <version>1.6</version>
- <interface>
- <name>IWifi</name>
- <instance>default</instance>
- </interface>
- </hal>
-</manifest>
diff --git a/wifi/1.6/default/hidl_callback_util.h b/wifi/1.6/default/hidl_callback_util.h
deleted file mode 100644
index aab0ae5..0000000
--- a/wifi/1.6/default/hidl_callback_util.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * 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 HIDL_CALLBACK_UTIL_H_
-#define HIDL_CALLBACK_UTIL_H_
-
-#include <set>
-
-#include <hidl/HidlSupport.h>
-#include <hidl/HidlTransportSupport.h>
-
-namespace {
-// Type of callback invoked by the death handler.
-using on_death_cb_function = std::function<void(uint64_t)>;
-
-// Private class used to keep track of death of individual
-// callbacks stored in HidlCallbackHandler.
-template <typename CallbackType>
-class HidlDeathHandler : public android::hardware::hidl_death_recipient {
- public:
- HidlDeathHandler(const on_death_cb_function& user_cb_function)
- : cb_function_(user_cb_function) {}
- ~HidlDeathHandler() = default;
-
- // Death notification for callbacks.
- void serviceDied(uint64_t cookie,
- const android::wp<android::hidl::base::V1_0::IBase>& /* who */) override {
- cb_function_(cookie);
- }
-
- private:
- on_death_cb_function cb_function_;
-
- DISALLOW_COPY_AND_ASSIGN(HidlDeathHandler);
-};
-} // namespace
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace hidl_callback_util {
-template <typename CallbackType>
-// Provides a class to manage callbacks for the various HIDL interfaces and
-// handle the death of the process hosting each callback.
-class HidlCallbackHandler {
- public:
- HidlCallbackHandler()
- : death_handler_(new HidlDeathHandler<CallbackType>(
- std::bind(&HidlCallbackHandler::onObjectDeath, this, std::placeholders::_1))) {}
- ~HidlCallbackHandler() = default;
-
- bool addCallback(const sp<CallbackType>& cb) {
- // TODO(b/33818800): Can't compare proxies yet. So, use the cookie
- // (callback proxy's raw pointer) to track the death of individual
- // clients.
- uint64_t cookie = reinterpret_cast<uint64_t>(cb.get());
- for (const auto& s : cb_set_) {
- if (interfacesEqual(cb, s)) {
- LOG(ERROR) << "Duplicate death notification registration";
- return true;
- }
- }
- if (!cb->linkToDeath(death_handler_, cookie)) {
- LOG(ERROR) << "Failed to register death notification";
- return false;
- }
- cb_set_.insert(cb);
- return true;
- }
-
- const std::set<android::sp<CallbackType>>& getCallbacks() { return cb_set_; }
-
- // Death notification for callbacks.
- void onObjectDeath(uint64_t cookie) {
- CallbackType* cb = reinterpret_cast<CallbackType*>(cookie);
- const auto& iter = cb_set_.find(cb);
- if (iter == cb_set_.end()) {
- LOG(ERROR) << "Unknown callback death notification received";
- return;
- }
- cb_set_.erase(iter);
- LOG(DEBUG) << "Dead callback removed from list";
- }
-
- void invalidate() {
- for (const sp<CallbackType>& cb : cb_set_) {
- if (!cb->unlinkToDeath(death_handler_)) {
- LOG(ERROR) << "Failed to deregister death notification";
- }
- }
- cb_set_.clear();
- }
-
- private:
- std::set<sp<CallbackType>> cb_set_;
- sp<HidlDeathHandler<CallbackType>> death_handler_;
-
- DISALLOW_COPY_AND_ASSIGN(HidlCallbackHandler);
-};
-
-} // namespace hidl_callback_util
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-#endif // HIDL_CALLBACK_UTIL_H_
diff --git a/wifi/1.6/default/hidl_return_util.h b/wifi/1.6/default/hidl_return_util.h
deleted file mode 100644
index a0efac2..0000000
--- a/wifi/1.6/default/hidl_return_util.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 HIDL_RETURN_UTIL_H_
-#define HIDL_RETURN_UTIL_H_
-
-#include "hidl_sync_util.h"
-#include "wifi_status_util.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace hidl_return_util {
-using namespace android::hardware::wifi::V1_0;
-
-/**
- * These utility functions are used to invoke a method on the provided
- * HIDL interface object.
- * These functions checks if the provided HIDL interface object is valid.
- * a) if valid, Invokes the corresponding internal implementation function of
- * the HIDL method. It then invokes the HIDL continuation callback with
- * the status and any returned values.
- * b) if invalid, invokes the HIDL continuation callback with the
- * provided error status and default values.
- */
-// Use for HIDL methods which return only an instance of WifiStatus.
-template <typename ObjT, typename WorkFuncT, typename... Args>
-Return<void> validateAndCall(ObjT* obj, WifiStatusCode status_code_if_invalid, WorkFuncT&& work,
- const std::function<void(const WifiStatus&)>& hidl_cb,
- Args&&... args) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
- if (obj->isValid()) {
- hidl_cb((obj->*work)(std::forward<Args>(args)...));
- } else {
- hidl_cb(createWifiStatus(status_code_if_invalid));
- }
- return Void();
-}
-
-// Use for HIDL methods which return only an instance of WifiStatus.
-// This version passes the global lock acquired to the body of the method.
-// Note: Only used by IWifi::stop() currently.
-template <typename ObjT, typename WorkFuncT, typename... Args>
-Return<void> validateAndCallWithLock(ObjT* obj, WifiStatusCode status_code_if_invalid,
- WorkFuncT&& work,
- const std::function<void(const WifiStatus&)>& hidl_cb,
- Args&&... args) {
- auto lock = hidl_sync_util::acquireGlobalLock();
- if (obj->isValid()) {
- hidl_cb((obj->*work)(&lock, std::forward<Args>(args)...));
- } else {
- hidl_cb(createWifiStatus(status_code_if_invalid));
- }
- return Void();
-}
-
-// Use for HIDL methods which return instance of WifiStatus and a single return
-// value.
-template <typename ObjT, typename WorkFuncT, typename ReturnT, typename... Args>
-Return<void> validateAndCall(ObjT* obj, WifiStatusCode status_code_if_invalid, WorkFuncT&& work,
- const std::function<void(const WifiStatus&, ReturnT)>& hidl_cb,
- Args&&... args) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
- if (obj->isValid()) {
- const auto& ret_pair = (obj->*work)(std::forward<Args>(args)...);
- const WifiStatus& status = std::get<0>(ret_pair);
- const auto& ret_value = std::get<1>(ret_pair);
- hidl_cb(status, ret_value);
- } else {
- hidl_cb(createWifiStatus(status_code_if_invalid),
- typename std::remove_reference<ReturnT>::type());
- }
- return Void();
-}
-
-// Use for HIDL methods which return instance of WifiStatus and 2 return
-// values.
-template <typename ObjT, typename WorkFuncT, typename ReturnT1, typename ReturnT2, typename... Args>
-Return<void> validateAndCall(
- ObjT* obj, WifiStatusCode status_code_if_invalid, WorkFuncT&& work,
- const std::function<void(const WifiStatus&, ReturnT1, ReturnT2)>& hidl_cb, Args&&... args) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
- if (obj->isValid()) {
- const auto& ret_tuple = (obj->*work)(std::forward<Args>(args)...);
- const WifiStatus& status = std::get<0>(ret_tuple);
- const auto& ret_value1 = std::get<1>(ret_tuple);
- const auto& ret_value2 = std::get<2>(ret_tuple);
- hidl_cb(status, ret_value1, ret_value2);
- } else {
- hidl_cb(createWifiStatus(status_code_if_invalid),
- typename std::remove_reference<ReturnT1>::type(),
- typename std::remove_reference<ReturnT2>::type());
- }
- return Void();
-}
-
-} // namespace hidl_return_util
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-#endif // HIDL_RETURN_UTIL_H_
diff --git a/wifi/1.6/default/hidl_struct_util.cpp b/wifi/1.6/default/hidl_struct_util.cpp
deleted file mode 100644
index 2112b26..0000000
--- a/wifi/1.6/default/hidl_struct_util.cpp
+++ /dev/null
@@ -1,3007 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-#include <utils/SystemClock.h>
-
-#include "hidl_struct_util.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace hidl_struct_util {
-
-using V1_6::NanConfigRequestSupplemental;
-
-WifiChannelWidthInMhz convertLegacyWifiChannelWidthToHidl(legacy_hal::wifi_channel_width type);
-
-hidl_string safeConvertChar(const char* str, size_t max_len) {
- const char* c = str;
- size_t size = 0;
- while (*c && (unsigned char)*c < 128 && size < max_len) {
- ++size;
- ++c;
- }
- return hidl_string(str, size);
-}
-
-IWifiChip::ChipCapabilityMask convertLegacyLoggerFeatureToHidlChipCapability(uint32_t feature) {
- using HidlChipCaps = IWifiChip::ChipCapabilityMask;
- switch (feature) {
- case legacy_hal::WIFI_LOGGER_MEMORY_DUMP_SUPPORTED:
- return HidlChipCaps::DEBUG_MEMORY_FIRMWARE_DUMP;
- case legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED:
- return HidlChipCaps::DEBUG_MEMORY_DRIVER_DUMP;
- case legacy_hal::WIFI_LOGGER_CONNECT_EVENT_SUPPORTED:
- return HidlChipCaps::DEBUG_RING_BUFFER_CONNECT_EVENT;
- case legacy_hal::WIFI_LOGGER_POWER_EVENT_SUPPORTED:
- return HidlChipCaps::DEBUG_RING_BUFFER_POWER_EVENT;
- case legacy_hal::WIFI_LOGGER_WAKE_LOCK_SUPPORTED:
- return HidlChipCaps::DEBUG_RING_BUFFER_WAKELOCK_EVENT;
- };
- CHECK(false) << "Unknown legacy feature: " << feature;
- return {};
-}
-
-IWifiStaIface::StaIfaceCapabilityMask convertLegacyLoggerFeatureToHidlStaIfaceCapability(
- uint32_t feature) {
- using HidlStaIfaceCaps = IWifiStaIface::StaIfaceCapabilityMask;
- switch (feature) {
- case legacy_hal::WIFI_LOGGER_PACKET_FATE_SUPPORTED:
- return HidlStaIfaceCaps::DEBUG_PACKET_FATE;
- };
- CHECK(false) << "Unknown legacy feature: " << feature;
- return {};
-}
-
-V1_5::IWifiChip::ChipCapabilityMask convertLegacyFeatureToHidlChipCapability(uint64_t feature) {
- using HidlChipCaps = V1_5::IWifiChip::ChipCapabilityMask;
- switch (feature) {
- case WIFI_FEATURE_SET_TX_POWER_LIMIT:
- return HidlChipCaps::SET_TX_POWER_LIMIT;
- case WIFI_FEATURE_USE_BODY_HEAD_SAR:
- return HidlChipCaps::USE_BODY_HEAD_SAR;
- case WIFI_FEATURE_D2D_RTT:
- return HidlChipCaps::D2D_RTT;
- case WIFI_FEATURE_D2AP_RTT:
- return HidlChipCaps::D2AP_RTT;
- case WIFI_FEATURE_INFRA_60G:
- return HidlChipCaps::WIGIG;
- case WIFI_FEATURE_SET_LATENCY_MODE:
- return HidlChipCaps::SET_LATENCY_MODE;
- case WIFI_FEATURE_P2P_RAND_MAC:
- return HidlChipCaps::P2P_RAND_MAC;
- };
- CHECK(false) << "Unknown legacy feature: " << feature;
- return {};
-}
-
-IWifiStaIface::StaIfaceCapabilityMask convertLegacyFeatureToHidlStaIfaceCapability(
- uint64_t feature) {
- using HidlStaIfaceCaps = IWifiStaIface::StaIfaceCapabilityMask;
- switch (feature) {
- case WIFI_FEATURE_GSCAN:
- return HidlStaIfaceCaps::BACKGROUND_SCAN;
- case WIFI_FEATURE_LINK_LAYER_STATS:
- return HidlStaIfaceCaps::LINK_LAYER_STATS;
- case WIFI_FEATURE_RSSI_MONITOR:
- return HidlStaIfaceCaps::RSSI_MONITOR;
- case WIFI_FEATURE_CONTROL_ROAMING:
- return HidlStaIfaceCaps::CONTROL_ROAMING;
- case WIFI_FEATURE_IE_WHITELIST:
- return HidlStaIfaceCaps::PROBE_IE_WHITELIST;
- case WIFI_FEATURE_SCAN_RAND:
- return HidlStaIfaceCaps::SCAN_RAND;
- case WIFI_FEATURE_INFRA_5G:
- return HidlStaIfaceCaps::STA_5G;
- case WIFI_FEATURE_HOTSPOT:
- return HidlStaIfaceCaps::HOTSPOT;
- case WIFI_FEATURE_PNO:
- return HidlStaIfaceCaps::PNO;
- case WIFI_FEATURE_TDLS:
- return HidlStaIfaceCaps::TDLS;
- case WIFI_FEATURE_TDLS_OFFCHANNEL:
- return HidlStaIfaceCaps::TDLS_OFFCHANNEL;
- case WIFI_FEATURE_CONFIG_NDO:
- return HidlStaIfaceCaps::ND_OFFLOAD;
- case WIFI_FEATURE_MKEEP_ALIVE:
- return HidlStaIfaceCaps::KEEP_ALIVE;
- };
- CHECK(false) << "Unknown legacy feature: " << feature;
- return {};
-}
-
-bool convertLegacyFeaturesToHidlChipCapabilities(uint64_t legacy_feature_set,
- uint32_t legacy_logger_feature_set,
- uint32_t* hidl_caps) {
- if (!hidl_caps) {
- return false;
- }
- *hidl_caps = {};
- using HidlChipCaps = IWifiChip::ChipCapabilityMask;
- for (const auto feature : {legacy_hal::WIFI_LOGGER_MEMORY_DUMP_SUPPORTED,
- legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED,
- legacy_hal::WIFI_LOGGER_CONNECT_EVENT_SUPPORTED,
- legacy_hal::WIFI_LOGGER_POWER_EVENT_SUPPORTED,
- legacy_hal::WIFI_LOGGER_WAKE_LOCK_SUPPORTED}) {
- if (feature & legacy_logger_feature_set) {
- *hidl_caps |= convertLegacyLoggerFeatureToHidlChipCapability(feature);
- }
- }
- std::vector<uint64_t> features = {WIFI_FEATURE_SET_TX_POWER_LIMIT,
- WIFI_FEATURE_USE_BODY_HEAD_SAR,
- WIFI_FEATURE_D2D_RTT,
- WIFI_FEATURE_D2AP_RTT,
- WIFI_FEATURE_INFRA_60G,
- WIFI_FEATURE_SET_LATENCY_MODE,
- WIFI_FEATURE_P2P_RAND_MAC};
- for (const auto feature : features) {
- if (feature & legacy_feature_set) {
- *hidl_caps |= convertLegacyFeatureToHidlChipCapability(feature);
- }
- }
-
- // There are no flags for these 3 in the legacy feature set. Adding them to
- // the set because all the current devices support it.
- *hidl_caps |= HidlChipCaps::DEBUG_RING_BUFFER_VENDOR_DATA;
- *hidl_caps |= HidlChipCaps::DEBUG_HOST_WAKE_REASON_STATS;
- *hidl_caps |= HidlChipCaps::DEBUG_ERROR_ALERTS;
- return true;
-}
-
-WifiDebugRingBufferFlags convertLegacyDebugRingBufferFlagsToHidl(uint32_t flag) {
- switch (flag) {
- case WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES:
- return WifiDebugRingBufferFlags::HAS_BINARY_ENTRIES;
- case WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES:
- return WifiDebugRingBufferFlags::HAS_ASCII_ENTRIES;
- };
- CHECK(false) << "Unknown legacy flag: " << flag;
- return {};
-}
-
-bool convertLegacyDebugRingBufferStatusToHidl(
- const legacy_hal::wifi_ring_buffer_status& legacy_status,
- WifiDebugRingBufferStatus* hidl_status) {
- if (!hidl_status) {
- return false;
- }
- *hidl_status = {};
- hidl_status->ringName = safeConvertChar(reinterpret_cast<const char*>(legacy_status.name),
- sizeof(legacy_status.name));
- hidl_status->flags = 0;
- for (const auto flag :
- {WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES, WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES}) {
- if (flag & legacy_status.flags) {
- hidl_status->flags |= static_cast<std::underlying_type<WifiDebugRingBufferFlags>::type>(
- convertLegacyDebugRingBufferFlagsToHidl(flag));
- }
- }
- hidl_status->ringId = legacy_status.ring_id;
- hidl_status->sizeInBytes = legacy_status.ring_buffer_byte_size;
- // Calculate free size of the ring the buffer. We don't need to send the
- // exact read/write pointers that were there in the legacy HAL interface.
- if (legacy_status.written_bytes >= legacy_status.read_bytes) {
- hidl_status->freeSizeInBytes = legacy_status.ring_buffer_byte_size -
- (legacy_status.written_bytes - legacy_status.read_bytes);
- } else {
- hidl_status->freeSizeInBytes = legacy_status.read_bytes - legacy_status.written_bytes;
- }
- hidl_status->verboseLevel = legacy_status.verbose_level;
- return true;
-}
-
-bool convertLegacyVectorOfDebugRingBufferStatusToHidl(
- const std::vector<legacy_hal::wifi_ring_buffer_status>& legacy_status_vec,
- std::vector<WifiDebugRingBufferStatus>* hidl_status_vec) {
- if (!hidl_status_vec) {
- return false;
- }
- *hidl_status_vec = {};
- for (const auto& legacy_status : legacy_status_vec) {
- WifiDebugRingBufferStatus hidl_status;
- if (!convertLegacyDebugRingBufferStatusToHidl(legacy_status, &hidl_status)) {
- return false;
- }
- hidl_status_vec->push_back(hidl_status);
- }
- return true;
-}
-
-bool convertLegacyWakeReasonStatsToHidl(const legacy_hal::WakeReasonStats& legacy_stats,
- WifiDebugHostWakeReasonStats* hidl_stats) {
- if (!hidl_stats) {
- return false;
- }
- *hidl_stats = {};
- hidl_stats->totalCmdEventWakeCnt = legacy_stats.wake_reason_cnt.total_cmd_event_wake;
- hidl_stats->cmdEventWakeCntPerType = legacy_stats.cmd_event_wake_cnt;
- hidl_stats->totalDriverFwLocalWakeCnt = legacy_stats.wake_reason_cnt.total_driver_fw_local_wake;
- hidl_stats->driverFwLocalWakeCntPerType = legacy_stats.driver_fw_local_wake_cnt;
- hidl_stats->totalRxPacketWakeCnt = legacy_stats.wake_reason_cnt.total_rx_data_wake;
- hidl_stats->rxPktWakeDetails.rxUnicastCnt =
- legacy_stats.wake_reason_cnt.rx_wake_details.rx_unicast_cnt;
- hidl_stats->rxPktWakeDetails.rxMulticastCnt =
- legacy_stats.wake_reason_cnt.rx_wake_details.rx_multicast_cnt;
- hidl_stats->rxPktWakeDetails.rxBroadcastCnt =
- legacy_stats.wake_reason_cnt.rx_wake_details.rx_broadcast_cnt;
- hidl_stats->rxMulticastPkWakeDetails.ipv4RxMulticastAddrCnt =
- legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.ipv4_rx_multicast_addr_cnt;
- hidl_stats->rxMulticastPkWakeDetails.ipv6RxMulticastAddrCnt =
- legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.ipv6_rx_multicast_addr_cnt;
- hidl_stats->rxMulticastPkWakeDetails.otherRxMulticastAddrCnt =
- legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.other_rx_multicast_addr_cnt;
- hidl_stats->rxIcmpPkWakeDetails.icmpPkt =
- legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp_pkt;
- hidl_stats->rxIcmpPkWakeDetails.icmp6Pkt =
- legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_pkt;
- hidl_stats->rxIcmpPkWakeDetails.icmp6Ra =
- legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ra;
- hidl_stats->rxIcmpPkWakeDetails.icmp6Na =
- legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_na;
- hidl_stats->rxIcmpPkWakeDetails.icmp6Ns =
- legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ns;
- return true;
-}
-
-legacy_hal::wifi_power_scenario convertHidlTxPowerScenarioToLegacy(
- V1_1::IWifiChip::TxPowerScenario hidl_scenario) {
- switch (hidl_scenario) {
- // This is the only supported scenario for V1_1
- case V1_1::IWifiChip::TxPowerScenario::VOICE_CALL:
- return legacy_hal::WIFI_POWER_SCENARIO_VOICE_CALL;
- };
- CHECK(false);
-}
-
-legacy_hal::wifi_power_scenario convertHidlTxPowerScenarioToLegacy_1_2(
- V1_2::IWifiChip::TxPowerScenario hidl_scenario) {
- switch (hidl_scenario) {
- // This is the only supported scenario for V1_1
- case V1_2::IWifiChip::TxPowerScenario::VOICE_CALL:
- return legacy_hal::WIFI_POWER_SCENARIO_VOICE_CALL;
- // Those are the supported scenarios for V1_2
- case V1_2::IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF:
- return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_OFF;
- case V1_2::IWifiChip::TxPowerScenario::ON_HEAD_CELL_ON:
- return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_ON;
- case V1_2::IWifiChip::TxPowerScenario::ON_BODY_CELL_OFF:
- return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_OFF;
- case V1_2::IWifiChip::TxPowerScenario::ON_BODY_CELL_ON:
- return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_ON;
- };
- CHECK(false);
-}
-
-legacy_hal::wifi_latency_mode convertHidlLatencyModeToLegacy(
- V1_3::IWifiChip::LatencyMode hidl_latency_mode) {
- switch (hidl_latency_mode) {
- case V1_3::IWifiChip::LatencyMode::NORMAL:
- return legacy_hal::WIFI_LATENCY_MODE_NORMAL;
- case V1_3::IWifiChip::LatencyMode::LOW:
- return legacy_hal::WIFI_LATENCY_MODE_LOW;
- }
- CHECK(false);
-}
-
-bool convertLegacyWifiMacInfoToHidl(
- const legacy_hal::WifiMacInfo& legacy_mac_info,
- V1_4::IWifiChipEventCallback::RadioModeInfo* hidl_radio_mode_info) {
- if (!hidl_radio_mode_info) {
- return false;
- }
- *hidl_radio_mode_info = {};
-
- hidl_radio_mode_info->radioId = legacy_mac_info.wlan_mac_id;
- // Convert from bitmask of bands in the legacy HAL to enum value in
- // the HIDL interface.
- if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND &&
- legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND &&
- legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_24GHZ_5GHZ_6GHZ;
- } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND &&
- legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_5GHZ_6GHZ;
- } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND) {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_6GHZ;
- } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND &&
- legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_24GHZ_5GHZ;
- } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_24GHZ;
- } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_5GHZ;
- } else {
- hidl_radio_mode_info->bandInfo = V1_4::WifiBand::BAND_UNSPECIFIED;
- }
- std::vector<V1_2::IWifiChipEventCallback::IfaceInfo> iface_info_vec;
- for (const auto& legacy_iface_info : legacy_mac_info.iface_infos) {
- V1_2::IWifiChipEventCallback::IfaceInfo iface_info;
- iface_info.name = legacy_iface_info.name;
- iface_info.channel = legacy_iface_info.channel;
- iface_info_vec.push_back(iface_info);
- }
- hidl_radio_mode_info->ifaceInfos = iface_info_vec;
- return true;
-}
-
-uint32_t convertHidlWifiBandToLegacyMacBand(V1_5::WifiBand hidl_band) {
- switch (hidl_band) {
- case V1_5::WifiBand::BAND_24GHZ:
- return legacy_hal::WLAN_MAC_2_4_BAND;
- case V1_5::WifiBand::BAND_5GHZ:
- case V1_5::WifiBand::BAND_5GHZ_DFS:
- case V1_5::WifiBand::BAND_5GHZ_WITH_DFS:
- return legacy_hal::WLAN_MAC_5_0_BAND;
- case V1_5::WifiBand::BAND_24GHZ_5GHZ:
- case V1_5::WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
- return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND);
- case V1_5::WifiBand::BAND_6GHZ:
- return legacy_hal::WLAN_MAC_6_0_BAND;
- case V1_5::WifiBand::BAND_5GHZ_6GHZ:
- return (legacy_hal::WLAN_MAC_5_0_BAND | legacy_hal::WLAN_MAC_6_0_BAND);
- case V1_5::WifiBand::BAND_24GHZ_5GHZ_6GHZ:
- case V1_5::WifiBand::BAND_24GHZ_5GHZ_WITH_DFS_6GHZ:
- return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND |
- legacy_hal::WLAN_MAC_6_0_BAND);
- case V1_5::WifiBand::BAND_60GHZ:
- return legacy_hal::WLAN_MAC_60_0_BAND;
- default:
- return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND |
- legacy_hal::WLAN_MAC_6_0_BAND | legacy_hal::WLAN_MAC_60_0_BAND);
- }
-}
-
-V1_5::WifiBand convertLegacyMacBandToHidlWifiBand(uint32_t band) {
- switch (band) {
- case legacy_hal::WLAN_MAC_2_4_BAND:
- return V1_5::WifiBand::BAND_24GHZ;
- case legacy_hal::WLAN_MAC_5_0_BAND:
- return V1_5::WifiBand::BAND_5GHZ;
- case legacy_hal::WLAN_MAC_6_0_BAND:
- return V1_5::WifiBand::BAND_6GHZ;
- case legacy_hal::WLAN_MAC_60_0_BAND:
- return V1_5::WifiBand::BAND_60GHZ;
- default:
- return V1_5::WifiBand::BAND_UNSPECIFIED;
- }
-}
-
-uint32_t convertHidlWifiIfaceModeToLegacy(uint32_t hidl_iface_mask) {
- uint32_t legacy_iface_mask = 0;
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_STA) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_STA);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_SOFTAP) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_SOFTAP);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_P2P_CLIENT) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_P2P_CLIENT);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_P2P_GO) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_P2P_GO);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_NAN) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_NAN);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_TDLS) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_TDLS);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_MESH) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_MESH);
- }
- if (hidl_iface_mask & V1_5::WifiIfaceMode::IFACE_MODE_IBSS) {
- legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_IBSS);
- }
- return legacy_iface_mask;
-}
-
-uint32_t convertLegacyWifiInterfaceModeToHidl(uint32_t legacy_iface_mask) {
- uint32_t hidl_iface_mask = 0;
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_STA)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_STA;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_SOFTAP)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_SOFTAP;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_P2P_CLIENT)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_P2P_CLIENT;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_P2P_GO)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_P2P_GO;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_NAN)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_NAN;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_TDLS)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_TDLS;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_MESH)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_MESH;
- }
- if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_IBSS)) {
- hidl_iface_mask |= V1_5::WifiIfaceMode::IFACE_MODE_IBSS;
- }
- return hidl_iface_mask;
-}
-
-uint32_t convertHidlUsableChannelFilterToLegacy(uint32_t hidl_filter_mask) {
- uint32_t legacy_filter_mask = 0;
- if (hidl_filter_mask & V1_5::IWifiChip::UsableChannelFilter::CELLULAR_COEXISTENCE) {
- legacy_filter_mask |= legacy_hal::WIFI_USABLE_CHANNEL_FILTER_CELLULAR_COEXISTENCE;
- }
- if (hidl_filter_mask & V1_5::IWifiChip::UsableChannelFilter::CONCURRENCY) {
- legacy_filter_mask |= legacy_hal::WIFI_USABLE_CHANNEL_FILTER_CONCURRENCY;
- }
- if (hidl_filter_mask & V1_6::IWifiChip::UsableChannelFilter::NAN_INSTANT_MODE) {
- legacy_filter_mask |= WIFI_USABLE_CHANNEL_FILTER_NAN_INSTANT_MODE;
- }
- return legacy_filter_mask;
-}
-
-bool convertLegacyWifiUsableChannelToHidl(
- const legacy_hal::wifi_usable_channel& legacy_usable_channel,
- V1_6::WifiUsableChannel* hidl_usable_channel) {
- if (!hidl_usable_channel) {
- return false;
- }
- *hidl_usable_channel = {};
- hidl_usable_channel->channel = legacy_usable_channel.freq;
- hidl_usable_channel->channelBandwidth =
- convertLegacyWifiChannelWidthToHidl(legacy_usable_channel.width);
- hidl_usable_channel->ifaceModeMask =
- convertLegacyWifiInterfaceModeToHidl(legacy_usable_channel.iface_mode_mask);
-
- return true;
-}
-
-bool convertLegacyWifiUsableChannelsToHidl(
- const std::vector<legacy_hal::wifi_usable_channel>& legacy_usable_channels,
- std::vector<V1_6::WifiUsableChannel>* hidl_usable_channels) {
- if (!hidl_usable_channels) {
- return false;
- }
- *hidl_usable_channels = {};
- for (const auto& legacy_usable_channel : legacy_usable_channels) {
- V1_6::WifiUsableChannel hidl_usable_channel;
- if (!convertLegacyWifiUsableChannelToHidl(legacy_usable_channel, &hidl_usable_channel)) {
- return false;
- }
- hidl_usable_channels->push_back(hidl_usable_channel);
- }
- return true;
-}
-
-bool convertLegacyWifiMacInfosToHidl(
- const std::vector<legacy_hal::WifiMacInfo>& legacy_mac_infos,
- std::vector<V1_4::IWifiChipEventCallback::RadioModeInfo>* hidl_radio_mode_infos) {
- if (!hidl_radio_mode_infos) {
- return false;
- }
- *hidl_radio_mode_infos = {};
-
- for (const auto& legacy_mac_info : legacy_mac_infos) {
- V1_4::IWifiChipEventCallback::RadioModeInfo hidl_radio_mode_info;
- if (!convertLegacyWifiMacInfoToHidl(legacy_mac_info, &hidl_radio_mode_info)) {
- return false;
- }
- hidl_radio_mode_infos->push_back(hidl_radio_mode_info);
- }
- return true;
-}
-
-bool convertLegacyFeaturesToHidlStaCapabilities(uint64_t legacy_feature_set,
- uint32_t legacy_logger_feature_set,
- uint32_t* hidl_caps) {
- if (!hidl_caps) {
- return false;
- }
- *hidl_caps = {};
- using HidlStaIfaceCaps = IWifiStaIface::StaIfaceCapabilityMask;
- for (const auto feature : {legacy_hal::WIFI_LOGGER_PACKET_FATE_SUPPORTED}) {
- if (feature & legacy_logger_feature_set) {
- *hidl_caps |= convertLegacyLoggerFeatureToHidlStaIfaceCapability(feature);
- }
- }
- for (const auto feature :
- {WIFI_FEATURE_GSCAN, WIFI_FEATURE_LINK_LAYER_STATS, WIFI_FEATURE_RSSI_MONITOR,
- WIFI_FEATURE_CONTROL_ROAMING, WIFI_FEATURE_IE_WHITELIST, WIFI_FEATURE_SCAN_RAND,
- WIFI_FEATURE_INFRA_5G, WIFI_FEATURE_HOTSPOT, WIFI_FEATURE_PNO, WIFI_FEATURE_TDLS,
- WIFI_FEATURE_TDLS_OFFCHANNEL, WIFI_FEATURE_CONFIG_NDO, WIFI_FEATURE_MKEEP_ALIVE}) {
- if (feature & legacy_feature_set) {
- *hidl_caps |= convertLegacyFeatureToHidlStaIfaceCapability(feature);
- }
- }
- // There is no flag for this one in the legacy feature set. Adding it to the
- // set because all the current devices support it.
- *hidl_caps |= HidlStaIfaceCaps::APF;
- return true;
-}
-
-bool convertLegacyApfCapabilitiesToHidl(const legacy_hal::PacketFilterCapabilities& legacy_caps,
- StaApfPacketFilterCapabilities* hidl_caps) {
- if (!hidl_caps) {
- return false;
- }
- *hidl_caps = {};
- hidl_caps->version = legacy_caps.version;
- hidl_caps->maxLength = legacy_caps.max_len;
- return true;
-}
-
-uint8_t convertHidlGscanReportEventFlagToLegacy(
- StaBackgroundScanBucketEventReportSchemeMask hidl_flag) {
- using HidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
- switch (hidl_flag) {
- case HidlFlag::EACH_SCAN:
- return REPORT_EVENTS_EACH_SCAN;
- case HidlFlag::FULL_RESULTS:
- return REPORT_EVENTS_FULL_RESULTS;
- case HidlFlag::NO_BATCH:
- return REPORT_EVENTS_NO_BATCH;
- };
- CHECK(false);
-}
-
-StaScanDataFlagMask convertLegacyGscanDataFlagToHidl(uint8_t legacy_flag) {
- switch (legacy_flag) {
- case legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED:
- return StaScanDataFlagMask::INTERRUPTED;
- };
- CHECK(false) << "Unknown legacy flag: " << legacy_flag;
- // To silence the compiler warning about reaching the end of non-void
- // function.
- return {};
-}
-
-bool convertLegacyGscanCapabilitiesToHidl(const legacy_hal::wifi_gscan_capabilities& legacy_caps,
- StaBackgroundScanCapabilities* hidl_caps) {
- if (!hidl_caps) {
- return false;
- }
- *hidl_caps = {};
- hidl_caps->maxCacheSize = legacy_caps.max_scan_cache_size;
- hidl_caps->maxBuckets = legacy_caps.max_scan_buckets;
- hidl_caps->maxApCachePerScan = legacy_caps.max_ap_cache_per_scan;
- hidl_caps->maxReportingThreshold = legacy_caps.max_scan_reporting_threshold;
- return true;
-}
-
-legacy_hal::wifi_band convertHidlWifiBandToLegacy(V1_0::WifiBand band) {
- switch (band) {
- case V1_0::WifiBand::BAND_UNSPECIFIED:
- return legacy_hal::WIFI_BAND_UNSPECIFIED;
- case V1_0::WifiBand::BAND_24GHZ:
- return legacy_hal::WIFI_BAND_BG;
- case V1_0::WifiBand::BAND_5GHZ:
- return legacy_hal::WIFI_BAND_A;
- case V1_0::WifiBand::BAND_5GHZ_DFS:
- return legacy_hal::WIFI_BAND_A_DFS;
- case V1_0::WifiBand::BAND_5GHZ_WITH_DFS:
- return legacy_hal::WIFI_BAND_A_WITH_DFS;
- case V1_0::WifiBand::BAND_24GHZ_5GHZ:
- return legacy_hal::WIFI_BAND_ABG;
- case V1_0::WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
- return legacy_hal::WIFI_BAND_ABG_WITH_DFS;
- };
- CHECK(false);
-}
-
-bool convertHidlGscanParamsToLegacy(const StaBackgroundScanParameters& hidl_scan_params,
- legacy_hal::wifi_scan_cmd_params* legacy_scan_params) {
- if (!legacy_scan_params) {
- return false;
- }
- *legacy_scan_params = {};
- legacy_scan_params->base_period = hidl_scan_params.basePeriodInMs;
- legacy_scan_params->max_ap_per_scan = hidl_scan_params.maxApPerScan;
- legacy_scan_params->report_threshold_percent = hidl_scan_params.reportThresholdPercent;
- legacy_scan_params->report_threshold_num_scans = hidl_scan_params.reportThresholdNumScans;
- if (hidl_scan_params.buckets.size() > MAX_BUCKETS) {
- return false;
- }
- legacy_scan_params->num_buckets = hidl_scan_params.buckets.size();
- for (uint32_t bucket_idx = 0; bucket_idx < hidl_scan_params.buckets.size(); bucket_idx++) {
- const StaBackgroundScanBucketParameters& hidl_bucket_spec =
- hidl_scan_params.buckets[bucket_idx];
- legacy_hal::wifi_scan_bucket_spec& legacy_bucket_spec =
- legacy_scan_params->buckets[bucket_idx];
- if (hidl_bucket_spec.bucketIdx >= MAX_BUCKETS) {
- return false;
- }
- legacy_bucket_spec.bucket = hidl_bucket_spec.bucketIdx;
- legacy_bucket_spec.band = convertHidlWifiBandToLegacy(hidl_bucket_spec.band);
- legacy_bucket_spec.period = hidl_bucket_spec.periodInMs;
- legacy_bucket_spec.max_period = hidl_bucket_spec.exponentialMaxPeriodInMs;
- legacy_bucket_spec.base = hidl_bucket_spec.exponentialBase;
- legacy_bucket_spec.step_count = hidl_bucket_spec.exponentialStepCount;
- legacy_bucket_spec.report_events = 0;
- using HidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
- for (const auto flag : {HidlFlag::EACH_SCAN, HidlFlag::FULL_RESULTS, HidlFlag::NO_BATCH}) {
- if (hidl_bucket_spec.eventReportScheme &
- static_cast<std::underlying_type<HidlFlag>::type>(flag)) {
- legacy_bucket_spec.report_events |= convertHidlGscanReportEventFlagToLegacy(flag);
- }
- }
- if (hidl_bucket_spec.frequencies.size() > MAX_CHANNELS) {
- return false;
- }
- legacy_bucket_spec.num_channels = hidl_bucket_spec.frequencies.size();
- for (uint32_t freq_idx = 0; freq_idx < hidl_bucket_spec.frequencies.size(); freq_idx++) {
- legacy_bucket_spec.channels[freq_idx].channel = hidl_bucket_spec.frequencies[freq_idx];
- }
- }
- return true;
-}
-
-bool convertLegacyIeToHidl(const legacy_hal::wifi_information_element& legacy_ie,
- WifiInformationElement* hidl_ie) {
- if (!hidl_ie) {
- return false;
- }
- *hidl_ie = {};
- hidl_ie->id = legacy_ie.id;
- hidl_ie->data = std::vector<uint8_t>(legacy_ie.data, legacy_ie.data + legacy_ie.len);
- return true;
-}
-
-bool convertLegacyIeBlobToHidl(const uint8_t* ie_blob, uint32_t ie_blob_len,
- std::vector<WifiInformationElement>* hidl_ies) {
- if (!ie_blob || !hidl_ies) {
- return false;
- }
- *hidl_ies = {};
- const uint8_t* ies_begin = ie_blob;
- const uint8_t* ies_end = ie_blob + ie_blob_len;
- const uint8_t* next_ie = ies_begin;
- using wifi_ie = legacy_hal::wifi_information_element;
- constexpr size_t kIeHeaderLen = sizeof(wifi_ie);
- // Each IE should atleast have the header (i.e |id| & |len| fields).
- while (next_ie + kIeHeaderLen <= ies_end) {
- const wifi_ie& legacy_ie = (*reinterpret_cast<const wifi_ie*>(next_ie));
- uint32_t curr_ie_len = kIeHeaderLen + legacy_ie.len;
- if (next_ie + curr_ie_len > ies_end) {
- LOG(ERROR) << "Error parsing IE blob. Next IE: " << (void*)next_ie
- << ", Curr IE len: " << curr_ie_len << ", IEs End: " << (void*)ies_end;
- break;
- }
- WifiInformationElement hidl_ie;
- if (!convertLegacyIeToHidl(legacy_ie, &hidl_ie)) {
- LOG(ERROR) << "Error converting IE. Id: " << legacy_ie.id << ", len: " << legacy_ie.len;
- break;
- }
- hidl_ies->push_back(std::move(hidl_ie));
- next_ie += curr_ie_len;
- }
- // Check if the blob has been fully consumed.
- if (next_ie != ies_end) {
- LOG(ERROR) << "Failed to fully parse IE blob. Next IE: " << (void*)next_ie
- << ", IEs End: " << (void*)ies_end;
- }
- return true;
-}
-
-bool convertLegacyGscanResultToHidl(const legacy_hal::wifi_scan_result& legacy_scan_result,
- bool has_ie_data, StaScanResult* hidl_scan_result) {
- if (!hidl_scan_result) {
- return false;
- }
- *hidl_scan_result = {};
- hidl_scan_result->timeStampInUs = legacy_scan_result.ts;
- hidl_scan_result->ssid = std::vector<uint8_t>(
- legacy_scan_result.ssid,
- legacy_scan_result.ssid +
- strnlen(legacy_scan_result.ssid, sizeof(legacy_scan_result.ssid) - 1));
- memcpy(hidl_scan_result->bssid.data(), legacy_scan_result.bssid,
- hidl_scan_result->bssid.size());
- hidl_scan_result->frequency = legacy_scan_result.channel;
- hidl_scan_result->rssi = legacy_scan_result.rssi;
- hidl_scan_result->beaconPeriodInMs = legacy_scan_result.beacon_period;
- hidl_scan_result->capability = legacy_scan_result.capability;
- if (has_ie_data) {
- std::vector<WifiInformationElement> ies;
- if (!convertLegacyIeBlobToHidl(reinterpret_cast<const uint8_t*>(legacy_scan_result.ie_data),
- legacy_scan_result.ie_length, &ies)) {
- return false;
- }
- hidl_scan_result->informationElements = std::move(ies);
- }
- return true;
-}
-
-bool convertLegacyCachedGscanResultsToHidl(
- const legacy_hal::wifi_cached_scan_results& legacy_cached_scan_result,
- StaScanData* hidl_scan_data) {
- if (!hidl_scan_data) {
- return false;
- }
- *hidl_scan_data = {};
- hidl_scan_data->flags = 0;
- for (const auto flag : {legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED}) {
- if (legacy_cached_scan_result.flags & flag) {
- hidl_scan_data->flags |= static_cast<std::underlying_type<StaScanDataFlagMask>::type>(
- convertLegacyGscanDataFlagToHidl(flag));
- }
- }
- hidl_scan_data->bucketsScanned = legacy_cached_scan_result.buckets_scanned;
-
- CHECK(legacy_cached_scan_result.num_results >= 0 &&
- legacy_cached_scan_result.num_results <= MAX_AP_CACHE_PER_SCAN);
- std::vector<StaScanResult> hidl_scan_results;
- for (int32_t result_idx = 0; result_idx < legacy_cached_scan_result.num_results; result_idx++) {
- StaScanResult hidl_scan_result;
- if (!convertLegacyGscanResultToHidl(legacy_cached_scan_result.results[result_idx], false,
- &hidl_scan_result)) {
- return false;
- }
- hidl_scan_results.push_back(hidl_scan_result);
- }
- hidl_scan_data->results = std::move(hidl_scan_results);
- return true;
-}
-
-bool convertLegacyVectorOfCachedGscanResultsToHidl(
- const std::vector<legacy_hal::wifi_cached_scan_results>& legacy_cached_scan_results,
- std::vector<StaScanData>* hidl_scan_datas) {
- if (!hidl_scan_datas) {
- return false;
- }
- *hidl_scan_datas = {};
- for (const auto& legacy_cached_scan_result : legacy_cached_scan_results) {
- StaScanData hidl_scan_data;
- if (!convertLegacyCachedGscanResultsToHidl(legacy_cached_scan_result, &hidl_scan_data)) {
- return false;
- }
- hidl_scan_datas->push_back(hidl_scan_data);
- }
- return true;
-}
-
-WifiDebugTxPacketFate convertLegacyDebugTxPacketFateToHidl(legacy_hal::wifi_tx_packet_fate fate) {
- switch (fate) {
- case legacy_hal::TX_PKT_FATE_ACKED:
- return WifiDebugTxPacketFate::ACKED;
- case legacy_hal::TX_PKT_FATE_SENT:
- return WifiDebugTxPacketFate::SENT;
- case legacy_hal::TX_PKT_FATE_FW_QUEUED:
- return WifiDebugTxPacketFate::FW_QUEUED;
- case legacy_hal::TX_PKT_FATE_FW_DROP_INVALID:
- return WifiDebugTxPacketFate::FW_DROP_INVALID;
- case legacy_hal::TX_PKT_FATE_FW_DROP_NOBUFS:
- return WifiDebugTxPacketFate::FW_DROP_NOBUFS;
- case legacy_hal::TX_PKT_FATE_FW_DROP_OTHER:
- return WifiDebugTxPacketFate::FW_DROP_OTHER;
- case legacy_hal::TX_PKT_FATE_DRV_QUEUED:
- return WifiDebugTxPacketFate::DRV_QUEUED;
- case legacy_hal::TX_PKT_FATE_DRV_DROP_INVALID:
- return WifiDebugTxPacketFate::DRV_DROP_INVALID;
- case legacy_hal::TX_PKT_FATE_DRV_DROP_NOBUFS:
- return WifiDebugTxPacketFate::DRV_DROP_NOBUFS;
- case legacy_hal::TX_PKT_FATE_DRV_DROP_OTHER:
- return WifiDebugTxPacketFate::DRV_DROP_OTHER;
- };
- CHECK(false) << "Unknown legacy fate type: " << fate;
-}
-
-WifiDebugRxPacketFate convertLegacyDebugRxPacketFateToHidl(legacy_hal::wifi_rx_packet_fate fate) {
- switch (fate) {
- case legacy_hal::RX_PKT_FATE_SUCCESS:
- return WifiDebugRxPacketFate::SUCCESS;
- case legacy_hal::RX_PKT_FATE_FW_QUEUED:
- return WifiDebugRxPacketFate::FW_QUEUED;
- case legacy_hal::RX_PKT_FATE_FW_DROP_FILTER:
- return WifiDebugRxPacketFate::FW_DROP_FILTER;
- case legacy_hal::RX_PKT_FATE_FW_DROP_INVALID:
- return WifiDebugRxPacketFate::FW_DROP_INVALID;
- case legacy_hal::RX_PKT_FATE_FW_DROP_NOBUFS:
- return WifiDebugRxPacketFate::FW_DROP_NOBUFS;
- case legacy_hal::RX_PKT_FATE_FW_DROP_OTHER:
- return WifiDebugRxPacketFate::FW_DROP_OTHER;
- case legacy_hal::RX_PKT_FATE_DRV_QUEUED:
- return WifiDebugRxPacketFate::DRV_QUEUED;
- case legacy_hal::RX_PKT_FATE_DRV_DROP_FILTER:
- return WifiDebugRxPacketFate::DRV_DROP_FILTER;
- case legacy_hal::RX_PKT_FATE_DRV_DROP_INVALID:
- return WifiDebugRxPacketFate::DRV_DROP_INVALID;
- case legacy_hal::RX_PKT_FATE_DRV_DROP_NOBUFS:
- return WifiDebugRxPacketFate::DRV_DROP_NOBUFS;
- case legacy_hal::RX_PKT_FATE_DRV_DROP_OTHER:
- return WifiDebugRxPacketFate::DRV_DROP_OTHER;
- };
- CHECK(false) << "Unknown legacy fate type: " << fate;
-}
-
-WifiDebugPacketFateFrameType convertLegacyDebugPacketFateFrameTypeToHidl(
- legacy_hal::frame_type type) {
- switch (type) {
- case legacy_hal::FRAME_TYPE_UNKNOWN:
- return WifiDebugPacketFateFrameType::UNKNOWN;
- case legacy_hal::FRAME_TYPE_ETHERNET_II:
- return WifiDebugPacketFateFrameType::ETHERNET_II;
- case legacy_hal::FRAME_TYPE_80211_MGMT:
- return WifiDebugPacketFateFrameType::MGMT_80211;
- };
- CHECK(false) << "Unknown legacy frame type: " << type;
-}
-
-bool convertLegacyDebugPacketFateFrameToHidl(const legacy_hal::frame_info& legacy_frame,
- WifiDebugPacketFateFrameInfo* hidl_frame) {
- if (!hidl_frame) {
- return false;
- }
- *hidl_frame = {};
- hidl_frame->frameType = convertLegacyDebugPacketFateFrameTypeToHidl(legacy_frame.payload_type);
- hidl_frame->frameLen = legacy_frame.frame_len;
- hidl_frame->driverTimestampUsec = legacy_frame.driver_timestamp_usec;
- hidl_frame->firmwareTimestampUsec = legacy_frame.firmware_timestamp_usec;
- const uint8_t* frame_begin =
- reinterpret_cast<const uint8_t*>(legacy_frame.frame_content.ethernet_ii_bytes);
- hidl_frame->frameContent =
- std::vector<uint8_t>(frame_begin, frame_begin + legacy_frame.frame_len);
- return true;
-}
-
-bool convertLegacyDebugTxPacketFateToHidl(const legacy_hal::wifi_tx_report& legacy_fate,
- WifiDebugTxPacketFateReport* hidl_fate) {
- if (!hidl_fate) {
- return false;
- }
- *hidl_fate = {};
- hidl_fate->fate = convertLegacyDebugTxPacketFateToHidl(legacy_fate.fate);
- return convertLegacyDebugPacketFateFrameToHidl(legacy_fate.frame_inf, &hidl_fate->frameInfo);
-}
-
-bool convertLegacyVectorOfDebugTxPacketFateToHidl(
- const std::vector<legacy_hal::wifi_tx_report>& legacy_fates,
- std::vector<WifiDebugTxPacketFateReport>* hidl_fates) {
- if (!hidl_fates) {
- return false;
- }
- *hidl_fates = {};
- for (const auto& legacy_fate : legacy_fates) {
- WifiDebugTxPacketFateReport hidl_fate;
- if (!convertLegacyDebugTxPacketFateToHidl(legacy_fate, &hidl_fate)) {
- return false;
- }
- hidl_fates->push_back(hidl_fate);
- }
- return true;
-}
-
-bool convertLegacyDebugRxPacketFateToHidl(const legacy_hal::wifi_rx_report& legacy_fate,
- WifiDebugRxPacketFateReport* hidl_fate) {
- if (!hidl_fate) {
- return false;
- }
- *hidl_fate = {};
- hidl_fate->fate = convertLegacyDebugRxPacketFateToHidl(legacy_fate.fate);
- return convertLegacyDebugPacketFateFrameToHidl(legacy_fate.frame_inf, &hidl_fate->frameInfo);
-}
-
-bool convertLegacyVectorOfDebugRxPacketFateToHidl(
- const std::vector<legacy_hal::wifi_rx_report>& legacy_fates,
- std::vector<WifiDebugRxPacketFateReport>* hidl_fates) {
- if (!hidl_fates) {
- return false;
- }
- *hidl_fates = {};
- for (const auto& legacy_fate : legacy_fates) {
- WifiDebugRxPacketFateReport hidl_fate;
- if (!convertLegacyDebugRxPacketFateToHidl(legacy_fate, &hidl_fate)) {
- return false;
- }
- hidl_fates->push_back(hidl_fate);
- }
- return true;
-}
-
-bool convertLegacyLinkLayerRadioStatsToHidl(
- const legacy_hal::LinkLayerRadioStats& legacy_radio_stat,
- V1_6::StaLinkLayerRadioStats* hidl_radio_stat) {
- if (!hidl_radio_stat) {
- return false;
- }
- *hidl_radio_stat = {};
-
- hidl_radio_stat->radioId = legacy_radio_stat.stats.radio;
- hidl_radio_stat->V1_0.onTimeInMs = legacy_radio_stat.stats.on_time;
- hidl_radio_stat->V1_0.txTimeInMs = legacy_radio_stat.stats.tx_time;
- hidl_radio_stat->V1_0.rxTimeInMs = legacy_radio_stat.stats.rx_time;
- hidl_radio_stat->V1_0.onTimeInMsForScan = legacy_radio_stat.stats.on_time_scan;
- hidl_radio_stat->V1_0.txTimeInMsPerLevel = legacy_radio_stat.tx_time_per_levels;
- hidl_radio_stat->onTimeInMsForNanScan = legacy_radio_stat.stats.on_time_nbd;
- hidl_radio_stat->onTimeInMsForBgScan = legacy_radio_stat.stats.on_time_gscan;
- hidl_radio_stat->onTimeInMsForRoamScan = legacy_radio_stat.stats.on_time_roam_scan;
- hidl_radio_stat->onTimeInMsForPnoScan = legacy_radio_stat.stats.on_time_pno_scan;
- hidl_radio_stat->onTimeInMsForHs20Scan = legacy_radio_stat.stats.on_time_hs20;
-
- std::vector<V1_6::WifiChannelStats> hidl_channel_stats;
-
- for (const auto& channel_stat : legacy_radio_stat.channel_stats) {
- V1_6::WifiChannelStats hidl_channel_stat;
- hidl_channel_stat.onTimeInMs = channel_stat.on_time;
- hidl_channel_stat.ccaBusyTimeInMs = channel_stat.cca_busy_time;
- /*
- * TODO once b/119142899 is fixed,
- * replace below code with convertLegacyWifiChannelInfoToHidl()
- */
- hidl_channel_stat.channel.width = WifiChannelWidthInMhz::WIDTH_20;
- hidl_channel_stat.channel.centerFreq = channel_stat.channel.center_freq;
- hidl_channel_stat.channel.centerFreq0 = channel_stat.channel.center_freq0;
- hidl_channel_stat.channel.centerFreq1 = channel_stat.channel.center_freq1;
- hidl_channel_stats.push_back(hidl_channel_stat);
- }
-
- hidl_radio_stat->channelStats = hidl_channel_stats;
-
- return true;
-}
-
-bool convertLegacyLinkLayerStatsToHidl(const legacy_hal::LinkLayerStats& legacy_stats,
- V1_6::StaLinkLayerStats* hidl_stats) {
- if (!hidl_stats) {
- return false;
- }
- *hidl_stats = {};
- // iface legacy_stats conversion.
- hidl_stats->iface.V1_0.beaconRx = legacy_stats.iface.beacon_rx;
- hidl_stats->iface.V1_0.avgRssiMgmt = legacy_stats.iface.rssi_mgmt;
- hidl_stats->iface.V1_0.wmeBePktStats.rxMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].rx_mpdu;
- hidl_stats->iface.V1_0.wmeBePktStats.txMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].tx_mpdu;
- hidl_stats->iface.V1_0.wmeBePktStats.lostMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].mpdu_lost;
- hidl_stats->iface.V1_0.wmeBePktStats.retries =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].retries;
- hidl_stats->iface.wmeBeContentionTimeStats.contentionTimeMinInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_min;
- hidl_stats->iface.wmeBeContentionTimeStats.contentionTimeMaxInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_max;
- hidl_stats->iface.wmeBeContentionTimeStats.contentionTimeAvgInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_avg;
- hidl_stats->iface.wmeBeContentionTimeStats.contentionNumSamples =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_num_samples;
- hidl_stats->iface.V1_0.wmeBkPktStats.rxMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].rx_mpdu;
- hidl_stats->iface.V1_0.wmeBkPktStats.txMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].tx_mpdu;
- hidl_stats->iface.V1_0.wmeBkPktStats.lostMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].mpdu_lost;
- hidl_stats->iface.V1_0.wmeBkPktStats.retries =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].retries;
- hidl_stats->iface.wmeBkContentionTimeStats.contentionTimeMinInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_min;
- hidl_stats->iface.wmeBkContentionTimeStats.contentionTimeMaxInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_max;
- hidl_stats->iface.wmeBkContentionTimeStats.contentionTimeAvgInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_avg;
- hidl_stats->iface.wmeBkContentionTimeStats.contentionNumSamples =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_num_samples;
- hidl_stats->iface.V1_0.wmeViPktStats.rxMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].rx_mpdu;
- hidl_stats->iface.V1_0.wmeViPktStats.txMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].tx_mpdu;
- hidl_stats->iface.V1_0.wmeViPktStats.lostMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].mpdu_lost;
- hidl_stats->iface.V1_0.wmeViPktStats.retries =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].retries;
- hidl_stats->iface.wmeViContentionTimeStats.contentionTimeMinInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_min;
- hidl_stats->iface.wmeViContentionTimeStats.contentionTimeMaxInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_max;
- hidl_stats->iface.wmeViContentionTimeStats.contentionTimeAvgInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_avg;
- hidl_stats->iface.wmeViContentionTimeStats.contentionNumSamples =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_num_samples;
- hidl_stats->iface.V1_0.wmeVoPktStats.rxMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].rx_mpdu;
- hidl_stats->iface.V1_0.wmeVoPktStats.txMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].tx_mpdu;
- hidl_stats->iface.V1_0.wmeVoPktStats.lostMpdu =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].mpdu_lost;
- hidl_stats->iface.V1_0.wmeVoPktStats.retries =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].retries;
- hidl_stats->iface.wmeVoContentionTimeStats.contentionTimeMinInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_min;
- hidl_stats->iface.wmeVoContentionTimeStats.contentionTimeMaxInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_max;
- hidl_stats->iface.wmeVoContentionTimeStats.contentionTimeAvgInUsec =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_avg;
- hidl_stats->iface.wmeVoContentionTimeStats.contentionNumSamples =
- legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_num_samples;
- hidl_stats->iface.timeSliceDutyCycleInPercent =
- legacy_stats.iface.info.time_slicing_duty_cycle_percent;
- // peer info legacy_stats conversion.
- std::vector<V1_6::StaPeerInfo> hidl_peers_info_stats;
- for (const auto& legacy_peer_info_stats : legacy_stats.peers) {
- V1_6::StaPeerInfo hidl_peer_info_stats;
- if (!convertLegacyPeerInfoStatsToHidl(legacy_peer_info_stats, &hidl_peer_info_stats)) {
- return false;
- }
- hidl_peers_info_stats.push_back(hidl_peer_info_stats);
- }
- hidl_stats->iface.peers = hidl_peers_info_stats;
- // radio legacy_stats conversion.
- std::vector<V1_6::StaLinkLayerRadioStats> hidl_radios_stats;
- for (const auto& legacy_radio_stats : legacy_stats.radios) {
- V1_6::StaLinkLayerRadioStats hidl_radio_stats;
- if (!convertLegacyLinkLayerRadioStatsToHidl(legacy_radio_stats, &hidl_radio_stats)) {
- return false;
- }
- hidl_radios_stats.push_back(hidl_radio_stats);
- }
- hidl_stats->radios = hidl_radios_stats;
- // Timestamp in the HAL wrapper here since it's not provided in the legacy
- // HAL API.
- hidl_stats->timeStampInMs = uptimeMillis();
- return true;
-}
-
-bool convertLegacyPeerInfoStatsToHidl(const legacy_hal::WifiPeerInfo& legacy_peer_info_stats,
- V1_6::StaPeerInfo* hidl_peer_info_stats) {
- if (!hidl_peer_info_stats) {
- return false;
- }
- *hidl_peer_info_stats = {};
- hidl_peer_info_stats->staCount = legacy_peer_info_stats.peer_info.bssload.sta_count;
- hidl_peer_info_stats->chanUtil = legacy_peer_info_stats.peer_info.bssload.chan_util;
-
- std::vector<V1_6::StaRateStat> hidlRateStats;
- for (const auto& legacy_rate_stats : legacy_peer_info_stats.rate_stats) {
- V1_6::StaRateStat rateStat;
- if (!convertLegacyWifiRateInfoToHidl(legacy_rate_stats.rate, &rateStat.rateInfo)) {
- return false;
- }
- rateStat.txMpdu = legacy_rate_stats.tx_mpdu;
- rateStat.rxMpdu = legacy_rate_stats.rx_mpdu;
- rateStat.mpduLost = legacy_rate_stats.mpdu_lost;
- rateStat.retries = legacy_rate_stats.retries;
- hidlRateStats.push_back(rateStat);
- }
- hidl_peer_info_stats->rateStats = hidlRateStats;
- return true;
-}
-
-bool convertLegacyRoamingCapabilitiesToHidl(
- const legacy_hal::wifi_roaming_capabilities& legacy_caps,
- StaRoamingCapabilities* hidl_caps) {
- if (!hidl_caps) {
- return false;
- }
- *hidl_caps = {};
- hidl_caps->maxBlacklistSize = legacy_caps.max_blacklist_size;
- hidl_caps->maxWhitelistSize = legacy_caps.max_whitelist_size;
- return true;
-}
-
-bool convertHidlRoamingConfigToLegacy(const StaRoamingConfig& hidl_config,
- legacy_hal::wifi_roaming_config* legacy_config) {
- if (!legacy_config) {
- return false;
- }
- *legacy_config = {};
- if (hidl_config.bssidBlacklist.size() > MAX_BLACKLIST_BSSID ||
- hidl_config.ssidWhitelist.size() > MAX_WHITELIST_SSID) {
- return false;
- }
- legacy_config->num_blacklist_bssid = hidl_config.bssidBlacklist.size();
- uint32_t i = 0;
- for (const auto& bssid : hidl_config.bssidBlacklist) {
- CHECK(bssid.size() == sizeof(legacy_hal::mac_addr));
- memcpy(legacy_config->blacklist_bssid[i++], bssid.data(), bssid.size());
- }
- legacy_config->num_whitelist_ssid = hidl_config.ssidWhitelist.size();
- i = 0;
- for (const auto& ssid : hidl_config.ssidWhitelist) {
- CHECK(ssid.size() <= sizeof(legacy_hal::ssid_t::ssid_str));
- legacy_config->whitelist_ssid[i].length = ssid.size();
- memcpy(legacy_config->whitelist_ssid[i].ssid_str, ssid.data(), ssid.size());
- i++;
- }
- return true;
-}
-
-legacy_hal::fw_roaming_state_t convertHidlRoamingStateToLegacy(StaRoamingState state) {
- switch (state) {
- case StaRoamingState::ENABLED:
- return legacy_hal::ROAMING_ENABLE;
- case StaRoamingState::DISABLED:
- return legacy_hal::ROAMING_DISABLE;
- };
- CHECK(false);
-}
-
-legacy_hal::NanMatchAlg convertHidlNanMatchAlgToLegacy(NanMatchAlg type) {
- switch (type) {
- case NanMatchAlg::MATCH_ONCE:
- return legacy_hal::NAN_MATCH_ALG_MATCH_ONCE;
- case NanMatchAlg::MATCH_CONTINUOUS:
- return legacy_hal::NAN_MATCH_ALG_MATCH_CONTINUOUS;
- case NanMatchAlg::MATCH_NEVER:
- return legacy_hal::NAN_MATCH_ALG_MATCH_NEVER;
- }
- CHECK(false);
-}
-
-legacy_hal::NanPublishType convertHidlNanPublishTypeToLegacy(NanPublishType type) {
- switch (type) {
- case NanPublishType::UNSOLICITED:
- return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED;
- case NanPublishType::SOLICITED:
- return legacy_hal::NAN_PUBLISH_TYPE_SOLICITED;
- case NanPublishType::UNSOLICITED_SOLICITED:
- return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED_SOLICITED;
- }
- CHECK(false);
-}
-
-legacy_hal::NanTxType convertHidlNanTxTypeToLegacy(NanTxType type) {
- switch (type) {
- case NanTxType::BROADCAST:
- return legacy_hal::NAN_TX_TYPE_BROADCAST;
- case NanTxType::UNICAST:
- return legacy_hal::NAN_TX_TYPE_UNICAST;
- }
- CHECK(false);
-}
-
-legacy_hal::NanSubscribeType convertHidlNanSubscribeTypeToLegacy(NanSubscribeType type) {
- switch (type) {
- case NanSubscribeType::PASSIVE:
- return legacy_hal::NAN_SUBSCRIBE_TYPE_PASSIVE;
- case NanSubscribeType::ACTIVE:
- return legacy_hal::NAN_SUBSCRIBE_TYPE_ACTIVE;
- }
- CHECK(false);
-}
-
-legacy_hal::NanSRFType convertHidlNanSrfTypeToLegacy(NanSrfType type) {
- switch (type) {
- case NanSrfType::BLOOM_FILTER:
- return legacy_hal::NAN_SRF_ATTR_BLOOM_FILTER;
- case NanSrfType::PARTIAL_MAC_ADDR:
- return legacy_hal::NAN_SRF_ATTR_PARTIAL_MAC_ADDR;
- }
- CHECK(false);
-}
-
-legacy_hal::NanDataPathChannelCfg convertHidlNanDataPathChannelCfgToLegacy(
- NanDataPathChannelCfg type) {
- switch (type) {
- case NanDataPathChannelCfg::CHANNEL_NOT_REQUESTED:
- return legacy_hal::NAN_DP_CHANNEL_NOT_REQUESTED;
- case NanDataPathChannelCfg::REQUEST_CHANNEL_SETUP:
- return legacy_hal::NAN_DP_REQUEST_CHANNEL_SETUP;
- case NanDataPathChannelCfg::FORCE_CHANNEL_SETUP:
- return legacy_hal::NAN_DP_FORCE_CHANNEL_SETUP;
- }
- CHECK(false);
-}
-
-NanStatusType convertLegacyNanStatusTypeToHidl(legacy_hal::NanStatusType type) {
- switch (type) {
- case legacy_hal::NAN_STATUS_SUCCESS:
- return NanStatusType::SUCCESS;
- case legacy_hal::NAN_STATUS_INTERNAL_FAILURE:
- return NanStatusType::INTERNAL_FAILURE;
- case legacy_hal::NAN_STATUS_PROTOCOL_FAILURE:
- return NanStatusType::PROTOCOL_FAILURE;
- case legacy_hal::NAN_STATUS_INVALID_PUBLISH_SUBSCRIBE_ID:
- return NanStatusType::INVALID_SESSION_ID;
- case legacy_hal::NAN_STATUS_NO_RESOURCE_AVAILABLE:
- return NanStatusType::NO_RESOURCES_AVAILABLE;
- case legacy_hal::NAN_STATUS_INVALID_PARAM:
- return NanStatusType::INVALID_ARGS;
- case legacy_hal::NAN_STATUS_INVALID_REQUESTOR_INSTANCE_ID:
- return NanStatusType::INVALID_PEER_ID;
- case legacy_hal::NAN_STATUS_INVALID_NDP_ID:
- return NanStatusType::INVALID_NDP_ID;
- case legacy_hal::NAN_STATUS_NAN_NOT_ALLOWED:
- return NanStatusType::NAN_NOT_ALLOWED;
- case legacy_hal::NAN_STATUS_NO_OTA_ACK:
- return NanStatusType::NO_OTA_ACK;
- case legacy_hal::NAN_STATUS_ALREADY_ENABLED:
- return NanStatusType::ALREADY_ENABLED;
- case legacy_hal::NAN_STATUS_FOLLOWUP_QUEUE_FULL:
- return NanStatusType::FOLLOWUP_TX_QUEUE_FULL;
- case legacy_hal::NAN_STATUS_UNSUPPORTED_CONCURRENCY_NAN_DISABLED:
- return NanStatusType::UNSUPPORTED_CONCURRENCY_NAN_DISABLED;
- }
- CHECK(false);
-}
-
-void convertToWifiNanStatus(legacy_hal::NanStatusType type, const char* str, size_t max_len,
- WifiNanStatus* wifiNanStatus) {
- wifiNanStatus->status = convertLegacyNanStatusTypeToHidl(type);
- wifiNanStatus->description = safeConvertChar(str, max_len);
-}
-
-bool convertHidlNanEnableRequestToLegacy(const V1_4::NanEnableRequest& hidl_request,
- legacy_hal::NanEnableRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: null legacy_request";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->config_2dot4g_support = 1;
- legacy_request->support_2dot4g_val =
- hidl_request.operateInBand[(size_t)NanBandIndex::NAN_BAND_24GHZ];
- legacy_request->config_support_5g = 1;
- legacy_request->support_5g_val =
- hidl_request.operateInBand[(size_t)NanBandIndex::NAN_BAND_5GHZ];
- legacy_request->config_hop_count_limit = 1;
- legacy_request->hop_count_limit_val = hidl_request.hopCountMax;
- legacy_request->master_pref = hidl_request.configParams.masterPref;
- legacy_request->discovery_indication_cfg = 0;
- legacy_request->discovery_indication_cfg |=
- hidl_request.configParams.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
- legacy_request->discovery_indication_cfg |=
- hidl_request.configParams.disableStartedClusterIndication ? 0x2 : 0x0;
- legacy_request->discovery_indication_cfg |=
- hidl_request.configParams.disableJoinedClusterIndication ? 0x4 : 0x0;
- legacy_request->config_sid_beacon = 1;
- if (hidl_request.configParams.numberOfPublishServiceIdsInBeacon > 127) {
- LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: "
- "numberOfPublishServiceIdsInBeacon > 127";
- return false;
- }
- legacy_request->sid_beacon_val =
- (hidl_request.configParams.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
- (hidl_request.configParams.numberOfPublishServiceIdsInBeacon << 1);
- legacy_request->config_subscribe_sid_beacon = 1;
- if (hidl_request.configParams.numberOfSubscribeServiceIdsInBeacon > 127) {
- LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: "
- "numberOfSubscribeServiceIdsInBeacon > 127";
- return false;
- }
- legacy_request->subscribe_sid_beacon_val =
- (hidl_request.configParams.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
- (hidl_request.configParams.numberOfSubscribeServiceIdsInBeacon << 1);
- legacy_request->config_rssi_window_size = 1;
- legacy_request->rssi_window_size_val = hidl_request.configParams.rssiWindowSize;
- legacy_request->config_disc_mac_addr_randomization = 1;
- legacy_request->disc_mac_addr_rand_interval_sec =
- hidl_request.configParams.macAddressRandomizationIntervalSec;
- legacy_request->config_2dot4g_rssi_close = 1;
- if (hidl_request.configParams.bandSpecificConfig.size() != 3) {
- LOG(ERROR) << "convertHidlNanEnableRequestToLegacy: "
- "bandSpecificConfig.size() != 3";
- return false;
- }
- legacy_request->rssi_close_2dot4g_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .rssiClose;
- legacy_request->config_2dot4g_rssi_middle = 1;
- legacy_request->rssi_middle_2dot4g_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .rssiMiddle;
- legacy_request->config_2dot4g_rssi_proximity = 1;
- legacy_request->rssi_proximity_2dot4g_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .rssiCloseProximity;
- legacy_request->config_scan_params = 1;
- legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .dwellTimeMs;
- legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .scanPeriodSec;
- legacy_request->config_dw.config_2dot4g_dw_band =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .validDiscoveryWindowIntervalVal;
- legacy_request->config_dw.dw_2dot4g_interval_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .discoveryWindowIntervalVal;
- legacy_request->config_5g_rssi_close = 1;
- legacy_request->rssi_close_5g_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .rssiClose;
- legacy_request->config_5g_rssi_middle = 1;
- legacy_request->rssi_middle_5g_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .rssiMiddle;
- legacy_request->config_5g_rssi_close_proximity = 1;
- legacy_request->rssi_close_proximity_5g_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .rssiCloseProximity;
- legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .dwellTimeMs;
- legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .scanPeriodSec;
- legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .dwellTimeMs;
- legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .scanPeriodSec;
- legacy_request->config_dw.config_5g_dw_band =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .validDiscoveryWindowIntervalVal;
- legacy_request->config_dw.dw_5g_interval_val =
- hidl_request.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .discoveryWindowIntervalVal;
- if (hidl_request.debugConfigs.validClusterIdVals) {
- legacy_request->cluster_low = hidl_request.debugConfigs.clusterIdBottomRangeVal;
- legacy_request->cluster_high = hidl_request.debugConfigs.clusterIdTopRangeVal;
- } else { // need 'else' since not configurable in legacy HAL
- legacy_request->cluster_low = 0x0000;
- legacy_request->cluster_high = 0xFFFF;
- }
- legacy_request->config_intf_addr = hidl_request.debugConfigs.validIntfAddrVal;
- memcpy(legacy_request->intf_addr_val, hidl_request.debugConfigs.intfAddrVal.data(), 6);
- legacy_request->config_oui = hidl_request.debugConfigs.validOuiVal;
- legacy_request->oui_val = hidl_request.debugConfigs.ouiVal;
- legacy_request->config_random_factor_force =
- hidl_request.debugConfigs.validRandomFactorForceVal;
- legacy_request->random_factor_force_val = hidl_request.debugConfigs.randomFactorForceVal;
- legacy_request->config_hop_count_force = hidl_request.debugConfigs.validHopCountForceVal;
- legacy_request->hop_count_force_val = hidl_request.debugConfigs.hopCountForceVal;
- legacy_request->config_24g_channel = hidl_request.debugConfigs.validDiscoveryChannelVal;
- legacy_request->channel_24g_val =
- hidl_request.debugConfigs.discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
- legacy_request->config_5g_channel = hidl_request.debugConfigs.validDiscoveryChannelVal;
- legacy_request->channel_5g_val =
- hidl_request.debugConfigs.discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
- legacy_request->config_2dot4g_beacons = hidl_request.debugConfigs.validUseBeaconsInBandVal;
- legacy_request->beacon_2dot4g_val =
- hidl_request.debugConfigs.useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
- legacy_request->config_5g_beacons = hidl_request.debugConfigs.validUseBeaconsInBandVal;
- legacy_request->beacon_5g_val =
- hidl_request.debugConfigs.useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
- legacy_request->config_2dot4g_sdf = hidl_request.debugConfigs.validUseSdfInBandVal;
- legacy_request->sdf_2dot4g_val =
- hidl_request.debugConfigs.useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
- legacy_request->config_5g_sdf = hidl_request.debugConfigs.validUseSdfInBandVal;
- legacy_request->sdf_5g_val =
- hidl_request.debugConfigs.useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
-
- /* TODO: b/145609058
- * Missing updates needed to legacy_hal::NanEnableRequest and conversion to
- * it for 6GHz band */
-
- return true;
-}
-
-bool convertHidlNanEnableRequest_1_6ToLegacy(const V1_4::NanEnableRequest& hidl_request1,
- const NanConfigRequestSupplemental& hidl_request2,
- legacy_hal::NanEnableRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanEnableRequest_1_6ToLegacy: null legacy_request";
- return false;
- }
-
- *legacy_request = {};
- if (!convertHidlNanEnableRequestToLegacy(hidl_request1, legacy_request)) {
- return false;
- }
-
- legacy_request->config_discovery_beacon_int = 1;
- legacy_request->discovery_beacon_interval = hidl_request2.V1_5.V1_2.discoveryBeaconIntervalMs;
- legacy_request->config_nss = 1;
- legacy_request->nss = hidl_request2.V1_5.V1_2.numberOfSpatialStreamsInDiscovery;
- legacy_request->config_dw_early_termination = 1;
- legacy_request->enable_dw_termination =
- hidl_request2.V1_5.V1_2.enableDiscoveryWindowEarlyTermination;
- legacy_request->config_enable_ranging = 1;
- legacy_request->enable_ranging = hidl_request2.V1_5.V1_2.enableRanging;
-
- legacy_request->config_enable_instant_mode = 1;
- legacy_request->enable_instant_mode = hidl_request2.V1_5.enableInstantCommunicationMode;
- legacy_request->config_instant_mode_channel = 1;
- legacy_request->instant_mode_channel = hidl_request2.instantModeChannel;
-
- return true;
-}
-
-bool convertHidlNanConfigRequest_1_6ToLegacy(const V1_4::NanConfigRequest& hidl_request1,
- const NanConfigRequestSupplemental& hidl_request2,
- legacy_hal::NanConfigRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanConfigRequest_1_6ToLegacy: null legacy_request";
- return false;
- }
-
- *legacy_request = {};
- if (!convertHidlNanConfigRequestToLegacy(hidl_request1, legacy_request)) {
- return false;
- }
-
- legacy_request->config_discovery_beacon_int = 1;
- legacy_request->discovery_beacon_interval = hidl_request2.V1_5.V1_2.discoveryBeaconIntervalMs;
- legacy_request->config_nss = 1;
- legacy_request->nss = hidl_request2.V1_5.V1_2.numberOfSpatialStreamsInDiscovery;
- legacy_request->config_dw_early_termination = 1;
- legacy_request->enable_dw_termination =
- hidl_request2.V1_5.V1_2.enableDiscoveryWindowEarlyTermination;
- legacy_request->config_enable_ranging = 1;
- legacy_request->enable_ranging = hidl_request2.V1_5.V1_2.enableRanging;
-
- legacy_request->config_enable_instant_mode = 1;
- legacy_request->enable_instant_mode = hidl_request2.V1_5.enableInstantCommunicationMode;
- legacy_request->config_instant_mode_channel = 1;
- legacy_request->instant_mode_channel = hidl_request2.instantModeChannel;
-
- return true;
-}
-
-bool convertHidlNanPublishRequestToLegacy(const V1_6::NanPublishRequest& hidl_request,
- legacy_hal::NanPublishRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: null legacy_request";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->publish_id = hidl_request.baseConfigs.sessionId;
- legacy_request->ttl = hidl_request.baseConfigs.ttlSec;
- legacy_request->period = hidl_request.baseConfigs.discoveryWindowPeriod;
- legacy_request->publish_count = hidl_request.baseConfigs.discoveryCount;
- legacy_request->service_name_len = hidl_request.baseConfigs.serviceName.size();
- if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: service_name_len "
- "too large";
- return false;
- }
- memcpy(legacy_request->service_name, hidl_request.baseConfigs.serviceName.data(),
- legacy_request->service_name_len);
- legacy_request->publish_match_indicator =
- convertHidlNanMatchAlgToLegacy(hidl_request.baseConfigs.discoveryMatchIndicator);
- legacy_request->service_specific_info_len = hidl_request.baseConfigs.serviceSpecificInfo.size();
- if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
- "service_specific_info_len too large";
- return false;
- }
- memcpy(legacy_request->service_specific_info,
- hidl_request.baseConfigs.serviceSpecificInfo.data(),
- legacy_request->service_specific_info_len);
- legacy_request->sdea_service_specific_info_len =
- hidl_request.baseConfigs.extendedServiceSpecificInfo.size();
- if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
- "sdea_service_specific_info_len too large";
- return false;
- }
- memcpy(legacy_request->sdea_service_specific_info,
- hidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
- legacy_request->sdea_service_specific_info_len);
- legacy_request->rx_match_filter_len = hidl_request.baseConfigs.rxMatchFilter.size();
- if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
- "rx_match_filter_len too large";
- return false;
- }
- memcpy(legacy_request->rx_match_filter, hidl_request.baseConfigs.rxMatchFilter.data(),
- legacy_request->rx_match_filter_len);
- legacy_request->tx_match_filter_len = hidl_request.baseConfigs.txMatchFilter.size();
- if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
- "tx_match_filter_len too large";
- return false;
- }
- memcpy(legacy_request->tx_match_filter, hidl_request.baseConfigs.txMatchFilter.data(),
- legacy_request->tx_match_filter_len);
- legacy_request->rssi_threshold_flag = hidl_request.baseConfigs.useRssiThreshold;
- legacy_request->recv_indication_cfg = 0;
- legacy_request->recv_indication_cfg |=
- hidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1 : 0x0;
- legacy_request->recv_indication_cfg |=
- hidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
- legacy_request->recv_indication_cfg |=
- hidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
- legacy_request->recv_indication_cfg |= 0x8;
- legacy_request->cipher_type = (unsigned int)hidl_request.baseConfigs.securityConfig.cipherType;
-
- legacy_request->scid_len = hidl_request.baseConfigs.securityConfig.scid.size();
- if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: scid_len too large";
- return false;
- }
- memcpy(legacy_request->scid, hidl_request.baseConfigs.securityConfig.scid.data(),
- legacy_request->scid_len);
-
- if (hidl_request.baseConfigs.securityConfig.securityType == NanDataPathSecurityType::PMK) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
- legacy_request->key_info.body.pmk_info.pmk_len =
- hidl_request.baseConfigs.securityConfig.pmk.size();
- if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: invalid pmk_len";
- return false;
- }
- memcpy(legacy_request->key_info.body.pmk_info.pmk,
- hidl_request.baseConfigs.securityConfig.pmk.data(),
- legacy_request->key_info.body.pmk_info.pmk_len);
- }
- if (hidl_request.baseConfigs.securityConfig.securityType ==
- NanDataPathSecurityType::PASSPHRASE) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
- legacy_request->key_info.body.passphrase_info.passphrase_len =
- hidl_request.baseConfigs.securityConfig.passphrase.size();
- if (legacy_request->key_info.body.passphrase_info.passphrase_len <
- NAN_SECURITY_MIN_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
- "passphrase_len too small";
- return false;
- }
- if (legacy_request->key_info.body.passphrase_info.passphrase_len >
- NAN_SECURITY_MAX_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanPublishRequestToLegacy: "
- "passphrase_len too large";
- return false;
- }
- memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
- hidl_request.baseConfigs.securityConfig.passphrase.data(),
- legacy_request->key_info.body.passphrase_info.passphrase_len);
- }
- legacy_request->sdea_params.security_cfg =
- (hidl_request.baseConfigs.securityConfig.securityType != NanDataPathSecurityType::OPEN)
- ? legacy_hal::NAN_DP_CONFIG_SECURITY
- : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
-
- legacy_request->sdea_params.ranging_state = hidl_request.baseConfigs.rangingRequired
- ? legacy_hal::NAN_RANGING_ENABLE
- : legacy_hal::NAN_RANGING_DISABLE;
- legacy_request->ranging_cfg.ranging_interval_msec =
- hidl_request.baseConfigs.rangingIntervalMsec;
- legacy_request->ranging_cfg.config_ranging_indications =
- hidl_request.baseConfigs.configRangingIndications;
- legacy_request->ranging_cfg.distance_ingress_mm =
- hidl_request.baseConfigs.distanceIngressCm * 10;
- legacy_request->ranging_cfg.distance_egress_mm = hidl_request.baseConfigs.distanceEgressCm * 10;
- legacy_request->ranging_auto_response = hidl_request.baseConfigs.rangingRequired
- ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
- : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
- legacy_request->sdea_params.range_report = legacy_hal::NAN_DISABLE_RANGE_REPORT;
- legacy_request->publish_type = convertHidlNanPublishTypeToLegacy(hidl_request.publishType);
- legacy_request->tx_type = convertHidlNanTxTypeToLegacy(hidl_request.txType);
- legacy_request->service_responder_policy = hidl_request.autoAcceptDataPathRequests
- ? legacy_hal::NAN_SERVICE_ACCEPT_POLICY_ALL
- : legacy_hal::NAN_SERVICE_ACCEPT_POLICY_NONE;
-
- return true;
-}
-
-bool convertHidlNanSubscribeRequestToLegacy(const V1_0::NanSubscribeRequest& hidl_request,
- legacy_hal::NanSubscribeRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->subscribe_id = hidl_request.baseConfigs.sessionId;
- legacy_request->ttl = hidl_request.baseConfigs.ttlSec;
- legacy_request->period = hidl_request.baseConfigs.discoveryWindowPeriod;
- legacy_request->subscribe_count = hidl_request.baseConfigs.discoveryCount;
- legacy_request->service_name_len = hidl_request.baseConfigs.serviceName.size();
- if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "service_name_len too large";
- return false;
- }
- memcpy(legacy_request->service_name, hidl_request.baseConfigs.serviceName.data(),
- legacy_request->service_name_len);
- legacy_request->subscribe_match_indicator =
- convertHidlNanMatchAlgToLegacy(hidl_request.baseConfigs.discoveryMatchIndicator);
- legacy_request->service_specific_info_len = hidl_request.baseConfigs.serviceSpecificInfo.size();
- if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "service_specific_info_len too large";
- return false;
- }
- memcpy(legacy_request->service_specific_info,
- hidl_request.baseConfigs.serviceSpecificInfo.data(),
- legacy_request->service_specific_info_len);
- legacy_request->sdea_service_specific_info_len =
- hidl_request.baseConfigs.extendedServiceSpecificInfo.size();
- if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "sdea_service_specific_info_len too large";
- return false;
- }
- memcpy(legacy_request->sdea_service_specific_info,
- hidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
- legacy_request->sdea_service_specific_info_len);
- legacy_request->rx_match_filter_len = hidl_request.baseConfigs.rxMatchFilter.size();
- if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "rx_match_filter_len too large";
- return false;
- }
- memcpy(legacy_request->rx_match_filter, hidl_request.baseConfigs.rxMatchFilter.data(),
- legacy_request->rx_match_filter_len);
- legacy_request->tx_match_filter_len = hidl_request.baseConfigs.txMatchFilter.size();
- if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "tx_match_filter_len too large";
- return false;
- }
- memcpy(legacy_request->tx_match_filter, hidl_request.baseConfigs.txMatchFilter.data(),
- legacy_request->tx_match_filter_len);
- legacy_request->rssi_threshold_flag = hidl_request.baseConfigs.useRssiThreshold;
- legacy_request->recv_indication_cfg = 0;
- legacy_request->recv_indication_cfg |=
- hidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1 : 0x0;
- legacy_request->recv_indication_cfg |=
- hidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
- legacy_request->recv_indication_cfg |=
- hidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
- legacy_request->cipher_type = (unsigned int)hidl_request.baseConfigs.securityConfig.cipherType;
- if (hidl_request.baseConfigs.securityConfig.securityType == NanDataPathSecurityType::PMK) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
- legacy_request->key_info.body.pmk_info.pmk_len =
- hidl_request.baseConfigs.securityConfig.pmk.size();
- if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: invalid pmk_len";
- return false;
- }
- memcpy(legacy_request->key_info.body.pmk_info.pmk,
- hidl_request.baseConfigs.securityConfig.pmk.data(),
- legacy_request->key_info.body.pmk_info.pmk_len);
- }
- if (hidl_request.baseConfigs.securityConfig.securityType ==
- NanDataPathSecurityType::PASSPHRASE) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
- legacy_request->key_info.body.passphrase_info.passphrase_len =
- hidl_request.baseConfigs.securityConfig.passphrase.size();
- if (legacy_request->key_info.body.passphrase_info.passphrase_len <
- NAN_SECURITY_MIN_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "passphrase_len too small";
- return false;
- }
- if (legacy_request->key_info.body.passphrase_info.passphrase_len >
- NAN_SECURITY_MAX_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "passphrase_len too large";
- return false;
- }
- memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
- hidl_request.baseConfigs.securityConfig.passphrase.data(),
- legacy_request->key_info.body.passphrase_info.passphrase_len);
- }
- legacy_request->sdea_params.security_cfg =
- (hidl_request.baseConfigs.securityConfig.securityType != NanDataPathSecurityType::OPEN)
- ? legacy_hal::NAN_DP_CONFIG_SECURITY
- : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
- legacy_request->sdea_params.ranging_state = hidl_request.baseConfigs.rangingRequired
- ? legacy_hal::NAN_RANGING_ENABLE
- : legacy_hal::NAN_RANGING_DISABLE;
- legacy_request->ranging_cfg.ranging_interval_msec =
- hidl_request.baseConfigs.rangingIntervalMsec;
- legacy_request->ranging_cfg.config_ranging_indications =
- hidl_request.baseConfigs.configRangingIndications;
- legacy_request->ranging_cfg.distance_ingress_mm =
- hidl_request.baseConfigs.distanceIngressCm * 10;
- legacy_request->ranging_cfg.distance_egress_mm = hidl_request.baseConfigs.distanceEgressCm * 10;
- legacy_request->ranging_auto_response = hidl_request.baseConfigs.rangingRequired
- ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
- : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
- legacy_request->sdea_params.range_report = legacy_hal::NAN_DISABLE_RANGE_REPORT;
- legacy_request->subscribe_type =
- convertHidlNanSubscribeTypeToLegacy(hidl_request.subscribeType);
- legacy_request->serviceResponseFilter = convertHidlNanSrfTypeToLegacy(hidl_request.srfType);
- legacy_request->serviceResponseInclude = hidl_request.srfRespondIfInAddressSet
- ? legacy_hal::NAN_SRF_INCLUDE_RESPOND
- : legacy_hal::NAN_SRF_INCLUDE_DO_NOT_RESPOND;
- legacy_request->useServiceResponseFilter =
- hidl_request.shouldUseSrf ? legacy_hal::NAN_USE_SRF : legacy_hal::NAN_DO_NOT_USE_SRF;
- legacy_request->ssiRequiredForMatchIndication =
- hidl_request.isSsiRequiredForMatch ? legacy_hal::NAN_SSI_REQUIRED_IN_MATCH_IND
- : legacy_hal::NAN_SSI_NOT_REQUIRED_IN_MATCH_IND;
- legacy_request->num_intf_addr_present = hidl_request.intfAddr.size();
- if (legacy_request->num_intf_addr_present > NAN_MAX_SUBSCRIBE_MAX_ADDRESS) {
- LOG(ERROR) << "convertHidlNanSubscribeRequestToLegacy: "
- "num_intf_addr_present - too many";
- return false;
- }
- for (int i = 0; i < legacy_request->num_intf_addr_present; i++) {
- memcpy(legacy_request->intf_addr[i], hidl_request.intfAddr[i].data(), 6);
- }
-
- return true;
-}
-
-bool convertHidlNanTransmitFollowupRequestToLegacy(
- const NanTransmitFollowupRequest& hidl_request,
- legacy_hal::NanTransmitFollowupRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanTransmitFollowupRequestToLegacy: "
- "legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->publish_subscribe_id = hidl_request.discoverySessionId;
- legacy_request->requestor_instance_id = hidl_request.peerId;
- memcpy(legacy_request->addr, hidl_request.addr.data(), 6);
- legacy_request->priority = hidl_request.isHighPriority ? legacy_hal::NAN_TX_PRIORITY_HIGH
- : legacy_hal::NAN_TX_PRIORITY_NORMAL;
- legacy_request->dw_or_faw = hidl_request.shouldUseDiscoveryWindow
- ? legacy_hal::NAN_TRANSMIT_IN_DW
- : legacy_hal::NAN_TRANSMIT_IN_FAW;
- legacy_request->service_specific_info_len = hidl_request.serviceSpecificInfo.size();
- if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanTransmitFollowupRequestToLegacy: "
- "service_specific_info_len too large";
- return false;
- }
- memcpy(legacy_request->service_specific_info, hidl_request.serviceSpecificInfo.data(),
- legacy_request->service_specific_info_len);
- legacy_request->sdea_service_specific_info_len =
- hidl_request.extendedServiceSpecificInfo.size();
- if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanTransmitFollowupRequestToLegacy: "
- "sdea_service_specific_info_len too large";
- return false;
- }
- memcpy(legacy_request->sdea_service_specific_info,
- hidl_request.extendedServiceSpecificInfo.data(),
- legacy_request->sdea_service_specific_info_len);
- legacy_request->recv_indication_cfg = hidl_request.disableFollowupResultIndication ? 0x1 : 0x0;
-
- return true;
-}
-
-bool convertHidlNanConfigRequestToLegacy(const V1_4::NanConfigRequest& hidl_request,
- legacy_hal::NanConfigRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanConfigRequestToLegacy: legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- // TODO: b/34059183 tracks missing configurations in legacy HAL or uknown
- // defaults
- legacy_request->master_pref = hidl_request.masterPref;
- legacy_request->discovery_indication_cfg = 0;
- legacy_request->discovery_indication_cfg |=
- hidl_request.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
- legacy_request->discovery_indication_cfg |=
- hidl_request.disableStartedClusterIndication ? 0x2 : 0x0;
- legacy_request->discovery_indication_cfg |=
- hidl_request.disableJoinedClusterIndication ? 0x4 : 0x0;
- legacy_request->config_sid_beacon = 1;
- if (hidl_request.numberOfPublishServiceIdsInBeacon > 127) {
- LOG(ERROR) << "convertHidlNanConfigRequestToLegacy: "
- "numberOfPublishServiceIdsInBeacon > 127";
- return false;
- }
- legacy_request->sid_beacon = (hidl_request.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
- (hidl_request.numberOfPublishServiceIdsInBeacon << 1);
- legacy_request->config_subscribe_sid_beacon = 1;
- if (hidl_request.numberOfSubscribeServiceIdsInBeacon > 127) {
- LOG(ERROR) << "convertHidlNanConfigRequestToLegacy: "
- "numberOfSubscribeServiceIdsInBeacon > 127";
- return false;
- }
- legacy_request->subscribe_sid_beacon_val =
- (hidl_request.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
- (hidl_request.numberOfSubscribeServiceIdsInBeacon << 1);
- legacy_request->config_rssi_window_size = 1;
- legacy_request->rssi_window_size_val = hidl_request.rssiWindowSize;
- legacy_request->config_disc_mac_addr_randomization = 1;
- legacy_request->disc_mac_addr_rand_interval_sec =
- hidl_request.macAddressRandomizationIntervalSec;
- /* TODO : missing
- legacy_request->config_2dot4g_rssi_close = 1;
- legacy_request->rssi_close_2dot4g_val =
- hidl_request.bandSpecificConfig[
- (size_t) NanBandIndex::NAN_BAND_24GHZ].rssiClose;
- legacy_request->config_2dot4g_rssi_middle = 1;
- legacy_request->rssi_middle_2dot4g_val =
- hidl_request.bandSpecificConfig[
- (size_t) NanBandIndex::NAN_BAND_24GHZ].rssiMiddle;
- legacy_request->config_2dot4g_rssi_proximity = 1;
- legacy_request->rssi_proximity_2dot4g_val =
- hidl_request.bandSpecificConfig[
- (size_t) NanBandIndex::NAN_BAND_24GHZ].rssiCloseProximity;
- */
- legacy_request->config_scan_params = 1;
- legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ].dwellTimeMs;
- legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ].scanPeriodSec;
- legacy_request->config_dw.config_2dot4g_dw_band =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .validDiscoveryWindowIntervalVal;
- legacy_request->config_dw.dw_2dot4g_interval_val =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
- .discoveryWindowIntervalVal;
- /* TODO: missing
- legacy_request->config_5g_rssi_close = 1;
- legacy_request->rssi_close_5g_val =
- hidl_request.bandSpecificConfig[
- (size_t) NanBandIndex::NAN_BAND_5GHZ].rssiClose;
- legacy_request->config_5g_rssi_middle = 1;
- legacy_request->rssi_middle_5g_val =
- hidl_request.bandSpecificConfig[
- (size_t) NanBandIndex::NAN_BAND_5GHZ].rssiMiddle;
- */
- legacy_request->config_5g_rssi_close_proximity = 1;
- legacy_request->rssi_close_proximity_5g_val =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].rssiCloseProximity;
- legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].dwellTimeMs;
- legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].scanPeriodSec;
- legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].dwellTimeMs;
- legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].scanPeriodSec;
- legacy_request->config_dw.config_5g_dw_band =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .validDiscoveryWindowIntervalVal;
- legacy_request->config_dw.dw_5g_interval_val =
- hidl_request.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
- .discoveryWindowIntervalVal;
- /* TODO: b/145609058
- * Missing updates needed to legacy_hal::NanConfigRequest and conversion to
- * it for 6GHz band */
-
- return true;
-}
-
-bool convertHidlNanDataPathInitiatorRequestToLegacy(
- const V1_0::NanInitiateDataPathRequest& hidl_request,
- legacy_hal::NanDataPathInitiatorRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->requestor_instance_id = hidl_request.peerId;
- memcpy(legacy_request->peer_disc_mac_addr, hidl_request.peerDiscMacAddr.data(), 6);
- legacy_request->channel_request_type =
- convertHidlNanDataPathChannelCfgToLegacy(hidl_request.channelRequestType);
- legacy_request->channel = hidl_request.channel;
- if (strnlen(hidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "ifaceName too long";
- return false;
- }
- strlcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
- legacy_request->ndp_cfg.security_cfg =
- (hidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
- ? legacy_hal::NAN_DP_CONFIG_SECURITY
- : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
- legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
- if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "ndp_app_info_len too large";
- return false;
- }
- memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
- legacy_request->app_info.ndp_app_info_len);
- legacy_request->cipher_type = (unsigned int)hidl_request.securityConfig.cipherType;
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
- legacy_request->key_info.body.pmk_info.pmk_len = hidl_request.securityConfig.pmk.size();
- if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "invalid pmk_len";
- return false;
- }
- memcpy(legacy_request->key_info.body.pmk_info.pmk, hidl_request.securityConfig.pmk.data(),
- legacy_request->key_info.body.pmk_info.pmk_len);
- }
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
- legacy_request->key_info.body.passphrase_info.passphrase_len =
- hidl_request.securityConfig.passphrase.size();
- if (legacy_request->key_info.body.passphrase_info.passphrase_len <
- NAN_SECURITY_MIN_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "passphrase_len too small";
- return false;
- }
- if (legacy_request->key_info.body.passphrase_info.passphrase_len >
- NAN_SECURITY_MAX_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "passphrase_len too large";
- return false;
- }
- memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
- hidl_request.securityConfig.passphrase.data(),
- legacy_request->key_info.body.passphrase_info.passphrase_len);
- }
- legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
- if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequestToLegacy: "
- "service_name_len too large";
- return false;
- }
- memcpy(legacy_request->service_name, hidl_request.serviceNameOutOfBand.data(),
- legacy_request->service_name_len);
-
- return true;
-}
-
-bool convertHidlNanDataPathInitiatorRequest_1_6ToLegacy(
- const V1_6::NanInitiateDataPathRequest& hidl_request,
- legacy_hal::NanDataPathInitiatorRequest* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->requestor_instance_id = hidl_request.peerId;
- memcpy(legacy_request->peer_disc_mac_addr, hidl_request.peerDiscMacAddr.data(), 6);
- legacy_request->channel_request_type =
- convertHidlNanDataPathChannelCfgToLegacy(hidl_request.channelRequestType);
- legacy_request->channel = hidl_request.channel;
- if (strnlen(hidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "ifaceName too long";
- return false;
- }
- strlcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
- legacy_request->ndp_cfg.security_cfg =
- (hidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
- ? legacy_hal::NAN_DP_CONFIG_SECURITY
- : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
- legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
- if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "ndp_app_info_len too large";
- return false;
- }
- memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
- legacy_request->app_info.ndp_app_info_len);
- legacy_request->cipher_type = (unsigned int)hidl_request.securityConfig.cipherType;
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
- legacy_request->key_info.body.pmk_info.pmk_len = hidl_request.securityConfig.pmk.size();
- if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "invalid pmk_len";
- return false;
- }
- memcpy(legacy_request->key_info.body.pmk_info.pmk, hidl_request.securityConfig.pmk.data(),
- legacy_request->key_info.body.pmk_info.pmk_len);
- }
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
- legacy_request->key_info.body.passphrase_info.passphrase_len =
- hidl_request.securityConfig.passphrase.size();
- if (legacy_request->key_info.body.passphrase_info.passphrase_len <
- NAN_SECURITY_MIN_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "passphrase_len too small";
- return false;
- }
- if (legacy_request->key_info.body.passphrase_info.passphrase_len >
- NAN_SECURITY_MAX_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "passphrase_len too large";
- return false;
- }
- memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
- hidl_request.securityConfig.passphrase.data(),
- legacy_request->key_info.body.passphrase_info.passphrase_len);
- }
- legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
- if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: "
- "service_name_len too large";
- return false;
- }
- memcpy(legacy_request->service_name, hidl_request.serviceNameOutOfBand.data(),
- legacy_request->service_name_len);
- legacy_request->scid_len = hidl_request.securityConfig.scid.size();
- if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathInitiatorRequest_1_6ToLegacy: scid_len too large";
- return false;
- }
- memcpy(legacy_request->scid, hidl_request.securityConfig.scid.data(), legacy_request->scid_len);
-
- return true;
-}
-
-bool convertHidlNanDataPathIndicationResponseToLegacy(
- const V1_0::NanRespondToDataPathIndicationRequest& hidl_request,
- legacy_hal::NanDataPathIndicationResponse* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->rsp_code = hidl_request.acceptRequest ? legacy_hal::NAN_DP_REQUEST_ACCEPT
- : legacy_hal::NAN_DP_REQUEST_REJECT;
- legacy_request->ndp_instance_id = hidl_request.ndpInstanceId;
- if (strnlen(hidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "ifaceName too long";
- return false;
- }
- strlcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
- legacy_request->ndp_cfg.security_cfg =
- (hidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
- ? legacy_hal::NAN_DP_CONFIG_SECURITY
- : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
- legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
- if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "ndp_app_info_len too large";
- return false;
- }
- memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
- legacy_request->app_info.ndp_app_info_len);
- legacy_request->cipher_type = (unsigned int)hidl_request.securityConfig.cipherType;
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
- legacy_request->key_info.body.pmk_info.pmk_len = hidl_request.securityConfig.pmk.size();
- if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "invalid pmk_len";
- return false;
- }
- memcpy(legacy_request->key_info.body.pmk_info.pmk, hidl_request.securityConfig.pmk.data(),
- legacy_request->key_info.body.pmk_info.pmk_len);
- }
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
- legacy_request->key_info.body.passphrase_info.passphrase_len =
- hidl_request.securityConfig.passphrase.size();
- if (legacy_request->key_info.body.passphrase_info.passphrase_len <
- NAN_SECURITY_MIN_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "passphrase_len too small";
- return false;
- }
- if (legacy_request->key_info.body.passphrase_info.passphrase_len >
- NAN_SECURITY_MAX_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "passphrase_len too large";
- return false;
- }
- memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
- hidl_request.securityConfig.passphrase.data(),
- legacy_request->key_info.body.passphrase_info.passphrase_len);
- }
- legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
- if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponseToLegacy: "
- "service_name_len too large";
- return false;
- }
- memcpy(legacy_request->service_name, hidl_request.serviceNameOutOfBand.data(),
- legacy_request->service_name_len);
-
- return true;
-}
-
-bool convertHidlNanDataPathIndicationResponse_1_6ToLegacy(
- const V1_6::NanRespondToDataPathIndicationRequest& hidl_request,
- legacy_hal::NanDataPathIndicationResponse* legacy_request) {
- if (!legacy_request) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "legacy_request is null";
- return false;
- }
- *legacy_request = {};
-
- legacy_request->rsp_code = hidl_request.acceptRequest ? legacy_hal::NAN_DP_REQUEST_ACCEPT
- : legacy_hal::NAN_DP_REQUEST_REJECT;
- legacy_request->ndp_instance_id = hidl_request.ndpInstanceId;
- if (strnlen(hidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "ifaceName too long";
- return false;
- }
- strlcpy(legacy_request->ndp_iface, hidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
- legacy_request->ndp_cfg.security_cfg =
- (hidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
- ? legacy_hal::NAN_DP_CONFIG_SECURITY
- : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
- legacy_request->app_info.ndp_app_info_len = hidl_request.appInfo.size();
- if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "ndp_app_info_len too large";
- return false;
- }
- memcpy(legacy_request->app_info.ndp_app_info, hidl_request.appInfo.data(),
- legacy_request->app_info.ndp_app_info_len);
- legacy_request->cipher_type = (unsigned int)hidl_request.securityConfig.cipherType;
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
- legacy_request->key_info.body.pmk_info.pmk_len = hidl_request.securityConfig.pmk.size();
- if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "invalid pmk_len";
- return false;
- }
- memcpy(legacy_request->key_info.body.pmk_info.pmk, hidl_request.securityConfig.pmk.data(),
- legacy_request->key_info.body.pmk_info.pmk_len);
- }
- if (hidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
- legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
- legacy_request->key_info.body.passphrase_info.passphrase_len =
- hidl_request.securityConfig.passphrase.size();
- if (legacy_request->key_info.body.passphrase_info.passphrase_len <
- NAN_SECURITY_MIN_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "passphrase_len too small";
- return false;
- }
- if (legacy_request->key_info.body.passphrase_info.passphrase_len >
- NAN_SECURITY_MAX_PASSPHRASE_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "passphrase_len too large";
- return false;
- }
- memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
- hidl_request.securityConfig.passphrase.data(),
- legacy_request->key_info.body.passphrase_info.passphrase_len);
- }
- legacy_request->service_name_len = hidl_request.serviceNameOutOfBand.size();
- if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: "
- "service_name_len too large";
- return false;
- }
- memcpy(legacy_request->service_name, hidl_request.serviceNameOutOfBand.data(),
- legacy_request->service_name_len);
- legacy_request->scid_len = hidl_request.securityConfig.scid.size();
- if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
- LOG(ERROR) << "convertHidlNanDataPathIndicationResponse_1_6ToLegacy: scid_len too large";
- return false;
- }
- memcpy(legacy_request->scid, hidl_request.securityConfig.scid.data(), legacy_request->scid_len);
-
- return true;
-}
-
-bool convertLegacyNanResponseHeaderToHidl(const legacy_hal::NanResponseMsg& legacy_response,
- WifiNanStatus* wifiNanStatus) {
- if (!wifiNanStatus) {
- LOG(ERROR) << "convertLegacyNanResponseHeaderToHidl: wifiNanStatus is null";
- return false;
- }
- *wifiNanStatus = {};
-
- convertToWifiNanStatus(legacy_response.status, legacy_response.nan_error,
- sizeof(legacy_response.nan_error), wifiNanStatus);
- return true;
-}
-
-bool convertLegacyNanCapabilitiesResponseToHidl(const legacy_hal::NanCapabilities& legacy_response,
- V1_6::NanCapabilities* hidl_response) {
- if (!hidl_response) {
- LOG(ERROR) << "convertLegacyNanCapabilitiesResponseToHidl: "
- "hidl_response is null";
- return false;
- }
- *hidl_response = {};
-
- hidl_response->maxConcurrentClusters = legacy_response.max_concurrent_nan_clusters;
- hidl_response->maxPublishes = legacy_response.max_publishes;
- hidl_response->maxSubscribes = legacy_response.max_subscribes;
- hidl_response->maxServiceNameLen = legacy_response.max_service_name_len;
- hidl_response->maxMatchFilterLen = legacy_response.max_match_filter_len;
- hidl_response->maxTotalMatchFilterLen = legacy_response.max_total_match_filter_len;
- hidl_response->maxServiceSpecificInfoLen = legacy_response.max_service_specific_info_len;
- hidl_response->maxExtendedServiceSpecificInfoLen =
- legacy_response.max_sdea_service_specific_info_len;
- hidl_response->maxNdiInterfaces = legacy_response.max_ndi_interfaces;
- hidl_response->maxNdpSessions = legacy_response.max_ndp_sessions;
- hidl_response->maxAppInfoLen = legacy_response.max_app_info_len;
- hidl_response->maxQueuedTransmitFollowupMsgs =
- legacy_response.max_queued_transmit_followup_msgs;
- hidl_response->maxSubscribeInterfaceAddresses = legacy_response.max_subscribe_address;
- hidl_response->supportedCipherSuites = legacy_response.cipher_suites_supported;
- hidl_response->instantCommunicationModeSupportFlag = legacy_response.is_instant_mode_supported;
-
- return true;
-}
-
-bool convertLegacyNanMatchIndToHidl(const legacy_hal::NanMatchInd& legacy_ind,
- V1_6::NanMatchInd* hidl_ind) {
- if (!hidl_ind) {
- LOG(ERROR) << "convertLegacyNanMatchIndToHidl: hidl_ind is null";
- return false;
- }
- *hidl_ind = {};
-
- hidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
- hidl_ind->peerId = legacy_ind.requestor_instance_id;
- hidl_ind->addr = hidl_array<uint8_t, 6>(legacy_ind.addr);
- hidl_ind->serviceSpecificInfo = std::vector<uint8_t>(
- legacy_ind.service_specific_info,
- legacy_ind.service_specific_info + legacy_ind.service_specific_info_len);
- hidl_ind->extendedServiceSpecificInfo = std::vector<uint8_t>(
- legacy_ind.sdea_service_specific_info,
- legacy_ind.sdea_service_specific_info + legacy_ind.sdea_service_specific_info_len);
- hidl_ind->matchFilter =
- std::vector<uint8_t>(legacy_ind.sdf_match_filter,
- legacy_ind.sdf_match_filter + legacy_ind.sdf_match_filter_len);
- hidl_ind->matchOccuredInBeaconFlag = legacy_ind.match_occured_flag == 1;
- hidl_ind->outOfResourceFlag = legacy_ind.out_of_resource_flag == 1;
- hidl_ind->rssiValue = legacy_ind.rssi_value;
- hidl_ind->peerCipherType = (V1_6::NanCipherSuiteType)legacy_ind.peer_cipher_type;
- hidl_ind->peerRequiresSecurityEnabledInNdp =
- legacy_ind.peer_sdea_params.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
- hidl_ind->peerRequiresRanging =
- legacy_ind.peer_sdea_params.ranging_state == legacy_hal::NAN_RANGING_ENABLE;
- hidl_ind->rangingMeasurementInMm = legacy_ind.range_info.range_measurement_mm;
- hidl_ind->rangingIndicationType = legacy_ind.range_info.ranging_event_type;
- hidl_ind->scid = std::vector<uint8_t>(legacy_ind.scid, legacy_ind.scid + legacy_ind.scid_len);
- return true;
-}
-
-bool convertLegacyNanFollowupIndToHidl(const legacy_hal::NanFollowupInd& legacy_ind,
- NanFollowupReceivedInd* hidl_ind) {
- if (!hidl_ind) {
- LOG(ERROR) << "convertLegacyNanFollowupIndToHidl: hidl_ind is null";
- return false;
- }
- *hidl_ind = {};
-
- hidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
- hidl_ind->peerId = legacy_ind.requestor_instance_id;
- hidl_ind->addr = hidl_array<uint8_t, 6>(legacy_ind.addr);
- hidl_ind->receivedInFaw = legacy_ind.dw_or_faw == 1;
- hidl_ind->serviceSpecificInfo = std::vector<uint8_t>(
- legacy_ind.service_specific_info,
- legacy_ind.service_specific_info + legacy_ind.service_specific_info_len);
- hidl_ind->extendedServiceSpecificInfo = std::vector<uint8_t>(
- legacy_ind.sdea_service_specific_info,
- legacy_ind.sdea_service_specific_info + legacy_ind.sdea_service_specific_info_len);
-
- return true;
-}
-
-bool convertLegacyNanDataPathRequestIndToHidl(const legacy_hal::NanDataPathRequestInd& legacy_ind,
- NanDataPathRequestInd* hidl_ind) {
- if (!hidl_ind) {
- LOG(ERROR) << "convertLegacyNanDataPathRequestIndToHidl: hidl_ind is null";
- return false;
- }
- *hidl_ind = {};
-
- hidl_ind->discoverySessionId = legacy_ind.service_instance_id;
- hidl_ind->peerDiscMacAddr = hidl_array<uint8_t, 6>(legacy_ind.peer_disc_mac_addr);
- hidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
- hidl_ind->securityRequired =
- legacy_ind.ndp_cfg.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
- hidl_ind->appInfo = std::vector<uint8_t>(
- legacy_ind.app_info.ndp_app_info,
- legacy_ind.app_info.ndp_app_info + legacy_ind.app_info.ndp_app_info_len);
-
- return true;
-}
-
-bool convertLegacyNdpChannelInfoToHidl(const legacy_hal::NanChannelInfo& legacy_struct,
- V1_6::NanDataPathChannelInfo* hidl_struct) {
- if (!hidl_struct) {
- LOG(ERROR) << "convertLegacyNdpChannelInfoToHidl: hidl_struct is null";
- return false;
- }
- *hidl_struct = {};
-
- hidl_struct->channelFreq = legacy_struct.channel;
- hidl_struct->channelBandwidth = convertLegacyWifiChannelWidthToHidl(
- (legacy_hal::wifi_channel_width)legacy_struct.bandwidth);
- hidl_struct->numSpatialStreams = legacy_struct.nss;
-
- return true;
-}
-
-bool convertLegacyNanDataPathConfirmIndToHidl(const legacy_hal::NanDataPathConfirmInd& legacy_ind,
- V1_6::NanDataPathConfirmInd* hidl_ind) {
- if (!hidl_ind) {
- LOG(ERROR) << "convertLegacyNanDataPathConfirmIndToHidl: hidl_ind is null";
- return false;
- }
- *hidl_ind = {};
-
- hidl_ind->V1_0.ndpInstanceId = legacy_ind.ndp_instance_id;
- hidl_ind->V1_0.dataPathSetupSuccess = legacy_ind.rsp_code == legacy_hal::NAN_DP_REQUEST_ACCEPT;
- hidl_ind->V1_0.peerNdiMacAddr = hidl_array<uint8_t, 6>(legacy_ind.peer_ndi_mac_addr);
- hidl_ind->V1_0.appInfo = std::vector<uint8_t>(
- legacy_ind.app_info.ndp_app_info,
- legacy_ind.app_info.ndp_app_info + legacy_ind.app_info.ndp_app_info_len);
- hidl_ind->V1_0.status.status = convertLegacyNanStatusTypeToHidl(legacy_ind.reason_code);
- hidl_ind->V1_0.status.description = ""; // TODO: b/34059183
-
- std::vector<V1_6::NanDataPathChannelInfo> channelInfo;
- for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
- V1_6::NanDataPathChannelInfo hidl_struct;
- if (!convertLegacyNdpChannelInfoToHidl(legacy_ind.channel_info[i], &hidl_struct)) {
- return false;
- }
- channelInfo.push_back(hidl_struct);
- }
- hidl_ind->channelInfo = channelInfo;
-
- return true;
-}
-
-bool convertLegacyNanDataPathScheduleUpdateIndToHidl(
- const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
- V1_6::NanDataPathScheduleUpdateInd* hidl_ind) {
- if (!hidl_ind) {
- LOG(ERROR) << "convertLegacyNanDataPathScheduleUpdateIndToHidl: "
- "hidl_ind is null";
- return false;
- }
- *hidl_ind = {};
-
- hidl_ind->peerDiscoveryAddress = hidl_array<uint8_t, 6>(legacy_ind.peer_mac_addr);
- std::vector<V1_6::NanDataPathChannelInfo> channelInfo;
- for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
- V1_6::NanDataPathChannelInfo hidl_struct;
- if (!convertLegacyNdpChannelInfoToHidl(legacy_ind.channel_info[i], &hidl_struct)) {
- return false;
- }
- channelInfo.push_back(hidl_struct);
- }
- hidl_ind->channelInfo = channelInfo;
- std::vector<uint32_t> ndpInstanceIds;
- for (unsigned int i = 0; i < legacy_ind.num_ndp_instances; ++i) {
- ndpInstanceIds.push_back(legacy_ind.ndp_instance_id[i]);
- }
- hidl_ind->ndpInstanceIds = ndpInstanceIds;
-
- return true;
-}
-
-legacy_hal::wifi_rtt_type convertHidlRttTypeToLegacy(RttType type) {
- switch (type) {
- case RttType::ONE_SIDED:
- return legacy_hal::RTT_TYPE_1_SIDED;
- case RttType::TWO_SIDED:
- return legacy_hal::RTT_TYPE_2_SIDED;
- };
- CHECK(false);
-}
-
-RttType convertLegacyRttTypeToHidl(legacy_hal::wifi_rtt_type type) {
- switch (type) {
- case legacy_hal::RTT_TYPE_1_SIDED:
- return RttType::ONE_SIDED;
- case legacy_hal::RTT_TYPE_2_SIDED:
- return RttType::TWO_SIDED;
- };
- CHECK(false) << "Unknown legacy type: " << type;
-}
-
-legacy_hal::rtt_peer_type convertHidlRttPeerTypeToLegacy(RttPeerType type) {
- switch (type) {
- case RttPeerType::AP:
- return legacy_hal::RTT_PEER_AP;
- case RttPeerType::STA:
- return legacy_hal::RTT_PEER_STA;
- case RttPeerType::P2P_GO:
- return legacy_hal::RTT_PEER_P2P_GO;
- case RttPeerType::P2P_CLIENT:
- return legacy_hal::RTT_PEER_P2P_CLIENT;
- case RttPeerType::NAN:
- return legacy_hal::RTT_PEER_NAN;
- };
- CHECK(false);
-}
-
-legacy_hal::wifi_channel_width convertHidlWifiChannelWidthToLegacy(WifiChannelWidthInMhz type) {
- switch (type) {
- case WifiChannelWidthInMhz::WIDTH_20:
- return legacy_hal::WIFI_CHAN_WIDTH_20;
- case WifiChannelWidthInMhz::WIDTH_40:
- return legacy_hal::WIFI_CHAN_WIDTH_40;
- case WifiChannelWidthInMhz::WIDTH_80:
- return legacy_hal::WIFI_CHAN_WIDTH_80;
- case WifiChannelWidthInMhz::WIDTH_160:
- return legacy_hal::WIFI_CHAN_WIDTH_160;
- case WifiChannelWidthInMhz::WIDTH_80P80:
- return legacy_hal::WIFI_CHAN_WIDTH_80P80;
- case WifiChannelWidthInMhz::WIDTH_5:
- return legacy_hal::WIFI_CHAN_WIDTH_5;
- case WifiChannelWidthInMhz::WIDTH_10:
- return legacy_hal::WIFI_CHAN_WIDTH_10;
- case V1_6::WifiChannelWidthInMhz::WIDTH_320:
- return legacy_hal::WIFI_CHAN_WIDTH_320;
- case WifiChannelWidthInMhz::WIDTH_INVALID:
- return legacy_hal::WIFI_CHAN_WIDTH_INVALID;
- };
- CHECK(false);
-}
-
-V1_6::WifiChannelWidthInMhz convertLegacyWifiChannelWidthToHidl(
- legacy_hal::wifi_channel_width type) {
- switch (type) {
- case legacy_hal::WIFI_CHAN_WIDTH_20:
- return WifiChannelWidthInMhz::WIDTH_20;
- case legacy_hal::WIFI_CHAN_WIDTH_40:
- return WifiChannelWidthInMhz::WIDTH_40;
- case legacy_hal::WIFI_CHAN_WIDTH_80:
- return WifiChannelWidthInMhz::WIDTH_80;
- case legacy_hal::WIFI_CHAN_WIDTH_160:
- return WifiChannelWidthInMhz::WIDTH_160;
- case legacy_hal::WIFI_CHAN_WIDTH_80P80:
- return WifiChannelWidthInMhz::WIDTH_80P80;
- case legacy_hal::WIFI_CHAN_WIDTH_5:
- return WifiChannelWidthInMhz::WIDTH_5;
- case legacy_hal::WIFI_CHAN_WIDTH_10:
- return WifiChannelWidthInMhz::WIDTH_10;
- case legacy_hal::WIFI_CHAN_WIDTH_320:
- return V1_6::WifiChannelWidthInMhz::WIDTH_320;
- default:
- return WifiChannelWidthInMhz::WIDTH_INVALID;
- };
-}
-
-legacy_hal::wifi_rtt_preamble convertHidlRttPreambleToLegacy(V1_6::RttPreamble type) {
- switch (type) {
- case V1_6::RttPreamble::LEGACY:
- return legacy_hal::WIFI_RTT_PREAMBLE_LEGACY;
- case V1_6::RttPreamble::HT:
- return legacy_hal::WIFI_RTT_PREAMBLE_HT;
- case V1_6::RttPreamble::VHT:
- return legacy_hal::WIFI_RTT_PREAMBLE_VHT;
- case V1_6::RttPreamble::HE:
- return legacy_hal::WIFI_RTT_PREAMBLE_HE;
- case V1_6::RttPreamble::EHT:
- return legacy_hal::WIFI_RTT_PREAMBLE_EHT;
- };
- CHECK(false);
-}
-
-V1_6::RttPreamble convertLegacyRttPreambleToHidl(legacy_hal::wifi_rtt_preamble type) {
- switch (type) {
- case legacy_hal::WIFI_RTT_PREAMBLE_LEGACY:
- return V1_6::RttPreamble::LEGACY;
- case legacy_hal::WIFI_RTT_PREAMBLE_HT:
- return V1_6::RttPreamble::HT;
- case legacy_hal::WIFI_RTT_PREAMBLE_VHT:
- return V1_6::RttPreamble::VHT;
- case legacy_hal::WIFI_RTT_PREAMBLE_HE:
- return V1_6::RttPreamble::HE;
- case legacy_hal::WIFI_RTT_PREAMBLE_EHT:
- return V1_6::RttPreamble::EHT;
- };
- CHECK(false) << "Unknown legacy type: " << type;
-}
-
-legacy_hal::wifi_rtt_bw convertHidlRttBwToLegacy(RttBw type) {
- switch (type) {
- case RttBw::BW_5MHZ:
- return legacy_hal::WIFI_RTT_BW_5;
- case RttBw::BW_10MHZ:
- return legacy_hal::WIFI_RTT_BW_10;
- case RttBw::BW_20MHZ:
- return legacy_hal::WIFI_RTT_BW_20;
- case RttBw::BW_40MHZ:
- return legacy_hal::WIFI_RTT_BW_40;
- case RttBw::BW_80MHZ:
- return legacy_hal::WIFI_RTT_BW_80;
- case RttBw::BW_160MHZ:
- return legacy_hal::WIFI_RTT_BW_160;
- case RttBw::BW_320MHZ:
- return legacy_hal::WIFI_RTT_BW_320;
- };
- CHECK(false);
-}
-
-RttBw convertLegacyRttBwToHidl(legacy_hal::wifi_rtt_bw type) {
- switch (type) {
- case legacy_hal::WIFI_RTT_BW_5:
- return RttBw::BW_5MHZ;
- case legacy_hal::WIFI_RTT_BW_10:
- return RttBw::BW_10MHZ;
- case legacy_hal::WIFI_RTT_BW_20:
- return RttBw::BW_20MHZ;
- case legacy_hal::WIFI_RTT_BW_40:
- return RttBw::BW_40MHZ;
- case legacy_hal::WIFI_RTT_BW_80:
- return RttBw::BW_80MHZ;
- case legacy_hal::WIFI_RTT_BW_160:
- return RttBw::BW_160MHZ;
- case legacy_hal::WIFI_RTT_BW_320:
- return RttBw::BW_320MHZ;
- };
- CHECK(false) << "Unknown legacy type: " << type;
-}
-
-legacy_hal::wifi_motion_pattern convertHidlRttMotionPatternToLegacy(RttMotionPattern type) {
- switch (type) {
- case RttMotionPattern::NOT_EXPECTED:
- return legacy_hal::WIFI_MOTION_NOT_EXPECTED;
- case RttMotionPattern::EXPECTED:
- return legacy_hal::WIFI_MOTION_EXPECTED;
- case RttMotionPattern::UNKNOWN:
- return legacy_hal::WIFI_MOTION_UNKNOWN;
- };
- CHECK(false);
-}
-
-V1_6::WifiRatePreamble convertLegacyWifiRatePreambleToHidl(uint8_t preamble) {
- switch (preamble) {
- case 0:
- return V1_6::WifiRatePreamble::OFDM;
- case 1:
- return V1_6::WifiRatePreamble::CCK;
- case 2:
- return V1_6::WifiRatePreamble::HT;
- case 3:
- return V1_6::WifiRatePreamble::VHT;
- case 4:
- return V1_6::WifiRatePreamble::HE;
- case 5:
- return V1_6::WifiRatePreamble::EHT;
- default:
- return V1_6::WifiRatePreamble::RESERVED;
- };
- CHECK(false) << "Unknown legacy preamble: " << preamble;
-}
-
-WifiRateNss convertLegacyWifiRateNssToHidl(uint8_t nss) {
- switch (nss) {
- case 0:
- return WifiRateNss::NSS_1x1;
- case 1:
- return WifiRateNss::NSS_2x2;
- case 2:
- return WifiRateNss::NSS_3x3;
- case 3:
- return WifiRateNss::NSS_4x4;
- };
- CHECK(false) << "Unknown legacy nss: " << nss;
- return {};
-}
-
-RttStatus convertLegacyRttStatusToHidl(legacy_hal::wifi_rtt_status status) {
- switch (status) {
- case legacy_hal::RTT_STATUS_SUCCESS:
- return RttStatus::SUCCESS;
- case legacy_hal::RTT_STATUS_FAILURE:
- return RttStatus::FAILURE;
- case legacy_hal::RTT_STATUS_FAIL_NO_RSP:
- return RttStatus::FAIL_NO_RSP;
- case legacy_hal::RTT_STATUS_FAIL_REJECTED:
- return RttStatus::FAIL_REJECTED;
- case legacy_hal::RTT_STATUS_FAIL_NOT_SCHEDULED_YET:
- return RttStatus::FAIL_NOT_SCHEDULED_YET;
- case legacy_hal::RTT_STATUS_FAIL_TM_TIMEOUT:
- return RttStatus::FAIL_TM_TIMEOUT;
- case legacy_hal::RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL:
- return RttStatus::FAIL_AP_ON_DIFF_CHANNEL;
- case legacy_hal::RTT_STATUS_FAIL_NO_CAPABILITY:
- return RttStatus::FAIL_NO_CAPABILITY;
- case legacy_hal::RTT_STATUS_ABORTED:
- return RttStatus::ABORTED;
- case legacy_hal::RTT_STATUS_FAIL_INVALID_TS:
- return RttStatus::FAIL_INVALID_TS;
- case legacy_hal::RTT_STATUS_FAIL_PROTOCOL:
- return RttStatus::FAIL_PROTOCOL;
- case legacy_hal::RTT_STATUS_FAIL_SCHEDULE:
- return RttStatus::FAIL_SCHEDULE;
- case legacy_hal::RTT_STATUS_FAIL_BUSY_TRY_LATER:
- return RttStatus::FAIL_BUSY_TRY_LATER;
- case legacy_hal::RTT_STATUS_INVALID_REQ:
- return RttStatus::INVALID_REQ;
- case legacy_hal::RTT_STATUS_NO_WIFI:
- return RttStatus::NO_WIFI;
- case legacy_hal::RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE:
- return RttStatus::FAIL_FTM_PARAM_OVERRIDE;
- case legacy_hal::RTT_STATUS_NAN_RANGING_PROTOCOL_FAILURE:
- return RttStatus::FAILURE; // TODO: add HIDL enumeration
- case legacy_hal::RTT_STATUS_NAN_RANGING_CONCURRENCY_NOT_SUPPORTED:
- return RttStatus::FAILURE; // TODO: add HIDL enumeration
- };
- CHECK(false) << "Unknown legacy status: " << status;
-}
-
-bool convertHidlWifiChannelInfoToLegacy(const WifiChannelInfo& hidl_info,
- legacy_hal::wifi_channel_info* legacy_info) {
- if (!legacy_info) {
- return false;
- }
- *legacy_info = {};
- legacy_info->width = convertHidlWifiChannelWidthToLegacy(hidl_info.width);
- legacy_info->center_freq = hidl_info.centerFreq;
- legacy_info->center_freq0 = hidl_info.centerFreq0;
- legacy_info->center_freq1 = hidl_info.centerFreq1;
- return true;
-}
-
-bool convertLegacyWifiChannelInfoToHidl(const legacy_hal::wifi_channel_info& legacy_info,
- WifiChannelInfo* hidl_info) {
- if (!hidl_info) {
- return false;
- }
- *hidl_info = {};
- hidl_info->width = convertLegacyWifiChannelWidthToHidl(legacy_info.width);
- hidl_info->centerFreq = legacy_info.center_freq;
- hidl_info->centerFreq0 = legacy_info.center_freq0;
- hidl_info->centerFreq1 = legacy_info.center_freq1;
- return true;
-}
-
-bool convertHidlRttConfigToLegacy(const V1_6::RttConfig& hidl_config,
- legacy_hal::wifi_rtt_config* legacy_config) {
- if (!legacy_config) {
- return false;
- }
- *legacy_config = {};
- CHECK(hidl_config.addr.size() == sizeof(legacy_config->addr));
- memcpy(legacy_config->addr, hidl_config.addr.data(), hidl_config.addr.size());
- legacy_config->type = convertHidlRttTypeToLegacy(hidl_config.type);
- legacy_config->peer = convertHidlRttPeerTypeToLegacy(hidl_config.peer);
- if (!convertHidlWifiChannelInfoToLegacy(hidl_config.channel, &legacy_config->channel)) {
- return false;
- }
- legacy_config->burst_period = hidl_config.burstPeriod;
- legacy_config->num_burst = hidl_config.numBurst;
- legacy_config->num_frames_per_burst = hidl_config.numFramesPerBurst;
- legacy_config->num_retries_per_rtt_frame = hidl_config.numRetriesPerRttFrame;
- legacy_config->num_retries_per_ftmr = hidl_config.numRetriesPerFtmr;
- legacy_config->LCI_request = hidl_config.mustRequestLci;
- legacy_config->LCR_request = hidl_config.mustRequestLcr;
- legacy_config->burst_duration = hidl_config.burstDuration;
- legacy_config->preamble = convertHidlRttPreambleToLegacy(hidl_config.preamble);
- legacy_config->bw = convertHidlRttBwToLegacy(hidl_config.bw);
- return true;
-}
-
-bool convertHidlVectorOfRttConfigToLegacy(
- const std::vector<V1_6::RttConfig>& hidl_configs,
- std::vector<legacy_hal::wifi_rtt_config>* legacy_configs) {
- if (!legacy_configs) {
- return false;
- }
- *legacy_configs = {};
- for (const auto& hidl_config : hidl_configs) {
- legacy_hal::wifi_rtt_config legacy_config;
- if (!convertHidlRttConfigToLegacy(hidl_config, &legacy_config)) {
- return false;
- }
- legacy_configs->push_back(legacy_config);
- }
- return true;
-}
-
-bool convertHidlRttLciInformationToLegacy(const RttLciInformation& hidl_info,
- legacy_hal::wifi_lci_information* legacy_info) {
- if (!legacy_info) {
- return false;
- }
- *legacy_info = {};
- legacy_info->latitude = hidl_info.latitude;
- legacy_info->longitude = hidl_info.longitude;
- legacy_info->altitude = hidl_info.altitude;
- legacy_info->latitude_unc = hidl_info.latitudeUnc;
- legacy_info->longitude_unc = hidl_info.longitudeUnc;
- legacy_info->altitude_unc = hidl_info.altitudeUnc;
- legacy_info->motion_pattern = convertHidlRttMotionPatternToLegacy(hidl_info.motionPattern);
- legacy_info->floor = hidl_info.floor;
- legacy_info->height_above_floor = hidl_info.heightAboveFloor;
- legacy_info->height_unc = hidl_info.heightUnc;
- return true;
-}
-
-bool convertHidlRttLcrInformationToLegacy(const RttLcrInformation& hidl_info,
- legacy_hal::wifi_lcr_information* legacy_info) {
- if (!legacy_info) {
- return false;
- }
- *legacy_info = {};
- CHECK(hidl_info.countryCode.size() == sizeof(legacy_info->country_code));
- memcpy(legacy_info->country_code, hidl_info.countryCode.data(), hidl_info.countryCode.size());
- if (hidl_info.civicInfo.size() > sizeof(legacy_info->civic_info)) {
- return false;
- }
- legacy_info->length = hidl_info.civicInfo.size();
- memcpy(legacy_info->civic_info, hidl_info.civicInfo.c_str(), hidl_info.civicInfo.size());
- return true;
-}
-
-bool convertHidlRttResponderToLegacy(const V1_6::RttResponder& hidl_responder,
- legacy_hal::wifi_rtt_responder* legacy_responder) {
- if (!legacy_responder) {
- return false;
- }
- *legacy_responder = {};
- if (!convertHidlWifiChannelInfoToLegacy(hidl_responder.channel, &legacy_responder->channel)) {
- return false;
- }
- legacy_responder->preamble = convertHidlRttPreambleToLegacy(hidl_responder.preamble);
- return true;
-}
-
-bool convertLegacyRttResponderToHidl(const legacy_hal::wifi_rtt_responder& legacy_responder,
- V1_6::RttResponder* hidl_responder) {
- if (!hidl_responder) {
- return false;
- }
- *hidl_responder = {};
- if (!convertLegacyWifiChannelInfoToHidl(legacy_responder.channel, &hidl_responder->channel)) {
- return false;
- }
- hidl_responder->preamble = convertLegacyRttPreambleToHidl(legacy_responder.preamble);
- return true;
-}
-
-bool convertLegacyRttCapabilitiesToHidl(
- const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
- V1_6::RttCapabilities* hidl_capabilities) {
- if (!hidl_capabilities) {
- return false;
- }
- *hidl_capabilities = {};
- hidl_capabilities->rttOneSidedSupported = legacy_capabilities.rtt_one_sided_supported;
- hidl_capabilities->rttFtmSupported = legacy_capabilities.rtt_ftm_supported;
- hidl_capabilities->lciSupported = legacy_capabilities.lci_support;
- hidl_capabilities->lcrSupported = legacy_capabilities.lcr_support;
- hidl_capabilities->responderSupported = legacy_capabilities.responder_supported;
- hidl_capabilities->preambleSupport = 0;
- for (const auto flag : {legacy_hal::WIFI_RTT_PREAMBLE_LEGACY, legacy_hal::WIFI_RTT_PREAMBLE_HT,
- legacy_hal::WIFI_RTT_PREAMBLE_VHT, legacy_hal::WIFI_RTT_PREAMBLE_HE,
- legacy_hal::WIFI_RTT_PREAMBLE_EHT}) {
- if (legacy_capabilities.preamble_support & flag) {
- hidl_capabilities->preambleSupport |=
- static_cast<std::underlying_type<V1_6::RttPreamble>::type>(
- convertLegacyRttPreambleToHidl(flag));
- }
- }
- hidl_capabilities->bwSupport = 0;
- for (const auto flag :
- {legacy_hal::WIFI_RTT_BW_5, legacy_hal::WIFI_RTT_BW_10, legacy_hal::WIFI_RTT_BW_20,
- legacy_hal::WIFI_RTT_BW_40, legacy_hal::WIFI_RTT_BW_80, legacy_hal::WIFI_RTT_BW_160,
- legacy_hal::WIFI_RTT_BW_320}) {
- if (legacy_capabilities.bw_support & flag) {
- hidl_capabilities->bwSupport |=
- static_cast<std::underlying_type<RttBw>::type>(convertLegacyRttBwToHidl(flag));
- }
- }
- hidl_capabilities->mcVersion = legacy_capabilities.mc_version;
- return true;
-}
-
-bool convertLegacyWifiRateInfoToHidl(const legacy_hal::wifi_rate& legacy_rate,
- V1_6::WifiRateInfo* hidl_rate) {
- if (!hidl_rate) {
- return false;
- }
- *hidl_rate = {};
- hidl_rate->preamble = convertLegacyWifiRatePreambleToHidl(legacy_rate.preamble);
- hidl_rate->nss = convertLegacyWifiRateNssToHidl(legacy_rate.nss);
- hidl_rate->bw = convertLegacyWifiChannelWidthToHidl(
- static_cast<legacy_hal::wifi_channel_width>(legacy_rate.bw));
- hidl_rate->rateMcsIdx = legacy_rate.rateMcsIdx;
- hidl_rate->bitRateInKbps = legacy_rate.bitrate;
- return true;
-}
-
-bool convertLegacyRttResultToHidl(const legacy_hal::wifi_rtt_result& legacy_result,
- V1_6::RttResult* hidl_result) {
- if (!hidl_result) {
- return false;
- }
- *hidl_result = {};
- CHECK(sizeof(legacy_result.addr) == hidl_result->addr.size());
- memcpy(hidl_result->addr.data(), legacy_result.addr, sizeof(legacy_result.addr));
- hidl_result->burstNum = legacy_result.burst_num;
- hidl_result->measurementNumber = legacy_result.measurement_number;
- hidl_result->successNumber = legacy_result.success_number;
- hidl_result->numberPerBurstPeer = legacy_result.number_per_burst_peer;
- hidl_result->status = convertLegacyRttStatusToHidl(legacy_result.status);
- hidl_result->retryAfterDuration = legacy_result.retry_after_duration;
- hidl_result->type = convertLegacyRttTypeToHidl(legacy_result.type);
- hidl_result->rssi = legacy_result.rssi;
- hidl_result->rssiSpread = legacy_result.rssi_spread;
- if (!convertLegacyWifiRateInfoToHidl(legacy_result.tx_rate, &hidl_result->txRate)) {
- return false;
- }
- if (!convertLegacyWifiRateInfoToHidl(legacy_result.rx_rate, &hidl_result->rxRate)) {
- return false;
- }
- hidl_result->rtt = legacy_result.rtt;
- hidl_result->rttSd = legacy_result.rtt_sd;
- hidl_result->rttSpread = legacy_result.rtt_spread;
- hidl_result->distanceInMm = legacy_result.distance_mm;
- hidl_result->distanceSdInMm = legacy_result.distance_sd_mm;
- hidl_result->distanceSpreadInMm = legacy_result.distance_spread_mm;
- hidl_result->timeStampInUs = legacy_result.ts;
- hidl_result->burstDurationInMs = legacy_result.burst_duration;
- hidl_result->negotiatedBurstNum = legacy_result.negotiated_burst_num;
- if (legacy_result.LCI && !convertLegacyIeToHidl(*legacy_result.LCI, &hidl_result->lci)) {
- return false;
- }
- if (legacy_result.LCR && !convertLegacyIeToHidl(*legacy_result.LCR, &hidl_result->lcr)) {
- return false;
- }
- return true;
-}
-
-bool convertLegacyVectorOfRttResultToHidl(
- const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
- std::vector<V1_6::RttResult>* hidl_results) {
- if (!hidl_results) {
- return false;
- }
- *hidl_results = {};
- for (const auto legacy_result : legacy_results) {
- V1_6::RttResult hidl_result;
- if (!convertLegacyRttResultToHidl(*legacy_result, &hidl_result)) {
- return false;
- }
- hidl_results->push_back(hidl_result);
- }
- return true;
-}
-
-legacy_hal::wifi_interface_type convertHidlIfaceTypeToLegacy(IfaceType hidl_interface_type) {
- switch (hidl_interface_type) {
- case IfaceType::STA:
- return legacy_hal::WIFI_INTERFACE_TYPE_STA;
- case IfaceType::AP:
- return legacy_hal::WIFI_INTERFACE_TYPE_AP;
- case IfaceType::P2P:
- return legacy_hal::WIFI_INTERFACE_TYPE_P2P;
- case IfaceType::NAN:
- return legacy_hal::WIFI_INTERFACE_TYPE_NAN;
- }
- CHECK(false);
-}
-
-legacy_hal::wifi_multi_sta_use_case convertHidlMultiStaUseCaseToLegacy(
- V1_5::IWifiChip::MultiStaUseCase use_case) {
- switch (use_case) {
- case V1_5::IWifiChip::MultiStaUseCase::DUAL_STA_TRANSIENT_PREFER_PRIMARY:
- return legacy_hal::WIFI_DUAL_STA_TRANSIENT_PREFER_PRIMARY;
- case V1_5::IWifiChip::MultiStaUseCase::DUAL_STA_NON_TRANSIENT_UNBIASED:
- return legacy_hal::WIFI_DUAL_STA_NON_TRANSIENT_UNBIASED;
- }
- CHECK(false);
-}
-
-bool convertHidlCoexUnsafeChannelToLegacy(
- const V1_5::IWifiChip::CoexUnsafeChannel& hidl_unsafe_channel,
- legacy_hal::wifi_coex_unsafe_channel* legacy_unsafe_channel) {
- if (!legacy_unsafe_channel) {
- return false;
- }
- *legacy_unsafe_channel = {};
- switch (hidl_unsafe_channel.band) {
- case V1_5::WifiBand::BAND_24GHZ:
- legacy_unsafe_channel->band = legacy_hal::WLAN_MAC_2_4_BAND;
- break;
- case V1_5::WifiBand::BAND_5GHZ:
- legacy_unsafe_channel->band = legacy_hal::WLAN_MAC_5_0_BAND;
- break;
- default:
- return false;
- };
- legacy_unsafe_channel->channel = hidl_unsafe_channel.channel;
- legacy_unsafe_channel->power_cap_dbm = hidl_unsafe_channel.powerCapDbm;
- return true;
-}
-
-bool convertHidlVectorOfCoexUnsafeChannelToLegacy(
- const std::vector<V1_5::IWifiChip::CoexUnsafeChannel>& hidl_unsafe_channels,
- std::vector<legacy_hal::wifi_coex_unsafe_channel>* legacy_unsafe_channels) {
- if (!legacy_unsafe_channels) {
- return false;
- }
- *legacy_unsafe_channels = {};
- for (const auto& hidl_unsafe_channel : hidl_unsafe_channels) {
- legacy_hal::wifi_coex_unsafe_channel legacy_unsafe_channel;
- if (!hidl_struct_util::convertHidlCoexUnsafeChannelToLegacy(hidl_unsafe_channel,
- &legacy_unsafe_channel)) {
- return false;
- }
- legacy_unsafe_channels->push_back(legacy_unsafe_channel);
- }
- return true;
-}
-
-V1_6::WifiAntennaMode convertLegacyAntennaConfigurationToHidl(uint32_t antenna_cfg) {
- switch (antenna_cfg) {
- case legacy_hal::WIFI_ANTENNA_1X1:
- return V1_6::WifiAntennaMode::WIFI_ANTENNA_MODE_1X1;
- case legacy_hal::WIFI_ANTENNA_2X2:
- return V1_6::WifiAntennaMode::WIFI_ANTENNA_MODE_2X2;
- case legacy_hal::WIFI_ANTENNA_3X3:
- return V1_6::WifiAntennaMode::WIFI_ANTENNA_MODE_3X3;
- case legacy_hal::WIFI_ANTENNA_4X4:
- return V1_6::WifiAntennaMode::WIFI_ANTENNA_MODE_4X4;
- default:
- return V1_6::WifiAntennaMode::WIFI_ANTENNA_MODE_UNSPECIFIED;
- }
-}
-
-bool convertLegacyWifiRadioConfigurationToHidl(
- legacy_hal::wifi_radio_configuration* radio_configuration,
- V1_6::WifiRadioConfiguration* hidl_radio_configuration) {
- if (!hidl_radio_configuration) {
- return false;
- }
- *hidl_radio_configuration = {};
- hidl_radio_configuration->bandInfo =
- hidl_struct_util::convertLegacyMacBandToHidlWifiBand(radio_configuration->band);
- if (hidl_radio_configuration->bandInfo == V1_5::WifiBand::BAND_UNSPECIFIED) {
- LOG(ERROR) << "Unspecified band";
- return false;
- }
- hidl_radio_configuration->antennaMode =
- hidl_struct_util::convertLegacyAntennaConfigurationToHidl(
- radio_configuration->antenna_cfg);
- return true;
-}
-
-bool convertLegacyRadioCombinationsMatrixToHidl(
- legacy_hal::wifi_radio_combination_matrix* legacy_matrix,
- WifiRadioCombinationMatrix* hidl_matrix) {
- if (!hidl_matrix || !legacy_matrix) {
- return false;
- }
- *hidl_matrix = {};
-
- int num_combinations = legacy_matrix->num_radio_combinations;
- std::vector<V1_6::WifiRadioCombination> radio_combinations_vec;
- if (!num_combinations) {
- LOG(ERROR) << "zero radio combinations";
- return false;
- }
- wifi_radio_combination* l_radio_combinations_ptr = legacy_matrix->radio_combinations;
- for (int i = 0; i < num_combinations; i++) {
- int num_configurations = l_radio_combinations_ptr->num_radio_configurations;
- WifiRadioCombination radioCombination;
- std::vector<V1_6::WifiRadioConfiguration> radio_configurations_vec;
- if (!num_configurations) {
- LOG(ERROR) << "zero radio configurations";
- return false;
- }
- for (int j = 0; j < num_configurations; j++) {
- WifiRadioConfiguration radioConfiguration;
- wifi_radio_configuration* l_radio_configurations_ptr =
- &l_radio_combinations_ptr->radio_configurations[j];
- if (!hidl_struct_util::convertLegacyWifiRadioConfigurationToHidl(
- l_radio_configurations_ptr, &radioConfiguration)) {
- LOG(ERROR) << "Error converting wifi radio configuration";
- return false;
- }
- radio_configurations_vec.push_back(radioConfiguration);
- }
- radioCombination.radioConfigurations = radio_configurations_vec;
- radio_combinations_vec.push_back(radioCombination);
- l_radio_combinations_ptr =
- (wifi_radio_combination*)((u8*)l_radio_combinations_ptr +
- sizeof(wifi_radio_combination) +
- (sizeof(wifi_radio_configuration) * num_configurations));
- }
- hidl_matrix->radioCombinations = radio_combinations_vec;
- return true;
-}
-
-} // namespace hidl_struct_util
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/hidl_struct_util.h b/wifi/1.6/default/hidl_struct_util.h
deleted file mode 100644
index 2d4a5f1..0000000
--- a/wifi/1.6/default/hidl_struct_util.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 HIDL_STRUCT_UTIL_H_
-#define HIDL_STRUCT_UTIL_H_
-
-#include <vector>
-
-#include <android/hardware/wifi/1.0/IWifiChip.h>
-#include <android/hardware/wifi/1.0/types.h>
-#include <android/hardware/wifi/1.2/types.h>
-#include <android/hardware/wifi/1.3/types.h>
-#include <android/hardware/wifi/1.4/IWifiChipEventCallback.h>
-#include <android/hardware/wifi/1.4/types.h>
-#include <android/hardware/wifi/1.6/IWifiChip.h>
-#include <android/hardware/wifi/1.6/types.h>
-
-#include "wifi_legacy_hal.h"
-
-/**
- * This file contains a bunch of functions to convert structs from the legacy
- * HAL to HIDL and vice versa.
- * TODO(b/32093047): Add unit tests for these conversion methods in the VTS test
- * suite.
- */
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace hidl_struct_util {
-using namespace android::hardware::wifi::V1_0;
-
-// Chip conversion methods.
-bool convertLegacyFeaturesToHidlChipCapabilities(uint64_t legacy_feature_set,
- uint32_t legacy_logger_feature_set,
- uint32_t* hidl_caps);
-bool convertLegacyDebugRingBufferStatusToHidl(
- const legacy_hal::wifi_ring_buffer_status& legacy_status,
- WifiDebugRingBufferStatus* hidl_status);
-bool convertLegacyVectorOfDebugRingBufferStatusToHidl(
- const std::vector<legacy_hal::wifi_ring_buffer_status>& legacy_status_vec,
- std::vector<WifiDebugRingBufferStatus>* hidl_status_vec);
-bool convertLegacyWakeReasonStatsToHidl(const legacy_hal::WakeReasonStats& legacy_stats,
- WifiDebugHostWakeReasonStats* hidl_stats);
-legacy_hal::wifi_power_scenario convertHidlTxPowerScenarioToLegacy(
- V1_1::IWifiChip::TxPowerScenario hidl_scenario);
-legacy_hal::wifi_latency_mode convertHidlLatencyModeToLegacy(
- V1_3::IWifiChip::LatencyMode hidl_latency_mode);
-legacy_hal::wifi_power_scenario convertHidlTxPowerScenarioToLegacy_1_2(
- V1_2::IWifiChip::TxPowerScenario hidl_scenario);
-bool convertLegacyWifiMacInfosToHidl(
- const std::vector<legacy_hal::WifiMacInfo>& legacy_mac_infos,
- std::vector<V1_4::IWifiChipEventCallback::RadioModeInfo>* hidl_radio_mode_infos);
-legacy_hal::wifi_interface_type convertHidlIfaceTypeToLegacy(IfaceType hidl_interface_type);
-legacy_hal::wifi_multi_sta_use_case convertHidlMultiStaUseCaseToLegacy(
- V1_5::IWifiChip::MultiStaUseCase use_case);
-bool convertHidlCoexUnsafeChannelToLegacy(
- const V1_5::IWifiChip::CoexUnsafeChannel& hidl_unsafe_channel,
- legacy_hal::wifi_coex_unsafe_channel* legacy_unsafe_channel);
-bool convertHidlVectorOfCoexUnsafeChannelToLegacy(
- const std::vector<V1_5::IWifiChip::CoexUnsafeChannel>& hidl_unsafe_channels,
- std::vector<legacy_hal::wifi_coex_unsafe_channel>* legacy_unsafe_channels);
-bool convertLegacyRadioCombinationsMatrixToHidl(
- legacy_hal::wifi_radio_combination_matrix* legacy_matrix,
- V1_6::WifiRadioCombinationMatrix* hidl_matrix);
-V1_5::WifiBand convertLegacyMacBandToHidlWifiBand(uint32_t band);
-V1_6::WifiAntennaMode convertLegacyAntennaConfigurationToHidl(uint32_t antenna_cfg);
-
-// STA iface conversion methods.
-bool convertLegacyFeaturesToHidlStaCapabilities(uint64_t legacy_feature_set,
- uint32_t legacy_logger_feature_set,
- uint32_t* hidl_caps);
-bool convertLegacyApfCapabilitiesToHidl(const legacy_hal::PacketFilterCapabilities& legacy_caps,
- StaApfPacketFilterCapabilities* hidl_caps);
-bool convertLegacyGscanCapabilitiesToHidl(const legacy_hal::wifi_gscan_capabilities& legacy_caps,
- StaBackgroundScanCapabilities* hidl_caps);
-legacy_hal::wifi_band convertHidlWifiBandToLegacy(V1_0::WifiBand band);
-bool convertHidlGscanParamsToLegacy(const StaBackgroundScanParameters& hidl_scan_params,
- legacy_hal::wifi_scan_cmd_params* legacy_scan_params);
-// |has_ie_data| indicates whether or not the wifi_scan_result includes 802.11
-// Information Elements (IEs)
-bool convertLegacyGscanResultToHidl(const legacy_hal::wifi_scan_result& legacy_scan_result,
- bool has_ie_data, StaScanResult* hidl_scan_result);
-// |cached_results| is assumed to not include IEs.
-bool convertLegacyVectorOfCachedGscanResultsToHidl(
- const std::vector<legacy_hal::wifi_cached_scan_results>& legacy_cached_scan_results,
- std::vector<StaScanData>* hidl_scan_datas);
-bool convertLegacyLinkLayerStatsToHidl(const legacy_hal::LinkLayerStats& legacy_stats,
- V1_6::StaLinkLayerStats* hidl_stats);
-bool convertLegacyRoamingCapabilitiesToHidl(
- const legacy_hal::wifi_roaming_capabilities& legacy_caps,
- StaRoamingCapabilities* hidl_caps);
-bool convertHidlRoamingConfigToLegacy(const StaRoamingConfig& hidl_config,
- legacy_hal::wifi_roaming_config* legacy_config);
-legacy_hal::fw_roaming_state_t convertHidlRoamingStateToLegacy(StaRoamingState state);
-bool convertLegacyVectorOfDebugTxPacketFateToHidl(
- const std::vector<legacy_hal::wifi_tx_report>& legacy_fates,
- std::vector<WifiDebugTxPacketFateReport>* hidl_fates);
-bool convertLegacyVectorOfDebugRxPacketFateToHidl(
- const std::vector<legacy_hal::wifi_rx_report>& legacy_fates,
- std::vector<WifiDebugRxPacketFateReport>* hidl_fates);
-
-// NAN iface conversion methods.
-void convertToWifiNanStatus(legacy_hal::NanStatusType type, const char* str, size_t max_len,
- WifiNanStatus* wifiNanStatus);
-bool convertHidlNanEnableRequestToLegacy(const V1_4::NanEnableRequest& hidl_request,
- legacy_hal::NanEnableRequest* legacy_request);
-bool convertHidlNanConfigRequestToLegacy(const V1_4::NanConfigRequest& hidl_request,
- legacy_hal::NanConfigRequest* legacy_request);
-bool convertHidlNanEnableRequest_1_6ToLegacy(
- const V1_4::NanEnableRequest& hidl_request1,
- const V1_6::NanConfigRequestSupplemental& hidl_request2,
- legacy_hal::NanEnableRequest* legacy_request);
-bool convertHidlNanConfigRequest_1_6ToLegacy(
- const V1_4::NanConfigRequest& hidl_request1,
- const V1_6::NanConfigRequestSupplemental& hidl_request2,
- legacy_hal::NanConfigRequest* legacy_request);
-bool convertHidlNanPublishRequestToLegacy(const V1_6::NanPublishRequest& hidl_request,
- legacy_hal::NanPublishRequest* legacy_request);
-bool convertHidlNanSubscribeRequestToLegacy(const V1_0::NanSubscribeRequest& hidl_request,
- legacy_hal::NanSubscribeRequest* legacy_request);
-bool convertHidlNanTransmitFollowupRequestToLegacy(
- const NanTransmitFollowupRequest& hidl_request,
- legacy_hal::NanTransmitFollowupRequest* legacy_request);
-bool convertHidlNanDataPathInitiatorRequestToLegacy(
- const V1_0::NanInitiateDataPathRequest& hidl_request,
- legacy_hal::NanDataPathInitiatorRequest* legacy_request);
-bool convertHidlNanDataPathIndicationResponseToLegacy(
- const V1_0::NanRespondToDataPathIndicationRequest& hidl_response,
- legacy_hal::NanDataPathIndicationResponse* legacy_response);
-bool convertHidlNanDataPathInitiatorRequest_1_6ToLegacy(
- const V1_6::NanInitiateDataPathRequest& hidl_request,
- legacy_hal::NanDataPathInitiatorRequest* legacy_request);
-bool convertHidlNanDataPathIndicationResponse_1_6ToLegacy(
- const V1_6::NanRespondToDataPathIndicationRequest& hidl_response,
- legacy_hal::NanDataPathIndicationResponse* legacy_response);
-
-bool convertLegacyNanResponseHeaderToHidl(const legacy_hal::NanResponseMsg& legacy_response,
- WifiNanStatus* wifiNanStatus);
-bool convertLegacyNanCapabilitiesResponseToHidl(const legacy_hal::NanCapabilities& legacy_response,
- V1_6::NanCapabilities* hidl_response);
-bool convertLegacyNanMatchIndToHidl(const legacy_hal::NanMatchInd& legacy_ind,
- V1_6::NanMatchInd* hidl_ind);
-bool convertLegacyNanFollowupIndToHidl(const legacy_hal::NanFollowupInd& legacy_ind,
- NanFollowupReceivedInd* hidl_ind);
-bool convertLegacyNanDataPathRequestIndToHidl(const legacy_hal::NanDataPathRequestInd& legacy_ind,
- NanDataPathRequestInd* hidl_ind);
-bool convertLegacyNanDataPathConfirmIndToHidl(const legacy_hal::NanDataPathConfirmInd& legacy_ind,
- V1_6::NanDataPathConfirmInd* hidl_ind);
-bool convertLegacyNanDataPathScheduleUpdateIndToHidl(
- const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
- V1_6::NanDataPathScheduleUpdateInd* hidl_ind);
-
-// RTT controller conversion methods.
-bool convertHidlVectorOfRttConfigToLegacy(const std::vector<V1_6::RttConfig>& hidl_configs,
- std::vector<legacy_hal::wifi_rtt_config>* legacy_configs);
-bool convertHidlRttLciInformationToLegacy(const RttLciInformation& hidl_info,
- legacy_hal::wifi_lci_information* legacy_info);
-bool convertHidlRttLcrInformationToLegacy(const RttLcrInformation& hidl_info,
- legacy_hal::wifi_lcr_information* legacy_info);
-bool convertHidlRttResponderToLegacy(const V1_6::RttResponder& hidl_responder,
- legacy_hal::wifi_rtt_responder* legacy_responder);
-bool convertHidlWifiChannelInfoToLegacy(const V1_6::WifiChannelInfo& hidl_info,
- legacy_hal::wifi_channel_info* legacy_info);
-bool convertLegacyRttResponderToHidl(const legacy_hal::wifi_rtt_responder& legacy_responder,
- V1_6::RttResponder* hidl_responder);
-bool convertLegacyRttCapabilitiesToHidl(
- const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
- V1_6::RttCapabilities* hidl_capabilities);
-bool convertLegacyVectorOfRttResultToHidl(
- const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
- std::vector<V1_6::RttResult>* hidl_results);
-uint32_t convertHidlWifiBandToLegacyMacBand(V1_5::WifiBand band);
-uint32_t convertHidlWifiIfaceModeToLegacy(uint32_t hidl_iface_mask);
-uint32_t convertHidlUsableChannelFilterToLegacy(uint32_t hidl_filter_mask);
-bool convertLegacyWifiUsableChannelsToHidl(
- const std::vector<legacy_hal::wifi_usable_channel>& legacy_usable_channels,
- std::vector<V1_6::WifiUsableChannel>* hidl_usable_channels);
-bool convertLegacyPeerInfoStatsToHidl(const legacy_hal::WifiPeerInfo& legacy_peer_info_stats,
- V1_6::StaPeerInfo* hidl_peer_info_stats);
-bool convertLegacyWifiRateInfoToHidl(const legacy_hal::wifi_rate& legacy_rate,
- V1_6::WifiRateInfo* hidl_rate);
-} // namespace hidl_struct_util
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // HIDL_STRUCT_UTIL_H_
diff --git a/wifi/1.6/default/service.cpp b/wifi/1.6/default/service.cpp
deleted file mode 100644
index c874d8b..0000000
--- a/wifi/1.6/default/service.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-#include <hidl/HidlLazyUtils.h>
-#include <hidl/HidlTransportSupport.h>
-#include <signal.h>
-#include <utils/Looper.h>
-#include <utils/StrongPointer.h>
-
-#include "wifi.h"
-#include "wifi_feature_flags.h"
-#include "wifi_legacy_hal.h"
-#include "wifi_legacy_hal_factory.h"
-#include "wifi_mode_controller.h"
-
-using android::hardware::configureRpcThreadpool;
-using android::hardware::joinRpcThreadpool;
-using android::hardware::LazyServiceRegistrar;
-using android::hardware::wifi::V1_6::implementation::feature_flags::WifiFeatureFlags;
-using android::hardware::wifi::V1_6::implementation::legacy_hal::WifiLegacyHal;
-using android::hardware::wifi::V1_6::implementation::legacy_hal::WifiLegacyHalFactory;
-using android::hardware::wifi::V1_6::implementation::mode_controller::WifiModeController;
-
-#ifdef LAZY_SERVICE
-const bool kLazyService = true;
-#else
-const bool kLazyService = false;
-#endif
-
-int main(int /*argc*/, char** argv) {
- signal(SIGPIPE, SIG_IGN);
- android::base::InitLogging(argv, android::base::LogdLogger(android::base::SYSTEM));
- LOG(INFO) << "Wifi Hal is booting up...";
-
- configureRpcThreadpool(1, true /* callerWillJoin */);
-
- const auto iface_tool = std::make_shared<android::wifi_system::InterfaceTool>();
- const auto legacy_hal_factory = std::make_shared<WifiLegacyHalFactory>(iface_tool);
-
- // Setup hwbinder service
- android::sp<android::hardware::wifi::V1_6::IWifi> service =
- new android::hardware::wifi::V1_6::implementation::Wifi(
- iface_tool, legacy_hal_factory, std::make_shared<WifiModeController>(),
- std::make_shared<WifiFeatureFlags>());
- if (kLazyService) {
- auto registrar = LazyServiceRegistrar::getInstance();
- CHECK_EQ(registrar.registerService(service), android::NO_ERROR)
- << "Failed to register wifi HAL";
- } else {
- CHECK_EQ(service->registerAsService(), android::NO_ERROR) << "Failed to register wifi HAL";
- }
-
- joinRpcThreadpool();
-
- LOG(INFO) << "Wifi Hal is terminating...";
- return 0;
-}
diff --git a/wifi/1.6/default/tests/wifi_nan_iface_unit_tests.cpp b/wifi/1.6/default/tests/wifi_nan_iface_unit_tests.cpp
deleted file mode 100644
index 8a5ddcd..0000000
--- a/wifi/1.6/default/tests/wifi_nan_iface_unit_tests.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2019, The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-#include <android-base/macros.h>
-#include <cutils/properties.h>
-#include <gmock/gmock.h>
-
-#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
-#include "wifi_nan_iface.h"
-
-#include "mock_interface_tool.h"
-#include "mock_wifi_feature_flags.h"
-#include "mock_wifi_iface_util.h"
-#include "mock_wifi_legacy_hal.h"
-
-using testing::NiceMock;
-using testing::Return;
-using testing::Test;
-
-namespace {
-constexpr char kIfaceName[] = "mockWlan0";
-} // namespace
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-
-using android::hardware::wifi::V1_2::NanDataPathConfirmInd;
-
-bool CaptureIfaceEventHandlers(const std::string& /* iface_name*/,
- iface_util::IfaceEventHandlers in_iface_event_handlers,
- iface_util::IfaceEventHandlers* out_iface_event_handlers) {
- *out_iface_event_handlers = in_iface_event_handlers;
- return true;
-}
-
-class MockNanIfaceEventCallback : public V1_5::IWifiNanIfaceEventCallback {
- public:
- MockNanIfaceEventCallback() = default;
-
- MOCK_METHOD3(notifyCapabilitiesResponse,
- Return<void>(uint16_t, const WifiNanStatus&,
- const android::hardware::wifi::V1_0::NanCapabilities&));
- MOCK_METHOD2(notifyEnableResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD2(notifyConfigResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD2(notifyDisableResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD3(notifyStartPublishResponse, Return<void>(uint16_t, const WifiNanStatus&, uint8_t));
- MOCK_METHOD2(notifyStopPublishResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD3(notifyStartSubscribeResponse,
- Return<void>(uint16_t, const WifiNanStatus&, uint8_t));
- MOCK_METHOD2(notifyStopSubscribeResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD2(notifyTransmitFollowupResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD2(notifyCreateDataInterfaceResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD2(notifyDeleteDataInterfaceResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD3(notifyInitiateDataPathResponse,
- Return<void>(uint16_t, const WifiNanStatus&, uint32_t));
- MOCK_METHOD2(notifyRespondToDataPathIndicationResponse,
- Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD2(notifyTerminateDataPathResponse, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD1(eventClusterEvent, Return<void>(const NanClusterEventInd&));
- MOCK_METHOD1(eventDisabled, Return<void>(const WifiNanStatus&));
- MOCK_METHOD2(eventPublishTerminated, Return<void>(uint8_t, const WifiNanStatus&));
- MOCK_METHOD2(eventSubscribeTerminated, Return<void>(uint8_t, const WifiNanStatus&));
- MOCK_METHOD1(eventMatch, Return<void>(const V1_0::NanMatchInd&));
- MOCK_METHOD1(eventMatch_1_6, Return<void>(const NanMatchInd&));
- MOCK_METHOD2(eventMatchExpired, Return<void>(uint8_t, uint32_t));
- MOCK_METHOD1(eventFollowupReceived, Return<void>(const NanFollowupReceivedInd&));
- MOCK_METHOD2(eventTransmitFollowup, Return<void>(uint16_t, const WifiNanStatus&));
- MOCK_METHOD1(eventDataPathRequest, Return<void>(const NanDataPathRequestInd&));
- MOCK_METHOD1(eventDataPathConfirm,
- Return<void>(const android::hardware::wifi::V1_0::NanDataPathConfirmInd&));
- MOCK_METHOD1(eventDataPathTerminated, Return<void>(uint32_t));
- MOCK_METHOD1(eventDataPathConfirm_1_2,
- Return<void>(const android::hardware::wifi::V1_2::NanDataPathConfirmInd&));
- MOCK_METHOD1(eventDataPathConfirm_1_6, Return<void>(const NanDataPathConfirmInd&));
- MOCK_METHOD1(eventDataPathScheduleUpdate,
- Return<void>(const android::hardware::wifi::V1_2::NanDataPathScheduleUpdateInd&));
- MOCK_METHOD1(eventDataPathScheduleUpdate_1_6,
- Return<void>(const NanDataPathScheduleUpdateInd&));
- MOCK_METHOD3(notifyCapabilitiesResponse_1_5,
- Return<void>(uint16_t, const WifiNanStatus&, const V1_5::NanCapabilities&));
-};
-
-class WifiNanIfaceTest : public Test {
- protected:
- legacy_hal::wifi_hal_fn fake_func_table_;
- std::shared_ptr<NiceMock<wifi_system::MockInterfaceTool>> iface_tool_{
- new NiceMock<wifi_system::MockInterfaceTool>};
- std::shared_ptr<NiceMock<legacy_hal::MockWifiLegacyHal>> legacy_hal_{
- new NiceMock<legacy_hal::MockWifiLegacyHal>(iface_tool_, fake_func_table_, true)};
- std::shared_ptr<NiceMock<iface_util::MockWifiIfaceUtil>> iface_util_{
- new NiceMock<iface_util::MockWifiIfaceUtil>(iface_tool_, legacy_hal_)};
-};
-
-TEST_F(WifiNanIfaceTest, IfacEventHandlers_OnStateToggleOffOn) {
- iface_util::IfaceEventHandlers captured_iface_event_handlers = {};
- EXPECT_CALL(*legacy_hal_, nanRegisterCallbackHandlers(testing::_, testing::_))
- .WillOnce(testing::Return(legacy_hal::WIFI_SUCCESS));
- EXPECT_CALL(*iface_util_, registerIfaceEventHandlers(testing::_, testing::_))
- .WillOnce(testing::Invoke(bind(CaptureIfaceEventHandlers, std::placeholders::_1,
- std::placeholders::_2, &captured_iface_event_handlers)));
- sp<WifiNanIface> nan_iface = new WifiNanIface(kIfaceName, false, legacy_hal_, iface_util_);
-
- // Register a mock nan event callback.
- sp<NiceMock<MockNanIfaceEventCallback>> mock_event_callback{
- new NiceMock<MockNanIfaceEventCallback>};
- nan_iface->registerEventCallback(mock_event_callback, [](const WifiStatus& status) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- });
- // Ensure that the eventDisabled() function in mock callback will be
- // invoked.
- WifiNanStatus expected_nan_status = {NanStatusType::UNSUPPORTED_CONCURRENCY_NAN_DISABLED, ""};
- EXPECT_CALL(*mock_event_callback, eventDisabled(expected_nan_status)).Times(1);
-
- // Trigger the iface state toggle callback.
- captured_iface_event_handlers.on_state_toggle_off_on(kIfaceName);
-}
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/wifi.h b/wifi/1.6/default/wifi.h
deleted file mode 100644
index 435358e..0000000
--- a/wifi/1.6/default/wifi.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_H_
-#define WIFI_H_
-
-// HACK: NAN is a macro defined in math.h, which can be included in various
-// headers. This wifi HAL uses an enum called NAN, which does not compile when
-// the macro is defined. Undefine NAN to work around it.
-#undef NAN
-#include <android/hardware/wifi/1.6/IWifi.h>
-
-#include <android-base/macros.h>
-#include <utils/Looper.h>
-#include <functional>
-
-#include "hidl_callback_util.h"
-#include "wifi_chip.h"
-#include "wifi_feature_flags.h"
-#include "wifi_legacy_hal.h"
-#include "wifi_legacy_hal_factory.h"
-#include "wifi_mode_controller.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-
-/**
- * Root HIDL interface object used to control the Wifi HAL.
- */
-class Wifi : public V1_6::IWifi {
- public:
- Wifi(const std::shared_ptr<wifi_system::InterfaceTool> iface_tool,
- const std::shared_ptr<legacy_hal::WifiLegacyHalFactory> legacy_hal_factory,
- const std::shared_ptr<mode_controller::WifiModeController> mode_controller,
- const std::shared_ptr<feature_flags::WifiFeatureFlags> feature_flags);
-
- bool isValid();
-
- // HIDL methods exposed.
- Return<void> registerEventCallback(const sp<V1_0::IWifiEventCallback>& event_callback,
- registerEventCallback_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_5(const sp<V1_5::IWifiEventCallback>& event_callback,
- registerEventCallback_1_5_cb hidl_status_cb) override;
- Return<bool> isStarted() override;
- Return<void> start(start_cb hidl_status_cb) override;
- Return<void> stop(stop_cb hidl_status_cb) override;
- Return<void> getChipIds(getChipIds_cb hidl_status_cb) override;
- Return<void> getChip(ChipId chip_id, getChip_cb hidl_status_cb) override;
- Return<void> debug(const hidl_handle& handle, const hidl_vec<hidl_string>& options) override;
-
- private:
- enum class RunState { STOPPED, STARTED, STOPPING };
-
- // Corresponding worker functions for the HIDL methods.
- WifiStatus registerEventCallbackInternal(
- const sp<V1_0::IWifiEventCallback>& event_callback __unused);
- WifiStatus registerEventCallbackInternal_1_5(
- const sp<V1_5::IWifiEventCallback>& event_callback);
- WifiStatus startInternal();
- WifiStatus stopInternal(std::unique_lock<std::recursive_mutex>* lock);
- std::pair<WifiStatus, std::vector<ChipId>> getChipIdsInternal();
- std::pair<WifiStatus, sp<V1_4::IWifiChip>> getChipInternal(ChipId chip_id);
-
- WifiStatus initializeModeControllerAndLegacyHal();
- WifiStatus stopLegacyHalAndDeinitializeModeController(
- std::unique_lock<std::recursive_mutex>* lock);
- ChipId getChipIdFromWifiChip(sp<WifiChip>& chip);
-
- // Instance is created in this root level |IWifi| HIDL interface object
- // and shared with all the child HIDL interface objects.
- std::shared_ptr<wifi_system::InterfaceTool> iface_tool_;
- std::shared_ptr<legacy_hal::WifiLegacyHalFactory> legacy_hal_factory_;
- std::shared_ptr<mode_controller::WifiModeController> mode_controller_;
- std::vector<std::shared_ptr<legacy_hal::WifiLegacyHal>> legacy_hals_;
- std::shared_ptr<feature_flags::WifiFeatureFlags> feature_flags_;
- RunState run_state_;
- std::vector<sp<WifiChip>> chips_;
- hidl_callback_util::HidlCallbackHandler<V1_5::IWifiEventCallback> event_cb_handler_;
-
- DISALLOW_COPY_AND_ASSIGN(Wifi);
-};
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_H_
diff --git a/wifi/1.6/default/wifi_ap_iface.cpp b/wifi/1.6/default/wifi_ap_iface.cpp
deleted file mode 100644
index b2957db..0000000
--- a/wifi/1.6/default/wifi_ap_iface.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-
-#include "hidl_return_util.h"
-#include "hidl_struct_util.h"
-#include "wifi_ap_iface.h"
-#include "wifi_status_util.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
-
-WifiApIface::WifiApIface(const std::string& ifname, const std::vector<std::string>& instances,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
- : ifname_(ifname),
- instances_(instances),
- legacy_hal_(legacy_hal),
- iface_util_(iface_util),
- is_valid_(true) {}
-
-void WifiApIface::invalidate() {
- legacy_hal_.reset();
- is_valid_ = false;
-}
-
-bool WifiApIface::isValid() {
- return is_valid_;
-}
-
-std::string WifiApIface::getName() {
- return ifname_;
-}
-
-void WifiApIface::removeInstance(std::string instance) {
- instances_.erase(std::remove(instances_.begin(), instances_.end(), instance), instances_.end());
-}
-
-Return<void> WifiApIface::getName(getName_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::getNameInternal, hidl_status_cb);
-}
-
-Return<void> WifiApIface::getType(getType_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::getTypeInternal, hidl_status_cb);
-}
-
-Return<void> WifiApIface::setCountryCode(const hidl_array<int8_t, 2>& code,
- setCountryCode_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::setCountryCodeInternal, hidl_status_cb, code);
-}
-
-Return<void> WifiApIface::getValidFrequenciesForBand(V1_0::WifiBand band,
- getValidFrequenciesForBand_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::getValidFrequenciesForBandInternal, hidl_status_cb, band);
-}
-
-Return<void> WifiApIface::setMacAddress(const hidl_array<uint8_t, 6>& mac,
- setMacAddress_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::setMacAddressInternal, hidl_status_cb, mac);
-}
-
-Return<void> WifiApIface::getFactoryMacAddress(getFactoryMacAddress_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::getFactoryMacAddressInternal, hidl_status_cb,
- instances_.size() > 0 ? instances_[0] : ifname_);
-}
-
-Return<void> WifiApIface::resetToFactoryMacAddress(resetToFactoryMacAddress_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::resetToFactoryMacAddressInternal, hidl_status_cb);
-}
-
-Return<void> WifiApIface::getBridgedInstances(getBridgedInstances_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiApIface::getBridgedInstancesInternal, hidl_status_cb);
-}
-
-std::pair<WifiStatus, std::string> WifiApIface::getNameInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), ifname_};
-}
-
-std::pair<WifiStatus, IfaceType> WifiApIface::getTypeInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), IfaceType::AP};
-}
-
-WifiStatus WifiApIface::setCountryCodeInternal(const std::array<int8_t, 2>& code) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->setCountryCode(
- instances_.size() > 0 ? instances_[0] : ifname_, code);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, std::vector<WifiChannelInMhz>>
-WifiApIface::getValidFrequenciesForBandInternal(V1_0::WifiBand band) {
- static_assert(sizeof(WifiChannelInMhz) == sizeof(uint32_t), "Size mismatch");
- legacy_hal::wifi_error legacy_status;
- std::vector<uint32_t> valid_frequencies;
- std::tie(legacy_status, valid_frequencies) = legacy_hal_.lock()->getValidFrequenciesForBand(
- instances_.size() > 0 ? instances_[0] : ifname_,
- hidl_struct_util::convertHidlWifiBandToLegacy(band));
- return {createWifiStatusFromLegacyError(legacy_status), valid_frequencies};
-}
-
-WifiStatus WifiApIface::setMacAddressInternal(const std::array<uint8_t, 6>& mac) {
- // Support random MAC up to 2 interfaces
- if (instances_.size() == 2) {
- int rbyte = 1;
- for (auto const& intf : instances_) {
- std::array<uint8_t, 6> rmac = mac;
- // reverse the bits to avoid collision
- rmac[rbyte] = 0xff - rmac[rbyte];
- if (!iface_util_.lock()->setMacAddress(intf, rmac)) {
- LOG(INFO) << "Failed to set random mac address on " << intf;
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- rbyte++;
- }
- }
- // It also needs to set mac address for bridged interface, otherwise the mac
- // address of bridged interface will be changed after one of instance
- // down.
- if (!iface_util_.lock()->setMacAddress(ifname_, mac)) {
- LOG(ERROR) << "Fail to config MAC for interface " << ifname_;
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-std::pair<WifiStatus, std::array<uint8_t, 6>> WifiApIface::getFactoryMacAddressInternal(
- const std::string& ifaceName) {
- std::array<uint8_t, 6> mac = iface_util_.lock()->getFactoryMacAddress(ifaceName);
- if (mac[0] == 0 && mac[1] == 0 && mac[2] == 0 && mac[3] == 0 && mac[4] == 0 && mac[5] == 0) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), mac};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), mac};
-}
-
-WifiStatus WifiApIface::resetToFactoryMacAddressInternal() {
- std::pair<WifiStatus, std::array<uint8_t, 6>> getMacResult;
- if (instances_.size() == 2) {
- for (auto const& intf : instances_) {
- getMacResult = getFactoryMacAddressInternal(intf);
- LOG(DEBUG) << "Reset MAC to factory MAC on " << intf;
- if (getMacResult.first.code != WifiStatusCode::SUCCESS ||
- !iface_util_.lock()->setMacAddress(intf, getMacResult.second)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- }
- // It needs to set mac address for bridged interface, otherwise the mac
- // address of the bridged interface will be changed after one of the
- // instance down. Thus we are generating a random MAC address for the
- // bridged interface even if we got the request to reset the Factory
- // MAC. Since the bridged interface is an internal interface for the
- // operation of bpf and others networking operation.
- if (!iface_util_.lock()->setMacAddress(ifname_,
- iface_util_.lock()->createRandomMacAddress())) {
- LOG(ERROR) << "Fail to config MAC for bridged interface " << ifname_;
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- } else {
- getMacResult = getFactoryMacAddressInternal(ifname_);
- LOG(DEBUG) << "Reset MAC to factory MAC on " << ifname_;
- if (getMacResult.first.code != WifiStatusCode::SUCCESS ||
- !iface_util_.lock()->setMacAddress(ifname_, getMacResult.second)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-std::pair<WifiStatus, std::vector<hidl_string>> WifiApIface::getBridgedInstancesInternal() {
- std::vector<hidl_string> instances;
- for (const auto& instance_name : instances_) {
- instances.push_back(instance_name);
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), instances};
-}
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/wifi_ap_iface.h b/wifi/1.6/default/wifi_ap_iface.h
deleted file mode 100644
index d1c0642..0000000
--- a/wifi/1.6/default/wifi_ap_iface.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_AP_IFACE_H_
-#define WIFI_AP_IFACE_H_
-
-#include <android-base/macros.h>
-#include <android/hardware/wifi/1.5/IWifiApIface.h>
-
-#include "wifi_iface_util.h"
-#include "wifi_legacy_hal.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
-
-/**
- * HIDL interface object used to control a AP Iface instance.
- */
-class WifiApIface : public V1_5::IWifiApIface {
- public:
- WifiApIface(const std::string& ifname, const std::vector<std::string>& instances,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
- // Refer to |WifiChip::invalidate()|.
- void invalidate();
- bool isValid();
- std::string getName();
- void removeInstance(std::string instance);
-
- // HIDL methods exposed.
- Return<void> getName(getName_cb hidl_status_cb) override;
- Return<void> getType(getType_cb hidl_status_cb) override;
- Return<void> setCountryCode(const hidl_array<int8_t, 2>& code,
- setCountryCode_cb hidl_status_cb) override;
- Return<void> getValidFrequenciesForBand(V1_0::WifiBand band,
- getValidFrequenciesForBand_cb hidl_status_cb) override;
- Return<void> setMacAddress(const hidl_array<uint8_t, 6>& mac,
- setMacAddress_cb hidl_status_cb) override;
- Return<void> getFactoryMacAddress(getFactoryMacAddress_cb hidl_status_cb) override;
- Return<void> resetToFactoryMacAddress(resetToFactoryMacAddress_cb hidl_status_cb) override;
-
- Return<void> getBridgedInstances(getBridgedInstances_cb hidl_status_cb) override;
-
- private:
- // Corresponding worker functions for the HIDL methods.
- std::pair<WifiStatus, std::string> getNameInternal();
- std::pair<WifiStatus, IfaceType> getTypeInternal();
- WifiStatus setCountryCodeInternal(const std::array<int8_t, 2>& code);
- std::pair<WifiStatus, std::vector<WifiChannelInMhz>> getValidFrequenciesForBandInternal(
- V1_0::WifiBand band);
- WifiStatus setMacAddressInternal(const std::array<uint8_t, 6>& mac);
- std::pair<WifiStatus, std::array<uint8_t, 6>> getFactoryMacAddressInternal(
- const std::string& ifaceName);
- WifiStatus resetToFactoryMacAddressInternal();
- std::pair<WifiStatus, std::vector<hidl_string>> getBridgedInstancesInternal();
-
- std::string ifname_;
- std::vector<std::string> instances_;
- std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
- std::weak_ptr<iface_util::WifiIfaceUtil> iface_util_;
- bool is_valid_;
-
- DISALLOW_COPY_AND_ASSIGN(WifiApIface);
-};
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_AP_IFACE_H_
diff --git a/wifi/1.6/default/wifi_chip.h b/wifi/1.6/default/wifi_chip.h
deleted file mode 100644
index e8ddaa6..0000000
--- a/wifi/1.6/default/wifi_chip.h
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_CHIP_H_
-#define WIFI_CHIP_H_
-
-// HACK: NAN is a macro defined in math.h, which can be included in various
-// headers. This wifi HAL uses an enum called NAN, which does not compile when
-// the macro is defined. Undefine NAN to work around it.
-#undef NAN
-
-#include <list>
-#include <map>
-#include <mutex>
-
-#include <android-base/macros.h>
-#include <android/hardware/wifi/1.6/IWifiChip.h>
-#include <android/hardware/wifi/1.6/IWifiRttController.h>
-#include <android/hardware/wifi/1.6/IWifiStaIface.h>
-
-#include "hidl_callback_util.h"
-#include "ringbuffer.h"
-#include "wifi_ap_iface.h"
-#include "wifi_feature_flags.h"
-#include "wifi_legacy_hal.h"
-#include "wifi_mode_controller.h"
-#include "wifi_nan_iface.h"
-#include "wifi_p2p_iface.h"
-#include "wifi_rtt_controller.h"
-#include "wifi_sta_iface.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
-using V1_5::WifiBand;
-
-/**
- * HIDL interface object used to control a Wifi HAL chip instance.
- * Since there is only a single chip instance used today, there is no
- * identifying handle information stored here.
- */
-class WifiChip : public V1_6::IWifiChip {
- public:
- WifiChip(ChipId chip_id, bool is_primary,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
- const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
- const std::weak_ptr<feature_flags::WifiFeatureFlags> feature_flags,
- const std::function<void(const std::string&)>& subsystemCallbackHandler);
- // HIDL does not provide a built-in mechanism to let the server invalidate
- // a HIDL interface object after creation. If any client process holds onto
- // a reference to the object in their context, any method calls on that
- // reference will continue to be directed to the server.
- //
- // However Wifi HAL needs to control the lifetime of these objects. So, add
- // a public |invalidate| method to |WifiChip| and it's child objects. This
- // will be used to mark an object invalid when either:
- // a) Wifi HAL is stopped, or
- // b) Wifi Chip is reconfigured.
- //
- // All HIDL method implementations should check if the object is still
- // marked valid before processing them.
- void invalidate();
- bool isValid();
- std::set<sp<V1_4::IWifiChipEventCallback>> getEventCallbacks();
-
- // HIDL methods exposed.
- Return<void> getId(getId_cb hidl_status_cb) override;
- // Deprecated support for this callback
- Return<void> registerEventCallback(const sp<V1_0::IWifiChipEventCallback>& event_callback,
- registerEventCallback_cb hidl_status_cb) override;
- Return<void> getCapabilities(getCapabilities_cb hidl_status_cb) override;
- Return<void> getAvailableModes(getAvailableModes_cb hidl_status_cb) override;
- Return<void> configureChip(ChipModeId mode_id, configureChip_cb hidl_status_cb) override;
- Return<void> getMode(getMode_cb hidl_status_cb) override;
- Return<void> requestChipDebugInfo(requestChipDebugInfo_cb hidl_status_cb) override;
- Return<void> requestDriverDebugDump(requestDriverDebugDump_cb hidl_status_cb) override;
- Return<void> requestFirmwareDebugDump(requestFirmwareDebugDump_cb hidl_status_cb) override;
- Return<void> createApIface(createApIface_cb hidl_status_cb) override;
- Return<void> createBridgedApIface(createBridgedApIface_cb hidl_status_cb) override;
- Return<void> getApIfaceNames(getApIfaceNames_cb hidl_status_cb) override;
- Return<void> getApIface(const hidl_string& ifname, getApIface_cb hidl_status_cb) override;
- Return<void> removeApIface(const hidl_string& ifname, removeApIface_cb hidl_status_cb) override;
- Return<void> removeIfaceInstanceFromBridgedApIface(
- const hidl_string& brIfaceName, const hidl_string& ifaceInstanceName,
- removeIfaceInstanceFromBridgedApIface_cb hidl_status_cb) override;
- Return<void> createNanIface(createNanIface_cb hidl_status_cb) override;
- Return<void> getNanIfaceNames(getNanIfaceNames_cb hidl_status_cb) override;
- Return<void> getNanIface(const hidl_string& ifname, getNanIface_cb hidl_status_cb) override;
- Return<void> removeNanIface(const hidl_string& ifname,
- removeNanIface_cb hidl_status_cb) override;
- Return<void> createP2pIface(createP2pIface_cb hidl_status_cb) override;
- Return<void> getP2pIfaceNames(getP2pIfaceNames_cb hidl_status_cb) override;
- Return<void> getP2pIface(const hidl_string& ifname, getP2pIface_cb hidl_status_cb) override;
- Return<void> removeP2pIface(const hidl_string& ifname,
- removeP2pIface_cb hidl_status_cb) override;
- Return<void> createStaIface(createStaIface_cb hidl_status_cb) override;
- Return<void> getStaIfaceNames(getStaIfaceNames_cb hidl_status_cb) override;
- Return<void> getStaIface(const hidl_string& ifname, getStaIface_cb hidl_status_cb) override;
- Return<void> removeStaIface(const hidl_string& ifname,
- removeStaIface_cb hidl_status_cb) override;
- Return<void> createRttController(const sp<IWifiIface>& bound_iface,
- createRttController_cb hidl_status_cb) override;
- Return<void> getDebugRingBuffersStatus(getDebugRingBuffersStatus_cb hidl_status_cb) override;
- Return<void> startLoggingToDebugRingBuffer(
- const hidl_string& ring_name, WifiDebugRingBufferVerboseLevel verbose_level,
- uint32_t max_interval_in_sec, uint32_t min_data_size_in_bytes,
- startLoggingToDebugRingBuffer_cb hidl_status_cb) override;
- Return<void> forceDumpToDebugRingBuffer(const hidl_string& ring_name,
- forceDumpToDebugRingBuffer_cb hidl_status_cb) override;
- Return<void> flushRingBufferToFile(flushRingBufferToFile_cb hidl_status_cb) override;
- Return<void> stopLoggingToDebugRingBuffer(
- stopLoggingToDebugRingBuffer_cb hidl_status_cb) override;
- Return<void> getDebugHostWakeReasonStats(
- getDebugHostWakeReasonStats_cb hidl_status_cb) override;
- Return<void> enableDebugErrorAlerts(bool enable,
- enableDebugErrorAlerts_cb hidl_status_cb) override;
- Return<void> selectTxPowerScenario(V1_1::IWifiChip::TxPowerScenario scenario,
- selectTxPowerScenario_cb hidl_status_cb) override;
- Return<void> resetTxPowerScenario(resetTxPowerScenario_cb hidl_status_cb) override;
- Return<void> setLatencyMode(LatencyMode mode, setLatencyMode_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_2(const sp<V1_2::IWifiChipEventCallback>& event_callback,
- registerEventCallback_1_2_cb hidl_status_cb) override;
- Return<void> selectTxPowerScenario_1_2(TxPowerScenario scenario,
- selectTxPowerScenario_cb hidl_status_cb) override;
- Return<void> getCapabilities_1_3(getCapabilities_cb hidl_status_cb) override;
- Return<void> getCapabilities_1_5(getCapabilities_1_5_cb hidl_status_cb) override;
- Return<void> debug(const hidl_handle& handle, const hidl_vec<hidl_string>& options) override;
- Return<void> createRttController_1_4(const sp<IWifiIface>& bound_iface,
- createRttController_1_4_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_4(const sp<V1_4::IWifiChipEventCallback>& event_callback,
- registerEventCallback_1_4_cb hidl_status_cb) override;
- Return<void> setMultiStaPrimaryConnection(
- const hidl_string& ifname, setMultiStaPrimaryConnection_cb hidl_status_cb) override;
- Return<void> setMultiStaUseCase(MultiStaUseCase use_case,
- setMultiStaUseCase_cb hidl_status_cb) override;
- Return<void> setCoexUnsafeChannels(const hidl_vec<CoexUnsafeChannel>& unsafe_channels,
- hidl_bitfield<IfaceType> restrictions,
- setCoexUnsafeChannels_cb hidl_status_cb) override;
- Return<void> setCountryCode(const hidl_array<int8_t, 2>& code,
- setCountryCode_cb _hidl_cb) override;
- Return<void> getUsableChannels(WifiBand band, hidl_bitfield<V1_5::WifiIfaceMode> ifaceModeMask,
- hidl_bitfield<V1_5::IWifiChip::UsableChannelFilter> filterMask,
- getUsableChannels_cb _hidl_cb) override;
- Return<void> triggerSubsystemRestart(triggerSubsystemRestart_cb hidl_status_cb) override;
- Return<void> createRttController_1_6(const sp<IWifiIface>& bound_iface,
- createRttController_1_6_cb hidl_status_cb) override;
- Return<void> getUsableChannels_1_6(WifiBand band,
- hidl_bitfield<V1_5::WifiIfaceMode> ifaceModeMask,
- hidl_bitfield<UsableChannelFilter> filterMask,
- getUsableChannels_1_6_cb _hidl_cb) override;
- Return<void> getSupportedRadioCombinationsMatrix(
- getSupportedRadioCombinationsMatrix_cb hidl_status_cb) override;
- Return<void> getAvailableModes_1_6(getAvailableModes_1_6_cb hidl_status_cb) override;
-
- private:
- void invalidateAndRemoveAllIfaces();
- // When a STA iface is removed any dependent NAN-ifaces/RTT-controllers are
- // invalidated & removed.
- void invalidateAndRemoveDependencies(const std::string& removed_iface_name);
-
- // Corresponding worker functions for the HIDL methods.
- std::pair<WifiStatus, ChipId> getIdInternal();
- // Deprecated support for this callback
- WifiStatus registerEventCallbackInternal(
- const sp<V1_0::IWifiChipEventCallback>& event_callback);
- std::pair<WifiStatus, uint32_t> getCapabilitiesInternal();
- std::pair<WifiStatus, std::vector<V1_0::IWifiChip::ChipMode>> getAvailableModesInternal();
- WifiStatus configureChipInternal(std::unique_lock<std::recursive_mutex>* lock,
- ChipModeId mode_id);
- std::pair<WifiStatus, uint32_t> getModeInternal();
- std::pair<WifiStatus, IWifiChip::ChipDebugInfo> requestChipDebugInfoInternal();
- std::pair<WifiStatus, std::vector<uint8_t>> requestDriverDebugDumpInternal();
- std::pair<WifiStatus, std::vector<uint8_t>> requestFirmwareDebugDumpInternal();
- sp<WifiApIface> newWifiApIface(std::string& ifname);
- WifiStatus createVirtualApInterface(const std::string& apVirtIf);
- std::pair<WifiStatus, sp<V1_5::IWifiApIface>> createApIfaceInternal();
- std::pair<WifiStatus, sp<V1_5::IWifiApIface>> createBridgedApIfaceInternal();
- std::pair<WifiStatus, std::vector<hidl_string>> getApIfaceNamesInternal();
- std::pair<WifiStatus, sp<V1_5::IWifiApIface>> getApIfaceInternal(const std::string& ifname);
- WifiStatus removeApIfaceInternal(const std::string& ifname);
- WifiStatus removeIfaceInstanceFromBridgedApIfaceInternal(const std::string& brIfaceName,
- const std::string& ifInstanceName);
- std::pair<WifiStatus, sp<V1_4::IWifiNanIface>> createNanIfaceInternal();
- std::pair<WifiStatus, std::vector<hidl_string>> getNanIfaceNamesInternal();
- std::pair<WifiStatus, sp<V1_4::IWifiNanIface>> getNanIfaceInternal(const std::string& ifname);
- WifiStatus removeNanIfaceInternal(const std::string& ifname);
- std::pair<WifiStatus, sp<IWifiP2pIface>> createP2pIfaceInternal();
- std::pair<WifiStatus, std::vector<hidl_string>> getP2pIfaceNamesInternal();
- std::pair<WifiStatus, sp<IWifiP2pIface>> getP2pIfaceInternal(const std::string& ifname);
- WifiStatus removeP2pIfaceInternal(const std::string& ifname);
- std::pair<WifiStatus, sp<V1_6::IWifiStaIface>> createStaIfaceInternal();
- std::pair<WifiStatus, std::vector<hidl_string>> getStaIfaceNamesInternal();
- std::pair<WifiStatus, sp<V1_6::IWifiStaIface>> getStaIfaceInternal(const std::string& ifname);
- WifiStatus removeStaIfaceInternal(const std::string& ifname);
- std::pair<WifiStatus, sp<V1_0::IWifiRttController>> createRttControllerInternal(
- const sp<IWifiIface>& bound_iface);
- std::pair<WifiStatus, std::vector<WifiDebugRingBufferStatus>>
- getDebugRingBuffersStatusInternal();
- WifiStatus startLoggingToDebugRingBufferInternal(const hidl_string& ring_name,
- WifiDebugRingBufferVerboseLevel verbose_level,
- uint32_t max_interval_in_sec,
- uint32_t min_data_size_in_bytes);
- WifiStatus forceDumpToDebugRingBufferInternal(const hidl_string& ring_name);
- WifiStatus flushRingBufferToFileInternal();
- WifiStatus stopLoggingToDebugRingBufferInternal();
- std::pair<WifiStatus, WifiDebugHostWakeReasonStats> getDebugHostWakeReasonStatsInternal();
- WifiStatus enableDebugErrorAlertsInternal(bool enable);
- WifiStatus selectTxPowerScenarioInternal(V1_1::IWifiChip::TxPowerScenario scenario);
- WifiStatus resetTxPowerScenarioInternal();
- WifiStatus setLatencyModeInternal(LatencyMode mode);
- WifiStatus registerEventCallbackInternal_1_2(
- const sp<V1_2::IWifiChipEventCallback>& event_callback);
- WifiStatus selectTxPowerScenarioInternal_1_2(TxPowerScenario scenario);
- std::pair<WifiStatus, uint32_t> getCapabilitiesInternal_1_3();
- std::pair<WifiStatus, uint32_t> getCapabilitiesInternal_1_5();
- std::pair<WifiStatus, sp<V1_4::IWifiRttController>> createRttControllerInternal_1_4(
- const sp<IWifiIface>& bound_iface);
- WifiStatus registerEventCallbackInternal_1_4(
- const sp<V1_4::IWifiChipEventCallback>& event_callback);
- WifiStatus setMultiStaPrimaryConnectionInternal(const std::string& ifname);
- WifiStatus setMultiStaUseCaseInternal(MultiStaUseCase use_case);
- WifiStatus setCoexUnsafeChannelsInternal(std::vector<CoexUnsafeChannel> unsafe_channels,
- uint32_t restrictions);
- WifiStatus setCountryCodeInternal(const std::array<int8_t, 2>& code);
- std::pair<WifiStatus, std::vector<V1_5::WifiUsableChannel>> getUsableChannelsInternal(
- WifiBand band, uint32_t ifaceModeMask, uint32_t filterMask);
- WifiStatus handleChipConfiguration(std::unique_lock<std::recursive_mutex>* lock,
- ChipModeId mode_id);
- WifiStatus registerDebugRingBufferCallback();
- WifiStatus registerRadioModeChangeCallback();
- std::vector<V1_6::IWifiChip::ChipConcurrencyCombination>
- getCurrentModeConcurrencyCombinations();
- std::map<IfaceConcurrencyType, size_t> getCurrentConcurrencyCombination();
- std::vector<std::map<IfaceConcurrencyType, size_t>> expandConcurrencyCombinations(
- const V1_6::IWifiChip::ChipConcurrencyCombination& combination);
- bool canExpandedConcurrencyComboSupportConcurrencyTypeWithCurrentTypes(
- const std::map<IfaceConcurrencyType, size_t>& expanded_combo,
- IfaceConcurrencyType requested_type);
- bool canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType requested_type);
- bool canExpandedConcurrencyComboSupportConcurrencyCombo(
- const std::map<IfaceConcurrencyType, size_t>& expanded_combo,
- const std::map<IfaceConcurrencyType, size_t>& req_combo);
- bool canCurrentModeSupportConcurrencyCombo(
- const std::map<IfaceConcurrencyType, size_t>& req_combo);
- bool canCurrentModeSupportConcurrencyType(IfaceConcurrencyType requested_type);
- bool isValidModeId(ChipModeId mode_id);
- bool isStaApConcurrencyAllowedInCurrentMode();
- bool isDualStaConcurrencyAllowedInCurrentMode();
- uint32_t startIdxOfApIface();
- std::string getFirstActiveWlanIfaceName();
- std::string allocateApOrStaIfaceName(IfaceType type, uint32_t start_idx);
- std::string allocateApIfaceName();
- std::vector<std::string> allocateBridgedApInstanceNames();
- std::string allocateStaIfaceName();
- bool writeRingbufferFilesInternal();
- std::string getWlanIfaceNameWithType(IfaceType type, unsigned idx);
- void invalidateAndClearBridgedApAll();
- void deleteApIface(const std::string& if_name);
- bool findUsingNameFromBridgedApInstances(const std::string& name);
- WifiStatus triggerSubsystemRestartInternal();
- std::pair<WifiStatus, sp<V1_6::IWifiRttController>> createRttControllerInternal_1_6(
- const sp<IWifiIface>& bound_iface);
- std::pair<WifiStatus, std::vector<V1_6::WifiUsableChannel>> getUsableChannelsInternal_1_6(
- WifiBand band, uint32_t ifaceModeMask, uint32_t filterMask);
- std::pair<WifiStatus, WifiRadioCombinationMatrix> getSupportedRadioCombinationsMatrixInternal();
- std::pair<WifiStatus, std::vector<V1_6::IWifiChip::ChipMode>> getAvailableModesInternal_1_6();
-
- ChipId chip_id_;
- std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
- std::weak_ptr<mode_controller::WifiModeController> mode_controller_;
- std::shared_ptr<iface_util::WifiIfaceUtil> iface_util_;
- std::vector<sp<WifiApIface>> ap_ifaces_;
- std::vector<sp<WifiNanIface>> nan_ifaces_;
- std::vector<sp<WifiP2pIface>> p2p_ifaces_;
- std::vector<sp<WifiStaIface>> sta_ifaces_;
- std::vector<sp<WifiRttController>> rtt_controllers_;
- std::map<std::string, Ringbuffer> ringbuffer_map_;
- bool is_valid_;
- // Members pertaining to chip configuration.
- uint32_t current_mode_id_;
- std::mutex lock_t;
- std::vector<V1_6::IWifiChip::ChipMode> modes_;
- // The legacy ring buffer callback API has only a global callback
- // registration mechanism. Use this to check if we have already
- // registered a callback.
- bool debug_ring_buffer_cb_registered_;
- hidl_callback_util::HidlCallbackHandler<V1_4::IWifiChipEventCallback> event_cb_handler_;
-
- const std::function<void(const std::string&)> subsystemCallbackHandler_;
- std::map<std::string, std::vector<std::string>> br_ifaces_ap_instances_;
- DISALLOW_COPY_AND_ASSIGN(WifiChip);
-};
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_CHIP_H_
diff --git a/wifi/1.6/default/wifi_feature_flags.cpp b/wifi/1.6/default/wifi_feature_flags.cpp
deleted file mode 100644
index e80a3cd..0000000
--- a/wifi/1.6/default/wifi_feature_flags.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <string>
-
-#include <android-base/logging.h>
-#include <cutils/properties.h>
-
-#include "wifi_feature_flags.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace feature_flags {
-
-using V1_0::ChipModeId;
-using V1_0::IWifiChip;
-using V1_6::IfaceConcurrencyType;
-
-/* The chip may either have a single mode supporting any number of combinations,
- * or a fixed dual-mode (so it involves firmware loading to switch between
- * modes) setting. If there is a need to support more modes, it needs to be
- * implemented manually in WiFi HAL (see changeFirmwareMode in
- * WifiChip::handleChipConfiguration).
- *
- * Supported combinations are defined in device's makefile, for example:
- * WIFI_HAL_INTERFACE_COMBINATIONS := {{{STA, AP}, 1}, {{P2P, NAN}, 1}},
- * WIFI_HAL_INTERFACE_COMBINATIONS += {{{STA}, 1}, {{AP}, 2}}
- * What means:
- * Interface concurrency combination 1: 1 STA or AP and 1 P2P or NAN concurrent iface
- * operations.
- * Interface concurrency combination 2: 1 STA and 2 AP concurrent iface operations.
- *
- * For backward compatibility, the following makefile flags can be used to
- * generate combinations list:
- * - WIFI_HIDL_FEATURE_DUAL_INTERFACE
- * - WIFI_HIDL_FEATURE_DISABLE_AP
- * - WIFI_HIDL_FEATURE_AWARE
- * However, they are ignored if WIFI_HAL_INTERFACE_COMBINATIONS was provided.
- * With WIFI_HIDL_FEATURE_DUAL_INTERFACE flag set, there is a single mode with
- * two concurrency combinations:
- * Interface Concurrency Combination 1: Will support 1 STA and 1 P2P or NAN (optional)
- * concurrent iface operations.
- * Interface Concurrency Combination 2: Will support 1 STA and 1 AP concurrent
- * iface operations.
- *
- * The only dual-mode configuration supported is for alternating STA and AP
- * mode, that may involve firmware reloading. In such case, there are 2 separate
- * modes of operation with 1 concurrency combination each:
- * Mode 1 (STA mode): Will support 1 STA and 1 P2P or NAN (optional)
- * concurrent iface operations.
- * Mode 2 (AP mode): Will support 1 AP iface operation.
- *
- * If Aware is enabled, the concurrency combination will be modified to support either
- * P2P or NAN in place of just P2P.
- */
-// clang-format off
-#ifdef WIFI_HAL_INTERFACE_COMBINATIONS
-constexpr ChipModeId kMainModeId = chip_mode_ids::kV3;
-#elif defined(WIFI_HIDL_FEATURE_DUAL_INTERFACE)
-// former V2 (fixed dual interface) setup expressed as V3
-constexpr ChipModeId kMainModeId = chip_mode_ids::kV3;
-# ifdef WIFI_HIDL_FEATURE_DISABLE_AP
-# ifdef WIFI_HIDL_FEATURE_AWARE
-// 1 STA + 1 of (P2P or NAN)
-# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P, NAN}, 1}}
-# else
-// 1 STA + 1 P2P
-# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P}, 1}}
-# endif
-# else
-# ifdef WIFI_HIDL_FEATURE_AWARE
-// (1 STA + 1 AP) or (1 STA + 1 of (P2P or NAN))
-# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{AP}, 1}},\
- {{{STA}, 1}, {{P2P, NAN}, 1}}
-# else
-// (1 STA + 1 AP) or (1 STA + 1 P2P)
-# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{AP}, 1}},\
- {{{STA}, 1}, {{P2P}, 1}}
-# endif
-# endif
-#else
-// V1 (fixed single interface, dual-mode chip)
-constexpr ChipModeId kMainModeId = chip_mode_ids::kV1Sta;
-# ifdef WIFI_HIDL_FEATURE_AWARE
-// 1 STA + 1 of (P2P or NAN)
-# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P, NAN}, 1}}
-# else
-// 1 STA + 1 P2P
-# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P}, 1}}
-# endif
-
-# ifndef WIFI_HIDL_FEATURE_DISABLE_AP
-# define WIFI_HAL_INTERFACE_COMBINATIONS_AP {{{AP}, 1}}
-# endif
-#endif
-// clang-format on
-
-/**
- * Helper class to convert a collection of combination limits to a combination.
- *
- * The main point here is to simplify the syntax required by
- * WIFI_HAL_INTERFACE_COMBINATIONS.
- */
-struct ChipConcurrencyCombination
- : public hidl_vec<V1_6::IWifiChip::ChipConcurrencyCombinationLimit> {
- ChipConcurrencyCombination(
- const std::initializer_list<V1_6::IWifiChip::ChipConcurrencyCombinationLimit> list)
- : hidl_vec(list) {}
-
- operator V1_6::IWifiChip::ChipConcurrencyCombination() const { return {*this}; }
-
- static hidl_vec<V1_6::IWifiChip::ChipConcurrencyCombination> make_vec(
- const std::initializer_list<ChipConcurrencyCombination> list) {
- return hidl_vec<V1_6::IWifiChip::ChipConcurrencyCombination>( //
- std::begin(list), std::end(list));
- }
-};
-
-#define STA IfaceConcurrencyType::STA
-#define AP IfaceConcurrencyType::AP
-#define AP_BRIDGED IfaceConcurrencyType::AP_BRIDGED
-#define P2P IfaceConcurrencyType::P2P
-#define NAN IfaceConcurrencyType::NAN
-static const std::vector<V1_6::IWifiChip::ChipMode> kChipModesPrimary{
- {kMainModeId, ChipConcurrencyCombination::make_vec({WIFI_HAL_INTERFACE_COMBINATIONS})},
-#ifdef WIFI_HAL_INTERFACE_COMBINATIONS_AP
- {chip_mode_ids::kV1Ap,
- ChipConcurrencyCombination::make_vec({WIFI_HAL_INTERFACE_COMBINATIONS_AP})},
-#endif
-};
-
-static const std::vector<V1_6::IWifiChip::ChipMode> kChipModesSecondary{
-#ifdef WIFI_HAL_INTERFACE_COMBINATIONS_SECONDARY_CHIP
- {chip_mode_ids::kV3,
- ChipConcurrencyCombination::make_vec({WIFI_HAL_INTERFACE_COMBINATIONS_SECONDARY_CHIP})},
-#endif
-};
-
-constexpr char kDebugPresetInterfaceCombinationIdxProperty[] =
- "persist.vendor.debug.wifi.hal.preset_interface_combination_idx";
-// List of pre-defined concurrency combinations that can be enabled at runtime via
-// setting the property: "kDebugPresetInterfaceCombinationIdxProperty" to the
-// corresponding index value.
-static const std::vector<std::pair<std::string, std::vector<V1_6::IWifiChip::ChipMode>>>
- kDebugChipModes{// Legacy combination - No STA/AP concurrencies.
- // 0 - (1 AP) or (1 STA + 1 of (P2P or NAN))
- {"No STA/AP Concurrency",
- {{kMainModeId, ChipConcurrencyCombination::make_vec(
- {{{{AP}, 1}}, {{{STA}, 1}, {{P2P, NAN}, 1}}})}}},
-
- // STA + AP concurrency
- // 1 - (1 STA + 1 AP) or (1 STA + 1 of (P2P or NAN))
- {"STA + AP Concurrency",
- {{kMainModeId,
- ChipConcurrencyCombination::make_vec(
- {{{{STA}, 1}, {{AP}, 1}}, {{{STA}, 1}, {{P2P, NAN}, 1}}})}}},
-
- // STA + STA concurrency
- // 2 - (1 STA + 1 AP) or (2 STA + 1 of (P2P or NAN))
- {"Dual STA Concurrency",
- {{kMainModeId,
- ChipConcurrencyCombination::make_vec(
- {{{{STA}, 1}, {{AP}, 1}}, {{{STA}, 2}, {{P2P, NAN}, 1}}})}}},
-
- // AP + AP + STA concurrency
- // 3 - (1 STA + 2 AP) or (1 STA + 1 of (P2P or NAN))
- {"Dual AP Concurrency",
- {{kMainModeId,
- ChipConcurrencyCombination::make_vec(
- {{{{STA}, 1}, {{AP}, 2}}, {{{STA}, 1}, {{P2P, NAN}, 1}}})}}},
-
- // STA + STA concurrency and AP + AP + STA concurrency
- // 4 - (1 STA + 2 AP) or (2 STA + 1 of (P2P or NAN))
- {"Dual STA & Dual AP Concurrency",
- {{kMainModeId,
- ChipConcurrencyCombination::make_vec(
- {{{{STA}, 1}, {{AP}, 2}}, {{{STA}, 2}, {{P2P, NAN}, 1}}})}}},
-
- // STA + STA concurrency
- // 5 - (1 STA + 1 AP (bridged or single) | P2P | NAN), or (2 STA))
- {"Dual STA or STA plus single other interface",
- {{kMainModeId, ChipConcurrencyCombination::make_vec(
- {{{{STA}, 1}, {{P2P, NAN, AP, AP_BRIDGED}, 1}},
- {{{STA}, 2}}})}}}};
-
-#undef STA
-#undef AP
-#undef P2P
-#undef NAN
-
-#ifdef WIFI_HIDL_FEATURE_DISABLE_AP_MAC_RANDOMIZATION
-#pragma message \
- "WIFI_HIDL_FEATURE_DISABLE_AP_MAC_RANDOMIZATION is deprecated; override " \
- "'config_wifi_ap_randomization_supported' in " \
- "frameworks/base/core/res/res/values/config.xml in the device overlay " \
- "instead"
-#endif // WIFI_HIDL_FEATURE_DISABLE_AP_MAC_RANDOMIZATION
-
-WifiFeatureFlags::WifiFeatureFlags() {}
-
-std::vector<V1_6::IWifiChip::ChipMode> WifiFeatureFlags::getChipModesForPrimary() {
- std::array<char, PROPERTY_VALUE_MAX> buffer;
- auto res = property_get(kDebugPresetInterfaceCombinationIdxProperty, buffer.data(), nullptr);
- // Debug property not set, use the device preset concurrency combination.
- if (res <= 0) return kChipModesPrimary;
-
- // Debug property set, use one of the debug preset concurrency combination.
- unsigned long idx = std::stoul(buffer.data());
- if (idx >= kDebugChipModes.size()) {
- LOG(ERROR) << "Invalid index set in property: "
- << kDebugPresetInterfaceCombinationIdxProperty;
- return kChipModesPrimary;
- }
- std::string name;
- std::vector<V1_6::IWifiChip::ChipMode> chip_modes;
- std::tie(name, chip_modes) = kDebugChipModes[idx];
- LOG(INFO) << "Using debug chip mode: <" << name
- << "> set via property: " << kDebugPresetInterfaceCombinationIdxProperty;
- return chip_modes;
-}
-
-std::vector<V1_6::IWifiChip::ChipMode> WifiFeatureFlags::getChipModes(bool is_primary) {
- return (is_primary) ? getChipModesForPrimary() : kChipModesSecondary;
-}
-
-} // namespace feature_flags
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/wifi_nan_iface.cpp b/wifi/1.6/default/wifi_nan_iface.cpp
deleted file mode 100644
index ac2ebc9..0000000
--- a/wifi/1.6/default/wifi_nan_iface.cpp
+++ /dev/null
@@ -1,1016 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-
-#include "hidl_return_util.h"
-#include "hidl_struct_util.h"
-#include "wifi_nan_iface.h"
-#include "wifi_status_util.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
-
-WifiNanIface::WifiNanIface(const std::string& ifname, bool is_dedicated_iface,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
- : ifname_(ifname),
- is_dedicated_iface_(is_dedicated_iface),
- legacy_hal_(legacy_hal),
- iface_util_(iface_util),
- is_valid_(true) {
- if (is_dedicated_iface_) {
- // If using a dedicated iface, set the iface up first.
- if (!iface_util_.lock()->setUpState(ifname_, true)) {
- // Fatal failure, invalidate the iface object.
- invalidate();
- return;
- }
- }
- // Register all the callbacks here. these should be valid for the lifetime
- // of the object. Whenever the mode changes legacy HAL will remove
- // all of these callbacks.
- legacy_hal::NanCallbackHandlers callback_handlers;
- android::wp<WifiNanIface> weak_ptr_this(this);
-
- // Callback for response.
- callback_handlers.on_notify_response = [weak_ptr_this](legacy_hal::transaction_id id,
- const legacy_hal::NanResponseMsg& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- WifiNanStatus wifiNanStatus;
- if (!hidl_struct_util::convertLegacyNanResponseHeaderToHidl(msg, &wifiNanStatus)) {
- LOG(ERROR) << "Failed to convert nan response header";
- return;
- }
-
- switch (msg.response_type) {
- case legacy_hal::NAN_RESPONSE_ENABLED: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyEnableResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_DISABLED: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyDisableResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_PUBLISH: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyStartPublishResponse(id, wifiNanStatus,
- msg.body.publish_response.publish_id)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_PUBLISH_CANCEL: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyStopPublishResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_TRANSMIT_FOLLOWUP: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyTransmitFollowupResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_SUBSCRIBE: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyStartSubscribeResponse(
- id, wifiNanStatus,
- msg.body.subscribe_response.subscribe_id)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_SUBSCRIBE_CANCEL: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyStopSubscribeResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_CONFIG: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyConfigResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_GET_CAPABILITIES: {
- V1_6::NanCapabilities hidl_struct;
- if (!hidl_struct_util::convertLegacyNanCapabilitiesResponseToHidl(
- msg.body.nan_capabilities, &hidl_struct)) {
- LOG(ERROR) << "Failed to convert nan capabilities response";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks_1_6()) {
- if (!callback->notifyCapabilitiesResponse_1_6(id, wifiNanStatus, hidl_struct)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_DP_INTERFACE_CREATE: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyCreateDataInterfaceResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_DP_INTERFACE_DELETE: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyDeleteDataInterfaceResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_DP_INITIATOR_RESPONSE: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyInitiateDataPathResponse(
- id, wifiNanStatus,
- msg.body.data_request_response.ndp_instance_id)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_DP_RESPONDER_RESPONSE: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyRespondToDataPathIndicationResponse(id, wifiNanStatus)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_DP_END: {
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->notifyTerminateDataPathResponse(id, wifiNanStatus).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- break;
- }
- case legacy_hal::NAN_RESPONSE_BEACON_SDF_PAYLOAD:
- /* fall through */
- case legacy_hal::NAN_RESPONSE_TCA:
- /* fall through */
- case legacy_hal::NAN_RESPONSE_STATS:
- /* fall through */
- case legacy_hal::NAN_RESPONSE_ERROR:
- /* fall through */
- default:
- LOG(ERROR) << "Unknown or unhandled response type: " << msg.response_type;
- return;
- }
- };
-
- callback_handlers.on_event_disc_eng_event =
- [weak_ptr_this](const legacy_hal::NanDiscEngEventInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- NanClusterEventInd hidl_struct;
- // event types defined identically - hence can be cast
- hidl_struct.eventType = (NanClusterEventType)msg.event_type;
- hidl_struct.addr = msg.data.mac_addr.addr;
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventClusterEvent(hidl_struct).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_disabled = [weak_ptr_this](const legacy_hal::NanDisabledInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- WifiNanStatus status;
- hidl_struct_util::convertToWifiNanStatus(msg.reason, msg.nan_reason, sizeof(msg.nan_reason),
- &status);
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventDisabled(status).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_publish_terminated =
- [weak_ptr_this](const legacy_hal::NanPublishTerminatedInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- WifiNanStatus status;
- hidl_struct_util::convertToWifiNanStatus(msg.reason, msg.nan_reason,
- sizeof(msg.nan_reason), &status);
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventPublishTerminated(msg.publish_id, status).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_subscribe_terminated =
- [weak_ptr_this](const legacy_hal::NanSubscribeTerminatedInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- WifiNanStatus status;
- hidl_struct_util::convertToWifiNanStatus(msg.reason, msg.nan_reason,
- sizeof(msg.nan_reason), &status);
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventSubscribeTerminated(msg.subscribe_id, status).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_match = [weak_ptr_this](const legacy_hal::NanMatchInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- V1_6::NanMatchInd hidl_struct;
- if (!hidl_struct_util::convertLegacyNanMatchIndToHidl(msg, &hidl_struct)) {
- LOG(ERROR) << "Failed to convert nan capabilities response";
- return;
- }
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks_1_6()) {
- if (!callback->eventMatch_1_6(hidl_struct).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_match_expired = [weak_ptr_this](
- const legacy_hal::NanMatchExpiredInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventMatchExpired(msg.publish_subscribe_id, msg.requestor_instance_id)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_followup = [weak_ptr_this](const legacy_hal::NanFollowupInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- NanFollowupReceivedInd hidl_struct;
- if (!hidl_struct_util::convertLegacyNanFollowupIndToHidl(msg, &hidl_struct)) {
- LOG(ERROR) << "Failed to convert nan capabilities response";
- return;
- }
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventFollowupReceived(hidl_struct).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_transmit_follow_up =
- [weak_ptr_this](const legacy_hal::NanTransmitFollowupInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- WifiNanStatus status;
- hidl_struct_util::convertToWifiNanStatus(msg.reason, msg.nan_reason,
- sizeof(msg.nan_reason), &status);
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventTransmitFollowup(msg.id, status).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_data_path_request =
- [weak_ptr_this](const legacy_hal::NanDataPathRequestInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- NanDataPathRequestInd hidl_struct;
- if (!hidl_struct_util::convertLegacyNanDataPathRequestIndToHidl(msg,
- &hidl_struct)) {
- LOG(ERROR) << "Failed to convert nan capabilities response";
- return;
- }
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventDataPathRequest(hidl_struct).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_data_path_confirm =
- [weak_ptr_this](const legacy_hal::NanDataPathConfirmInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- V1_6::NanDataPathConfirmInd hidl_struct;
- if (!hidl_struct_util::convertLegacyNanDataPathConfirmIndToHidl(msg,
- &hidl_struct)) {
- LOG(ERROR) << "Failed to convert nan capabilities response";
- return;
- }
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks_1_6()) {
- if (!callback->eventDataPathConfirm_1_6(hidl_struct).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- callback_handlers.on_event_data_path_end =
- [weak_ptr_this](const legacy_hal::NanDataPathEndInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- for (int i = 0; i < msg.num_ndp_instances; ++i) {
- if (!callback->eventDataPathTerminated(msg.ndp_instance_id[i]).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- }
- };
-
- callback_handlers.on_event_beacon_sdf_payload =
- [weak_ptr_this](const legacy_hal::NanBeaconSdfPayloadInd& /* msg */) {
- LOG(ERROR) << "on_event_beacon_sdf_payload - should not be called";
- };
-
- callback_handlers.on_event_range_request =
- [weak_ptr_this](const legacy_hal::NanRangeRequestInd& /* msg */) {
- LOG(ERROR) << "on_event_range_request - should not be called";
- };
-
- callback_handlers.on_event_range_report =
- [weak_ptr_this](const legacy_hal::NanRangeReportInd& /* msg */) {
- LOG(ERROR) << "on_event_range_report - should not be called";
- };
-
- callback_handlers.on_event_schedule_update =
- [weak_ptr_this](const legacy_hal::NanDataPathScheduleUpdateInd& msg) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- V1_6::NanDataPathScheduleUpdateInd hidl_struct;
- if (!hidl_struct_util::convertLegacyNanDataPathScheduleUpdateIndToHidl(
- msg, &hidl_struct)) {
- LOG(ERROR) << "Failed to convert nan capabilities response";
- return;
- }
-
- for (const auto& callback : shared_ptr_this->getEventCallbacks_1_6()) {
- if (!callback->eventDataPathScheduleUpdate_1_6(hidl_struct).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
-
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanRegisterCallbackHandlers(ifname_, callback_handlers);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- LOG(ERROR) << "Failed to register nan callbacks. Invalidating object";
- invalidate();
- }
-
- // Register for iface state toggle events.
- iface_util::IfaceEventHandlers event_handlers = {};
- event_handlers.on_state_toggle_off_on = [weak_ptr_this](const std::string& /* iface_name */) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- // Tell framework that NAN has been disabled.
- WifiNanStatus status = {NanStatusType::UNSUPPORTED_CONCURRENCY_NAN_DISABLED, ""};
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->eventDisabled(status).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
- iface_util_.lock()->registerIfaceEventHandlers(ifname_, event_handlers);
-}
-
-void WifiNanIface::invalidate() {
- if (!isValid()) {
- return;
- }
- // send commands to HAL to actually disable and destroy interfaces
- legacy_hal_.lock()->nanDisableRequest(ifname_, 0xFFFF);
- legacy_hal_.lock()->nanDataInterfaceDelete(ifname_, 0xFFFE, "aware_data0");
- legacy_hal_.lock()->nanDataInterfaceDelete(ifname_, 0xFFFD, "aware_data1");
- iface_util_.lock()->unregisterIfaceEventHandlers(ifname_);
- legacy_hal_.reset();
- event_cb_handler_.invalidate();
- event_cb_handler_1_2_.invalidate();
- event_cb_handler_1_5_.invalidate();
- is_valid_ = false;
- if (is_dedicated_iface_) {
- // If using a dedicated iface, set the iface down.
- iface_util_.lock()->setUpState(ifname_, false);
- }
-}
-
-bool WifiNanIface::isValid() {
- return is_valid_;
-}
-
-std::string WifiNanIface::getName() {
- return ifname_;
-}
-
-std::set<sp<V1_0::IWifiNanIfaceEventCallback>> WifiNanIface::getEventCallbacks() {
- return event_cb_handler_.getCallbacks();
-}
-
-std::set<sp<V1_2::IWifiNanIfaceEventCallback>> WifiNanIface::getEventCallbacks_1_2() {
- return event_cb_handler_1_2_.getCallbacks();
-}
-
-std::set<sp<V1_5::IWifiNanIfaceEventCallback>> WifiNanIface::getEventCallbacks_1_5() {
- return event_cb_handler_1_5_.getCallbacks();
-}
-
-std::set<sp<V1_6::IWifiNanIfaceEventCallback>> WifiNanIface::getEventCallbacks_1_6() {
- return event_cb_handler_1_6_.getCallbacks();
-}
-
-Return<void> WifiNanIface::getName(getName_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::getNameInternal, hidl_status_cb);
-}
-
-Return<void> WifiNanIface::getType(getType_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::getTypeInternal, hidl_status_cb);
-}
-
-Return<void> WifiNanIface::registerEventCallback(
- const sp<V1_0::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::registerEventCallbackInternal, hidl_status_cb, callback);
-}
-
-Return<void> WifiNanIface::getCapabilitiesRequest(uint16_t cmd_id,
- getCapabilitiesRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::getCapabilitiesRequestInternal, hidl_status_cb, cmd_id);
-}
-
-Return<void> WifiNanIface::enableRequest(uint16_t cmd_id, const V1_0::NanEnableRequest& msg,
- enableRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::enableRequestInternal, hidl_status_cb, cmd_id, msg);
-}
-
-Return<void> WifiNanIface::configRequest(uint16_t cmd_id, const V1_0::NanConfigRequest& msg,
- configRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::configRequestInternal, hidl_status_cb, cmd_id, msg);
-}
-
-Return<void> WifiNanIface::disableRequest(uint16_t cmd_id, disableRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::disableRequestInternal, hidl_status_cb, cmd_id);
-}
-
-Return<void> WifiNanIface::startPublishRequest(uint16_t cmd_id, const V1_0::NanPublishRequest& msg,
- startPublishRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::startPublishRequestInternal, hidl_status_cb, cmd_id, msg);
-}
-
-Return<void> WifiNanIface::stopPublishRequest(uint16_t cmd_id, uint8_t sessionId,
- stopPublishRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::stopPublishRequestInternal, hidl_status_cb, cmd_id,
- sessionId);
-}
-
-Return<void> WifiNanIface::startSubscribeRequest(uint16_t cmd_id,
- const V1_0::NanSubscribeRequest& msg,
- startSubscribeRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::startSubscribeRequestInternal, hidl_status_cb, cmd_id,
- msg);
-}
-
-Return<void> WifiNanIface::stopSubscribeRequest(uint16_t cmd_id, uint8_t sessionId,
- stopSubscribeRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::stopSubscribeRequestInternal, hidl_status_cb, cmd_id,
- sessionId);
-}
-
-Return<void> WifiNanIface::transmitFollowupRequest(uint16_t cmd_id,
- const NanTransmitFollowupRequest& msg,
- transmitFollowupRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::transmitFollowupRequestInternal, hidl_status_cb, cmd_id,
- msg);
-}
-
-Return<void> WifiNanIface::createDataInterfaceRequest(
- uint16_t cmd_id, const hidl_string& iface_name,
- createDataInterfaceRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::createDataInterfaceRequestInternal, hidl_status_cb,
- cmd_id, iface_name);
-}
-
-Return<void> WifiNanIface::deleteDataInterfaceRequest(
- uint16_t cmd_id, const hidl_string& iface_name,
- deleteDataInterfaceRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::deleteDataInterfaceRequestInternal, hidl_status_cb,
- cmd_id, iface_name);
-}
-
-Return<void> WifiNanIface::initiateDataPathRequest(uint16_t cmd_id,
- const V1_0::NanInitiateDataPathRequest& msg,
- initiateDataPathRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::initiateDataPathRequestInternal, hidl_status_cb, cmd_id,
- msg);
-}
-
-Return<void> WifiNanIface::respondToDataPathIndicationRequest(
- uint16_t cmd_id, const V1_0::NanRespondToDataPathIndicationRequest& msg,
- respondToDataPathIndicationRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::respondToDataPathIndicationRequestInternal,
- hidl_status_cb, cmd_id, msg);
-}
-
-Return<void> WifiNanIface::terminateDataPathRequest(uint16_t cmd_id, uint32_t ndpInstanceId,
- terminateDataPathRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::terminateDataPathRequestInternal, hidl_status_cb, cmd_id,
- ndpInstanceId);
-}
-
-Return<void> WifiNanIface::registerEventCallback_1_2(
- const sp<V1_2::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_1_2_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::registerEventCallback_1_2Internal, hidl_status_cb,
- callback);
-}
-
-Return<void> WifiNanIface::enableRequest_1_2(uint16_t cmd_id, const V1_0::NanEnableRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- enableRequest_1_2_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::enableRequest_1_2Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::configRequest_1_2(uint16_t cmd_id, const V1_0::NanConfigRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- configRequest_1_2_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::configRequest_1_2Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::enableRequest_1_4(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- enableRequest_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::enableRequest_1_4Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::configRequest_1_4(uint16_t cmd_id, const V1_4::NanConfigRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- configRequest_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::configRequest_1_4Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::registerEventCallback_1_5(
- const sp<V1_5::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::registerEventCallback_1_5Internal, hidl_status_cb,
- callback);
-}
-
-Return<void> WifiNanIface::enableRequest_1_5(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_5::NanConfigRequestSupplemental& msg2,
- enableRequest_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::enableRequest_1_5Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::configRequest_1_5(uint16_t cmd_id, const V1_4::NanConfigRequest& msg1,
- const V1_5::NanConfigRequestSupplemental& msg2,
- configRequest_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::configRequest_1_5Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::getCapabilitiesRequest_1_5(
- uint16_t cmd_id, getCapabilitiesRequest_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::getCapabilitiesRequest_1_5Internal, hidl_status_cb,
- cmd_id);
-}
-
-Return<void> WifiNanIface::enableRequest_1_6(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2,
- enableRequest_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::enableRequest_1_6Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::configRequest_1_6(uint16_t cmd_id, const V1_4::NanConfigRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2,
- configRequest_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::configRequest_1_6Internal, hidl_status_cb, cmd_id, msg1,
- msg2);
-}
-
-Return<void> WifiNanIface::initiateDataPathRequest_1_6(uint16_t cmd_id,
- const V1_6::NanInitiateDataPathRequest& msg,
- initiateDataPathRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::initiateDataPathRequest_1_6Internal, hidl_status_cb,
- cmd_id, msg);
-}
-
-Return<void> WifiNanIface::respondToDataPathIndicationRequest_1_6(
- uint16_t cmd_id, const V1_6::NanRespondToDataPathIndicationRequest& msg,
- respondToDataPathIndicationRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::respondToDataPathIndicationRequest_1_6Internal,
- hidl_status_cb, cmd_id, msg);
-}
-
-Return<void> WifiNanIface::startPublishRequest_1_6(uint16_t cmd_id,
- const V1_6::NanPublishRequest& msg,
- startPublishRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::startPublishRequest_1_6Internal, hidl_status_cb, cmd_id,
- msg);
-}
-
-std::pair<WifiStatus, std::string> WifiNanIface::getNameInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), ifname_};
-}
-
-std::pair<WifiStatus, IfaceType> WifiNanIface::getTypeInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), IfaceType::NAN};
-}
-
-Return<void> WifiNanIface::registerEventCallback_1_6(
- const sp<V1_6::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiNanIface::registerEventCallback_1_6Internal, hidl_status_cb,
- callback);
-}
-
-WifiStatus WifiNanIface::registerEventCallbackInternal(
- const sp<V1_0::IWifiNanIfaceEventCallback>& callback) {
- if (!event_cb_handler_.addCallback(callback)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-WifiStatus WifiNanIface::getCapabilitiesRequestInternal(uint16_t /* cmd_id */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::enableRequestInternal(uint16_t /* cmd_id */,
- const V1_0::NanEnableRequest& /* msg */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::configRequestInternal(uint16_t /* cmd_id */,
- const V1_0::NanConfigRequest& /* msg */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::disableRequestInternal(uint16_t cmd_id) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->nanDisableRequest(ifname_, cmd_id);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::startPublishRequestInternal(uint16_t /* cmd_id */,
- const V1_0::NanPublishRequest& /* msg */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::stopPublishRequestInternal(uint16_t cmd_id, uint8_t sessionId) {
- legacy_hal::NanPublishCancelRequest legacy_msg;
- legacy_msg.publish_id = sessionId;
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanPublishCancelRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::startSubscribeRequestInternal(uint16_t cmd_id,
- const V1_0::NanSubscribeRequest& msg) {
- legacy_hal::NanSubscribeRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanSubscribeRequestToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanSubscribeRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::stopSubscribeRequestInternal(uint16_t cmd_id, uint8_t sessionId) {
- legacy_hal::NanSubscribeCancelRequest legacy_msg;
- legacy_msg.subscribe_id = sessionId;
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanSubscribeCancelRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::transmitFollowupRequestInternal(uint16_t cmd_id,
- const NanTransmitFollowupRequest& msg) {
- legacy_hal::NanTransmitFollowupRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanTransmitFollowupRequestToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanTransmitFollowupRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::createDataInterfaceRequestInternal(uint16_t cmd_id,
- const std::string& iface_name) {
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataInterfaceCreate(ifname_, cmd_id, iface_name);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-WifiStatus WifiNanIface::deleteDataInterfaceRequestInternal(uint16_t cmd_id,
- const std::string& iface_name) {
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataInterfaceDelete(ifname_, cmd_id, iface_name);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-WifiStatus WifiNanIface::initiateDataPathRequestInternal(
- uint16_t cmd_id, const V1_0::NanInitiateDataPathRequest& msg) {
- legacy_hal::NanDataPathInitiatorRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanDataPathInitiatorRequestToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataRequestInitiator(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-WifiStatus WifiNanIface::respondToDataPathIndicationRequestInternal(
- uint16_t cmd_id, const V1_0::NanRespondToDataPathIndicationRequest& msg) {
- legacy_hal::NanDataPathIndicationResponse legacy_msg;
- if (!hidl_struct_util::convertHidlNanDataPathIndicationResponseToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataIndicationResponse(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-WifiStatus WifiNanIface::terminateDataPathRequestInternal(uint16_t cmd_id, uint32_t ndpInstanceId) {
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataEnd(ifname_, cmd_id, ndpInstanceId);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::registerEventCallback_1_2Internal(
- const sp<V1_2::IWifiNanIfaceEventCallback>& callback) {
- sp<V1_0::IWifiNanIfaceEventCallback> callback_1_0 = callback;
- if (!event_cb_handler_.addCallback(callback_1_0)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- if (!event_cb_handler_1_2_.addCallback(callback)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-WifiStatus WifiNanIface::enableRequest_1_2Internal(
- uint16_t /* cmd_id */, const V1_0::NanEnableRequest& /* msg1 */,
- const V1_2::NanConfigRequestSupplemental& /* msg2 */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::configRequest_1_2Internal(
- uint16_t /* cmd_id */, const V1_0::NanConfigRequest& /* msg1 */,
- const V1_2::NanConfigRequestSupplemental& /* msg2 */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::enableRequest_1_4Internal(
- uint16_t /* cmd_id */, const V1_4::NanEnableRequest& /* msg1 */,
- const V1_2::NanConfigRequestSupplemental& /* msg2 */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::configRequest_1_4Internal(
- uint16_t /* cmd_id */, const V1_4::NanConfigRequest& /* msg1 */,
- const V1_2::NanConfigRequestSupplemental& /* msg2 */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::registerEventCallback_1_5Internal(
- const sp<V1_5::IWifiNanIfaceEventCallback>& callback) {
- sp<V1_0::IWifiNanIfaceEventCallback> callback_1_0 = callback;
- if (!event_cb_handler_.addCallback(callback_1_0)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- sp<V1_2::IWifiNanIfaceEventCallback> callback_1_2 = callback;
- if (!event_cb_handler_1_2_.addCallback(callback_1_2)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- if (!event_cb_handler_1_5_.addCallback(callback)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-WifiStatus WifiNanIface::getCapabilitiesRequest_1_5Internal(uint16_t cmd_id) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->nanGetCapabilities(ifname_, cmd_id);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::enableRequest_1_5Internal(
- uint16_t /* cmd_id */, const V1_4::NanEnableRequest& /* msg1 */,
- const V1_5::NanConfigRequestSupplemental& /* msg2 */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::configRequest_1_5Internal(
- uint16_t /* cmd_id */, const V1_4::NanConfigRequest& /* msg1 */,
- const V1_5::NanConfigRequestSupplemental& /* msg2 */) {
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiNanIface::enableRequest_1_6Internal(uint16_t cmd_id,
- const V1_4::NanEnableRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2) {
- legacy_hal::NanEnableRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanEnableRequest_1_6ToLegacy(msg1, msg2, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanEnableRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::configRequest_1_6Internal(uint16_t cmd_id,
- const V1_4::NanConfigRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2) {
- legacy_hal::NanConfigRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanConfigRequest_1_6ToLegacy(msg1, msg2, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanConfigRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::initiateDataPathRequest_1_6Internal(
- uint16_t cmd_id, const V1_6::NanInitiateDataPathRequest& msg) {
- legacy_hal::NanDataPathInitiatorRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanDataPathInitiatorRequest_1_6ToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataRequestInitiator(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::respondToDataPathIndicationRequest_1_6Internal(
- uint16_t cmd_id, const V1_6::NanRespondToDataPathIndicationRequest& msg) {
- legacy_hal::NanDataPathIndicationResponse legacy_msg;
- if (!hidl_struct_util::convertHidlNanDataPathIndicationResponse_1_6ToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanDataIndicationResponse(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::startPublishRequest_1_6Internal(uint16_t cmd_id,
- const V1_6::NanPublishRequest& msg) {
- legacy_hal::NanPublishRequest legacy_msg;
- if (!hidl_struct_util::convertHidlNanPublishRequestToLegacy(msg, &legacy_msg)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->nanPublishRequest(ifname_, cmd_id, legacy_msg);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiNanIface::registerEventCallback_1_6Internal(
- const sp<V1_6::IWifiNanIfaceEventCallback>& callback) {
- sp<V1_0::IWifiNanIfaceEventCallback> callback_1_0 = callback;
- if (!event_cb_handler_.addCallback(callback_1_0)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- sp<V1_2::IWifiNanIfaceEventCallback> callback_1_2 = callback;
- if (!event_cb_handler_1_2_.addCallback(callback_1_2)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- sp<V1_5::IWifiNanIfaceEventCallback> callback_1_5 = callback;
- if (!event_cb_handler_1_5_.addCallback(callback_1_5)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- if (!event_cb_handler_1_6_.addCallback(callback)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/wifi_nan_iface.h b/wifi/1.6/default/wifi_nan_iface.h
deleted file mode 100644
index 15bf572..0000000
--- a/wifi/1.6/default/wifi_nan_iface.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_NAN_IFACE_H_
-#define WIFI_NAN_IFACE_H_
-
-#include <android-base/macros.h>
-#include <android/hardware/wifi/1.6/IWifiNanIface.h>
-#include <android/hardware/wifi/1.6/IWifiNanIfaceEventCallback.h>
-
-#include "hidl_callback_util.h"
-#include "wifi_iface_util.h"
-#include "wifi_legacy_hal.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
-using namespace android::hardware::wifi::V1_2;
-using namespace android::hardware::wifi::V1_4;
-using namespace android::hardware::wifi::V1_6;
-
-/**
- * HIDL interface object used to control a NAN Iface instance.
- */
-class WifiNanIface : public V1_6::IWifiNanIface {
- public:
- WifiNanIface(const std::string& ifname, bool is_dedicated_iface,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
- // Refer to |WifiChip::invalidate()|.
- void invalidate();
- bool isValid();
- std::string getName();
-
- // HIDL methods exposed.
- Return<void> getName(getName_cb hidl_status_cb) override;
- Return<void> getType(getType_cb hidl_status_cb) override;
- Return<void> registerEventCallback(const sp<V1_0::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_cb hidl_status_cb) override;
- Return<void> getCapabilitiesRequest(uint16_t cmd_id,
- getCapabilitiesRequest_cb hidl_status_cb) override;
- Return<void> enableRequest(uint16_t cmd_id, const V1_0::NanEnableRequest& msg,
- enableRequest_cb hidl_status_cb) override;
- Return<void> configRequest(uint16_t cmd_id, const V1_0::NanConfigRequest& msg,
- configRequest_cb hidl_status_cb) override;
- Return<void> disableRequest(uint16_t cmd_id, disableRequest_cb hidl_status_cb) override;
- Return<void> startPublishRequest(uint16_t cmd_id, const V1_0::NanPublishRequest& msg,
- startPublishRequest_cb hidl_status_cb) override;
- Return<void> stopPublishRequest(uint16_t cmd_id, uint8_t sessionId,
- stopPublishRequest_cb hidl_status_cb) override;
- Return<void> startSubscribeRequest(uint16_t cmd_id, const V1_0::NanSubscribeRequest& msg,
- startSubscribeRequest_cb hidl_status_cb) override;
- Return<void> stopSubscribeRequest(uint16_t cmd_id, uint8_t sessionId,
- stopSubscribeRequest_cb hidl_status_cb) override;
- Return<void> transmitFollowupRequest(uint16_t cmd_id, const NanTransmitFollowupRequest& msg,
- transmitFollowupRequest_cb hidl_status_cb) override;
- Return<void> createDataInterfaceRequest(uint16_t cmd_id, const hidl_string& iface_name,
- createDataInterfaceRequest_cb hidl_status_cb) override;
- Return<void> deleteDataInterfaceRequest(uint16_t cmd_id, const hidl_string& iface_name,
- deleteDataInterfaceRequest_cb hidl_status_cb) override;
- Return<void> initiateDataPathRequest(uint16_t cmd_id,
- const V1_0::NanInitiateDataPathRequest& msg,
- initiateDataPathRequest_cb hidl_status_cb) override;
- Return<void> respondToDataPathIndicationRequest(
- uint16_t cmd_id, const V1_0::NanRespondToDataPathIndicationRequest& msg,
- respondToDataPathIndicationRequest_cb hidl_status_cb) override;
- Return<void> terminateDataPathRequest(uint16_t cmd_id, uint32_t ndpInstanceId,
- terminateDataPathRequest_cb hidl_status_cb) override;
-
- Return<void> registerEventCallback_1_2(const sp<V1_2::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_1_2_cb hidl_status_cb) override;
- Return<void> enableRequest_1_2(uint16_t cmd_id, const V1_0::NanEnableRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- enableRequest_1_2_cb hidl_status_cb) override;
- Return<void> configRequest_1_2(uint16_t cmd_id, const V1_0::NanConfigRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- configRequest_1_2_cb hidl_status_cb) override;
- Return<void> enableRequest_1_4(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- enableRequest_1_4_cb hidl_status_cb) override;
- Return<void> configRequest_1_4(uint16_t cmd_id, const V1_4::NanConfigRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2,
- configRequest_1_4_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_5(const sp<V1_5::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_1_5_cb hidl_status_cb) override;
- Return<void> enableRequest_1_5(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_5::NanConfigRequestSupplemental& msg2,
- enableRequest_1_5_cb hidl_status_cb) override;
- Return<void> configRequest_1_5(uint16_t cmd_id, const V1_4::NanConfigRequest& msg1,
- const V1_5::NanConfigRequestSupplemental& msg2,
- configRequest_1_5_cb hidl_status_cb) override;
- Return<void> getCapabilitiesRequest_1_5(uint16_t cmd_id,
- getCapabilitiesRequest_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_6(const sp<V1_6::IWifiNanIfaceEventCallback>& callback,
- registerEventCallback_1_6_cb hidl_status_cb) override;
- Return<void> initiateDataPathRequest_1_6(
- uint16_t cmd_id, const V1_6::NanInitiateDataPathRequest& msg,
- initiateDataPathRequest_1_6_cb hidl_status_cb) override;
- Return<void> respondToDataPathIndicationRequest_1_6(
- uint16_t cmd_id, const V1_6::NanRespondToDataPathIndicationRequest& msg,
- respondToDataPathIndicationRequest_1_6_cb hidl_status_cb) override;
- Return<void> enableRequest_1_6(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2,
- enableRequest_1_6_cb hidl_status_cb) override;
- Return<void> configRequest_1_6(uint16_t cmd_id, const V1_4::NanConfigRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2,
- configRequest_1_6_cb hidl_status_cb) override;
- Return<void> startPublishRequest_1_6(uint16_t cmd_id, const V1_6::NanPublishRequest& msg,
- startPublishRequest_cb hidl_status_cb) override;
-
- private:
- // Corresponding worker functions for the HIDL methods.
- std::pair<WifiStatus, std::string> getNameInternal();
- std::pair<WifiStatus, IfaceType> getTypeInternal();
- WifiStatus registerEventCallbackInternal(const sp<V1_0::IWifiNanIfaceEventCallback>& callback);
- WifiStatus getCapabilitiesRequestInternal(uint16_t cmd_id);
- WifiStatus enableRequestInternal(uint16_t cmd_id, const V1_0::NanEnableRequest& msg);
- WifiStatus configRequestInternal(uint16_t cmd_id, const V1_0::NanConfigRequest& msg);
- WifiStatus disableRequestInternal(uint16_t cmd_id);
- WifiStatus startPublishRequestInternal(uint16_t cmd_id, const V1_0::NanPublishRequest& msg);
- WifiStatus stopPublishRequestInternal(uint16_t cmd_id, uint8_t sessionId);
- WifiStatus startSubscribeRequestInternal(uint16_t cmd_id, const V1_0::NanSubscribeRequest& msg);
- WifiStatus stopSubscribeRequestInternal(uint16_t cmd_id, uint8_t sessionId);
- WifiStatus transmitFollowupRequestInternal(uint16_t cmd_id,
- const NanTransmitFollowupRequest& msg);
- WifiStatus createDataInterfaceRequestInternal(uint16_t cmd_id, const std::string& iface_name);
- WifiStatus deleteDataInterfaceRequestInternal(uint16_t cmd_id, const std::string& iface_name);
- WifiStatus initiateDataPathRequestInternal(uint16_t cmd_id,
- const V1_0::NanInitiateDataPathRequest& msg);
- WifiStatus respondToDataPathIndicationRequestInternal(
- uint16_t cmd_id, const V1_0::NanRespondToDataPathIndicationRequest& msg);
- WifiStatus terminateDataPathRequestInternal(uint16_t cmd_id, uint32_t ndpInstanceId);
-
- WifiStatus registerEventCallback_1_2Internal(
- const sp<V1_2::IWifiNanIfaceEventCallback>& callback);
- WifiStatus enableRequest_1_2Internal(uint16_t cmd_id, const V1_0::NanEnableRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2);
- WifiStatus configRequest_1_2Internal(uint16_t cmd_id, const V1_0::NanConfigRequest& msg,
- const V1_2::NanConfigRequestSupplemental& msg2);
- WifiStatus enableRequest_1_4Internal(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_2::NanConfigRequestSupplemental& msg2);
- WifiStatus configRequest_1_4Internal(uint16_t cmd_id, const V1_4::NanConfigRequest& msg,
- const V1_2::NanConfigRequestSupplemental& msg2);
- WifiStatus registerEventCallback_1_5Internal(
- const sp<V1_5::IWifiNanIfaceEventCallback>& callback);
- WifiStatus enableRequest_1_5Internal(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_5::NanConfigRequestSupplemental& msg2);
- WifiStatus configRequest_1_5Internal(uint16_t cmd_id, const V1_4::NanConfigRequest& msg,
- const V1_5::NanConfigRequestSupplemental& msg2);
- WifiStatus getCapabilitiesRequest_1_5Internal(uint16_t cmd_id);
- WifiStatus registerEventCallback_1_6Internal(
- const sp<V1_6::IWifiNanIfaceEventCallback>& callback);
-
- WifiStatus enableRequest_1_6Internal(uint16_t cmd_id, const V1_4::NanEnableRequest& msg1,
- const V1_6::NanConfigRequestSupplemental& msg2);
- WifiStatus configRequest_1_6Internal(uint16_t cmd_id, const V1_4::NanConfigRequest& msg,
- const V1_6::NanConfigRequestSupplemental& msg2);
- WifiStatus startPublishRequest_1_6Internal(uint16_t cmd_id, const V1_6::NanPublishRequest& msg);
- WifiStatus initiateDataPathRequest_1_6Internal(uint16_t cmd_id,
- const V1_6::NanInitiateDataPathRequest& msg);
- WifiStatus respondToDataPathIndicationRequest_1_6Internal(
- uint16_t cmd_id, const V1_6::NanRespondToDataPathIndicationRequest& msg);
-
- // all 1_0 and descendant callbacks
- std::set<sp<V1_0::IWifiNanIfaceEventCallback>> getEventCallbacks();
- // all 1_2 and descendant callbacks
- std::set<sp<V1_2::IWifiNanIfaceEventCallback>> getEventCallbacks_1_2();
- // all 1_5 and descendant callbacks
- std::set<sp<V1_5::IWifiNanIfaceEventCallback>> getEventCallbacks_1_5();
- // all 1_6 and descendant callbacks
- std::set<sp<V1_6::IWifiNanIfaceEventCallback>> getEventCallbacks_1_6();
-
- std::string ifname_;
- bool is_dedicated_iface_;
- std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
- std::weak_ptr<iface_util::WifiIfaceUtil> iface_util_;
- bool is_valid_;
- hidl_callback_util::HidlCallbackHandler<V1_0::IWifiNanIfaceEventCallback> event_cb_handler_;
- hidl_callback_util::HidlCallbackHandler<V1_2::IWifiNanIfaceEventCallback> event_cb_handler_1_2_;
- hidl_callback_util::HidlCallbackHandler<V1_5::IWifiNanIfaceEventCallback> event_cb_handler_1_5_;
- hidl_callback_util::HidlCallbackHandler<V1_6::IWifiNanIfaceEventCallback> event_cb_handler_1_6_;
-
- DISALLOW_COPY_AND_ASSIGN(WifiNanIface);
-};
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_NAN_IFACE_H_
diff --git a/wifi/1.6/default/wifi_rtt_controller.cpp b/wifi/1.6/default/wifi_rtt_controller.cpp
deleted file mode 100644
index aa9ee2f..0000000
--- a/wifi/1.6/default/wifi_rtt_controller.cpp
+++ /dev/null
@@ -1,377 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-
-#include "hidl_return_util.h"
-#include "hidl_struct_util.h"
-#include "wifi_rtt_controller.h"
-#include "wifi_status_util.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
-
-WifiRttController::WifiRttController(const std::string& iface_name,
- const sp<IWifiIface>& bound_iface,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal)
- : ifname_(iface_name), bound_iface_(bound_iface), legacy_hal_(legacy_hal), is_valid_(true) {}
-
-void WifiRttController::invalidate() {
- legacy_hal_.reset();
- event_callbacks_.clear();
- is_valid_ = false;
-}
-
-bool WifiRttController::isValid() {
- return is_valid_;
-}
-
-std::vector<sp<V1_6::IWifiRttControllerEventCallback>> WifiRttController::getEventCallbacks() {
- return event_callbacks_;
-}
-
-std::string WifiRttController::getIfaceName() {
- return ifname_;
-}
-
-Return<void> WifiRttController::getBoundIface(getBoundIface_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getBoundIfaceInternal, hidl_status_cb);
-}
-
-Return<void> WifiRttController::registerEventCallback(
- const sp<V1_0::IWifiRttControllerEventCallback>& callback,
- registerEventCallback_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::registerEventCallbackInternal, hidl_status_cb,
- callback);
-}
-
-Return<void> WifiRttController::rangeRequest(uint32_t cmd_id,
- const hidl_vec<V1_0::RttConfig>& rtt_configs,
- rangeRequest_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::rangeRequestInternal, hidl_status_cb, cmd_id,
- rtt_configs);
-}
-
-Return<void> WifiRttController::rangeCancel(uint32_t cmd_id,
- const hidl_vec<hidl_array<uint8_t, 6>>& addrs,
- rangeCancel_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::rangeCancelInternal, hidl_status_cb, cmd_id, addrs);
-}
-
-Return<void> WifiRttController::getCapabilities(getCapabilities_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getCapabilitiesInternal, hidl_status_cb);
-}
-
-Return<void> WifiRttController::setLci(uint32_t cmd_id, const RttLciInformation& lci,
- setLci_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::setLciInternal, hidl_status_cb, cmd_id, lci);
-}
-
-Return<void> WifiRttController::setLcr(uint32_t cmd_id, const RttLcrInformation& lcr,
- setLcr_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::setLcrInternal, hidl_status_cb, cmd_id, lcr);
-}
-
-Return<void> WifiRttController::getResponderInfo(getResponderInfo_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getResponderInfoInternal, hidl_status_cb);
-}
-
-Return<void> WifiRttController::enableResponder(uint32_t cmd_id,
- const V1_0::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_0::RttResponder& info,
- enableResponder_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::enableResponderInternal, hidl_status_cb, cmd_id,
- channel_hint, max_duration_seconds, info);
-}
-
-Return<void> WifiRttController::disableResponder(uint32_t cmd_id,
- disableResponder_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::disableResponderInternal, hidl_status_cb, cmd_id);
-}
-
-Return<void> WifiRttController::registerEventCallback_1_4(
- const sp<V1_4::IWifiRttControllerEventCallback>& callback,
- registerEventCallback_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::registerEventCallbackInternal_1_4, hidl_status_cb,
- callback);
-}
-
-Return<void> WifiRttController::rangeRequest_1_4(uint32_t cmd_id,
- const hidl_vec<V1_4::RttConfig>& rtt_configs,
- rangeRequest_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::rangeRequestInternal_1_4, hidl_status_cb, cmd_id,
- rtt_configs);
-}
-
-Return<void> WifiRttController::getCapabilities_1_4(getCapabilities_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getCapabilitiesInternal_1_4, hidl_status_cb);
-}
-
-Return<void> WifiRttController::getResponderInfo_1_4(getResponderInfo_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getResponderInfoInternal_1_4, hidl_status_cb);
-}
-
-Return<void> WifiRttController::enableResponder_1_4(uint32_t cmd_id,
- const V1_0::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_4::RttResponder& info,
- enableResponder_1_4_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::enableResponderInternal_1_4, hidl_status_cb, cmd_id,
- channel_hint, max_duration_seconds, info);
-}
-
-Return<void> WifiRttController::registerEventCallback_1_6(
- const sp<V1_6::IWifiRttControllerEventCallback>& callback,
- registerEventCallback_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::registerEventCallbackInternal_1_6, hidl_status_cb,
- callback);
-}
-
-Return<void> WifiRttController::rangeRequest_1_6(uint32_t cmd_id,
- const hidl_vec<V1_6::RttConfig>& rtt_configs,
- rangeRequest_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::rangeRequestInternal_1_6, hidl_status_cb, cmd_id,
- rtt_configs);
-}
-
-Return<void> WifiRttController::getCapabilities_1_6(getCapabilities_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getCapabilitiesInternal_1_6, hidl_status_cb);
-}
-
-Return<void> WifiRttController::getResponderInfo_1_6(getResponderInfo_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::getResponderInfoInternal_1_6, hidl_status_cb);
-}
-
-Return<void> WifiRttController::enableResponder_1_6(uint32_t cmd_id,
- const V1_6::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_6::RttResponder& info,
- enableResponder_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
- &WifiRttController::enableResponderInternal_1_6, hidl_status_cb, cmd_id,
- channel_hint, max_duration_seconds, info);
-}
-
-std::pair<WifiStatus, sp<IWifiIface>> WifiRttController::getBoundIfaceInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), bound_iface_};
-}
-
-WifiStatus WifiRttController::registerEventCallbackInternal(
- const sp<V1_0::IWifiRttControllerEventCallback>& /* callback */) {
- // Deprecated support for this api
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiRttController::rangeRequestInternal(
- uint32_t /* cmd_id */, const std::vector<V1_0::RttConfig>& /* rtt_configs */) {
- // Deprecated support for this api
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiRttController::rangeCancelInternal(
- uint32_t cmd_id, const std::vector<hidl_array<uint8_t, 6>>& addrs) {
- std::vector<std::array<uint8_t, 6>> legacy_addrs;
- for (const auto& addr : addrs) {
- legacy_addrs.push_back(addr);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->cancelRttRangeRequest(ifname_, cmd_id, legacy_addrs);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, V1_0::RttCapabilities> WifiRttController::getCapabilitiesInternal() {
- // Deprecated support for this api
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-WifiStatus WifiRttController::setLciInternal(uint32_t cmd_id, const RttLciInformation& lci) {
- legacy_hal::wifi_lci_information legacy_lci;
- if (!hidl_struct_util::convertHidlRttLciInformationToLegacy(lci, &legacy_lci)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->setRttLci(ifname_, cmd_id, legacy_lci);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiRttController::setLcrInternal(uint32_t cmd_id, const RttLcrInformation& lcr) {
- legacy_hal::wifi_lcr_information legacy_lcr;
- if (!hidl_struct_util::convertHidlRttLcrInformationToLegacy(lcr, &legacy_lcr)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->setRttLcr(ifname_, cmd_id, legacy_lcr);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, V1_0::RttResponder> WifiRttController::getResponderInfoInternal() {
- // Deprecated support for this api
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-WifiStatus WifiRttController::enableResponderInternal(
- uint32_t /* cmd_id */, const V1_0::WifiChannelInfo& /* channel_hint */,
- uint32_t /* max_duration_seconds */, const V1_0::RttResponder& /* info */) {
- // Deprecated support for this api
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED)};
-}
-
-WifiStatus WifiRttController::disableResponderInternal(uint32_t cmd_id) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->disableRttResponder(ifname_, cmd_id);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiRttController::registerEventCallbackInternal_1_4(
- const sp<V1_4::IWifiRttControllerEventCallback>& /* callback */) {
- // Deprecated support for this api
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiRttController::rangeRequestInternal_1_4(
- uint32_t /* cmd_id */, const std::vector<V1_4::RttConfig>& /* rtt_configs */) {
- // Deprecated support for this api
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-std::pair<WifiStatus, V1_4::RttCapabilities> WifiRttController::getCapabilitiesInternal_1_4() {
- // Deprecated support for this api
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-std::pair<WifiStatus, V1_4::RttResponder> WifiRttController::getResponderInfoInternal_1_4() {
- // Deprecated support for this api
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-WifiStatus WifiRttController::enableResponderInternal_1_4(
- uint32_t /* cmd_id */, const V1_0::WifiChannelInfo& /* channel_hint */,
- uint32_t /* max_duration_seconds */, const V1_4::RttResponder& /* info */) {
- // Deprecated support for this api
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED)};
-}
-
-WifiStatus WifiRttController::registerEventCallbackInternal_1_6(
- const sp<V1_6::IWifiRttControllerEventCallback>& callback) {
- // TODO(b/31632518): remove the callback when the client is destroyed
- event_callbacks_.emplace_back(callback);
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-WifiStatus WifiRttController::rangeRequestInternal_1_6(
- uint32_t cmd_id, const std::vector<V1_6::RttConfig>& rtt_configs) {
- std::vector<legacy_hal::wifi_rtt_config> legacy_configs;
- if (!hidl_struct_util::convertHidlVectorOfRttConfigToLegacy(rtt_configs, &legacy_configs)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- android::wp<WifiRttController> weak_ptr_this(this);
- const auto& on_results_callback =
- [weak_ptr_this](legacy_hal::wifi_request_id id,
- const std::vector<const legacy_hal::wifi_rtt_result*>& results) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- std::vector<V1_6::RttResult> hidl_results;
- if (!hidl_struct_util::convertLegacyVectorOfRttResultToHidl(results,
- &hidl_results)) {
- LOG(ERROR) << "Failed to convert rtt results to HIDL structs";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->onResults_1_6(id, hidl_results).isOk()) {
- LOG(ERROR) << "Failed to invoke the callback";
- }
- }
- };
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startRttRangeRequest(
- ifname_, cmd_id, legacy_configs, on_results_callback);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, V1_6::RttCapabilities> WifiRttController::getCapabilitiesInternal_1_6() {
- legacy_hal::wifi_error legacy_status;
- legacy_hal::wifi_rtt_capabilities legacy_caps;
- std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getRttCapabilities(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- V1_6::RttCapabilities hidl_caps;
- if (!hidl_struct_util::convertLegacyRttCapabilitiesToHidl(legacy_caps, &hidl_caps)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_caps};
-}
-
-std::pair<WifiStatus, V1_6::RttResponder> WifiRttController::getResponderInfoInternal_1_6() {
- legacy_hal::wifi_error legacy_status;
- legacy_hal::wifi_rtt_responder legacy_responder;
- std::tie(legacy_status, legacy_responder) = legacy_hal_.lock()->getRttResponderInfo(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- V1_6::RttResponder hidl_responder;
- if (!hidl_struct_util::convertLegacyRttResponderToHidl(legacy_responder, &hidl_responder)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_responder};
-}
-
-WifiStatus WifiRttController::enableResponderInternal_1_6(uint32_t cmd_id,
- const V1_6::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_6::RttResponder& info) {
- legacy_hal::wifi_channel_info legacy_channel_info;
- if (!hidl_struct_util::convertHidlWifiChannelInfoToLegacy(channel_hint, &legacy_channel_info)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_rtt_responder legacy_responder;
- if (!hidl_struct_util::convertHidlRttResponderToLegacy(info, &legacy_responder)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->enableRttResponder(
- ifname_, cmd_id, legacy_channel_info, max_duration_seconds, legacy_responder);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/wifi_rtt_controller.h b/wifi/1.6/default/wifi_rtt_controller.h
deleted file mode 100644
index fd5f68b..0000000
--- a/wifi/1.6/default/wifi_rtt_controller.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_RTT_CONTROLLER_H_
-#define WIFI_RTT_CONTROLLER_H_
-
-#include <android-base/macros.h>
-#include <android/hardware/wifi/1.0/IWifiIface.h>
-#include <android/hardware/wifi/1.6/IWifiRttController.h>
-#include <android/hardware/wifi/1.6/IWifiRttControllerEventCallback.h>
-
-#include "wifi_legacy_hal.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-
-/**
- * HIDL interface object used to control all RTT operations.
- */
-class WifiRttController : public V1_6::IWifiRttController {
- public:
- WifiRttController(const std::string& iface_name, const sp<IWifiIface>& bound_iface,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal);
- // Refer to |WifiChip::invalidate()|.
- void invalidate();
- bool isValid();
- std::vector<sp<V1_6::IWifiRttControllerEventCallback>> getEventCallbacks();
- std::string getIfaceName();
-
- // HIDL methods exposed.
- Return<void> getBoundIface(getBoundIface_cb hidl_status_cb) override;
- Return<void> registerEventCallback(const sp<V1_0::IWifiRttControllerEventCallback>& callback,
- registerEventCallback_cb hidl_status_cb) override;
- Return<void> rangeRequest(uint32_t cmd_id, const hidl_vec<V1_0::RttConfig>& rtt_configs,
- rangeRequest_cb hidl_status_cb) override;
- Return<void> rangeCancel(uint32_t cmd_id, const hidl_vec<hidl_array<uint8_t, 6>>& addrs,
- rangeCancel_cb hidl_status_cb) override;
- Return<void> getCapabilities(getCapabilities_cb hidl_status_cb) override;
- Return<void> setLci(uint32_t cmd_id, const RttLciInformation& lci,
- setLci_cb hidl_status_cb) override;
- Return<void> setLcr(uint32_t cmd_id, const RttLcrInformation& lcr,
- setLcr_cb hidl_status_cb) override;
- Return<void> getResponderInfo(getResponderInfo_cb hidl_status_cb) override;
- Return<void> enableResponder(uint32_t cmd_id, const V1_0::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds, const V1_0::RttResponder& info,
- enableResponder_cb hidl_status_cb) override;
- Return<void> disableResponder(uint32_t cmd_id, disableResponder_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_4(
- const sp<V1_4::IWifiRttControllerEventCallback>& callback,
- registerEventCallback_1_4_cb hidl_status_cb) override;
- Return<void> rangeRequest_1_4(uint32_t cmd_id, const hidl_vec<V1_4::RttConfig>& rtt_configs,
- rangeRequest_1_4_cb hidl_status_cb) override;
- Return<void> getCapabilities_1_4(getCapabilities_1_4_cb hidl_status_cb) override;
- Return<void> getResponderInfo_1_4(getResponderInfo_1_4_cb hidl_status_cb) override;
- Return<void> enableResponder_1_4(uint32_t cmd_id, const V1_0::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds, const V1_4::RttResponder& info,
- enableResponder_1_4_cb hidl_status_cb) override;
- Return<void> registerEventCallback_1_6(
- const sp<V1_6::IWifiRttControllerEventCallback>& callback,
- registerEventCallback_1_6_cb hidl_status_cb) override;
- Return<void> rangeRequest_1_6(uint32_t cmd_id, const hidl_vec<V1_6::RttConfig>& rtt_configs,
- rangeRequest_1_6_cb hidl_status_cb) override;
- Return<void> getCapabilities_1_6(getCapabilities_1_6_cb hidl_status_cb) override;
- Return<void> getResponderInfo_1_6(getResponderInfo_1_6_cb hidl_status_cb) override;
- Return<void> enableResponder_1_6(uint32_t cmd_id, const V1_6::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds, const V1_6::RttResponder& info,
- enableResponder_1_6_cb hidl_status_cb) override;
-
- private:
- // Corresponding worker functions for the HIDL methods.
- std::pair<WifiStatus, sp<IWifiIface>> getBoundIfaceInternal();
- WifiStatus registerEventCallbackInternal(
- const sp<V1_0::IWifiRttControllerEventCallback>& callback);
- WifiStatus rangeRequestInternal(uint32_t cmd_id,
- const std::vector<V1_0::RttConfig>& rtt_configs);
- WifiStatus rangeCancelInternal(uint32_t cmd_id,
- const std::vector<hidl_array<uint8_t, 6>>& addrs);
- std::pair<WifiStatus, V1_0::RttCapabilities> getCapabilitiesInternal();
- WifiStatus setLciInternal(uint32_t cmd_id, const RttLciInformation& lci);
- WifiStatus setLcrInternal(uint32_t cmd_id, const RttLcrInformation& lcr);
- std::pair<WifiStatus, V1_0::RttResponder> getResponderInfoInternal();
- WifiStatus enableResponderInternal(uint32_t cmd_id, const V1_0::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_0::RttResponder& info);
- WifiStatus disableResponderInternal(uint32_t cmd_id);
- WifiStatus registerEventCallbackInternal_1_4(
- const sp<V1_4::IWifiRttControllerEventCallback>& callback);
- WifiStatus rangeRequestInternal_1_4(uint32_t cmd_id,
- const std::vector<V1_4::RttConfig>& rtt_configs);
- std::pair<WifiStatus, V1_4::RttCapabilities> getCapabilitiesInternal_1_4();
- std::pair<WifiStatus, V1_4::RttResponder> getResponderInfoInternal_1_4();
- WifiStatus enableResponderInternal_1_4(uint32_t cmd_id,
- const V1_0::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_4::RttResponder& info);
- WifiStatus registerEventCallbackInternal_1_6(
- const sp<V1_6::IWifiRttControllerEventCallback>& callback);
- WifiStatus rangeRequestInternal_1_6(uint32_t cmd_id,
- const std::vector<V1_6::RttConfig>& rtt_configs);
- std::pair<WifiStatus, V1_6::RttCapabilities> getCapabilitiesInternal_1_6();
- std::pair<WifiStatus, V1_6::RttResponder> getResponderInfoInternal_1_6();
- WifiStatus enableResponderInternal_1_6(uint32_t cmd_id,
- const V1_6::WifiChannelInfo& channel_hint,
- uint32_t max_duration_seconds,
- const V1_6::RttResponder& info);
-
- std::string ifname_;
- sp<IWifiIface> bound_iface_;
- std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
- std::vector<sp<V1_6::IWifiRttControllerEventCallback>> event_callbacks_;
- bool is_valid_;
-
- DISALLOW_COPY_AND_ASSIGN(WifiRttController);
-};
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_RTT_CONTROLLER_H_
diff --git a/wifi/1.6/default/wifi_sta_iface.cpp b/wifi/1.6/default/wifi_sta_iface.cpp
deleted file mode 100644
index dd11839..0000000
--- a/wifi/1.6/default/wifi_sta_iface.cpp
+++ /dev/null
@@ -1,592 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 <android-base/logging.h>
-
-#include "hidl_return_util.h"
-#include "hidl_struct_util.h"
-#include "wifi_sta_iface.h"
-#include "wifi_status_util.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
-
-WifiStaIface::WifiStaIface(const std::string& ifname,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
- : ifname_(ifname), legacy_hal_(legacy_hal), iface_util_(iface_util), is_valid_(true) {
- // Turn on DFS channel usage for STA iface.
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->setDfsFlag(ifname_, true);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- LOG(ERROR) << "Failed to set DFS flag; DFS channels may be unavailable.";
- }
-}
-
-void WifiStaIface::invalidate() {
- legacy_hal_.reset();
- event_cb_handler_.invalidate();
- is_valid_ = false;
-}
-
-bool WifiStaIface::isValid() {
- return is_valid_;
-}
-
-std::string WifiStaIface::getName() {
- return ifname_;
-}
-
-std::set<sp<IWifiStaIfaceEventCallback>> WifiStaIface::getEventCallbacks() {
- return event_cb_handler_.getCallbacks();
-}
-
-Return<void> WifiStaIface::getName(getName_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getNameInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getType(getType_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getTypeInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::registerEventCallback(const sp<IWifiStaIfaceEventCallback>& callback,
- registerEventCallback_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::registerEventCallbackInternal, hidl_status_cb, callback);
-}
-
-Return<void> WifiStaIface::getCapabilities(getCapabilities_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getCapabilitiesInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getApfPacketFilterCapabilities(
- getApfPacketFilterCapabilities_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getApfPacketFilterCapabilitiesInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::installApfPacketFilter(uint32_t cmd_id, const hidl_vec<uint8_t>& program,
- installApfPacketFilter_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::installApfPacketFilterInternal, hidl_status_cb, cmd_id,
- program);
-}
-
-Return<void> WifiStaIface::readApfPacketFilterData(readApfPacketFilterData_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::readApfPacketFilterDataInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getBackgroundScanCapabilities(
- getBackgroundScanCapabilities_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getBackgroundScanCapabilitiesInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getValidFrequenciesForBand(
- V1_0::WifiBand band, getValidFrequenciesForBand_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getValidFrequenciesForBandInternal, hidl_status_cb, band);
-}
-
-Return<void> WifiStaIface::startBackgroundScan(uint32_t cmd_id,
- const StaBackgroundScanParameters& params,
- startBackgroundScan_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::startBackgroundScanInternal, hidl_status_cb, cmd_id,
- params);
-}
-
-Return<void> WifiStaIface::stopBackgroundScan(uint32_t cmd_id,
- stopBackgroundScan_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::stopBackgroundScanInternal, hidl_status_cb, cmd_id);
-}
-
-Return<void> WifiStaIface::enableLinkLayerStatsCollection(
- bool debug, enableLinkLayerStatsCollection_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::enableLinkLayerStatsCollectionInternal, hidl_status_cb,
- debug);
-}
-
-Return<void> WifiStaIface::disableLinkLayerStatsCollection(
- disableLinkLayerStatsCollection_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::disableLinkLayerStatsCollectionInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getLinkLayerStats(getLinkLayerStats_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getLinkLayerStatsInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getLinkLayerStats_1_3(getLinkLayerStats_1_3_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getLinkLayerStatsInternal_1_3, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getLinkLayerStats_1_5(getLinkLayerStats_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getLinkLayerStatsInternal_1_5, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getLinkLayerStats_1_6(getLinkLayerStats_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getLinkLayerStatsInternal_1_6, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::startRssiMonitoring(uint32_t cmd_id, int32_t max_rssi, int32_t min_rssi,
- startRssiMonitoring_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::startRssiMonitoringInternal, hidl_status_cb, cmd_id,
- max_rssi, min_rssi);
-}
-
-Return<void> WifiStaIface::stopRssiMonitoring(uint32_t cmd_id,
- stopRssiMonitoring_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::stopRssiMonitoringInternal, hidl_status_cb, cmd_id);
-}
-
-Return<void> WifiStaIface::getRoamingCapabilities(getRoamingCapabilities_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getRoamingCapabilitiesInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::configureRoaming(const StaRoamingConfig& config,
- configureRoaming_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::configureRoamingInternal, hidl_status_cb, config);
-}
-
-Return<void> WifiStaIface::setRoamingState(StaRoamingState state,
- setRoamingState_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::setRoamingStateInternal, hidl_status_cb, state);
-}
-
-Return<void> WifiStaIface::enableNdOffload(bool enable, enableNdOffload_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::enableNdOffloadInternal, hidl_status_cb, enable);
-}
-
-Return<void> WifiStaIface::startSendingKeepAlivePackets(
- uint32_t cmd_id, const hidl_vec<uint8_t>& ip_packet_data, uint16_t ether_type,
- const hidl_array<uint8_t, 6>& src_address, const hidl_array<uint8_t, 6>& dst_address,
- uint32_t period_in_ms, startSendingKeepAlivePackets_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::startSendingKeepAlivePacketsInternal, hidl_status_cb,
- cmd_id, ip_packet_data, ether_type, src_address, dst_address,
- period_in_ms);
-}
-
-Return<void> WifiStaIface::stopSendingKeepAlivePackets(
- uint32_t cmd_id, stopSendingKeepAlivePackets_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::stopSendingKeepAlivePacketsInternal, hidl_status_cb,
- cmd_id);
-}
-
-Return<void> WifiStaIface::setScanningMacOui(const hidl_array<uint8_t, 3>& oui,
- setScanningMacOui_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::setScanningMacOuiInternal, hidl_status_cb, oui);
-}
-
-Return<void> WifiStaIface::startDebugPacketFateMonitoring(
- startDebugPacketFateMonitoring_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::startDebugPacketFateMonitoringInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getDebugTxPacketFates(getDebugTxPacketFates_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getDebugTxPacketFatesInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::getDebugRxPacketFates(getDebugRxPacketFates_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getDebugRxPacketFatesInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::setMacAddress(const hidl_array<uint8_t, 6>& mac,
- setMacAddress_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::setMacAddressInternal, hidl_status_cb, mac);
-}
-
-Return<void> WifiStaIface::getFactoryMacAddress(getFactoryMacAddress_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::getFactoryMacAddressInternal, hidl_status_cb);
-}
-
-Return<void> WifiStaIface::setScanMode(bool enable, setScanMode_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiStaIface::setScanModeInternal, hidl_status_cb, enable);
-}
-
-std::pair<WifiStatus, std::string> WifiStaIface::getNameInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), ifname_};
-}
-
-std::pair<WifiStatus, IfaceType> WifiStaIface::getTypeInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), IfaceType::STA};
-}
-
-WifiStatus WifiStaIface::registerEventCallbackInternal(
- const sp<IWifiStaIfaceEventCallback>& callback) {
- if (!event_cb_handler_.addCallback(callback)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-std::pair<WifiStatus, uint32_t> WifiStaIface::getCapabilitiesInternal() {
- legacy_hal::wifi_error legacy_status;
- uint64_t legacy_feature_set;
- std::tie(legacy_status, legacy_feature_set) =
- legacy_hal_.lock()->getSupportedFeatureSet(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), 0};
- }
- uint32_t legacy_logger_feature_set;
- std::tie(legacy_status, legacy_logger_feature_set) =
- legacy_hal_.lock()->getLoggerSupportedFeatureSet(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- // some devices don't support querying logger feature set
- legacy_logger_feature_set = 0;
- }
- uint32_t hidl_caps;
- if (!hidl_struct_util::convertLegacyFeaturesToHidlStaCapabilities(
- legacy_feature_set, legacy_logger_feature_set, &hidl_caps)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), 0};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_caps};
-}
-
-std::pair<WifiStatus, StaApfPacketFilterCapabilities>
-WifiStaIface::getApfPacketFilterCapabilitiesInternal() {
- legacy_hal::wifi_error legacy_status;
- legacy_hal::PacketFilterCapabilities legacy_caps;
- std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getPacketFilterCapabilities(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- StaApfPacketFilterCapabilities hidl_caps;
- if (!hidl_struct_util::convertLegacyApfCapabilitiesToHidl(legacy_caps, &hidl_caps)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_caps};
-}
-
-WifiStatus WifiStaIface::installApfPacketFilterInternal(uint32_t /* cmd_id */,
- const std::vector<uint8_t>& program) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->setPacketFilter(ifname_, program);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, std::vector<uint8_t>> WifiStaIface::readApfPacketFilterDataInternal() {
- const std::pair<legacy_hal::wifi_error, std::vector<uint8_t>> legacy_status_and_data =
- legacy_hal_.lock()->readApfPacketFilterData(ifname_);
- return {createWifiStatusFromLegacyError(legacy_status_and_data.first),
- std::move(legacy_status_and_data.second)};
-}
-
-std::pair<WifiStatus, StaBackgroundScanCapabilities>
-WifiStaIface::getBackgroundScanCapabilitiesInternal() {
- legacy_hal::wifi_error legacy_status;
- legacy_hal::wifi_gscan_capabilities legacy_caps;
- std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getGscanCapabilities(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- StaBackgroundScanCapabilities hidl_caps;
- if (!hidl_struct_util::convertLegacyGscanCapabilitiesToHidl(legacy_caps, &hidl_caps)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_caps};
-}
-
-std::pair<WifiStatus, std::vector<WifiChannelInMhz>>
-WifiStaIface::getValidFrequenciesForBandInternal(V1_0::WifiBand band) {
- static_assert(sizeof(WifiChannelInMhz) == sizeof(uint32_t), "Size mismatch");
- legacy_hal::wifi_error legacy_status;
- std::vector<uint32_t> valid_frequencies;
- std::tie(legacy_status, valid_frequencies) = legacy_hal_.lock()->getValidFrequenciesForBand(
- ifname_, hidl_struct_util::convertHidlWifiBandToLegacy(band));
- return {createWifiStatusFromLegacyError(legacy_status), valid_frequencies};
-}
-
-WifiStatus WifiStaIface::startBackgroundScanInternal(uint32_t cmd_id,
- const StaBackgroundScanParameters& params) {
- legacy_hal::wifi_scan_cmd_params legacy_params;
- if (!hidl_struct_util::convertHidlGscanParamsToLegacy(params, &legacy_params)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- android::wp<WifiStaIface> weak_ptr_this(this);
- const auto& on_failure_callback = [weak_ptr_this](legacy_hal::wifi_request_id id) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->onBackgroundScanFailure(id).isOk()) {
- LOG(ERROR) << "Failed to invoke onBackgroundScanFailure callback";
- }
- }
- };
- const auto& on_results_callback =
- [weak_ptr_this](legacy_hal::wifi_request_id id,
- const std::vector<legacy_hal::wifi_cached_scan_results>& results) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- std::vector<StaScanData> hidl_scan_datas;
- if (!hidl_struct_util::convertLegacyVectorOfCachedGscanResultsToHidl(
- results, &hidl_scan_datas)) {
- LOG(ERROR) << "Failed to convert scan results to HIDL structs";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->onBackgroundScanResults(id, hidl_scan_datas).isOk()) {
- LOG(ERROR) << "Failed to invoke onBackgroundScanResults callback";
- }
- }
- };
- const auto& on_full_result_callback = [weak_ptr_this](
- legacy_hal::wifi_request_id id,
- const legacy_hal::wifi_scan_result* result,
- uint32_t buckets_scanned) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- StaScanResult hidl_scan_result;
- if (!hidl_struct_util::convertLegacyGscanResultToHidl(*result, true, &hidl_scan_result)) {
- LOG(ERROR) << "Failed to convert full scan results to HIDL structs";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->onBackgroundFullScanResult(id, buckets_scanned, hidl_scan_result)
- .isOk()) {
- LOG(ERROR) << "Failed to invoke onBackgroundFullScanResult callback";
- }
- }
- };
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->startGscan(ifname_, cmd_id, legacy_params, on_failure_callback,
- on_results_callback, on_full_result_callback);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::stopBackgroundScanInternal(uint32_t cmd_id) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->stopGscan(ifname_, cmd_id);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::enableLinkLayerStatsCollectionInternal(bool debug) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->enableLinkLayerStats(ifname_, debug);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::disableLinkLayerStatsCollectionInternal() {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->disableLinkLayerStats(ifname_);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, V1_0::StaLinkLayerStats> WifiStaIface::getLinkLayerStatsInternal() {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-std::pair<WifiStatus, V1_3::StaLinkLayerStats> WifiStaIface::getLinkLayerStatsInternal_1_3() {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-std::pair<WifiStatus, V1_5::StaLinkLayerStats> WifiStaIface::getLinkLayerStatsInternal_1_5() {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-std::pair<WifiStatus, V1_6::StaLinkLayerStats> WifiStaIface::getLinkLayerStatsInternal_1_6() {
- legacy_hal::wifi_error legacy_status;
- legacy_hal::LinkLayerStats legacy_stats;
- std::tie(legacy_status, legacy_stats) = legacy_hal_.lock()->getLinkLayerStats(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- V1_6::StaLinkLayerStats hidl_stats;
- if (!hidl_struct_util::convertLegacyLinkLayerStatsToHidl(legacy_stats, &hidl_stats)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_stats};
-}
-
-WifiStatus WifiStaIface::startRssiMonitoringInternal(uint32_t cmd_id, int32_t max_rssi,
- int32_t min_rssi) {
- android::wp<WifiStaIface> weak_ptr_this(this);
- const auto& on_threshold_breached_callback = [weak_ptr_this](legacy_hal::wifi_request_id id,
- std::array<uint8_t, 6> bssid,
- int8_t rssi) {
- const auto shared_ptr_this = weak_ptr_this.promote();
- if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
- LOG(ERROR) << "Callback invoked on an invalid object";
- return;
- }
- for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->onRssiThresholdBreached(id, bssid, rssi).isOk()) {
- LOG(ERROR) << "Failed to invoke onRssiThresholdBreached callback";
- }
- }
- };
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startRssiMonitoring(
- ifname_, cmd_id, max_rssi, min_rssi, on_threshold_breached_callback);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::stopRssiMonitoringInternal(uint32_t cmd_id) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->stopRssiMonitoring(ifname_, cmd_id);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, StaRoamingCapabilities> WifiStaIface::getRoamingCapabilitiesInternal() {
- legacy_hal::wifi_error legacy_status;
- legacy_hal::wifi_roaming_capabilities legacy_caps;
- std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getRoamingCapabilities(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- StaRoamingCapabilities hidl_caps;
- if (!hidl_struct_util::convertLegacyRoamingCapabilitiesToHidl(legacy_caps, &hidl_caps)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_caps};
-}
-
-WifiStatus WifiStaIface::configureRoamingInternal(const StaRoamingConfig& config) {
- legacy_hal::wifi_roaming_config legacy_config;
- if (!hidl_struct_util::convertHidlRoamingConfigToLegacy(config, &legacy_config)) {
- return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
- }
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->configureRoaming(ifname_, legacy_config);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::setRoamingStateInternal(StaRoamingState state) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->enableFirmwareRoaming(
- ifname_, hidl_struct_util::convertHidlRoamingStateToLegacy(state));
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::enableNdOffloadInternal(bool enable) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->configureNdOffload(ifname_, enable);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::startSendingKeepAlivePacketsInternal(
- uint32_t cmd_id, const std::vector<uint8_t>& ip_packet_data, uint16_t ether_type,
- const std::array<uint8_t, 6>& src_address, const std::array<uint8_t, 6>& dst_address,
- uint32_t period_in_ms) {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startSendingOffloadedPacket(
- ifname_, cmd_id, ether_type, ip_packet_data, src_address, dst_address, period_in_ms);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::stopSendingKeepAlivePacketsInternal(uint32_t cmd_id) {
- legacy_hal::wifi_error legacy_status =
- legacy_hal_.lock()->stopSendingOffloadedPacket(ifname_, cmd_id);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-WifiStatus WifiStaIface::setScanningMacOuiInternal(const std::array<uint8_t, 3>& /* oui */) {
- // deprecated.
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiStaIface::startDebugPacketFateMonitoringInternal() {
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startPktFateMonitoring(ifname_);
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, std::vector<WifiDebugTxPacketFateReport>>
-WifiStaIface::getDebugTxPacketFatesInternal() {
- legacy_hal::wifi_error legacy_status;
- std::vector<legacy_hal::wifi_tx_report> legacy_fates;
- std::tie(legacy_status, legacy_fates) = legacy_hal_.lock()->getTxPktFates(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- std::vector<WifiDebugTxPacketFateReport> hidl_fates;
- if (!hidl_struct_util::convertLegacyVectorOfDebugTxPacketFateToHidl(legacy_fates,
- &hidl_fates)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_fates};
-}
-
-std::pair<WifiStatus, std::vector<WifiDebugRxPacketFateReport>>
-WifiStaIface::getDebugRxPacketFatesInternal() {
- legacy_hal::wifi_error legacy_status;
- std::vector<legacy_hal::wifi_rx_report> legacy_fates;
- std::tie(legacy_status, legacy_fates) = legacy_hal_.lock()->getRxPktFates(ifname_);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
- }
- std::vector<WifiDebugRxPacketFateReport> hidl_fates;
- if (!hidl_struct_util::convertLegacyVectorOfDebugRxPacketFateToHidl(legacy_fates,
- &hidl_fates)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_fates};
-}
-
-WifiStatus WifiStaIface::setMacAddressInternal(const std::array<uint8_t, 6>& mac) {
- bool status = iface_util_.lock()->setMacAddress(ifname_, mac);
- if (!status) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-std::pair<WifiStatus, std::array<uint8_t, 6>> WifiStaIface::getFactoryMacAddressInternal() {
- std::array<uint8_t, 6> mac = iface_util_.lock()->getFactoryMacAddress(ifname_);
- if (mac[0] == 0 && mac[1] == 0 && mac[2] == 0 && mac[3] == 0 && mac[4] == 0 && mac[5] == 0) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), mac};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), mac};
-}
-
-WifiStatus WifiStaIface::setScanModeInternal(bool enable) {
- // OEM's need to implement this on their devices if needed.
- LOG(WARNING) << "setScanModeInternal(" << enable << ") not supported";
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
diff --git a/wifi/1.6/default/wifi_sta_iface.h b/wifi/1.6/default/wifi_sta_iface.h
deleted file mode 100644
index c01c50b..0000000
--- a/wifi/1.6/default/wifi_sta_iface.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_STA_IFACE_H_
-#define WIFI_STA_IFACE_H_
-
-#include <android-base/macros.h>
-#include <android/hardware/wifi/1.0/IWifiStaIfaceEventCallback.h>
-#include <android/hardware/wifi/1.6/IWifiStaIface.h>
-
-#include "hidl_callback_util.h"
-#include "wifi_iface_util.h"
-#include "wifi_legacy_hal.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
-
-/**
- * HIDL interface object used to control a STA Iface instance.
- */
-class WifiStaIface : public V1_6::IWifiStaIface {
- public:
- WifiStaIface(const std::string& ifname,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
- const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
- // Refer to |WifiChip::invalidate()|.
- void invalidate();
- bool isValid();
- std::set<sp<IWifiStaIfaceEventCallback>> getEventCallbacks();
- std::string getName();
-
- // HIDL methods exposed.
- Return<void> getName(getName_cb hidl_status_cb) override;
- Return<void> getType(getType_cb hidl_status_cb) override;
- Return<void> registerEventCallback(const sp<IWifiStaIfaceEventCallback>& callback,
- registerEventCallback_cb hidl_status_cb) override;
- Return<void> getCapabilities(getCapabilities_cb hidl_status_cb) override;
- Return<void> getApfPacketFilterCapabilities(
- getApfPacketFilterCapabilities_cb hidl_status_cb) override;
- Return<void> installApfPacketFilter(uint32_t cmd_id, const hidl_vec<uint8_t>& program,
- installApfPacketFilter_cb hidl_status_cb) override;
- Return<void> readApfPacketFilterData(readApfPacketFilterData_cb hidl_status_cb) override;
- Return<void> getBackgroundScanCapabilities(
- getBackgroundScanCapabilities_cb hidl_status_cb) override;
- Return<void> getValidFrequenciesForBand(V1_0::WifiBand band,
- getValidFrequenciesForBand_cb hidl_status_cb) override;
- Return<void> startBackgroundScan(uint32_t cmd_id, const StaBackgroundScanParameters& params,
- startBackgroundScan_cb hidl_status_cb) override;
- Return<void> stopBackgroundScan(uint32_t cmd_id, stopBackgroundScan_cb hidl_status_cb) override;
- Return<void> enableLinkLayerStatsCollection(
- bool debug, enableLinkLayerStatsCollection_cb hidl_status_cb) override;
- Return<void> disableLinkLayerStatsCollection(
- disableLinkLayerStatsCollection_cb hidl_status_cb) override;
- Return<void> getLinkLayerStats(getLinkLayerStats_cb hidl_status_cb) override;
- Return<void> getLinkLayerStats_1_3(getLinkLayerStats_1_3_cb hidl_status_cb) override;
- Return<void> getLinkLayerStats_1_5(getLinkLayerStats_1_5_cb hidl_status_cb) override;
- Return<void> getLinkLayerStats_1_6(getLinkLayerStats_1_6_cb hidl_status_cb) override;
- Return<void> startRssiMonitoring(uint32_t cmd_id, int32_t max_rssi, int32_t min_rssi,
- startRssiMonitoring_cb hidl_status_cb) override;
- Return<void> stopRssiMonitoring(uint32_t cmd_id, stopRssiMonitoring_cb hidl_status_cb) override;
- Return<void> getRoamingCapabilities(getRoamingCapabilities_cb hidl_status_cb) override;
- Return<void> configureRoaming(const StaRoamingConfig& config,
- configureRoaming_cb hidl_status_cb) override;
- Return<void> setRoamingState(StaRoamingState state, setRoamingState_cb hidl_status_cb) override;
- Return<void> enableNdOffload(bool enable, enableNdOffload_cb hidl_status_cb) override;
- Return<void> startSendingKeepAlivePackets(
- uint32_t cmd_id, const hidl_vec<uint8_t>& ip_packet_data, uint16_t ether_type,
- const hidl_array<uint8_t, 6>& src_address, const hidl_array<uint8_t, 6>& dst_address,
- uint32_t period_in_ms, startSendingKeepAlivePackets_cb hidl_status_cb) override;
- Return<void> stopSendingKeepAlivePackets(
- uint32_t cmd_id, stopSendingKeepAlivePackets_cb hidl_status_cb) override;
- Return<void> setScanningMacOui(const hidl_array<uint8_t, 3>& oui,
- setScanningMacOui_cb hidl_status_cb) override;
- Return<void> startDebugPacketFateMonitoring(
- startDebugPacketFateMonitoring_cb hidl_status_cb) override;
- Return<void> getDebugTxPacketFates(getDebugTxPacketFates_cb hidl_status_cb) override;
- Return<void> getDebugRxPacketFates(getDebugRxPacketFates_cb hidl_status_cb) override;
- Return<void> setMacAddress(const hidl_array<uint8_t, 6>& mac,
- setMacAddress_cb hidl_status_cb) override;
- Return<void> getFactoryMacAddress(getFactoryMacAddress_cb hidl_status_cb) override;
- Return<void> setScanMode(bool enable, setScanMode_cb hidl_status_cb) override;
-
- private:
- // Corresponding worker functions for the HIDL methods.
- std::pair<WifiStatus, std::string> getNameInternal();
- std::pair<WifiStatus, IfaceType> getTypeInternal();
- WifiStatus registerEventCallbackInternal(const sp<IWifiStaIfaceEventCallback>& callback);
- std::pair<WifiStatus, uint32_t> getCapabilitiesInternal();
- std::pair<WifiStatus, StaApfPacketFilterCapabilities> getApfPacketFilterCapabilitiesInternal();
- WifiStatus installApfPacketFilterInternal(uint32_t cmd_id, const std::vector<uint8_t>& program);
- std::pair<WifiStatus, std::vector<uint8_t>> readApfPacketFilterDataInternal();
- std::pair<WifiStatus, StaBackgroundScanCapabilities> getBackgroundScanCapabilitiesInternal();
- std::pair<WifiStatus, std::vector<WifiChannelInMhz>> getValidFrequenciesForBandInternal(
- V1_0::WifiBand band);
- WifiStatus startBackgroundScanInternal(uint32_t cmd_id,
- const StaBackgroundScanParameters& params);
- WifiStatus stopBackgroundScanInternal(uint32_t cmd_id);
- WifiStatus enableLinkLayerStatsCollectionInternal(bool debug);
- WifiStatus disableLinkLayerStatsCollectionInternal();
- std::pair<WifiStatus, V1_0::StaLinkLayerStats> getLinkLayerStatsInternal();
- std::pair<WifiStatus, V1_3::StaLinkLayerStats> getLinkLayerStatsInternal_1_3();
- std::pair<WifiStatus, V1_5::StaLinkLayerStats> getLinkLayerStatsInternal_1_5();
- std::pair<WifiStatus, V1_6::StaLinkLayerStats> getLinkLayerStatsInternal_1_6();
- WifiStatus startRssiMonitoringInternal(uint32_t cmd_id, int32_t max_rssi, int32_t min_rssi);
- WifiStatus stopRssiMonitoringInternal(uint32_t cmd_id);
- std::pair<WifiStatus, StaRoamingCapabilities> getRoamingCapabilitiesInternal();
- WifiStatus configureRoamingInternal(const StaRoamingConfig& config);
- WifiStatus setRoamingStateInternal(StaRoamingState state);
- WifiStatus enableNdOffloadInternal(bool enable);
- WifiStatus startSendingKeepAlivePacketsInternal(uint32_t cmd_id,
- const std::vector<uint8_t>& ip_packet_data,
- uint16_t ether_type,
- const std::array<uint8_t, 6>& src_address,
- const std::array<uint8_t, 6>& dst_address,
- uint32_t period_in_ms);
- WifiStatus stopSendingKeepAlivePacketsInternal(uint32_t cmd_id);
- WifiStatus setScanningMacOuiInternal(const std::array<uint8_t, 3>& oui);
- WifiStatus startDebugPacketFateMonitoringInternal();
- std::pair<WifiStatus, std::vector<WifiDebugTxPacketFateReport>> getDebugTxPacketFatesInternal();
- std::pair<WifiStatus, std::vector<WifiDebugRxPacketFateReport>> getDebugRxPacketFatesInternal();
- WifiStatus setMacAddressInternal(const std::array<uint8_t, 6>& mac);
- std::pair<WifiStatus, std::array<uint8_t, 6>> getFactoryMacAddressInternal();
- WifiStatus setScanModeInternal(bool enable);
-
- std::string ifname_;
- std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
- std::weak_ptr<iface_util::WifiIfaceUtil> iface_util_;
- bool is_valid_;
- hidl_callback_util::HidlCallbackHandler<IWifiStaIfaceEventCallback> event_cb_handler_;
-
- DISALLOW_COPY_AND_ASSIGN(WifiStaIface);
-};
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_STA_IFACE_H_
diff --git a/wifi/1.6/default/wifi_status_util.h b/wifi/1.6/default/wifi_status_util.h
deleted file mode 100644
index ea1c294..0000000
--- a/wifi/1.6/default/wifi_status_util.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * 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 WIFI_STATUS_UTIL_H_
-#define WIFI_STATUS_UTIL_H_
-
-#include <android/hardware/wifi/1.4/IWifi.h>
-
-#include "wifi_legacy_hal.h"
-
-namespace android {
-namespace hardware {
-namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
-
-std::string legacyErrorToString(legacy_hal::wifi_error error);
-WifiStatus createWifiStatus(WifiStatusCode code, const std::string& description);
-WifiStatus createWifiStatus(WifiStatusCode code);
-WifiStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error,
- const std::string& description);
-WifiStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error);
-
-} // namespace implementation
-} // namespace V1_6
-} // namespace wifi
-} // namespace hardware
-} // namespace android
-
-#endif // WIFI_STATUS_UTIL_H_
diff --git a/wifi/1.6/default/Android.bp b/wifi/aidl/default/Android.bp
similarity index 66%
rename from wifi/1.6/default/Android.bp
rename to wifi/aidl/default/Android.bp
index 0f98e71..441d461 100644
--- a/wifi/1.6/default/Android.bp
+++ b/wifi/aidl/default/Android.bp
@@ -1,4 +1,4 @@
-// Copyright (C) 2021 The Android Open Source Project
+// Copyright (C) 2022 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@
}
wifi_hal_cc_defaults {
- name: "android.hardware.wifi@1.0-service-cppflags-defaults",
+ name: "android.hardware.wifi-service-cppflags-defaults",
soong_config_variables: {
hidl_feature_aware: {
cppflags: ["-DWIFI_HIDL_FEATURE_AWARE"],
@@ -60,8 +60,8 @@
}
cc_library_static {
- name: "android.hardware.wifi@1.0-service-lib",
- defaults: ["android.hardware.wifi@1.0-service-cppflags-defaults"],
+ name: "android.hardware.wifi-service-lib",
+ defaults: ["android.hardware.wifi-service-cppflags-defaults"],
proprietary: true,
compile_multilib: "first",
cppflags: [
@@ -72,8 +72,8 @@
// Allow implicit fallthroughs in wifi_legacy_hal.cpp until they are fixed.
cflags: ["-Wno-error=implicit-fallthrough"],
srcs: [
- "hidl_struct_util.cpp",
- "hidl_sync_util.cpp",
+ "aidl_struct_util.cpp",
+ "aidl_sync_util.cpp",
"ringbuffer.cpp",
"wifi.cpp",
"wifi_ap_iface.cpp",
@@ -93,29 +93,23 @@
shared_libs: [
"libbase",
+ "libbinder_ndk",
"libcutils",
- "libhidlbase",
"liblog",
"libnl",
"libutils",
"libwifi-hal",
"libwifi-system-iface",
"libxml2",
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi@1.6",
+ "android.hardware.wifi-V1-ndk",
],
export_include_dirs: ["."],
}
cc_binary {
- name: "android.hardware.wifi@1.0-service",
- vintf_fragments: ["android.hardware.wifi@1.0-service.xml"],
+ name: "android.hardware.wifi-service",
+ vintf_fragments: ["android.hardware.wifi-service.xml"],
relative_install_path: "hw",
proprietary: true,
cppflags: [
@@ -126,30 +120,24 @@
srcs: ["service.cpp"],
shared_libs: [
"libbase",
+ "libbinder_ndk",
"libcutils",
- "libhidlbase",
"liblog",
"libnl",
"libutils",
"libwifi-hal",
"libwifi-system-iface",
"libxml2",
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi@1.6",
+ "android.hardware.wifi-V1-ndk",
],
- static_libs: ["android.hardware.wifi@1.0-service-lib"],
- init_rc: ["android.hardware.wifi@1.0-service.rc"],
+ static_libs: ["android.hardware.wifi-service-lib"],
+ init_rc: ["android.hardware.wifi-service.rc"],
}
cc_binary {
- name: "android.hardware.wifi@1.0-service-lazy",
- vintf_fragments: ["android.hardware.wifi@1.0-service.xml"],
- overrides: ["android.hardware.wifi@1.0-service"],
+ name: "android.hardware.wifi-service-lazy",
+ vintf_fragments: ["android.hardware.wifi-service.xml"],
+ overrides: ["android.hardware.wifi-service"],
cflags: ["-DLAZY_SERVICE"],
relative_install_path: "hw",
proprietary: true,
@@ -161,28 +149,22 @@
srcs: ["service.cpp"],
shared_libs: [
"libbase",
+ "libbinder_ndk",
"libcutils",
- "libhidlbase",
"liblog",
"libnl",
"libutils",
"libwifi-hal",
"libwifi-system-iface",
"libxml2",
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi@1.6",
+ "android.hardware.wifi-V1-ndk",
],
- static_libs: ["android.hardware.wifi@1.0-service-lib"],
- init_rc: ["android.hardware.wifi@1.0-service-lazy.rc"],
+ static_libs: ["android.hardware.wifi-service-lib"],
+ init_rc: ["android.hardware.wifi-service-lazy.rc"],
}
cc_test {
- name: "android.hardware.wifi@1.0-service-tests",
+ name: "android.hardware.wifi-service-tests",
proprietary: true,
compile_multilib: "first",
cppflags: [
@@ -191,7 +173,7 @@
"-Wextra",
],
srcs: [
- "tests/hidl_struct_util_unit_tests.cpp",
+ "tests/aidl_struct_util_unit_tests.cpp",
"tests/main.cpp",
"tests/mock_interface_tool.cpp",
"tests/mock_wifi_feature_flags.cpp",
@@ -206,19 +188,13 @@
static_libs: [
"libgmock",
"libgtest",
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi@1.6",
- "android.hardware.wifi@1.0-service-lib",
+ "android.hardware.wifi-V1-ndk",
+ "android.hardware.wifi-service-lib",
],
shared_libs: [
"libbase",
+ "libbinder_ndk",
"libcutils",
- "libhidlbase",
"liblog",
"libnl",
"libutils",
@@ -228,11 +204,11 @@
}
filegroup {
- name: "default-android.hardware.wifi@1.0-service.rc",
- srcs: ["android.hardware.wifi@1.0-service.rc"],
+ name: "default-android.hardware.wifi-service.rc",
+ srcs: ["android.hardware.wifi-service.rc"],
}
filegroup {
- name: "default-android.hardware.wifi@1.0-service.xml",
- srcs: ["android.hardware.wifi@1.0-service.xml"],
+ name: "default-android.hardware.wifi-service.xml",
+ srcs: ["android.hardware.wifi-service.xml"],
}
diff --git a/wifi/1.6/default/THREADING.README b/wifi/aidl/default/THREADING.README
similarity index 82%
rename from wifi/1.6/default/THREADING.README
rename to wifi/aidl/default/THREADING.README
index 8366ca0..45679da 100644
--- a/wifi/1.6/default/THREADING.README
+++ b/wifi/aidl/default/THREADING.README
@@ -1,7 +1,7 @@
Vendor HAL Threading Model
==========================
The vendor HAL service has two threads:
-1. HIDL thread: This is the main thread which processes all the incoming HIDL
+1. AIDL thread: This is the main thread which processes all the incoming AIDL
RPC's.
2. Legacy HAL event loop thread: This is the thread forked off for processing
the legacy HAL event loop (wifi_event_loop()). This thread is used to process
@@ -11,9 +11,9 @@
Synchronization Concerns
========================
wifi_legacy_hal.cpp has a bunch of global "C" style functions to handle the
-legacy callbacks. Each of these "C" style function invokes a corresponding
+legacy callbacks. Each of these "C" style functions invokes a corresponding
"std::function" version of the callback which does the actual processing.
-The variables holding these "std::function" callbacks are reset from the HIDL
+The variables holding these "std::function" callbacks are reset from the AIDL
thread when they are no longer used. For example: stopGscan() will reset the
corresponding "on_gscan_*" callback variables which were set when startGscan()
was invoked. This is not thread safe since these callback variables are
@@ -24,12 +24,12 @@
Adding a global lock seems to be the most trivial solution to the problem.
a) All of the asynchronous "C" style callbacks will acquire the global lock
before invoking the corresponding "std::function" callback variables.
-b) All of the HIDL methods will also acquire the global lock before processing
-(in hidl_return_util::validateAndCall()).
+b) All of the AIDL methods will also acquire the global lock before processing
+(in aidl_return_util::validateAndCall()).
Note: It's important that we only acquire the global lock for asynchronous
callbacks, because there is no guarantee (or documentation to clarify) that the
synchronous callbacks are invoked on the same invocation thread. If that is not
the case in some implementation, we will end up deadlocking the system since the
-HIDL thread would have acquired the global lock which is needed by the
+AIDL thread would have acquired the global lock which is needed by the
synchronous callback executed on the legacy hal event loop thread.
diff --git a/wifi/aidl/default/aidl_callback_util.h b/wifi/aidl/default/aidl_callback_util.h
new file mode 100644
index 0000000..41d70a5
--- /dev/null
+++ b/wifi/aidl/default/aidl_callback_util.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 AIDL_CALLBACK_UTIL_H_
+#define AIDL_CALLBACK_UTIL_H_
+
+#include <android-base/logging.h>
+
+#include <set>
+#include <unordered_map>
+
+namespace {
+std::unordered_map<void* /* callback */, void* /* handler */> callback_handler_map_;
+}
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace aidl_callback_util {
+
+// Provides a class to manage callbacks for the various AIDL interfaces and
+// handle the death of the process hosting each callback.
+template <typename CallbackType>
+class AidlCallbackHandler {
+ public:
+ AidlCallbackHandler() {
+ death_handler_ = AIBinder_DeathRecipient_new(AidlCallbackHandler::onCallbackDeath);
+ }
+ ~AidlCallbackHandler() { invalidate(); }
+
+ bool addCallback(const std::shared_ptr<CallbackType>& cb) {
+ void* cbPtr = reinterpret_cast<void*>(cb->asBinder().get());
+ const auto& cbPosition = findCbInSet(cbPtr);
+ if (cbPosition != cb_set_.end()) {
+ LOG(WARNING) << "Duplicate death notification registration";
+ return true;
+ }
+
+ if (AIBinder_linkToDeath(cb->asBinder().get(), death_handler_, cbPtr /* cookie */) !=
+ STATUS_OK) {
+ LOG(ERROR) << "Failed to register death notification";
+ return false;
+ }
+
+ callback_handler_map_[cbPtr] = reinterpret_cast<void*>(this);
+ cb_set_.insert(cb);
+ return true;
+ }
+
+ const std::set<std::shared_ptr<CallbackType>>& getCallbacks() { return cb_set_; }
+
+ void invalidate() {
+ for (auto cb : cb_set_) {
+ void* cookie = reinterpret_cast<void*>(cb->asBinder().get());
+ if (AIBinder_unlinkToDeath(cb->asBinder().get(), death_handler_, cookie) != STATUS_OK) {
+ LOG(ERROR) << "Failed to deregister death notification";
+ }
+ if (!removeCbFromHandlerMap(cookie)) {
+ LOG(ERROR) << "Failed to remove callback from handler map";
+ }
+ }
+ cb_set_.clear();
+ }
+
+ // Entry point for the death handling logic. AIBinder_DeathRecipient
+ // can only call a static function, so use the cookie to find the
+ // proper handler and route the request there.
+ static void onCallbackDeath(void* cookie) {
+ auto cbQuery = callback_handler_map_.find(cookie);
+ if (cbQuery == callback_handler_map_.end()) {
+ LOG(ERROR) << "Invalid death cookie received";
+ return;
+ }
+
+ AidlCallbackHandler* cbHandler = reinterpret_cast<AidlCallbackHandler*>(cbQuery->second);
+ if (cbHandler == nullptr) {
+ LOG(ERROR) << "Handler mapping contained an invalid handler";
+ return;
+ }
+ cbHandler->handleCallbackDeath(cbQuery->first);
+ }
+
+ private:
+ std::set<std::shared_ptr<CallbackType>> cb_set_;
+ AIBinder_DeathRecipient* death_handler_;
+
+ typename std::set<std::shared_ptr<CallbackType>>::iterator findCbInSet(void* cbPtr) {
+ const auto& cbPosition = std::find_if(
+ cb_set_.begin(), cb_set_.end(), [cbPtr](const std::shared_ptr<CallbackType>& p) {
+ return cbPtr == reinterpret_cast<void*>(p->asBinder().get());
+ });
+ return cbPosition;
+ }
+
+ bool removeCbFromHandlerMap(void* cbPtr) {
+ auto cbQuery = callback_handler_map_.find(cbPtr);
+ if (cbQuery != callback_handler_map_.end()) {
+ callback_handler_map_.erase(cbQuery);
+ return true;
+ }
+ return false;
+ }
+
+ void handleCallbackDeath(void* cbPtr) {
+ const auto& cbPosition = findCbInSet(cbPtr);
+ if (cbPosition == cb_set_.end()) {
+ LOG(ERROR) << "Unknown callback death notification received";
+ return;
+ }
+ cb_set_.erase(cbPosition);
+
+ if (!removeCbFromHandlerMap(cbPtr)) {
+ LOG(ERROR) << "Callback was not in callback handler map";
+ }
+ }
+
+ DISALLOW_COPY_AND_ASSIGN(AidlCallbackHandler);
+};
+
+} // namespace aidl_callback_util
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // AIDL_CALLBACK_UTIL_H_
diff --git a/wifi/aidl/default/aidl_return_util.h b/wifi/aidl/default/aidl_return_util.h
new file mode 100644
index 0000000..9a49a22
--- /dev/null
+++ b/wifi/aidl/default/aidl_return_util.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 AIDL_RETURN_UTIL_H_
+#define AIDL_RETURN_UTIL_H_
+
+#include "aidl_sync_util.h"
+#include "wifi_status_util.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace aidl_return_util {
+using aidl::android::hardware::wifi::WifiStatusCode;
+using aidl::android::hardware::wifi::aidl_sync_util::acquireGlobalLock;
+
+/**
+ * These utility functions are used to invoke a method on the provided
+ * AIDL interface object.
+ * These functions checks if the provided AIDL interface object is valid.
+ * a) If valid, Invokes the corresponding internal implementation function of
+ * the AIDL method.
+ * b) If invalid, return without calling the internal implementation function.
+ */
+
+// Use for AIDL methods which return only an AIDL status.
+template <typename ObjT, typename WorkFuncT, typename... Args>
+::ndk::ScopedAStatus validateAndCall(ObjT* obj, WifiStatusCode status_code_if_invalid,
+ WorkFuncT&& work, Args&&... args) {
+ const auto lock = acquireGlobalLock();
+ if (obj->isValid()) {
+ return (obj->*work)(std::forward<Args>(args)...);
+ } else {
+ return createWifiStatus(status_code_if_invalid);
+ }
+}
+
+// Use for AIDL methods which return only an AIDL status.
+// This version passes the global lock acquired to the body of the method.
+template <typename ObjT, typename WorkFuncT, typename... Args>
+::ndk::ScopedAStatus validateAndCallWithLock(ObjT* obj, WifiStatusCode status_code_if_invalid,
+ WorkFuncT&& work, Args&&... args) {
+ auto lock = acquireGlobalLock();
+ if (obj->isValid()) {
+ return (obj->*work)(&lock, std::forward<Args>(args)...);
+ } else {
+ return createWifiStatus(status_code_if_invalid);
+ }
+}
+
+// Use for AIDL methods which have a return value along with the AIDL status
+template <typename ObjT, typename WorkFuncT, typename ReturnT, typename... Args>
+::ndk::ScopedAStatus validateAndCall(ObjT* obj, WifiStatusCode status_code_if_invalid,
+ WorkFuncT&& work, ReturnT* ret_val, Args&&... args) {
+ const auto lock = acquireGlobalLock();
+ if (obj->isValid()) {
+ auto call_pair = (obj->*work)(std::forward<Args>(args)...);
+ *ret_val = call_pair.first;
+ return std::forward<::ndk::ScopedAStatus>(call_pair.second);
+ } else {
+ return ndk::ScopedAStatus::fromServiceSpecificError(
+ static_cast<int32_t>(status_code_if_invalid));
+ }
+}
+
+} // namespace aidl_return_util
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+#endif // AIDL_RETURN_UTIL_H_
diff --git a/wifi/aidl/default/aidl_struct_util.cpp b/wifi/aidl/default/aidl_struct_util.cpp
new file mode 100644
index 0000000..07612b6
--- /dev/null
+++ b/wifi/aidl/default/aidl_struct_util.cpp
@@ -0,0 +1,2775 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <android-base/logging.h>
+#include <utils/SystemClock.h>
+
+#include "aidl_struct_util.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace aidl_struct_util {
+
+WifiChannelWidthInMhz convertLegacyWifiChannelWidthToAidl(legacy_hal::wifi_channel_width type);
+
+std::string safeConvertChar(const char* str, size_t max_len) {
+ const char* c = str;
+ size_t size = 0;
+ while (*c && (unsigned char)*c < 128 && size < max_len) {
+ ++size;
+ ++c;
+ }
+ return std::string(str, size);
+}
+
+inline std::vector<int32_t> uintToIntVec(const std::vector<uint32_t>& in) {
+ return std::vector<int32_t>(in.begin(), in.end());
+}
+
+IWifiChip::ChipCapabilityMask convertLegacyLoggerFeatureToAidlChipCapability(uint32_t feature) {
+ switch (feature) {
+ case legacy_hal::WIFI_LOGGER_MEMORY_DUMP_SUPPORTED:
+ return IWifiChip::ChipCapabilityMask::DEBUG_MEMORY_FIRMWARE_DUMP;
+ case legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED:
+ return IWifiChip::ChipCapabilityMask::DEBUG_MEMORY_DRIVER_DUMP;
+ case legacy_hal::WIFI_LOGGER_CONNECT_EVENT_SUPPORTED:
+ return IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_CONNECT_EVENT;
+ case legacy_hal::WIFI_LOGGER_POWER_EVENT_SUPPORTED:
+ return IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_POWER_EVENT;
+ case legacy_hal::WIFI_LOGGER_WAKE_LOCK_SUPPORTED:
+ return IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_WAKELOCK_EVENT;
+ };
+ CHECK(false) << "Unknown legacy feature: " << feature;
+ return {};
+}
+
+IWifiStaIface::StaIfaceCapabilityMask convertLegacyLoggerFeatureToAidlStaIfaceCapability(
+ uint32_t feature) {
+ switch (feature) {
+ case legacy_hal::WIFI_LOGGER_PACKET_FATE_SUPPORTED:
+ return IWifiStaIface::StaIfaceCapabilityMask::DEBUG_PACKET_FATE;
+ };
+ CHECK(false) << "Unknown legacy feature: " << feature;
+ return {};
+}
+
+IWifiChip::ChipCapabilityMask convertLegacyFeatureToAidlChipCapability(uint64_t feature) {
+ switch (feature) {
+ case WIFI_FEATURE_SET_TX_POWER_LIMIT:
+ return IWifiChip::ChipCapabilityMask::SET_TX_POWER_LIMIT;
+ case WIFI_FEATURE_USE_BODY_HEAD_SAR:
+ return IWifiChip::ChipCapabilityMask::USE_BODY_HEAD_SAR;
+ case WIFI_FEATURE_D2D_RTT:
+ return IWifiChip::ChipCapabilityMask::D2D_RTT;
+ case WIFI_FEATURE_D2AP_RTT:
+ return IWifiChip::ChipCapabilityMask::D2AP_RTT;
+ case WIFI_FEATURE_INFRA_60G:
+ return IWifiChip::ChipCapabilityMask::WIGIG;
+ case WIFI_FEATURE_SET_LATENCY_MODE:
+ return IWifiChip::ChipCapabilityMask::SET_LATENCY_MODE;
+ case WIFI_FEATURE_P2P_RAND_MAC:
+ return IWifiChip::ChipCapabilityMask::P2P_RAND_MAC;
+ };
+ CHECK(false) << "Unknown legacy feature: " << feature;
+ return {};
+}
+
+IWifiStaIface::StaIfaceCapabilityMask convertLegacyFeatureToAidlStaIfaceCapability(
+ uint64_t feature) {
+ switch (feature) {
+ case WIFI_FEATURE_GSCAN:
+ return IWifiStaIface::StaIfaceCapabilityMask::BACKGROUND_SCAN;
+ case WIFI_FEATURE_LINK_LAYER_STATS:
+ return IWifiStaIface::StaIfaceCapabilityMask::LINK_LAYER_STATS;
+ case WIFI_FEATURE_RSSI_MONITOR:
+ return IWifiStaIface::StaIfaceCapabilityMask::RSSI_MONITOR;
+ case WIFI_FEATURE_CONTROL_ROAMING:
+ return IWifiStaIface::StaIfaceCapabilityMask::CONTROL_ROAMING;
+ case WIFI_FEATURE_IE_WHITELIST:
+ return IWifiStaIface::StaIfaceCapabilityMask::PROBE_IE_ALLOWLIST;
+ case WIFI_FEATURE_SCAN_RAND:
+ return IWifiStaIface::StaIfaceCapabilityMask::SCAN_RAND;
+ case WIFI_FEATURE_INFRA_5G:
+ return IWifiStaIface::StaIfaceCapabilityMask::STA_5G;
+ case WIFI_FEATURE_HOTSPOT:
+ return IWifiStaIface::StaIfaceCapabilityMask::HOTSPOT;
+ case WIFI_FEATURE_PNO:
+ return IWifiStaIface::StaIfaceCapabilityMask::PNO;
+ case WIFI_FEATURE_TDLS:
+ return IWifiStaIface::StaIfaceCapabilityMask::TDLS;
+ case WIFI_FEATURE_TDLS_OFFCHANNEL:
+ return IWifiStaIface::StaIfaceCapabilityMask::TDLS_OFFCHANNEL;
+ case WIFI_FEATURE_CONFIG_NDO:
+ return IWifiStaIface::StaIfaceCapabilityMask::ND_OFFLOAD;
+ case WIFI_FEATURE_MKEEP_ALIVE:
+ return IWifiStaIface::StaIfaceCapabilityMask::KEEP_ALIVE;
+ };
+ CHECK(false) << "Unknown legacy feature: " << feature;
+ return {};
+}
+
+bool convertLegacyFeaturesToAidlChipCapabilities(uint64_t legacy_feature_set,
+ uint32_t legacy_logger_feature_set,
+ uint32_t* aidl_caps) {
+ if (!aidl_caps) {
+ return false;
+ }
+ *aidl_caps = {};
+ for (const auto feature : {legacy_hal::WIFI_LOGGER_MEMORY_DUMP_SUPPORTED,
+ legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED,
+ legacy_hal::WIFI_LOGGER_CONNECT_EVENT_SUPPORTED,
+ legacy_hal::WIFI_LOGGER_POWER_EVENT_SUPPORTED,
+ legacy_hal::WIFI_LOGGER_WAKE_LOCK_SUPPORTED}) {
+ if (feature & legacy_logger_feature_set) {
+ *aidl_caps |=
+ static_cast<uint32_t>(convertLegacyLoggerFeatureToAidlChipCapability(feature));
+ }
+ }
+ std::vector<uint64_t> features = {WIFI_FEATURE_SET_TX_POWER_LIMIT,
+ WIFI_FEATURE_USE_BODY_HEAD_SAR,
+ WIFI_FEATURE_D2D_RTT,
+ WIFI_FEATURE_D2AP_RTT,
+ WIFI_FEATURE_INFRA_60G,
+ WIFI_FEATURE_SET_LATENCY_MODE,
+ WIFI_FEATURE_P2P_RAND_MAC};
+ for (const auto feature : features) {
+ if (feature & legacy_feature_set) {
+ *aidl_caps |= static_cast<uint32_t>(convertLegacyFeatureToAidlChipCapability(feature));
+ }
+ }
+
+ // There are no flags for these 3 in the legacy feature set. Adding them to
+ // the set because all the current devices support it.
+ *aidl_caps |=
+ static_cast<uint32_t>(IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_VENDOR_DATA);
+ *aidl_caps |=
+ static_cast<uint32_t>(IWifiChip::ChipCapabilityMask::DEBUG_HOST_WAKE_REASON_STATS);
+ *aidl_caps |= static_cast<uint32_t>(IWifiChip::ChipCapabilityMask::DEBUG_ERROR_ALERTS);
+ return true;
+}
+
+WifiDebugRingBufferFlags convertLegacyDebugRingBufferFlagsToAidl(uint32_t flag) {
+ switch (flag) {
+ case WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES:
+ return WifiDebugRingBufferFlags::HAS_BINARY_ENTRIES;
+ case WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES:
+ return WifiDebugRingBufferFlags::HAS_ASCII_ENTRIES;
+ };
+ CHECK(false) << "Unknown legacy flag: " << flag;
+ return {};
+}
+
+bool convertLegacyDebugRingBufferStatusToAidl(
+ const legacy_hal::wifi_ring_buffer_status& legacy_status,
+ WifiDebugRingBufferStatus* aidl_status) {
+ if (!aidl_status) {
+ return false;
+ }
+ *aidl_status = {};
+ aidl_status->ringName = safeConvertChar(reinterpret_cast<const char*>(legacy_status.name),
+ sizeof(legacy_status.name));
+ aidl_status->flags = 0;
+ for (const auto flag :
+ {WIFI_RING_BUFFER_FLAG_HAS_BINARY_ENTRIES, WIFI_RING_BUFFER_FLAG_HAS_ASCII_ENTRIES}) {
+ if (flag & legacy_status.flags) {
+ aidl_status->flags |= static_cast<std::underlying_type<WifiDebugRingBufferFlags>::type>(
+ convertLegacyDebugRingBufferFlagsToAidl(flag));
+ }
+ }
+ aidl_status->ringId = legacy_status.ring_id;
+ aidl_status->sizeInBytes = legacy_status.ring_buffer_byte_size;
+ // Calculate free size of the ring the buffer. We don't need to send the
+ // exact read/write pointers that were there in the legacy HAL interface.
+ if (legacy_status.written_bytes >= legacy_status.read_bytes) {
+ aidl_status->freeSizeInBytes = legacy_status.ring_buffer_byte_size -
+ (legacy_status.written_bytes - legacy_status.read_bytes);
+ } else {
+ aidl_status->freeSizeInBytes = legacy_status.read_bytes - legacy_status.written_bytes;
+ }
+ aidl_status->verboseLevel = legacy_status.verbose_level;
+ return true;
+}
+
+bool convertLegacyVectorOfDebugRingBufferStatusToAidl(
+ const std::vector<legacy_hal::wifi_ring_buffer_status>& legacy_status_vec,
+ std::vector<WifiDebugRingBufferStatus>* aidl_status_vec) {
+ if (!aidl_status_vec) {
+ return false;
+ }
+ *aidl_status_vec = {};
+ for (const auto& legacy_status : legacy_status_vec) {
+ WifiDebugRingBufferStatus aidl_status;
+ if (!convertLegacyDebugRingBufferStatusToAidl(legacy_status, &aidl_status)) {
+ return false;
+ }
+ aidl_status_vec->push_back(aidl_status);
+ }
+ return true;
+}
+
+bool convertLegacyWakeReasonStatsToAidl(const legacy_hal::WakeReasonStats& legacy_stats,
+ WifiDebugHostWakeReasonStats* aidl_stats) {
+ if (!aidl_stats) {
+ return false;
+ }
+ *aidl_stats = {};
+ aidl_stats->totalCmdEventWakeCnt = legacy_stats.wake_reason_cnt.total_cmd_event_wake;
+ aidl_stats->cmdEventWakeCntPerType = uintToIntVec(legacy_stats.cmd_event_wake_cnt);
+ aidl_stats->totalDriverFwLocalWakeCnt = legacy_stats.wake_reason_cnt.total_driver_fw_local_wake;
+ aidl_stats->driverFwLocalWakeCntPerType = uintToIntVec(legacy_stats.driver_fw_local_wake_cnt);
+ aidl_stats->totalRxPacketWakeCnt = legacy_stats.wake_reason_cnt.total_rx_data_wake;
+ aidl_stats->rxPktWakeDetails.rxUnicastCnt =
+ legacy_stats.wake_reason_cnt.rx_wake_details.rx_unicast_cnt;
+ aidl_stats->rxPktWakeDetails.rxMulticastCnt =
+ legacy_stats.wake_reason_cnt.rx_wake_details.rx_multicast_cnt;
+ aidl_stats->rxPktWakeDetails.rxBroadcastCnt =
+ legacy_stats.wake_reason_cnt.rx_wake_details.rx_broadcast_cnt;
+ aidl_stats->rxMulticastPkWakeDetails.ipv4RxMulticastAddrCnt =
+ legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.ipv4_rx_multicast_addr_cnt;
+ aidl_stats->rxMulticastPkWakeDetails.ipv6RxMulticastAddrCnt =
+ legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.ipv6_rx_multicast_addr_cnt;
+ aidl_stats->rxMulticastPkWakeDetails.otherRxMulticastAddrCnt =
+ legacy_stats.wake_reason_cnt.rx_multicast_wake_pkt_info.other_rx_multicast_addr_cnt;
+ aidl_stats->rxIcmpPkWakeDetails.icmpPkt =
+ legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp_pkt;
+ aidl_stats->rxIcmpPkWakeDetails.icmp6Pkt =
+ legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_pkt;
+ aidl_stats->rxIcmpPkWakeDetails.icmp6Ra =
+ legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ra;
+ aidl_stats->rxIcmpPkWakeDetails.icmp6Na =
+ legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_na;
+ aidl_stats->rxIcmpPkWakeDetails.icmp6Ns =
+ legacy_stats.wake_reason_cnt.rx_wake_pkt_classification_info.icmp6_ns;
+ return true;
+}
+
+legacy_hal::wifi_power_scenario convertAidlTxPowerScenarioToLegacy(
+ IWifiChip::TxPowerScenario aidl_scenario) {
+ switch (aidl_scenario) {
+ case IWifiChip::TxPowerScenario::VOICE_CALL:
+ return legacy_hal::WIFI_POWER_SCENARIO_VOICE_CALL;
+ case IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF:
+ return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_OFF;
+ case IWifiChip::TxPowerScenario::ON_HEAD_CELL_ON:
+ return legacy_hal::WIFI_POWER_SCENARIO_ON_HEAD_CELL_ON;
+ case IWifiChip::TxPowerScenario::ON_BODY_CELL_OFF:
+ return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_OFF;
+ case IWifiChip::TxPowerScenario::ON_BODY_CELL_ON:
+ return legacy_hal::WIFI_POWER_SCENARIO_ON_BODY_CELL_ON;
+ };
+ CHECK(false);
+}
+
+legacy_hal::wifi_latency_mode convertAidlLatencyModeToLegacy(
+ IWifiChip::LatencyMode aidl_latency_mode) {
+ switch (aidl_latency_mode) {
+ case IWifiChip::LatencyMode::NORMAL:
+ return legacy_hal::WIFI_LATENCY_MODE_NORMAL;
+ case IWifiChip::LatencyMode::LOW:
+ return legacy_hal::WIFI_LATENCY_MODE_LOW;
+ }
+ CHECK(false);
+}
+
+bool convertLegacyWifiMacInfoToAidl(const legacy_hal::WifiMacInfo& legacy_mac_info,
+ IWifiChipEventCallback::RadioModeInfo* aidl_radio_mode_info) {
+ if (!aidl_radio_mode_info) {
+ return false;
+ }
+ *aidl_radio_mode_info = {};
+
+ aidl_radio_mode_info->radioId = legacy_mac_info.wlan_mac_id;
+ // Convert from bitmask of bands in the legacy HAL to enum value in
+ // the AIDL interface.
+ if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND &&
+ legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND &&
+ legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ_5GHZ_6GHZ;
+ } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND &&
+ legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_5GHZ_6GHZ;
+ } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_6_0_BAND) {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_6GHZ;
+ } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND &&
+ legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ_5GHZ;
+ } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_2_4_BAND) {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_24GHZ;
+ } else if (legacy_mac_info.mac_band & legacy_hal::WLAN_MAC_5_0_BAND) {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_5GHZ;
+ } else {
+ aidl_radio_mode_info->bandInfo = WifiBand::BAND_UNSPECIFIED;
+ }
+ std::vector<IWifiChipEventCallback::IfaceInfo> iface_info_vec;
+ for (const auto& legacy_iface_info : legacy_mac_info.iface_infos) {
+ IWifiChipEventCallback::IfaceInfo iface_info;
+ iface_info.name = legacy_iface_info.name;
+ iface_info.channel = legacy_iface_info.channel;
+ iface_info_vec.push_back(iface_info);
+ }
+ aidl_radio_mode_info->ifaceInfos = iface_info_vec;
+ return true;
+}
+
+uint32_t convertAidlWifiBandToLegacyMacBand(WifiBand aidl_band) {
+ switch (aidl_band) {
+ case WifiBand::BAND_24GHZ:
+ return legacy_hal::WLAN_MAC_2_4_BAND;
+ case WifiBand::BAND_5GHZ:
+ case WifiBand::BAND_5GHZ_DFS:
+ case WifiBand::BAND_5GHZ_WITH_DFS:
+ return legacy_hal::WLAN_MAC_5_0_BAND;
+ case WifiBand::BAND_24GHZ_5GHZ:
+ case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
+ return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND);
+ case WifiBand::BAND_6GHZ:
+ return legacy_hal::WLAN_MAC_6_0_BAND;
+ case WifiBand::BAND_5GHZ_6GHZ:
+ return (legacy_hal::WLAN_MAC_5_0_BAND | legacy_hal::WLAN_MAC_6_0_BAND);
+ case WifiBand::BAND_24GHZ_5GHZ_6GHZ:
+ case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS_6GHZ:
+ return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND |
+ legacy_hal::WLAN_MAC_6_0_BAND);
+ case WifiBand::BAND_60GHZ:
+ return legacy_hal::WLAN_MAC_60_0_BAND;
+ default:
+ return (legacy_hal::WLAN_MAC_2_4_BAND | legacy_hal::WLAN_MAC_5_0_BAND |
+ legacy_hal::WLAN_MAC_6_0_BAND | legacy_hal::WLAN_MAC_60_0_BAND);
+ }
+}
+
+WifiBand convertLegacyMacBandToAidlWifiBand(uint32_t band) {
+ switch (band) {
+ case legacy_hal::WLAN_MAC_2_4_BAND:
+ return WifiBand::BAND_24GHZ;
+ case legacy_hal::WLAN_MAC_5_0_BAND:
+ return WifiBand::BAND_5GHZ;
+ case legacy_hal::WLAN_MAC_6_0_BAND:
+ return WifiBand::BAND_6GHZ;
+ case legacy_hal::WLAN_MAC_60_0_BAND:
+ return WifiBand::BAND_60GHZ;
+ default:
+ return WifiBand::BAND_UNSPECIFIED;
+ }
+}
+
+uint32_t convertAidlWifiIfaceModeToLegacy(uint32_t aidl_iface_mask) {
+ uint32_t legacy_iface_mask = 0;
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_STA)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_STA);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_SOFTAP)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_SOFTAP);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_CLIENT)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_P2P_CLIENT);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_GO)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_P2P_GO);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_NAN)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_NAN);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_TDLS)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_TDLS);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_MESH)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_MESH);
+ }
+ if (aidl_iface_mask & static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_IBSS)) {
+ legacy_iface_mask |= (1 << legacy_hal::WIFI_INTERFACE_IBSS);
+ }
+ return legacy_iface_mask;
+}
+
+uint32_t convertLegacyWifiInterfaceModeToAidl(uint32_t legacy_iface_mask) {
+ uint32_t aidl_iface_mask = 0;
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_STA)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_STA);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_SOFTAP)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_SOFTAP);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_P2P_CLIENT)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_CLIENT);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_P2P_GO)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_P2P_GO);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_NAN)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_NAN);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_TDLS)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_TDLS);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_MESH)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_MESH);
+ }
+ if (legacy_iface_mask & (1 << legacy_hal::WIFI_INTERFACE_IBSS)) {
+ aidl_iface_mask |= static_cast<int32_t>(WifiIfaceMode::IFACE_MODE_IBSS);
+ }
+ return aidl_iface_mask;
+}
+
+uint32_t convertAidlUsableChannelFilterToLegacy(uint32_t aidl_filter_mask) {
+ uint32_t legacy_filter_mask = 0;
+ if (aidl_filter_mask &
+ static_cast<int32_t>(IWifiChip::UsableChannelFilter::CELLULAR_COEXISTENCE)) {
+ legacy_filter_mask |= legacy_hal::WIFI_USABLE_CHANNEL_FILTER_CELLULAR_COEXISTENCE;
+ }
+ if (aidl_filter_mask & static_cast<int32_t>(IWifiChip::UsableChannelFilter::CONCURRENCY)) {
+ legacy_filter_mask |= legacy_hal::WIFI_USABLE_CHANNEL_FILTER_CONCURRENCY;
+ }
+ if (aidl_filter_mask & static_cast<int32_t>(IWifiChip::UsableChannelFilter::NAN_INSTANT_MODE)) {
+ legacy_filter_mask |= WIFI_USABLE_CHANNEL_FILTER_NAN_INSTANT_MODE;
+ }
+ return legacy_filter_mask;
+}
+
+bool convertLegacyWifiUsableChannelToAidl(
+ const legacy_hal::wifi_usable_channel& legacy_usable_channel,
+ WifiUsableChannel* aidl_usable_channel) {
+ if (!aidl_usable_channel) {
+ return false;
+ }
+ *aidl_usable_channel = {};
+ aidl_usable_channel->channel = legacy_usable_channel.freq;
+ aidl_usable_channel->channelBandwidth =
+ convertLegacyWifiChannelWidthToAidl(legacy_usable_channel.width);
+ aidl_usable_channel->ifaceModeMask = static_cast<WifiIfaceMode>(
+ convertLegacyWifiInterfaceModeToAidl(legacy_usable_channel.iface_mode_mask));
+
+ return true;
+}
+
+bool convertLegacyWifiUsableChannelsToAidl(
+ const std::vector<legacy_hal::wifi_usable_channel>& legacy_usable_channels,
+ std::vector<WifiUsableChannel>* aidl_usable_channels) {
+ if (!aidl_usable_channels) {
+ return false;
+ }
+ *aidl_usable_channels = {};
+ for (const auto& legacy_usable_channel : legacy_usable_channels) {
+ WifiUsableChannel aidl_usable_channel;
+ if (!convertLegacyWifiUsableChannelToAidl(legacy_usable_channel, &aidl_usable_channel)) {
+ return false;
+ }
+ aidl_usable_channels->push_back(aidl_usable_channel);
+ }
+ return true;
+}
+
+bool convertLegacyWifiMacInfosToAidl(
+ const std::vector<legacy_hal::WifiMacInfo>& legacy_mac_infos,
+ std::vector<IWifiChipEventCallback::RadioModeInfo>* aidl_radio_mode_infos) {
+ if (!aidl_radio_mode_infos) {
+ return false;
+ }
+ *aidl_radio_mode_infos = {};
+
+ for (const auto& legacy_mac_info : legacy_mac_infos) {
+ IWifiChipEventCallback::RadioModeInfo aidl_radio_mode_info;
+ if (!convertLegacyWifiMacInfoToAidl(legacy_mac_info, &aidl_radio_mode_info)) {
+ return false;
+ }
+ aidl_radio_mode_infos->push_back(aidl_radio_mode_info);
+ }
+ return true;
+}
+
+bool convertLegacyFeaturesToAidlStaCapabilities(uint64_t legacy_feature_set,
+ uint32_t legacy_logger_feature_set,
+ uint32_t* aidl_caps) {
+ if (!aidl_caps) {
+ return false;
+ }
+ *aidl_caps = {};
+ for (const auto feature : {legacy_hal::WIFI_LOGGER_PACKET_FATE_SUPPORTED}) {
+ if (feature & legacy_logger_feature_set) {
+ *aidl_caps |= static_cast<uint32_t>(
+ convertLegacyLoggerFeatureToAidlStaIfaceCapability(feature));
+ }
+ }
+ for (const auto feature :
+ {WIFI_FEATURE_GSCAN, WIFI_FEATURE_LINK_LAYER_STATS, WIFI_FEATURE_RSSI_MONITOR,
+ WIFI_FEATURE_CONTROL_ROAMING, WIFI_FEATURE_IE_WHITELIST, WIFI_FEATURE_SCAN_RAND,
+ WIFI_FEATURE_INFRA_5G, WIFI_FEATURE_HOTSPOT, WIFI_FEATURE_PNO, WIFI_FEATURE_TDLS,
+ WIFI_FEATURE_TDLS_OFFCHANNEL, WIFI_FEATURE_CONFIG_NDO, WIFI_FEATURE_MKEEP_ALIVE}) {
+ if (feature & legacy_feature_set) {
+ *aidl_caps |=
+ static_cast<uint32_t>(convertLegacyFeatureToAidlStaIfaceCapability(feature));
+ }
+ }
+ // There is no flag for this one in the legacy feature set. Adding it to the
+ // set because all the current devices support it.
+ *aidl_caps |= static_cast<uint32_t>(IWifiStaIface::StaIfaceCapabilityMask::APF);
+ return true;
+}
+
+bool convertLegacyApfCapabilitiesToAidl(const legacy_hal::PacketFilterCapabilities& legacy_caps,
+ StaApfPacketFilterCapabilities* aidl_caps) {
+ if (!aidl_caps) {
+ return false;
+ }
+ *aidl_caps = {};
+ aidl_caps->version = legacy_caps.version;
+ aidl_caps->maxLength = legacy_caps.max_len;
+ return true;
+}
+
+uint8_t convertAidlGscanReportEventFlagToLegacy(
+ StaBackgroundScanBucketEventReportSchemeMask aidl_flag) {
+ using AidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
+ switch (aidl_flag) {
+ case AidlFlag::EACH_SCAN:
+ return REPORT_EVENTS_EACH_SCAN;
+ case AidlFlag::FULL_RESULTS:
+ return REPORT_EVENTS_FULL_RESULTS;
+ case AidlFlag::NO_BATCH:
+ return REPORT_EVENTS_NO_BATCH;
+ };
+ CHECK(false);
+}
+
+StaScanDataFlagMask convertLegacyGscanDataFlagToAidl(uint8_t legacy_flag) {
+ switch (legacy_flag) {
+ case legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED:
+ return StaScanDataFlagMask::INTERRUPTED;
+ };
+ CHECK(false) << "Unknown legacy flag: " << legacy_flag;
+ // To silence the compiler warning about reaching the end of non-void
+ // function.
+ return {};
+}
+
+bool convertLegacyGscanCapabilitiesToAidl(const legacy_hal::wifi_gscan_capabilities& legacy_caps,
+ StaBackgroundScanCapabilities* aidl_caps) {
+ if (!aidl_caps) {
+ return false;
+ }
+ *aidl_caps = {};
+ aidl_caps->maxCacheSize = legacy_caps.max_scan_cache_size;
+ aidl_caps->maxBuckets = legacy_caps.max_scan_buckets;
+ aidl_caps->maxApCachePerScan = legacy_caps.max_ap_cache_per_scan;
+ aidl_caps->maxReportingThreshold = legacy_caps.max_scan_reporting_threshold;
+ return true;
+}
+
+legacy_hal::wifi_band convertAidlWifiBandToLegacy(WifiBand band) {
+ switch (band) {
+ case WifiBand::BAND_UNSPECIFIED:
+ return legacy_hal::WIFI_BAND_UNSPECIFIED;
+ case WifiBand::BAND_24GHZ:
+ return legacy_hal::WIFI_BAND_BG;
+ case WifiBand::BAND_5GHZ:
+ return legacy_hal::WIFI_BAND_A;
+ case WifiBand::BAND_5GHZ_DFS:
+ return legacy_hal::WIFI_BAND_A_DFS;
+ case WifiBand::BAND_5GHZ_WITH_DFS:
+ return legacy_hal::WIFI_BAND_A_WITH_DFS;
+ case WifiBand::BAND_24GHZ_5GHZ:
+ return legacy_hal::WIFI_BAND_ABG;
+ case WifiBand::BAND_24GHZ_5GHZ_WITH_DFS:
+ return legacy_hal::WIFI_BAND_ABG_WITH_DFS;
+ default:
+ CHECK(false);
+ return {};
+ };
+}
+
+bool convertAidlGscanParamsToLegacy(const StaBackgroundScanParameters& aidl_scan_params,
+ legacy_hal::wifi_scan_cmd_params* legacy_scan_params) {
+ if (!legacy_scan_params) {
+ return false;
+ }
+ *legacy_scan_params = {};
+ legacy_scan_params->base_period = aidl_scan_params.basePeriodInMs;
+ legacy_scan_params->max_ap_per_scan = aidl_scan_params.maxApPerScan;
+ legacy_scan_params->report_threshold_percent = aidl_scan_params.reportThresholdPercent;
+ legacy_scan_params->report_threshold_num_scans = aidl_scan_params.reportThresholdNumScans;
+ if (aidl_scan_params.buckets.size() > MAX_BUCKETS) {
+ return false;
+ }
+ legacy_scan_params->num_buckets = aidl_scan_params.buckets.size();
+ for (uint32_t bucket_idx = 0; bucket_idx < aidl_scan_params.buckets.size(); bucket_idx++) {
+ const StaBackgroundScanBucketParameters& aidl_bucket_spec =
+ aidl_scan_params.buckets[bucket_idx];
+ legacy_hal::wifi_scan_bucket_spec& legacy_bucket_spec =
+ legacy_scan_params->buckets[bucket_idx];
+ if (aidl_bucket_spec.bucketIdx >= MAX_BUCKETS) {
+ return false;
+ }
+ legacy_bucket_spec.bucket = aidl_bucket_spec.bucketIdx;
+ legacy_bucket_spec.band = convertAidlWifiBandToLegacy(aidl_bucket_spec.band);
+ legacy_bucket_spec.period = aidl_bucket_spec.periodInMs;
+ legacy_bucket_spec.max_period = aidl_bucket_spec.exponentialMaxPeriodInMs;
+ legacy_bucket_spec.base = aidl_bucket_spec.exponentialBase;
+ legacy_bucket_spec.step_count = aidl_bucket_spec.exponentialStepCount;
+ legacy_bucket_spec.report_events = 0;
+ using AidlFlag = StaBackgroundScanBucketEventReportSchemeMask;
+ for (const auto flag : {AidlFlag::EACH_SCAN, AidlFlag::FULL_RESULTS, AidlFlag::NO_BATCH}) {
+ if (static_cast<int32_t>(aidl_bucket_spec.eventReportScheme) &
+ static_cast<std::underlying_type<AidlFlag>::type>(flag)) {
+ legacy_bucket_spec.report_events |= convertAidlGscanReportEventFlagToLegacy(flag);
+ }
+ }
+ if (aidl_bucket_spec.frequencies.size() > MAX_CHANNELS) {
+ return false;
+ }
+ legacy_bucket_spec.num_channels = aidl_bucket_spec.frequencies.size();
+ for (uint32_t freq_idx = 0; freq_idx < aidl_bucket_spec.frequencies.size(); freq_idx++) {
+ legacy_bucket_spec.channels[freq_idx].channel = aidl_bucket_spec.frequencies[freq_idx];
+ }
+ }
+ return true;
+}
+
+bool convertLegacyIeToAidl(const legacy_hal::wifi_information_element& legacy_ie,
+ WifiInformationElement* aidl_ie) {
+ if (!aidl_ie) {
+ return false;
+ }
+ *aidl_ie = {};
+ aidl_ie->id = legacy_ie.id;
+ aidl_ie->data = std::vector<uint8_t>(legacy_ie.data, legacy_ie.data + legacy_ie.len);
+ return true;
+}
+
+bool convertLegacyIeBlobToAidl(const uint8_t* ie_blob, uint32_t ie_blob_len,
+ std::vector<WifiInformationElement>* aidl_ies) {
+ if (!ie_blob || !aidl_ies) {
+ return false;
+ }
+ *aidl_ies = {};
+ const uint8_t* ies_begin = ie_blob;
+ const uint8_t* ies_end = ie_blob + ie_blob_len;
+ const uint8_t* next_ie = ies_begin;
+ using wifi_ie = legacy_hal::wifi_information_element;
+ constexpr size_t kIeHeaderLen = sizeof(wifi_ie);
+ // Each IE should at least have the header (i.e |id| & |len| fields).
+ while (next_ie + kIeHeaderLen <= ies_end) {
+ const wifi_ie& legacy_ie = (*reinterpret_cast<const wifi_ie*>(next_ie));
+ uint32_t curr_ie_len = kIeHeaderLen + legacy_ie.len;
+ if (next_ie + curr_ie_len > ies_end) {
+ LOG(ERROR) << "Error parsing IE blob. Next IE: " << (void*)next_ie
+ << ", Curr IE len: " << curr_ie_len << ", IEs End: " << (void*)ies_end;
+ break;
+ }
+ WifiInformationElement aidl_ie;
+ if (!convertLegacyIeToAidl(legacy_ie, &aidl_ie)) {
+ LOG(ERROR) << "Error converting IE. Id: " << legacy_ie.id << ", len: " << legacy_ie.len;
+ break;
+ }
+ aidl_ies->push_back(std::move(aidl_ie));
+ next_ie += curr_ie_len;
+ }
+ // Check if the blob has been fully consumed.
+ if (next_ie != ies_end) {
+ LOG(ERROR) << "Failed to fully parse IE blob. Next IE: " << (void*)next_ie
+ << ", IEs End: " << (void*)ies_end;
+ }
+ return true;
+}
+
+bool convertLegacyGscanResultToAidl(const legacy_hal::wifi_scan_result& legacy_scan_result,
+ bool has_ie_data, StaScanResult* aidl_scan_result) {
+ if (!aidl_scan_result) {
+ return false;
+ }
+ *aidl_scan_result = {};
+ aidl_scan_result->timeStampInUs = legacy_scan_result.ts;
+ aidl_scan_result->ssid = std::vector<uint8_t>(
+ legacy_scan_result.ssid,
+ legacy_scan_result.ssid +
+ strnlen(legacy_scan_result.ssid, sizeof(legacy_scan_result.ssid) - 1));
+ aidl_scan_result->bssid = std::array<uint8_t, 6>();
+ std::copy(legacy_scan_result.bssid, legacy_scan_result.bssid + 6,
+ std::begin(aidl_scan_result->bssid));
+ aidl_scan_result->frequency = legacy_scan_result.channel;
+ aidl_scan_result->rssi = legacy_scan_result.rssi;
+ aidl_scan_result->beaconPeriodInMs = legacy_scan_result.beacon_period;
+ aidl_scan_result->capability = legacy_scan_result.capability;
+ if (has_ie_data) {
+ std::vector<WifiInformationElement> ies;
+ if (!convertLegacyIeBlobToAidl(reinterpret_cast<const uint8_t*>(legacy_scan_result.ie_data),
+ legacy_scan_result.ie_length, &ies)) {
+ return false;
+ }
+ aidl_scan_result->informationElements = std::move(ies);
+ }
+ return true;
+}
+
+bool convertLegacyCachedGscanResultsToAidl(
+ const legacy_hal::wifi_cached_scan_results& legacy_cached_scan_result,
+ StaScanData* aidl_scan_data) {
+ if (!aidl_scan_data) {
+ return false;
+ }
+ *aidl_scan_data = {};
+ int32_t flags = 0;
+ for (const auto flag : {legacy_hal::WIFI_SCAN_FLAG_INTERRUPTED}) {
+ if (legacy_cached_scan_result.flags & flag) {
+ flags |= static_cast<std::underlying_type<StaScanDataFlagMask>::type>(
+ convertLegacyGscanDataFlagToAidl(flag));
+ }
+ }
+ aidl_scan_data->flags = static_cast<StaScanDataFlagMask>(flags);
+ aidl_scan_data->bucketsScanned = legacy_cached_scan_result.buckets_scanned;
+
+ CHECK(legacy_cached_scan_result.num_results >= 0 &&
+ legacy_cached_scan_result.num_results <= MAX_AP_CACHE_PER_SCAN);
+ std::vector<StaScanResult> aidl_scan_results;
+ for (int32_t result_idx = 0; result_idx < legacy_cached_scan_result.num_results; result_idx++) {
+ StaScanResult aidl_scan_result;
+ if (!convertLegacyGscanResultToAidl(legacy_cached_scan_result.results[result_idx], false,
+ &aidl_scan_result)) {
+ return false;
+ }
+ aidl_scan_results.push_back(aidl_scan_result);
+ }
+ aidl_scan_data->results = std::move(aidl_scan_results);
+ return true;
+}
+
+bool convertLegacyVectorOfCachedGscanResultsToAidl(
+ const std::vector<legacy_hal::wifi_cached_scan_results>& legacy_cached_scan_results,
+ std::vector<StaScanData>* aidl_scan_datas) {
+ if (!aidl_scan_datas) {
+ return false;
+ }
+ *aidl_scan_datas = {};
+ for (const auto& legacy_cached_scan_result : legacy_cached_scan_results) {
+ StaScanData aidl_scan_data;
+ if (!convertLegacyCachedGscanResultsToAidl(legacy_cached_scan_result, &aidl_scan_data)) {
+ return false;
+ }
+ aidl_scan_datas->push_back(aidl_scan_data);
+ }
+ return true;
+}
+
+WifiDebugTxPacketFate convertLegacyDebugTxPacketFateToAidl(legacy_hal::wifi_tx_packet_fate fate) {
+ switch (fate) {
+ case legacy_hal::TX_PKT_FATE_ACKED:
+ return WifiDebugTxPacketFate::ACKED;
+ case legacy_hal::TX_PKT_FATE_SENT:
+ return WifiDebugTxPacketFate::SENT;
+ case legacy_hal::TX_PKT_FATE_FW_QUEUED:
+ return WifiDebugTxPacketFate::FW_QUEUED;
+ case legacy_hal::TX_PKT_FATE_FW_DROP_INVALID:
+ return WifiDebugTxPacketFate::FW_DROP_INVALID;
+ case legacy_hal::TX_PKT_FATE_FW_DROP_NOBUFS:
+ return WifiDebugTxPacketFate::FW_DROP_NOBUFS;
+ case legacy_hal::TX_PKT_FATE_FW_DROP_OTHER:
+ return WifiDebugTxPacketFate::FW_DROP_OTHER;
+ case legacy_hal::TX_PKT_FATE_DRV_QUEUED:
+ return WifiDebugTxPacketFate::DRV_QUEUED;
+ case legacy_hal::TX_PKT_FATE_DRV_DROP_INVALID:
+ return WifiDebugTxPacketFate::DRV_DROP_INVALID;
+ case legacy_hal::TX_PKT_FATE_DRV_DROP_NOBUFS:
+ return WifiDebugTxPacketFate::DRV_DROP_NOBUFS;
+ case legacy_hal::TX_PKT_FATE_DRV_DROP_OTHER:
+ return WifiDebugTxPacketFate::DRV_DROP_OTHER;
+ };
+ CHECK(false) << "Unknown legacy fate type: " << fate;
+}
+
+WifiDebugRxPacketFate convertLegacyDebugRxPacketFateToAidl(legacy_hal::wifi_rx_packet_fate fate) {
+ switch (fate) {
+ case legacy_hal::RX_PKT_FATE_SUCCESS:
+ return WifiDebugRxPacketFate::SUCCESS;
+ case legacy_hal::RX_PKT_FATE_FW_QUEUED:
+ return WifiDebugRxPacketFate::FW_QUEUED;
+ case legacy_hal::RX_PKT_FATE_FW_DROP_FILTER:
+ return WifiDebugRxPacketFate::FW_DROP_FILTER;
+ case legacy_hal::RX_PKT_FATE_FW_DROP_INVALID:
+ return WifiDebugRxPacketFate::FW_DROP_INVALID;
+ case legacy_hal::RX_PKT_FATE_FW_DROP_NOBUFS:
+ return WifiDebugRxPacketFate::FW_DROP_NOBUFS;
+ case legacy_hal::RX_PKT_FATE_FW_DROP_OTHER:
+ return WifiDebugRxPacketFate::FW_DROP_OTHER;
+ case legacy_hal::RX_PKT_FATE_DRV_QUEUED:
+ return WifiDebugRxPacketFate::DRV_QUEUED;
+ case legacy_hal::RX_PKT_FATE_DRV_DROP_FILTER:
+ return WifiDebugRxPacketFate::DRV_DROP_FILTER;
+ case legacy_hal::RX_PKT_FATE_DRV_DROP_INVALID:
+ return WifiDebugRxPacketFate::DRV_DROP_INVALID;
+ case legacy_hal::RX_PKT_FATE_DRV_DROP_NOBUFS:
+ return WifiDebugRxPacketFate::DRV_DROP_NOBUFS;
+ case legacy_hal::RX_PKT_FATE_DRV_DROP_OTHER:
+ return WifiDebugRxPacketFate::DRV_DROP_OTHER;
+ };
+ CHECK(false) << "Unknown legacy fate type: " << fate;
+}
+
+WifiDebugPacketFateFrameType convertLegacyDebugPacketFateFrameTypeToAidl(
+ legacy_hal::frame_type type) {
+ switch (type) {
+ case legacy_hal::FRAME_TYPE_UNKNOWN:
+ return WifiDebugPacketFateFrameType::UNKNOWN;
+ case legacy_hal::FRAME_TYPE_ETHERNET_II:
+ return WifiDebugPacketFateFrameType::ETHERNET_II;
+ case legacy_hal::FRAME_TYPE_80211_MGMT:
+ return WifiDebugPacketFateFrameType::MGMT_80211;
+ };
+ CHECK(false) << "Unknown legacy frame type: " << type;
+}
+
+bool convertLegacyDebugPacketFateFrameToAidl(const legacy_hal::frame_info& legacy_frame,
+ WifiDebugPacketFateFrameInfo* aidl_frame) {
+ if (!aidl_frame) {
+ return false;
+ }
+ *aidl_frame = {};
+ aidl_frame->frameType = convertLegacyDebugPacketFateFrameTypeToAidl(legacy_frame.payload_type);
+ aidl_frame->frameLen = legacy_frame.frame_len;
+ aidl_frame->driverTimestampUsec = legacy_frame.driver_timestamp_usec;
+ aidl_frame->firmwareTimestampUsec = legacy_frame.firmware_timestamp_usec;
+ const uint8_t* frame_begin =
+ reinterpret_cast<const uint8_t*>(legacy_frame.frame_content.ethernet_ii_bytes);
+ aidl_frame->frameContent =
+ std::vector<uint8_t>(frame_begin, frame_begin + legacy_frame.frame_len);
+ return true;
+}
+
+bool convertLegacyDebugTxPacketFateToAidl(const legacy_hal::wifi_tx_report& legacy_fate,
+ WifiDebugTxPacketFateReport* aidl_fate) {
+ if (!aidl_fate) {
+ return false;
+ }
+ *aidl_fate = {};
+ aidl_fate->fate = convertLegacyDebugTxPacketFateToAidl(legacy_fate.fate);
+ return convertLegacyDebugPacketFateFrameToAidl(legacy_fate.frame_inf, &aidl_fate->frameInfo);
+}
+
+bool convertLegacyVectorOfDebugTxPacketFateToAidl(
+ const std::vector<legacy_hal::wifi_tx_report>& legacy_fates,
+ std::vector<WifiDebugTxPacketFateReport>* aidl_fates) {
+ if (!aidl_fates) {
+ return false;
+ }
+ *aidl_fates = {};
+ for (const auto& legacy_fate : legacy_fates) {
+ WifiDebugTxPacketFateReport aidl_fate;
+ if (!convertLegacyDebugTxPacketFateToAidl(legacy_fate, &aidl_fate)) {
+ return false;
+ }
+ aidl_fates->push_back(aidl_fate);
+ }
+ return true;
+}
+
+bool convertLegacyDebugRxPacketFateToAidl(const legacy_hal::wifi_rx_report& legacy_fate,
+ WifiDebugRxPacketFateReport* aidl_fate) {
+ if (!aidl_fate) {
+ return false;
+ }
+ *aidl_fate = {};
+ aidl_fate->fate = convertLegacyDebugRxPacketFateToAidl(legacy_fate.fate);
+ return convertLegacyDebugPacketFateFrameToAidl(legacy_fate.frame_inf, &aidl_fate->frameInfo);
+}
+
+bool convertLegacyVectorOfDebugRxPacketFateToAidl(
+ const std::vector<legacy_hal::wifi_rx_report>& legacy_fates,
+ std::vector<WifiDebugRxPacketFateReport>* aidl_fates) {
+ if (!aidl_fates) {
+ return false;
+ }
+ *aidl_fates = {};
+ for (const auto& legacy_fate : legacy_fates) {
+ WifiDebugRxPacketFateReport aidl_fate;
+ if (!convertLegacyDebugRxPacketFateToAidl(legacy_fate, &aidl_fate)) {
+ return false;
+ }
+ aidl_fates->push_back(aidl_fate);
+ }
+ return true;
+}
+
+bool convertLegacyLinkLayerRadioStatsToAidl(
+ const legacy_hal::LinkLayerRadioStats& legacy_radio_stat,
+ StaLinkLayerRadioStats* aidl_radio_stat) {
+ if (!aidl_radio_stat) {
+ return false;
+ }
+ *aidl_radio_stat = {};
+
+ aidl_radio_stat->radioId = legacy_radio_stat.stats.radio;
+ aidl_radio_stat->onTimeInMs = legacy_radio_stat.stats.on_time;
+ aidl_radio_stat->txTimeInMs = legacy_radio_stat.stats.tx_time;
+ aidl_radio_stat->rxTimeInMs = legacy_radio_stat.stats.rx_time;
+ aidl_radio_stat->onTimeInMsForScan = legacy_radio_stat.stats.on_time_scan;
+ aidl_radio_stat->txTimeInMsPerLevel = uintToIntVec(legacy_radio_stat.tx_time_per_levels);
+ aidl_radio_stat->onTimeInMsForNanScan = legacy_radio_stat.stats.on_time_nbd;
+ aidl_radio_stat->onTimeInMsForBgScan = legacy_radio_stat.stats.on_time_gscan;
+ aidl_radio_stat->onTimeInMsForRoamScan = legacy_radio_stat.stats.on_time_roam_scan;
+ aidl_radio_stat->onTimeInMsForPnoScan = legacy_radio_stat.stats.on_time_pno_scan;
+ aidl_radio_stat->onTimeInMsForHs20Scan = legacy_radio_stat.stats.on_time_hs20;
+
+ std::vector<WifiChannelStats> aidl_channel_stats;
+
+ for (const auto& channel_stat : legacy_radio_stat.channel_stats) {
+ WifiChannelStats aidl_channel_stat;
+ aidl_channel_stat.onTimeInMs = channel_stat.on_time;
+ aidl_channel_stat.ccaBusyTimeInMs = channel_stat.cca_busy_time;
+ aidl_channel_stat.channel.width = WifiChannelWidthInMhz::WIDTH_20;
+ aidl_channel_stat.channel.centerFreq = channel_stat.channel.center_freq;
+ aidl_channel_stat.channel.centerFreq0 = channel_stat.channel.center_freq0;
+ aidl_channel_stat.channel.centerFreq1 = channel_stat.channel.center_freq1;
+ aidl_channel_stats.push_back(aidl_channel_stat);
+ }
+
+ aidl_radio_stat->channelStats = aidl_channel_stats;
+
+ return true;
+}
+
+bool convertLegacyLinkLayerStatsToAidl(const legacy_hal::LinkLayerStats& legacy_stats,
+ StaLinkLayerStats* aidl_stats) {
+ if (!aidl_stats) {
+ return false;
+ }
+ *aidl_stats = {};
+ // iface legacy_stats conversion.
+ aidl_stats->iface.beaconRx = legacy_stats.iface.beacon_rx;
+ aidl_stats->iface.avgRssiMgmt = legacy_stats.iface.rssi_mgmt;
+ aidl_stats->iface.wmeBePktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].rx_mpdu;
+ aidl_stats->iface.wmeBePktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].tx_mpdu;
+ aidl_stats->iface.wmeBePktStats.lostMpdu =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].mpdu_lost;
+ aidl_stats->iface.wmeBePktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].retries;
+ aidl_stats->iface.wmeBeContentionTimeStats.contentionTimeMinInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_min;
+ aidl_stats->iface.wmeBeContentionTimeStats.contentionTimeMaxInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_max;
+ aidl_stats->iface.wmeBeContentionTimeStats.contentionTimeAvgInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_avg;
+ aidl_stats->iface.wmeBeContentionTimeStats.contentionNumSamples =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_num_samples;
+ aidl_stats->iface.wmeBkPktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].rx_mpdu;
+ aidl_stats->iface.wmeBkPktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].tx_mpdu;
+ aidl_stats->iface.wmeBkPktStats.lostMpdu =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].mpdu_lost;
+ aidl_stats->iface.wmeBkPktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].retries;
+ aidl_stats->iface.wmeBkContentionTimeStats.contentionTimeMinInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_min;
+ aidl_stats->iface.wmeBkContentionTimeStats.contentionTimeMaxInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_max;
+ aidl_stats->iface.wmeBkContentionTimeStats.contentionTimeAvgInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_avg;
+ aidl_stats->iface.wmeBkContentionTimeStats.contentionNumSamples =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_num_samples;
+ aidl_stats->iface.wmeViPktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].rx_mpdu;
+ aidl_stats->iface.wmeViPktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].tx_mpdu;
+ aidl_stats->iface.wmeViPktStats.lostMpdu =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].mpdu_lost;
+ aidl_stats->iface.wmeViPktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].retries;
+ aidl_stats->iface.wmeViContentionTimeStats.contentionTimeMinInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_min;
+ aidl_stats->iface.wmeViContentionTimeStats.contentionTimeMaxInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_max;
+ aidl_stats->iface.wmeViContentionTimeStats.contentionTimeAvgInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_avg;
+ aidl_stats->iface.wmeViContentionTimeStats.contentionNumSamples =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_num_samples;
+ aidl_stats->iface.wmeVoPktStats.rxMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].rx_mpdu;
+ aidl_stats->iface.wmeVoPktStats.txMpdu = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].tx_mpdu;
+ aidl_stats->iface.wmeVoPktStats.lostMpdu =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].mpdu_lost;
+ aidl_stats->iface.wmeVoPktStats.retries = legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].retries;
+ aidl_stats->iface.wmeVoContentionTimeStats.contentionTimeMinInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_min;
+ aidl_stats->iface.wmeVoContentionTimeStats.contentionTimeMaxInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_max;
+ aidl_stats->iface.wmeVoContentionTimeStats.contentionTimeAvgInUsec =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_avg;
+ aidl_stats->iface.wmeVoContentionTimeStats.contentionNumSamples =
+ legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_num_samples;
+ aidl_stats->iface.timeSliceDutyCycleInPercent =
+ legacy_stats.iface.info.time_slicing_duty_cycle_percent;
+ // peer info legacy_stats conversion.
+ std::vector<StaPeerInfo> aidl_peers_info_stats;
+ for (const auto& legacy_peer_info_stats : legacy_stats.peers) {
+ StaPeerInfo aidl_peer_info_stats;
+ if (!convertLegacyPeerInfoStatsToAidl(legacy_peer_info_stats, &aidl_peer_info_stats)) {
+ return false;
+ }
+ aidl_peers_info_stats.push_back(aidl_peer_info_stats);
+ }
+ aidl_stats->iface.peers = aidl_peers_info_stats;
+ // radio legacy_stats conversion.
+ std::vector<StaLinkLayerRadioStats> aidl_radios_stats;
+ for (const auto& legacy_radio_stats : legacy_stats.radios) {
+ StaLinkLayerRadioStats aidl_radio_stats;
+ if (!convertLegacyLinkLayerRadioStatsToAidl(legacy_radio_stats, &aidl_radio_stats)) {
+ return false;
+ }
+ aidl_radios_stats.push_back(aidl_radio_stats);
+ }
+ aidl_stats->radios = aidl_radios_stats;
+ aidl_stats->timeStampInMs = ::android::uptimeMillis();
+ return true;
+}
+
+bool convertLegacyPeerInfoStatsToAidl(const legacy_hal::WifiPeerInfo& legacy_peer_info_stats,
+ StaPeerInfo* aidl_peer_info_stats) {
+ if (!aidl_peer_info_stats) {
+ return false;
+ }
+ *aidl_peer_info_stats = {};
+ aidl_peer_info_stats->staCount = legacy_peer_info_stats.peer_info.bssload.sta_count;
+ aidl_peer_info_stats->chanUtil = legacy_peer_info_stats.peer_info.bssload.chan_util;
+
+ std::vector<StaRateStat> aidlRateStats;
+ for (const auto& legacy_rate_stats : legacy_peer_info_stats.rate_stats) {
+ StaRateStat rateStat;
+ if (!convertLegacyWifiRateInfoToAidl(legacy_rate_stats.rate, &rateStat.rateInfo)) {
+ return false;
+ }
+ rateStat.txMpdu = legacy_rate_stats.tx_mpdu;
+ rateStat.rxMpdu = legacy_rate_stats.rx_mpdu;
+ rateStat.mpduLost = legacy_rate_stats.mpdu_lost;
+ rateStat.retries = legacy_rate_stats.retries;
+ aidlRateStats.push_back(rateStat);
+ }
+ aidl_peer_info_stats->rateStats = aidlRateStats;
+ return true;
+}
+
+bool convertLegacyRoamingCapabilitiesToAidl(
+ const legacy_hal::wifi_roaming_capabilities& legacy_caps,
+ StaRoamingCapabilities* aidl_caps) {
+ if (!aidl_caps) {
+ return false;
+ }
+ *aidl_caps = {};
+ aidl_caps->maxBlocklistSize = legacy_caps.max_blacklist_size;
+ aidl_caps->maxAllowlistSize = legacy_caps.max_whitelist_size;
+ return true;
+}
+
+bool convertAidlRoamingConfigToLegacy(const StaRoamingConfig& aidl_config,
+ legacy_hal::wifi_roaming_config* legacy_config) {
+ if (!legacy_config) {
+ return false;
+ }
+ *legacy_config = {};
+ if (aidl_config.bssidBlocklist.size() > MAX_BLACKLIST_BSSID ||
+ aidl_config.ssidAllowlist.size() > MAX_WHITELIST_SSID) {
+ return false;
+ }
+ legacy_config->num_blacklist_bssid = aidl_config.bssidBlocklist.size();
+ uint32_t i = 0;
+ for (const auto& bssid : aidl_config.bssidBlocklist) {
+ CHECK(bssid.data.size() == sizeof(legacy_hal::mac_addr));
+ memcpy(legacy_config->blacklist_bssid[i++], bssid.data.data(), bssid.data.size());
+ }
+ legacy_config->num_whitelist_ssid = aidl_config.ssidAllowlist.size();
+ i = 0;
+ for (const auto& ssid : aidl_config.ssidAllowlist) {
+ CHECK(ssid.data.size() <= sizeof(legacy_hal::ssid_t::ssid_str));
+ legacy_config->whitelist_ssid[i].length = ssid.data.size();
+ memcpy(legacy_config->whitelist_ssid[i].ssid_str, ssid.data.data(), ssid.data.size());
+ i++;
+ }
+ return true;
+}
+
+legacy_hal::fw_roaming_state_t convertAidlRoamingStateToLegacy(StaRoamingState state) {
+ switch (state) {
+ case StaRoamingState::ENABLED:
+ return legacy_hal::ROAMING_ENABLE;
+ case StaRoamingState::DISABLED:
+ return legacy_hal::ROAMING_DISABLE;
+ };
+ CHECK(false);
+}
+
+legacy_hal::NanMatchAlg convertAidlNanMatchAlgToLegacy(NanMatchAlg type) {
+ switch (type) {
+ case NanMatchAlg::MATCH_ONCE:
+ return legacy_hal::NAN_MATCH_ALG_MATCH_ONCE;
+ case NanMatchAlg::MATCH_CONTINUOUS:
+ return legacy_hal::NAN_MATCH_ALG_MATCH_CONTINUOUS;
+ case NanMatchAlg::MATCH_NEVER:
+ return legacy_hal::NAN_MATCH_ALG_MATCH_NEVER;
+ }
+ CHECK(false);
+}
+
+legacy_hal::NanPublishType convertAidlNanPublishTypeToLegacy(NanPublishType type) {
+ switch (type) {
+ case NanPublishType::UNSOLICITED:
+ return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED;
+ case NanPublishType::SOLICITED:
+ return legacy_hal::NAN_PUBLISH_TYPE_SOLICITED;
+ case NanPublishType::UNSOLICITED_SOLICITED:
+ return legacy_hal::NAN_PUBLISH_TYPE_UNSOLICITED_SOLICITED;
+ }
+ CHECK(false);
+}
+
+legacy_hal::NanTxType convertAidlNanTxTypeToLegacy(NanTxType type) {
+ switch (type) {
+ case NanTxType::BROADCAST:
+ return legacy_hal::NAN_TX_TYPE_BROADCAST;
+ case NanTxType::UNICAST:
+ return legacy_hal::NAN_TX_TYPE_UNICAST;
+ }
+ CHECK(false);
+}
+
+legacy_hal::NanSubscribeType convertAidlNanSubscribeTypeToLegacy(NanSubscribeType type) {
+ switch (type) {
+ case NanSubscribeType::PASSIVE:
+ return legacy_hal::NAN_SUBSCRIBE_TYPE_PASSIVE;
+ case NanSubscribeType::ACTIVE:
+ return legacy_hal::NAN_SUBSCRIBE_TYPE_ACTIVE;
+ }
+ CHECK(false);
+}
+
+legacy_hal::NanSRFType convertAidlNanSrfTypeToLegacy(NanSrfType type) {
+ switch (type) {
+ case NanSrfType::BLOOM_FILTER:
+ return legacy_hal::NAN_SRF_ATTR_BLOOM_FILTER;
+ case NanSrfType::PARTIAL_MAC_ADDR:
+ return legacy_hal::NAN_SRF_ATTR_PARTIAL_MAC_ADDR;
+ }
+ CHECK(false);
+}
+
+legacy_hal::NanDataPathChannelCfg convertAidlNanDataPathChannelCfgToLegacy(
+ NanDataPathChannelCfg type) {
+ switch (type) {
+ case NanDataPathChannelCfg::CHANNEL_NOT_REQUESTED:
+ return legacy_hal::NAN_DP_CHANNEL_NOT_REQUESTED;
+ case NanDataPathChannelCfg::REQUEST_CHANNEL_SETUP:
+ return legacy_hal::NAN_DP_REQUEST_CHANNEL_SETUP;
+ case NanDataPathChannelCfg::FORCE_CHANNEL_SETUP:
+ return legacy_hal::NAN_DP_FORCE_CHANNEL_SETUP;
+ }
+ CHECK(false);
+}
+
+NanStatusCode convertLegacyNanStatusTypeToAidl(legacy_hal::NanStatusType type) {
+ switch (type) {
+ case legacy_hal::NAN_STATUS_SUCCESS:
+ return NanStatusCode::SUCCESS;
+ case legacy_hal::NAN_STATUS_INTERNAL_FAILURE:
+ return NanStatusCode::INTERNAL_FAILURE;
+ case legacy_hal::NAN_STATUS_PROTOCOL_FAILURE:
+ return NanStatusCode::PROTOCOL_FAILURE;
+ case legacy_hal::NAN_STATUS_INVALID_PUBLISH_SUBSCRIBE_ID:
+ return NanStatusCode::INVALID_SESSION_ID;
+ case legacy_hal::NAN_STATUS_NO_RESOURCE_AVAILABLE:
+ return NanStatusCode::NO_RESOURCES_AVAILABLE;
+ case legacy_hal::NAN_STATUS_INVALID_PARAM:
+ return NanStatusCode::INVALID_ARGS;
+ case legacy_hal::NAN_STATUS_INVALID_REQUESTOR_INSTANCE_ID:
+ return NanStatusCode::INVALID_PEER_ID;
+ case legacy_hal::NAN_STATUS_INVALID_NDP_ID:
+ return NanStatusCode::INVALID_NDP_ID;
+ case legacy_hal::NAN_STATUS_NAN_NOT_ALLOWED:
+ return NanStatusCode::NAN_NOT_ALLOWED;
+ case legacy_hal::NAN_STATUS_NO_OTA_ACK:
+ return NanStatusCode::NO_OTA_ACK;
+ case legacy_hal::NAN_STATUS_ALREADY_ENABLED:
+ return NanStatusCode::ALREADY_ENABLED;
+ case legacy_hal::NAN_STATUS_FOLLOWUP_QUEUE_FULL:
+ return NanStatusCode::FOLLOWUP_TX_QUEUE_FULL;
+ case legacy_hal::NAN_STATUS_UNSUPPORTED_CONCURRENCY_NAN_DISABLED:
+ return NanStatusCode::UNSUPPORTED_CONCURRENCY_NAN_DISABLED;
+ }
+ CHECK(false);
+}
+
+void convertToNanStatus(legacy_hal::NanStatusType type, const char* str, size_t max_len,
+ NanStatus* nanStatus) {
+ nanStatus->status = convertLegacyNanStatusTypeToAidl(type);
+ nanStatus->description = safeConvertChar(str, max_len);
+}
+
+bool convertAidlNanEnableRequestToLegacy(const NanEnableRequest& aidl_request1,
+ const NanConfigRequestSupplemental& aidl_request2,
+ legacy_hal::NanEnableRequest* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: null legacy_request";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->config_2dot4g_support = 1;
+ legacy_request->support_2dot4g_val =
+ aidl_request1.operateInBand[(size_t)NanBandIndex::NAN_BAND_24GHZ];
+ legacy_request->config_support_5g = 1;
+ legacy_request->support_5g_val =
+ aidl_request1.operateInBand[(size_t)NanBandIndex::NAN_BAND_5GHZ];
+ legacy_request->config_hop_count_limit = 1;
+ legacy_request->hop_count_limit_val = aidl_request1.hopCountMax;
+ legacy_request->master_pref = aidl_request1.configParams.masterPref;
+ legacy_request->discovery_indication_cfg = 0;
+ legacy_request->discovery_indication_cfg |=
+ aidl_request1.configParams.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
+ legacy_request->discovery_indication_cfg |=
+ aidl_request1.configParams.disableStartedClusterIndication ? 0x2 : 0x0;
+ legacy_request->discovery_indication_cfg |=
+ aidl_request1.configParams.disableJoinedClusterIndication ? 0x4 : 0x0;
+ legacy_request->config_sid_beacon = 1;
+ if (aidl_request1.configParams.numberOfPublishServiceIdsInBeacon < 0) {
+ LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: "
+ "numberOfPublishServiceIdsInBeacon < 0";
+ return false;
+ }
+ legacy_request->sid_beacon_val =
+ (aidl_request1.configParams.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
+ (aidl_request1.configParams.numberOfPublishServiceIdsInBeacon << 1);
+ legacy_request->config_subscribe_sid_beacon = 1;
+ if (aidl_request1.configParams.numberOfSubscribeServiceIdsInBeacon < 0) {
+ LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: "
+ "numberOfSubscribeServiceIdsInBeacon < 0";
+ return false;
+ }
+ legacy_request->subscribe_sid_beacon_val =
+ (aidl_request1.configParams.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
+ (aidl_request1.configParams.numberOfSubscribeServiceIdsInBeacon << 1);
+ legacy_request->config_rssi_window_size = 1;
+ legacy_request->rssi_window_size_val = aidl_request1.configParams.rssiWindowSize;
+ legacy_request->config_disc_mac_addr_randomization = 1;
+ legacy_request->disc_mac_addr_rand_interval_sec =
+ aidl_request1.configParams.macAddressRandomizationIntervalSec;
+ legacy_request->config_2dot4g_rssi_close = 1;
+ if (aidl_request1.configParams.bandSpecificConfig.size() != 3) {
+ LOG(ERROR) << "convertAidlNanEnableRequestToLegacy: "
+ "bandSpecificConfig.size() != 3";
+ return false;
+ }
+ legacy_request->rssi_close_2dot4g_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .rssiClose;
+ legacy_request->config_2dot4g_rssi_middle = 1;
+ legacy_request->rssi_middle_2dot4g_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .rssiMiddle;
+ legacy_request->config_2dot4g_rssi_proximity = 1;
+ legacy_request->rssi_proximity_2dot4g_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .rssiCloseProximity;
+ legacy_request->config_scan_params = 1;
+ legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .dwellTimeMs;
+ legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .scanPeriodSec;
+ legacy_request->config_dw.config_2dot4g_dw_band =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .validDiscoveryWindowIntervalVal;
+ legacy_request->config_dw.dw_2dot4g_interval_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .discoveryWindowIntervalVal;
+ legacy_request->config_5g_rssi_close = 1;
+ legacy_request->rssi_close_5g_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .rssiClose;
+ legacy_request->config_5g_rssi_middle = 1;
+ legacy_request->rssi_middle_5g_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .rssiMiddle;
+ legacy_request->config_5g_rssi_close_proximity = 1;
+ legacy_request->rssi_close_proximity_5g_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .rssiCloseProximity;
+ legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .dwellTimeMs;
+ legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .scanPeriodSec;
+ legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .dwellTimeMs;
+ legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .scanPeriodSec;
+ legacy_request->config_dw.config_5g_dw_band =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .validDiscoveryWindowIntervalVal;
+ legacy_request->config_dw.dw_5g_interval_val =
+ aidl_request1.configParams.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .discoveryWindowIntervalVal;
+ if (aidl_request1.debugConfigs.validClusterIdVals) {
+ legacy_request->cluster_low = aidl_request1.debugConfigs.clusterIdBottomRangeVal;
+ legacy_request->cluster_high = aidl_request1.debugConfigs.clusterIdTopRangeVal;
+ } else { // need 'else' since not configurable in legacy HAL
+ legacy_request->cluster_low = 0x0000;
+ legacy_request->cluster_high = 0xFFFF;
+ }
+ legacy_request->config_intf_addr = aidl_request1.debugConfigs.validIntfAddrVal;
+ memcpy(legacy_request->intf_addr_val, aidl_request1.debugConfigs.intfAddrVal.data(), 6);
+ legacy_request->config_oui = aidl_request1.debugConfigs.validOuiVal;
+ legacy_request->oui_val = aidl_request1.debugConfigs.ouiVal;
+ legacy_request->config_random_factor_force =
+ aidl_request1.debugConfigs.validRandomFactorForceVal;
+ legacy_request->random_factor_force_val = aidl_request1.debugConfigs.randomFactorForceVal;
+ legacy_request->config_hop_count_force = aidl_request1.debugConfigs.validHopCountForceVal;
+ legacy_request->hop_count_force_val = aidl_request1.debugConfigs.hopCountForceVal;
+ legacy_request->config_24g_channel = aidl_request1.debugConfigs.validDiscoveryChannelVal;
+ legacy_request->channel_24g_val =
+ aidl_request1.debugConfigs.discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
+ legacy_request->config_5g_channel = aidl_request1.debugConfigs.validDiscoveryChannelVal;
+ legacy_request->channel_5g_val =
+ aidl_request1.debugConfigs.discoveryChannelMhzVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
+ legacy_request->config_2dot4g_beacons = aidl_request1.debugConfigs.validUseBeaconsInBandVal;
+ legacy_request->beacon_2dot4g_val =
+ aidl_request1.debugConfigs.useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
+ legacy_request->config_5g_beacons = aidl_request1.debugConfigs.validUseBeaconsInBandVal;
+ legacy_request->beacon_5g_val =
+ aidl_request1.debugConfigs.useBeaconsInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
+ legacy_request->config_2dot4g_sdf = aidl_request1.debugConfigs.validUseSdfInBandVal;
+ legacy_request->sdf_2dot4g_val =
+ aidl_request1.debugConfigs.useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_24GHZ];
+ legacy_request->config_5g_sdf = aidl_request1.debugConfigs.validUseSdfInBandVal;
+ legacy_request->sdf_5g_val =
+ aidl_request1.debugConfigs.useSdfInBandVal[(size_t)NanBandIndex::NAN_BAND_5GHZ];
+
+ legacy_request->config_discovery_beacon_int = 1;
+ legacy_request->discovery_beacon_interval = aidl_request2.discoveryBeaconIntervalMs;
+ legacy_request->config_nss = 1;
+ legacy_request->nss = aidl_request2.numberOfSpatialStreamsInDiscovery;
+ legacy_request->config_dw_early_termination = 1;
+ legacy_request->enable_dw_termination = aidl_request2.enableDiscoveryWindowEarlyTermination;
+ legacy_request->config_enable_ranging = 1;
+ legacy_request->enable_ranging = aidl_request2.enableRanging;
+
+ legacy_request->config_enable_instant_mode = 1;
+ legacy_request->enable_instant_mode = aidl_request2.enableInstantCommunicationMode;
+ legacy_request->config_instant_mode_channel = 1;
+ legacy_request->instant_mode_channel = aidl_request2.instantModeChannel;
+
+ return true;
+}
+
+bool convertAidlNanConfigRequestToLegacy(const NanConfigRequest& aidl_request1,
+ const NanConfigRequestSupplemental& aidl_request2,
+ legacy_hal::NanConfigRequest* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanConfigRequestToLegacy: null legacy_request";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->master_pref = aidl_request1.masterPref;
+ legacy_request->discovery_indication_cfg = 0;
+ legacy_request->discovery_indication_cfg |=
+ aidl_request1.disableDiscoveryAddressChangeIndication ? 0x1 : 0x0;
+ legacy_request->discovery_indication_cfg |=
+ aidl_request1.disableStartedClusterIndication ? 0x2 : 0x0;
+ legacy_request->discovery_indication_cfg |=
+ aidl_request1.disableJoinedClusterIndication ? 0x4 : 0x0;
+ legacy_request->config_sid_beacon = 1;
+ if (aidl_request1.numberOfPublishServiceIdsInBeacon < 0) {
+ LOG(ERROR) << "convertAidlNanConfigRequestToLegacy: "
+ "numberOfPublishServiceIdsInBeacon < 0";
+ return false;
+ }
+ legacy_request->sid_beacon = (aidl_request1.includePublishServiceIdsInBeacon ? 0x1 : 0x0) |
+ (aidl_request1.numberOfPublishServiceIdsInBeacon << 1);
+ legacy_request->config_subscribe_sid_beacon = 1;
+ if (aidl_request1.numberOfSubscribeServiceIdsInBeacon < 0) {
+ LOG(ERROR) << "convertAidlNanConfigRequestToLegacy: "
+ "numberOfSubscribeServiceIdsInBeacon < 0";
+ return false;
+ }
+ legacy_request->subscribe_sid_beacon_val =
+ (aidl_request1.includeSubscribeServiceIdsInBeacon ? 0x1 : 0x0) |
+ (aidl_request1.numberOfSubscribeServiceIdsInBeacon << 1);
+ legacy_request->config_rssi_window_size = 1;
+ legacy_request->rssi_window_size_val = aidl_request1.rssiWindowSize;
+ legacy_request->config_disc_mac_addr_randomization = 1;
+ legacy_request->disc_mac_addr_rand_interval_sec =
+ aidl_request1.macAddressRandomizationIntervalSec;
+
+ legacy_request->config_scan_params = 1;
+ legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_24G_BAND] =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ].dwellTimeMs;
+ legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_24G_BAND] =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ].scanPeriodSec;
+ legacy_request->config_dw.config_2dot4g_dw_band =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .validDiscoveryWindowIntervalVal;
+ legacy_request->config_dw.dw_2dot4g_interval_val =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_24GHZ]
+ .discoveryWindowIntervalVal;
+
+ legacy_request->config_5g_rssi_close_proximity = 1;
+ legacy_request->rssi_close_proximity_5g_val =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .rssiCloseProximity;
+ legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].dwellTimeMs;
+ legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_LOW] =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].scanPeriodSec;
+ legacy_request->scan_params_val.dwell_time[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].dwellTimeMs;
+ legacy_request->scan_params_val.scan_period[legacy_hal::NAN_CHANNEL_5G_BAND_HIGH] =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ].scanPeriodSec;
+ legacy_request->config_dw.config_5g_dw_band =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .validDiscoveryWindowIntervalVal;
+ legacy_request->config_dw.dw_5g_interval_val =
+ aidl_request1.bandSpecificConfig[(size_t)NanBandIndex::NAN_BAND_5GHZ]
+ .discoveryWindowIntervalVal;
+
+ legacy_request->config_discovery_beacon_int = 1;
+ legacy_request->discovery_beacon_interval = aidl_request2.discoveryBeaconIntervalMs;
+ legacy_request->config_nss = 1;
+ legacy_request->nss = aidl_request2.numberOfSpatialStreamsInDiscovery;
+ legacy_request->config_dw_early_termination = 1;
+ legacy_request->enable_dw_termination = aidl_request2.enableDiscoveryWindowEarlyTermination;
+ legacy_request->config_enable_ranging = 1;
+ legacy_request->enable_ranging = aidl_request2.enableRanging;
+
+ legacy_request->config_enable_instant_mode = 1;
+ legacy_request->enable_instant_mode = aidl_request2.enableInstantCommunicationMode;
+ legacy_request->config_instant_mode_channel = 1;
+ legacy_request->instant_mode_channel = aidl_request2.instantModeChannel;
+
+ return true;
+}
+
+bool convertAidlNanPublishRequestToLegacy(const NanPublishRequest& aidl_request,
+ legacy_hal::NanPublishRequest* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: null legacy_request";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->publish_id = aidl_request.baseConfigs.sessionId;
+ legacy_request->ttl = aidl_request.baseConfigs.ttlSec;
+ legacy_request->period = aidl_request.baseConfigs.discoveryWindowPeriod;
+ legacy_request->publish_count = aidl_request.baseConfigs.discoveryCount;
+ legacy_request->service_name_len = aidl_request.baseConfigs.serviceName.size();
+ if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: service_name_len "
+ "too large";
+ return false;
+ }
+ memcpy(legacy_request->service_name, aidl_request.baseConfigs.serviceName.data(),
+ legacy_request->service_name_len);
+ legacy_request->publish_match_indicator =
+ convertAidlNanMatchAlgToLegacy(aidl_request.baseConfigs.discoveryMatchIndicator);
+ legacy_request->service_specific_info_len = aidl_request.baseConfigs.serviceSpecificInfo.size();
+ if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
+ "service_specific_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->service_specific_info,
+ aidl_request.baseConfigs.serviceSpecificInfo.data(),
+ legacy_request->service_specific_info_len);
+ legacy_request->sdea_service_specific_info_len =
+ aidl_request.baseConfigs.extendedServiceSpecificInfo.size();
+ if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
+ "sdea_service_specific_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->sdea_service_specific_info,
+ aidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
+ legacy_request->sdea_service_specific_info_len);
+ legacy_request->rx_match_filter_len = aidl_request.baseConfigs.rxMatchFilter.size();
+ if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
+ "rx_match_filter_len too large";
+ return false;
+ }
+ memcpy(legacy_request->rx_match_filter, aidl_request.baseConfigs.rxMatchFilter.data(),
+ legacy_request->rx_match_filter_len);
+ legacy_request->tx_match_filter_len = aidl_request.baseConfigs.txMatchFilter.size();
+ if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
+ "tx_match_filter_len too large";
+ return false;
+ }
+ memcpy(legacy_request->tx_match_filter, aidl_request.baseConfigs.txMatchFilter.data(),
+ legacy_request->tx_match_filter_len);
+ legacy_request->rssi_threshold_flag = aidl_request.baseConfigs.useRssiThreshold;
+ legacy_request->recv_indication_cfg = 0;
+ legacy_request->recv_indication_cfg |=
+ aidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1 : 0x0;
+ legacy_request->recv_indication_cfg |=
+ aidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
+ legacy_request->recv_indication_cfg |=
+ aidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
+ legacy_request->recv_indication_cfg |= 0x8;
+ legacy_request->cipher_type = (unsigned int)aidl_request.baseConfigs.securityConfig.cipherType;
+
+ legacy_request->scid_len = aidl_request.baseConfigs.securityConfig.scid.size();
+ if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: scid_len too large";
+ return false;
+ }
+ memcpy(legacy_request->scid, aidl_request.baseConfigs.securityConfig.scid.data(),
+ legacy_request->scid_len);
+
+ if (aidl_request.baseConfigs.securityConfig.securityType == NanDataPathSecurityType::PMK) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
+ legacy_request->key_info.body.pmk_info.pmk_len =
+ aidl_request.baseConfigs.securityConfig.pmk.size();
+ if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: invalid pmk_len";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.pmk_info.pmk,
+ aidl_request.baseConfigs.securityConfig.pmk.data(),
+ legacy_request->key_info.body.pmk_info.pmk_len);
+ }
+ if (aidl_request.baseConfigs.securityConfig.securityType ==
+ NanDataPathSecurityType::PASSPHRASE) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
+ legacy_request->key_info.body.passphrase_info.passphrase_len =
+ aidl_request.baseConfigs.securityConfig.passphrase.size();
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len <
+ NAN_SECURITY_MIN_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
+ "passphrase_len too small";
+ return false;
+ }
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len >
+ NAN_SECURITY_MAX_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanPublishRequestToLegacy: "
+ "passphrase_len too large";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
+ aidl_request.baseConfigs.securityConfig.passphrase.data(),
+ legacy_request->key_info.body.passphrase_info.passphrase_len);
+ }
+ legacy_request->sdea_params.security_cfg =
+ (aidl_request.baseConfigs.securityConfig.securityType != NanDataPathSecurityType::OPEN)
+ ? legacy_hal::NAN_DP_CONFIG_SECURITY
+ : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
+
+ legacy_request->sdea_params.ranging_state = aidl_request.baseConfigs.rangingRequired
+ ? legacy_hal::NAN_RANGING_ENABLE
+ : legacy_hal::NAN_RANGING_DISABLE;
+ legacy_request->ranging_cfg.ranging_interval_msec = aidl_request.baseConfigs.rangingIntervalMs;
+ legacy_request->ranging_cfg.config_ranging_indications =
+ static_cast<uint32_t>(aidl_request.baseConfigs.configRangingIndications);
+ legacy_request->ranging_cfg.distance_ingress_mm =
+ aidl_request.baseConfigs.distanceIngressCm * 10;
+ legacy_request->ranging_cfg.distance_egress_mm = aidl_request.baseConfigs.distanceEgressCm * 10;
+ legacy_request->ranging_auto_response = aidl_request.baseConfigs.rangingRequired
+ ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
+ : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
+ legacy_request->sdea_params.range_report = legacy_hal::NAN_DISABLE_RANGE_REPORT;
+ legacy_request->publish_type = convertAidlNanPublishTypeToLegacy(aidl_request.publishType);
+ legacy_request->tx_type = convertAidlNanTxTypeToLegacy(aidl_request.txType);
+ legacy_request->service_responder_policy = aidl_request.autoAcceptDataPathRequests
+ ? legacy_hal::NAN_SERVICE_ACCEPT_POLICY_ALL
+ : legacy_hal::NAN_SERVICE_ACCEPT_POLICY_NONE;
+
+ return true;
+}
+
+bool convertAidlNanSubscribeRequestToLegacy(const NanSubscribeRequest& aidl_request,
+ legacy_hal::NanSubscribeRequest* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: legacy_request is null";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->subscribe_id = aidl_request.baseConfigs.sessionId;
+ legacy_request->ttl = aidl_request.baseConfigs.ttlSec;
+ legacy_request->period = aidl_request.baseConfigs.discoveryWindowPeriod;
+ legacy_request->subscribe_count = aidl_request.baseConfigs.discoveryCount;
+ legacy_request->service_name_len = aidl_request.baseConfigs.serviceName.size();
+ if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "service_name_len too large";
+ return false;
+ }
+ memcpy(legacy_request->service_name, aidl_request.baseConfigs.serviceName.data(),
+ legacy_request->service_name_len);
+ legacy_request->subscribe_match_indicator =
+ convertAidlNanMatchAlgToLegacy(aidl_request.baseConfigs.discoveryMatchIndicator);
+ legacy_request->service_specific_info_len = aidl_request.baseConfigs.serviceSpecificInfo.size();
+ if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "service_specific_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->service_specific_info,
+ aidl_request.baseConfigs.serviceSpecificInfo.data(),
+ legacy_request->service_specific_info_len);
+ legacy_request->sdea_service_specific_info_len =
+ aidl_request.baseConfigs.extendedServiceSpecificInfo.size();
+ if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "sdea_service_specific_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->sdea_service_specific_info,
+ aidl_request.baseConfigs.extendedServiceSpecificInfo.data(),
+ legacy_request->sdea_service_specific_info_len);
+ legacy_request->rx_match_filter_len = aidl_request.baseConfigs.rxMatchFilter.size();
+ if (legacy_request->rx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "rx_match_filter_len too large";
+ return false;
+ }
+ memcpy(legacy_request->rx_match_filter, aidl_request.baseConfigs.rxMatchFilter.data(),
+ legacy_request->rx_match_filter_len);
+ legacy_request->tx_match_filter_len = aidl_request.baseConfigs.txMatchFilter.size();
+ if (legacy_request->tx_match_filter_len > NAN_MAX_MATCH_FILTER_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "tx_match_filter_len too large";
+ return false;
+ }
+ memcpy(legacy_request->tx_match_filter, aidl_request.baseConfigs.txMatchFilter.data(),
+ legacy_request->tx_match_filter_len);
+ legacy_request->rssi_threshold_flag = aidl_request.baseConfigs.useRssiThreshold;
+ legacy_request->recv_indication_cfg = 0;
+ legacy_request->recv_indication_cfg |=
+ aidl_request.baseConfigs.disableDiscoveryTerminationIndication ? 0x1 : 0x0;
+ legacy_request->recv_indication_cfg |=
+ aidl_request.baseConfigs.disableMatchExpirationIndication ? 0x2 : 0x0;
+ legacy_request->recv_indication_cfg |=
+ aidl_request.baseConfigs.disableFollowupReceivedIndication ? 0x4 : 0x0;
+ legacy_request->cipher_type = (unsigned int)aidl_request.baseConfigs.securityConfig.cipherType;
+ if (aidl_request.baseConfigs.securityConfig.securityType == NanDataPathSecurityType::PMK) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
+ legacy_request->key_info.body.pmk_info.pmk_len =
+ aidl_request.baseConfigs.securityConfig.pmk.size();
+ if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: invalid pmk_len";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.pmk_info.pmk,
+ aidl_request.baseConfigs.securityConfig.pmk.data(),
+ legacy_request->key_info.body.pmk_info.pmk_len);
+ }
+ if (aidl_request.baseConfigs.securityConfig.securityType ==
+ NanDataPathSecurityType::PASSPHRASE) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
+ legacy_request->key_info.body.passphrase_info.passphrase_len =
+ aidl_request.baseConfigs.securityConfig.passphrase.size();
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len <
+ NAN_SECURITY_MIN_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "passphrase_len too small";
+ return false;
+ }
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len >
+ NAN_SECURITY_MAX_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "passphrase_len too large";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
+ aidl_request.baseConfigs.securityConfig.passphrase.data(),
+ legacy_request->key_info.body.passphrase_info.passphrase_len);
+ }
+ legacy_request->sdea_params.security_cfg =
+ (aidl_request.baseConfigs.securityConfig.securityType != NanDataPathSecurityType::OPEN)
+ ? legacy_hal::NAN_DP_CONFIG_SECURITY
+ : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
+ legacy_request->sdea_params.ranging_state = aidl_request.baseConfigs.rangingRequired
+ ? legacy_hal::NAN_RANGING_ENABLE
+ : legacy_hal::NAN_RANGING_DISABLE;
+ legacy_request->ranging_cfg.ranging_interval_msec = aidl_request.baseConfigs.rangingIntervalMs;
+ legacy_request->ranging_cfg.config_ranging_indications =
+ static_cast<uint32_t>(aidl_request.baseConfigs.configRangingIndications);
+ legacy_request->ranging_cfg.distance_ingress_mm =
+ aidl_request.baseConfigs.distanceIngressCm * 10;
+ legacy_request->ranging_cfg.distance_egress_mm = aidl_request.baseConfigs.distanceEgressCm * 10;
+ legacy_request->ranging_auto_response = aidl_request.baseConfigs.rangingRequired
+ ? legacy_hal::NAN_RANGING_AUTO_RESPONSE_ENABLE
+ : legacy_hal::NAN_RANGING_AUTO_RESPONSE_DISABLE;
+ legacy_request->sdea_params.range_report = legacy_hal::NAN_DISABLE_RANGE_REPORT;
+ legacy_request->subscribe_type =
+ convertAidlNanSubscribeTypeToLegacy(aidl_request.subscribeType);
+ legacy_request->serviceResponseFilter = convertAidlNanSrfTypeToLegacy(aidl_request.srfType);
+ legacy_request->serviceResponseInclude = aidl_request.srfRespondIfInAddressSet
+ ? legacy_hal::NAN_SRF_INCLUDE_RESPOND
+ : legacy_hal::NAN_SRF_INCLUDE_DO_NOT_RESPOND;
+ legacy_request->useServiceResponseFilter =
+ aidl_request.shouldUseSrf ? legacy_hal::NAN_USE_SRF : legacy_hal::NAN_DO_NOT_USE_SRF;
+ legacy_request->ssiRequiredForMatchIndication =
+ aidl_request.isSsiRequiredForMatch ? legacy_hal::NAN_SSI_REQUIRED_IN_MATCH_IND
+ : legacy_hal::NAN_SSI_NOT_REQUIRED_IN_MATCH_IND;
+ legacy_request->num_intf_addr_present = aidl_request.intfAddr.size();
+ if (legacy_request->num_intf_addr_present > NAN_MAX_SUBSCRIBE_MAX_ADDRESS) {
+ LOG(ERROR) << "convertAidlNanSubscribeRequestToLegacy: "
+ "num_intf_addr_present - too many";
+ return false;
+ }
+ for (int i = 0; i < legacy_request->num_intf_addr_present; i++) {
+ memcpy(legacy_request->intf_addr[i], aidl_request.intfAddr[i].data.data(), 6);
+ }
+
+ return true;
+}
+
+bool convertAidlNanTransmitFollowupRequestToLegacy(
+ const NanTransmitFollowupRequest& aidl_request,
+ legacy_hal::NanTransmitFollowupRequest* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanTransmitFollowupRequestToLegacy: "
+ "legacy_request is null";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->publish_subscribe_id = aidl_request.discoverySessionId;
+ legacy_request->requestor_instance_id = aidl_request.peerId;
+ memcpy(legacy_request->addr, aidl_request.addr.data(), 6);
+ legacy_request->priority = aidl_request.isHighPriority ? legacy_hal::NAN_TX_PRIORITY_HIGH
+ : legacy_hal::NAN_TX_PRIORITY_NORMAL;
+ legacy_request->dw_or_faw = aidl_request.shouldUseDiscoveryWindow
+ ? legacy_hal::NAN_TRANSMIT_IN_DW
+ : legacy_hal::NAN_TRANSMIT_IN_FAW;
+ legacy_request->service_specific_info_len = aidl_request.serviceSpecificInfo.size();
+ if (legacy_request->service_specific_info_len > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanTransmitFollowupRequestToLegacy: "
+ "service_specific_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->service_specific_info, aidl_request.serviceSpecificInfo.data(),
+ legacy_request->service_specific_info_len);
+ legacy_request->sdea_service_specific_info_len =
+ aidl_request.extendedServiceSpecificInfo.size();
+ if (legacy_request->sdea_service_specific_info_len > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanTransmitFollowupRequestToLegacy: "
+ "sdea_service_specific_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->sdea_service_specific_info,
+ aidl_request.extendedServiceSpecificInfo.data(),
+ legacy_request->sdea_service_specific_info_len);
+ legacy_request->recv_indication_cfg = aidl_request.disableFollowupResultIndication ? 0x1 : 0x0;
+
+ return true;
+}
+
+bool convertAidlNanDataPathInitiatorRequestToLegacy(
+ const NanInitiateDataPathRequest& aidl_request,
+ legacy_hal::NanDataPathInitiatorRequest* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "legacy_request is null";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->requestor_instance_id = aidl_request.peerId;
+ memcpy(legacy_request->peer_disc_mac_addr, aidl_request.peerDiscMacAddr.data(), 6);
+ legacy_request->channel_request_type =
+ convertAidlNanDataPathChannelCfgToLegacy(aidl_request.channelRequestType);
+ legacy_request->channel = aidl_request.channel;
+ if (strnlen(aidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "ifaceName too long";
+ return false;
+ }
+ strlcpy(legacy_request->ndp_iface, aidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
+ legacy_request->ndp_cfg.security_cfg =
+ (aidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
+ ? legacy_hal::NAN_DP_CONFIG_SECURITY
+ : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
+ legacy_request->app_info.ndp_app_info_len = aidl_request.appInfo.size();
+ if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "ndp_app_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->app_info.ndp_app_info, aidl_request.appInfo.data(),
+ legacy_request->app_info.ndp_app_info_len);
+ legacy_request->cipher_type = (unsigned int)aidl_request.securityConfig.cipherType;
+ if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
+ legacy_request->key_info.body.pmk_info.pmk_len = aidl_request.securityConfig.pmk.size();
+ if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "invalid pmk_len";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.pmk_info.pmk, aidl_request.securityConfig.pmk.data(),
+ legacy_request->key_info.body.pmk_info.pmk_len);
+ }
+ if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
+ legacy_request->key_info.body.passphrase_info.passphrase_len =
+ aidl_request.securityConfig.passphrase.size();
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len <
+ NAN_SECURITY_MIN_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "passphrase_len too small";
+ return false;
+ }
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len >
+ NAN_SECURITY_MAX_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "passphrase_len too large";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
+ aidl_request.securityConfig.passphrase.data(),
+ legacy_request->key_info.body.passphrase_info.passphrase_len);
+ }
+ legacy_request->service_name_len = aidl_request.serviceNameOutOfBand.size();
+ if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: "
+ "service_name_len too large";
+ return false;
+ }
+ memcpy(legacy_request->service_name, aidl_request.serviceNameOutOfBand.data(),
+ legacy_request->service_name_len);
+ legacy_request->scid_len = aidl_request.securityConfig.scid.size();
+ if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathInitiatorRequestToLegacy: scid_len too large";
+ return false;
+ }
+ memcpy(legacy_request->scid, aidl_request.securityConfig.scid.data(), legacy_request->scid_len);
+
+ return true;
+}
+
+bool convertAidlNanDataPathIndicationResponseToLegacy(
+ const NanRespondToDataPathIndicationRequest& aidl_request,
+ legacy_hal::NanDataPathIndicationResponse* legacy_request) {
+ if (!legacy_request) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "legacy_request is null";
+ return false;
+ }
+ *legacy_request = {};
+
+ legacy_request->rsp_code = aidl_request.acceptRequest ? legacy_hal::NAN_DP_REQUEST_ACCEPT
+ : legacy_hal::NAN_DP_REQUEST_REJECT;
+ legacy_request->ndp_instance_id = aidl_request.ndpInstanceId;
+ if (strnlen(aidl_request.ifaceName.c_str(), IFNAMSIZ + 1) == IFNAMSIZ + 1) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "ifaceName too long";
+ return false;
+ }
+ strlcpy(legacy_request->ndp_iface, aidl_request.ifaceName.c_str(), IFNAMSIZ + 1);
+ legacy_request->ndp_cfg.security_cfg =
+ (aidl_request.securityConfig.securityType != NanDataPathSecurityType::OPEN)
+ ? legacy_hal::NAN_DP_CONFIG_SECURITY
+ : legacy_hal::NAN_DP_CONFIG_NO_SECURITY;
+ legacy_request->app_info.ndp_app_info_len = aidl_request.appInfo.size();
+ if (legacy_request->app_info.ndp_app_info_len > NAN_DP_MAX_APP_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "ndp_app_info_len too large";
+ return false;
+ }
+ memcpy(legacy_request->app_info.ndp_app_info, aidl_request.appInfo.data(),
+ legacy_request->app_info.ndp_app_info_len);
+ legacy_request->cipher_type = (unsigned int)aidl_request.securityConfig.cipherType;
+ if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PMK) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PMK;
+ legacy_request->key_info.body.pmk_info.pmk_len = aidl_request.securityConfig.pmk.size();
+ if (legacy_request->key_info.body.pmk_info.pmk_len != NAN_PMK_INFO_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "invalid pmk_len";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.pmk_info.pmk, aidl_request.securityConfig.pmk.data(),
+ legacy_request->key_info.body.pmk_info.pmk_len);
+ }
+ if (aidl_request.securityConfig.securityType == NanDataPathSecurityType::PASSPHRASE) {
+ legacy_request->key_info.key_type = legacy_hal::NAN_SECURITY_KEY_INPUT_PASSPHRASE;
+ legacy_request->key_info.body.passphrase_info.passphrase_len =
+ aidl_request.securityConfig.passphrase.size();
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len <
+ NAN_SECURITY_MIN_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "passphrase_len too small";
+ return false;
+ }
+ if (legacy_request->key_info.body.passphrase_info.passphrase_len >
+ NAN_SECURITY_MAX_PASSPHRASE_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "passphrase_len too large";
+ return false;
+ }
+ memcpy(legacy_request->key_info.body.passphrase_info.passphrase,
+ aidl_request.securityConfig.passphrase.data(),
+ legacy_request->key_info.body.passphrase_info.passphrase_len);
+ }
+ legacy_request->service_name_len = aidl_request.serviceNameOutOfBand.size();
+ if (legacy_request->service_name_len > NAN_MAX_SERVICE_NAME_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: "
+ "service_name_len too large";
+ return false;
+ }
+ memcpy(legacy_request->service_name, aidl_request.serviceNameOutOfBand.data(),
+ legacy_request->service_name_len);
+ legacy_request->scid_len = aidl_request.securityConfig.scid.size();
+ if (legacy_request->scid_len > NAN_MAX_SCID_BUF_LEN) {
+ LOG(ERROR) << "convertAidlNanDataPathIndicationResponseToLegacy: scid_len too large";
+ return false;
+ }
+ memcpy(legacy_request->scid, aidl_request.securityConfig.scid.data(), legacy_request->scid_len);
+
+ return true;
+}
+
+bool convertLegacyNanResponseHeaderToAidl(const legacy_hal::NanResponseMsg& legacy_response,
+ NanStatus* nanStatus) {
+ if (!nanStatus) {
+ LOG(ERROR) << "convertLegacyNanResponseHeaderToAidl: nanStatus is null";
+ return false;
+ }
+ *nanStatus = {};
+
+ convertToNanStatus(legacy_response.status, legacy_response.nan_error,
+ sizeof(legacy_response.nan_error), nanStatus);
+ return true;
+}
+
+bool convertLegacyNanCapabilitiesResponseToAidl(const legacy_hal::NanCapabilities& legacy_response,
+ NanCapabilities* aidl_response) {
+ if (!aidl_response) {
+ LOG(ERROR) << "convertLegacyNanCapabilitiesResponseToAidl: "
+ "aidl_response is null";
+ return false;
+ }
+ *aidl_response = {};
+
+ aidl_response->maxConcurrentClusters = legacy_response.max_concurrent_nan_clusters;
+ aidl_response->maxPublishes = legacy_response.max_publishes;
+ aidl_response->maxSubscribes = legacy_response.max_subscribes;
+ aidl_response->maxServiceNameLen = legacy_response.max_service_name_len;
+ aidl_response->maxMatchFilterLen = legacy_response.max_match_filter_len;
+ aidl_response->maxTotalMatchFilterLen = legacy_response.max_total_match_filter_len;
+ aidl_response->maxServiceSpecificInfoLen = legacy_response.max_service_specific_info_len;
+ aidl_response->maxExtendedServiceSpecificInfoLen =
+ legacy_response.max_sdea_service_specific_info_len;
+ aidl_response->maxNdiInterfaces = legacy_response.max_ndi_interfaces;
+ aidl_response->maxNdpSessions = legacy_response.max_ndp_sessions;
+ aidl_response->maxAppInfoLen = legacy_response.max_app_info_len;
+ aidl_response->maxQueuedTransmitFollowupMsgs =
+ legacy_response.max_queued_transmit_followup_msgs;
+ aidl_response->maxSubscribeInterfaceAddresses = legacy_response.max_subscribe_address;
+ aidl_response->supportedCipherSuites =
+ static_cast<NanCipherSuiteType>(legacy_response.cipher_suites_supported);
+ aidl_response->instantCommunicationModeSupportFlag = legacy_response.is_instant_mode_supported;
+
+ return true;
+}
+
+bool convertLegacyNanMatchIndToAidl(const legacy_hal::NanMatchInd& legacy_ind,
+ NanMatchInd* aidl_ind) {
+ if (!aidl_ind) {
+ LOG(ERROR) << "convertLegacyNanMatchIndToAidl: aidl_ind is null";
+ return false;
+ }
+ *aidl_ind = {};
+
+ aidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
+ aidl_ind->peerId = legacy_ind.requestor_instance_id;
+ aidl_ind->addr = std::array<uint8_t, 6>();
+ std::copy(legacy_ind.addr, legacy_ind.addr + 6, std::begin(aidl_ind->addr));
+ aidl_ind->serviceSpecificInfo = std::vector<uint8_t>(
+ legacy_ind.service_specific_info,
+ legacy_ind.service_specific_info + legacy_ind.service_specific_info_len);
+ aidl_ind->extendedServiceSpecificInfo = std::vector<uint8_t>(
+ legacy_ind.sdea_service_specific_info,
+ legacy_ind.sdea_service_specific_info + legacy_ind.sdea_service_specific_info_len);
+ aidl_ind->matchFilter =
+ std::vector<uint8_t>(legacy_ind.sdf_match_filter,
+ legacy_ind.sdf_match_filter + legacy_ind.sdf_match_filter_len);
+ aidl_ind->matchOccurredInBeaconFlag = legacy_ind.match_occured_flag == 1; // NOTYPO
+ aidl_ind->outOfResourceFlag = legacy_ind.out_of_resource_flag == 1;
+ aidl_ind->rssiValue = legacy_ind.rssi_value;
+ aidl_ind->peerCipherType = (NanCipherSuiteType)legacy_ind.peer_cipher_type;
+ aidl_ind->peerRequiresSecurityEnabledInNdp =
+ legacy_ind.peer_sdea_params.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
+ aidl_ind->peerRequiresRanging =
+ legacy_ind.peer_sdea_params.ranging_state == legacy_hal::NAN_RANGING_ENABLE;
+ aidl_ind->rangingMeasurementInMm = legacy_ind.range_info.range_measurement_mm;
+ aidl_ind->rangingIndicationType =
+ static_cast<NanRangingIndication>(legacy_ind.range_info.ranging_event_type);
+ aidl_ind->scid = std::vector<uint8_t>(legacy_ind.scid, legacy_ind.scid + legacy_ind.scid_len);
+ return true;
+}
+
+bool convertLegacyNanFollowupIndToAidl(const legacy_hal::NanFollowupInd& legacy_ind,
+ NanFollowupReceivedInd* aidl_ind) {
+ if (!aidl_ind) {
+ LOG(ERROR) << "convertLegacyNanFollowupIndToAidl: aidl_ind is null";
+ return false;
+ }
+ *aidl_ind = {};
+
+ aidl_ind->discoverySessionId = legacy_ind.publish_subscribe_id;
+ aidl_ind->peerId = legacy_ind.requestor_instance_id;
+ aidl_ind->addr = std::array<uint8_t, 6>();
+ std::copy(legacy_ind.addr, legacy_ind.addr + 6, std::begin(aidl_ind->addr));
+ aidl_ind->receivedInFaw = legacy_ind.dw_or_faw == 1;
+ aidl_ind->serviceSpecificInfo = std::vector<uint8_t>(
+ legacy_ind.service_specific_info,
+ legacy_ind.service_specific_info + legacy_ind.service_specific_info_len);
+ aidl_ind->extendedServiceSpecificInfo = std::vector<uint8_t>(
+ legacy_ind.sdea_service_specific_info,
+ legacy_ind.sdea_service_specific_info + legacy_ind.sdea_service_specific_info_len);
+
+ return true;
+}
+
+bool convertLegacyNanDataPathRequestIndToAidl(const legacy_hal::NanDataPathRequestInd& legacy_ind,
+ NanDataPathRequestInd* aidl_ind) {
+ if (!aidl_ind) {
+ LOG(ERROR) << "convertLegacyNanDataPathRequestIndToAidl: aidl_ind is null";
+ return false;
+ }
+ *aidl_ind = {};
+
+ aidl_ind->discoverySessionId = legacy_ind.service_instance_id;
+ aidl_ind->peerDiscMacAddr = std::array<uint8_t, 6>();
+ std::copy(legacy_ind.peer_disc_mac_addr, legacy_ind.peer_disc_mac_addr + 6,
+ std::begin(aidl_ind->peerDiscMacAddr));
+ aidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
+ aidl_ind->securityRequired =
+ legacy_ind.ndp_cfg.security_cfg == legacy_hal::NAN_DP_CONFIG_SECURITY;
+ aidl_ind->appInfo = std::vector<uint8_t>(
+ legacy_ind.app_info.ndp_app_info,
+ legacy_ind.app_info.ndp_app_info + legacy_ind.app_info.ndp_app_info_len);
+
+ return true;
+}
+
+bool convertLegacyNdpChannelInfoToAidl(const legacy_hal::NanChannelInfo& legacy_struct,
+ NanDataPathChannelInfo* aidl_struct) {
+ if (!aidl_struct) {
+ LOG(ERROR) << "convertLegacyNdpChannelInfoToAidl: aidl_struct is null";
+ return false;
+ }
+ *aidl_struct = {};
+
+ aidl_struct->channelFreq = legacy_struct.channel;
+ aidl_struct->channelBandwidth = convertLegacyWifiChannelWidthToAidl(
+ (legacy_hal::wifi_channel_width)legacy_struct.bandwidth);
+ aidl_struct->numSpatialStreams = legacy_struct.nss;
+
+ return true;
+}
+
+bool convertLegacyNanDataPathConfirmIndToAidl(const legacy_hal::NanDataPathConfirmInd& legacy_ind,
+ NanDataPathConfirmInd* aidl_ind) {
+ if (!aidl_ind) {
+ LOG(ERROR) << "convertLegacyNanDataPathConfirmIndToAidl: aidl_ind is null";
+ return false;
+ }
+ *aidl_ind = {};
+
+ aidl_ind->ndpInstanceId = legacy_ind.ndp_instance_id;
+ aidl_ind->dataPathSetupSuccess = legacy_ind.rsp_code == legacy_hal::NAN_DP_REQUEST_ACCEPT;
+ aidl_ind->peerNdiMacAddr = std::array<uint8_t, 6>();
+ std::copy(legacy_ind.peer_ndi_mac_addr, legacy_ind.peer_ndi_mac_addr + 6,
+ std::begin(aidl_ind->peerNdiMacAddr));
+ aidl_ind->appInfo = std::vector<uint8_t>(
+ legacy_ind.app_info.ndp_app_info,
+ legacy_ind.app_info.ndp_app_info + legacy_ind.app_info.ndp_app_info_len);
+ aidl_ind->status.status = convertLegacyNanStatusTypeToAidl(legacy_ind.reason_code);
+ aidl_ind->status.description = "";
+
+ std::vector<NanDataPathChannelInfo> channelInfo;
+ for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
+ NanDataPathChannelInfo aidl_struct;
+ if (!convertLegacyNdpChannelInfoToAidl(legacy_ind.channel_info[i], &aidl_struct)) {
+ return false;
+ }
+ channelInfo.push_back(aidl_struct);
+ }
+ aidl_ind->channelInfo = channelInfo;
+
+ return true;
+}
+
+bool convertLegacyNanDataPathScheduleUpdateIndToAidl(
+ const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
+ NanDataPathScheduleUpdateInd* aidl_ind) {
+ if (!aidl_ind) {
+ LOG(ERROR) << "convertLegacyNanDataPathScheduleUpdateIndToAidl: "
+ "aidl_ind is null";
+ return false;
+ }
+ *aidl_ind = {};
+
+ aidl_ind->peerDiscoveryAddress = std::array<uint8_t, 6>();
+ std::copy(legacy_ind.peer_mac_addr, legacy_ind.peer_mac_addr + 6,
+ std::begin(aidl_ind->peerDiscoveryAddress));
+ std::vector<NanDataPathChannelInfo> channelInfo;
+ for (unsigned int i = 0; i < legacy_ind.num_channels; ++i) {
+ NanDataPathChannelInfo aidl_struct;
+ if (!convertLegacyNdpChannelInfoToAidl(legacy_ind.channel_info[i], &aidl_struct)) {
+ return false;
+ }
+ channelInfo.push_back(aidl_struct);
+ }
+ aidl_ind->channelInfo = channelInfo;
+ std::vector<uint32_t> ndpInstanceIds;
+ for (unsigned int i = 0; i < legacy_ind.num_ndp_instances; ++i) {
+ ndpInstanceIds.push_back(legacy_ind.ndp_instance_id[i]);
+ }
+ aidl_ind->ndpInstanceIds = uintToIntVec(ndpInstanceIds);
+
+ return true;
+}
+
+legacy_hal::wifi_rtt_type convertAidlRttTypeToLegacy(RttType type) {
+ switch (type) {
+ case RttType::ONE_SIDED:
+ return legacy_hal::RTT_TYPE_1_SIDED;
+ case RttType::TWO_SIDED:
+ return legacy_hal::RTT_TYPE_2_SIDED;
+ };
+ CHECK(false);
+}
+
+RttType convertLegacyRttTypeToAidl(legacy_hal::wifi_rtt_type type) {
+ switch (type) {
+ case legacy_hal::RTT_TYPE_1_SIDED:
+ return RttType::ONE_SIDED;
+ case legacy_hal::RTT_TYPE_2_SIDED:
+ return RttType::TWO_SIDED;
+ };
+ CHECK(false) << "Unknown legacy type: " << type;
+}
+
+legacy_hal::rtt_peer_type convertAidlRttPeerTypeToLegacy(RttPeerType type) {
+ switch (type) {
+ case RttPeerType::AP:
+ return legacy_hal::RTT_PEER_AP;
+ case RttPeerType::STA:
+ return legacy_hal::RTT_PEER_STA;
+ case RttPeerType::P2P_GO:
+ return legacy_hal::RTT_PEER_P2P_GO;
+ case RttPeerType::P2P_CLIENT:
+ return legacy_hal::RTT_PEER_P2P_CLIENT;
+ case RttPeerType::NAN_TYPE:
+ return legacy_hal::RTT_PEER_NAN;
+ };
+ CHECK(false);
+}
+
+legacy_hal::wifi_channel_width convertAidlWifiChannelWidthToLegacy(WifiChannelWidthInMhz type) {
+ switch (type) {
+ case WifiChannelWidthInMhz::WIDTH_20:
+ return legacy_hal::WIFI_CHAN_WIDTH_20;
+ case WifiChannelWidthInMhz::WIDTH_40:
+ return legacy_hal::WIFI_CHAN_WIDTH_40;
+ case WifiChannelWidthInMhz::WIDTH_80:
+ return legacy_hal::WIFI_CHAN_WIDTH_80;
+ case WifiChannelWidthInMhz::WIDTH_160:
+ return legacy_hal::WIFI_CHAN_WIDTH_160;
+ case WifiChannelWidthInMhz::WIDTH_80P80:
+ return legacy_hal::WIFI_CHAN_WIDTH_80P80;
+ case WifiChannelWidthInMhz::WIDTH_5:
+ return legacy_hal::WIFI_CHAN_WIDTH_5;
+ case WifiChannelWidthInMhz::WIDTH_10:
+ return legacy_hal::WIFI_CHAN_WIDTH_10;
+ case WifiChannelWidthInMhz::WIDTH_320:
+ return legacy_hal::WIFI_CHAN_WIDTH_320;
+ case WifiChannelWidthInMhz::WIDTH_INVALID:
+ return legacy_hal::WIFI_CHAN_WIDTH_INVALID;
+ };
+ CHECK(false);
+}
+
+WifiChannelWidthInMhz convertLegacyWifiChannelWidthToAidl(legacy_hal::wifi_channel_width type) {
+ switch (type) {
+ case legacy_hal::WIFI_CHAN_WIDTH_20:
+ return WifiChannelWidthInMhz::WIDTH_20;
+ case legacy_hal::WIFI_CHAN_WIDTH_40:
+ return WifiChannelWidthInMhz::WIDTH_40;
+ case legacy_hal::WIFI_CHAN_WIDTH_80:
+ return WifiChannelWidthInMhz::WIDTH_80;
+ case legacy_hal::WIFI_CHAN_WIDTH_160:
+ return WifiChannelWidthInMhz::WIDTH_160;
+ case legacy_hal::WIFI_CHAN_WIDTH_80P80:
+ return WifiChannelWidthInMhz::WIDTH_80P80;
+ case legacy_hal::WIFI_CHAN_WIDTH_5:
+ return WifiChannelWidthInMhz::WIDTH_5;
+ case legacy_hal::WIFI_CHAN_WIDTH_10:
+ return WifiChannelWidthInMhz::WIDTH_10;
+ case legacy_hal::WIFI_CHAN_WIDTH_320:
+ return WifiChannelWidthInMhz::WIDTH_320;
+ default:
+ return WifiChannelWidthInMhz::WIDTH_INVALID;
+ };
+}
+
+legacy_hal::wifi_rtt_preamble convertAidlRttPreambleToLegacy(RttPreamble type) {
+ switch (type) {
+ case RttPreamble::LEGACY:
+ return legacy_hal::WIFI_RTT_PREAMBLE_LEGACY;
+ case RttPreamble::HT:
+ return legacy_hal::WIFI_RTT_PREAMBLE_HT;
+ case RttPreamble::VHT:
+ return legacy_hal::WIFI_RTT_PREAMBLE_VHT;
+ case RttPreamble::HE:
+ return legacy_hal::WIFI_RTT_PREAMBLE_HE;
+ case RttPreamble::EHT:
+ return legacy_hal::WIFI_RTT_PREAMBLE_EHT;
+ };
+ CHECK(false);
+}
+
+RttPreamble convertLegacyRttPreambleToAidl(legacy_hal::wifi_rtt_preamble type) {
+ switch (type) {
+ case legacy_hal::WIFI_RTT_PREAMBLE_LEGACY:
+ return RttPreamble::LEGACY;
+ case legacy_hal::WIFI_RTT_PREAMBLE_HT:
+ return RttPreamble::HT;
+ case legacy_hal::WIFI_RTT_PREAMBLE_VHT:
+ return RttPreamble::VHT;
+ case legacy_hal::WIFI_RTT_PREAMBLE_HE:
+ return RttPreamble::HE;
+ case legacy_hal::WIFI_RTT_PREAMBLE_EHT:
+ return RttPreamble::EHT;
+ };
+ CHECK(false) << "Unknown legacy type: " << type;
+}
+
+legacy_hal::wifi_rtt_bw convertAidlRttBwToLegacy(RttBw type) {
+ switch (type) {
+ case RttBw::BW_5MHZ:
+ return legacy_hal::WIFI_RTT_BW_5;
+ case RttBw::BW_10MHZ:
+ return legacy_hal::WIFI_RTT_BW_10;
+ case RttBw::BW_20MHZ:
+ return legacy_hal::WIFI_RTT_BW_20;
+ case RttBw::BW_40MHZ:
+ return legacy_hal::WIFI_RTT_BW_40;
+ case RttBw::BW_80MHZ:
+ return legacy_hal::WIFI_RTT_BW_80;
+ case RttBw::BW_160MHZ:
+ return legacy_hal::WIFI_RTT_BW_160;
+ case RttBw::BW_320MHZ:
+ return legacy_hal::WIFI_RTT_BW_320;
+ };
+ CHECK(false);
+}
+
+RttBw convertLegacyRttBwToAidl(legacy_hal::wifi_rtt_bw type) {
+ switch (type) {
+ case legacy_hal::WIFI_RTT_BW_5:
+ return RttBw::BW_5MHZ;
+ case legacy_hal::WIFI_RTT_BW_10:
+ return RttBw::BW_10MHZ;
+ case legacy_hal::WIFI_RTT_BW_20:
+ return RttBw::BW_20MHZ;
+ case legacy_hal::WIFI_RTT_BW_40:
+ return RttBw::BW_40MHZ;
+ case legacy_hal::WIFI_RTT_BW_80:
+ return RttBw::BW_80MHZ;
+ case legacy_hal::WIFI_RTT_BW_160:
+ return RttBw::BW_160MHZ;
+ case legacy_hal::WIFI_RTT_BW_320:
+ return RttBw::BW_320MHZ;
+ };
+ CHECK(false) << "Unknown legacy type: " << type;
+}
+
+legacy_hal::wifi_motion_pattern convertAidlRttMotionPatternToLegacy(RttMotionPattern type) {
+ switch (type) {
+ case RttMotionPattern::NOT_EXPECTED:
+ return legacy_hal::WIFI_MOTION_NOT_EXPECTED;
+ case RttMotionPattern::EXPECTED:
+ return legacy_hal::WIFI_MOTION_EXPECTED;
+ case RttMotionPattern::UNKNOWN:
+ return legacy_hal::WIFI_MOTION_UNKNOWN;
+ };
+ CHECK(false);
+}
+
+WifiRatePreamble convertLegacyWifiRatePreambleToAidl(uint8_t preamble) {
+ switch (preamble) {
+ case 0:
+ return WifiRatePreamble::OFDM;
+ case 1:
+ return WifiRatePreamble::CCK;
+ case 2:
+ return WifiRatePreamble::HT;
+ case 3:
+ return WifiRatePreamble::VHT;
+ case 4:
+ return WifiRatePreamble::HE;
+ case 5:
+ return WifiRatePreamble::EHT;
+ default:
+ return WifiRatePreamble::RESERVED;
+ };
+ CHECK(false) << "Unknown legacy preamble: " << preamble;
+}
+
+WifiRateNss convertLegacyWifiRateNssToAidl(uint8_t nss) {
+ switch (nss) {
+ case 0:
+ return WifiRateNss::NSS_1x1;
+ case 1:
+ return WifiRateNss::NSS_2x2;
+ case 2:
+ return WifiRateNss::NSS_3x3;
+ case 3:
+ return WifiRateNss::NSS_4x4;
+ };
+ CHECK(false) << "Unknown legacy nss: " << nss;
+ return {};
+}
+
+RttStatus convertLegacyRttStatusToAidl(legacy_hal::wifi_rtt_status status) {
+ switch (status) {
+ case legacy_hal::RTT_STATUS_SUCCESS:
+ return RttStatus::SUCCESS;
+ case legacy_hal::RTT_STATUS_FAILURE:
+ return RttStatus::FAILURE;
+ case legacy_hal::RTT_STATUS_FAIL_NO_RSP:
+ return RttStatus::FAIL_NO_RSP;
+ case legacy_hal::RTT_STATUS_FAIL_REJECTED:
+ return RttStatus::FAIL_REJECTED;
+ case legacy_hal::RTT_STATUS_FAIL_NOT_SCHEDULED_YET:
+ return RttStatus::FAIL_NOT_SCHEDULED_YET;
+ case legacy_hal::RTT_STATUS_FAIL_TM_TIMEOUT:
+ return RttStatus::FAIL_TM_TIMEOUT;
+ case legacy_hal::RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL:
+ return RttStatus::FAIL_AP_ON_DIFF_CHANNEL;
+ case legacy_hal::RTT_STATUS_FAIL_NO_CAPABILITY:
+ return RttStatus::FAIL_NO_CAPABILITY;
+ case legacy_hal::RTT_STATUS_ABORTED:
+ return RttStatus::ABORTED;
+ case legacy_hal::RTT_STATUS_FAIL_INVALID_TS:
+ return RttStatus::FAIL_INVALID_TS;
+ case legacy_hal::RTT_STATUS_FAIL_PROTOCOL:
+ return RttStatus::FAIL_PROTOCOL;
+ case legacy_hal::RTT_STATUS_FAIL_SCHEDULE:
+ return RttStatus::FAIL_SCHEDULE;
+ case legacy_hal::RTT_STATUS_FAIL_BUSY_TRY_LATER:
+ return RttStatus::FAIL_BUSY_TRY_LATER;
+ case legacy_hal::RTT_STATUS_INVALID_REQ:
+ return RttStatus::INVALID_REQ;
+ case legacy_hal::RTT_STATUS_NO_WIFI:
+ return RttStatus::NO_WIFI;
+ case legacy_hal::RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE:
+ return RttStatus::FAIL_FTM_PARAM_OVERRIDE;
+ case legacy_hal::RTT_STATUS_NAN_RANGING_PROTOCOL_FAILURE:
+ return RttStatus::NAN_RANGING_PROTOCOL_FAILURE;
+ case legacy_hal::RTT_STATUS_NAN_RANGING_CONCURRENCY_NOT_SUPPORTED:
+ return RttStatus::NAN_RANGING_CONCURRENCY_NOT_SUPPORTED;
+ };
+ CHECK(false) << "Unknown legacy status: " << status;
+}
+
+bool convertAidlWifiChannelInfoToLegacy(const WifiChannelInfo& aidl_info,
+ legacy_hal::wifi_channel_info* legacy_info) {
+ if (!legacy_info) {
+ return false;
+ }
+ *legacy_info = {};
+ legacy_info->width = convertAidlWifiChannelWidthToLegacy(aidl_info.width);
+ legacy_info->center_freq = aidl_info.centerFreq;
+ legacy_info->center_freq0 = aidl_info.centerFreq0;
+ legacy_info->center_freq1 = aidl_info.centerFreq1;
+ return true;
+}
+
+bool convertLegacyWifiChannelInfoToAidl(const legacy_hal::wifi_channel_info& legacy_info,
+ WifiChannelInfo* aidl_info) {
+ if (!aidl_info) {
+ return false;
+ }
+ *aidl_info = {};
+ aidl_info->width = convertLegacyWifiChannelWidthToAidl(legacy_info.width);
+ aidl_info->centerFreq = legacy_info.center_freq;
+ aidl_info->centerFreq0 = legacy_info.center_freq0;
+ aidl_info->centerFreq1 = legacy_info.center_freq1;
+ return true;
+}
+
+bool convertAidlRttConfigToLegacy(const RttConfig& aidl_config,
+ legacy_hal::wifi_rtt_config* legacy_config) {
+ if (!legacy_config) {
+ return false;
+ }
+ *legacy_config = {};
+ CHECK(aidl_config.addr.size() == sizeof(legacy_config->addr));
+ memcpy(legacy_config->addr, aidl_config.addr.data(), aidl_config.addr.size());
+ legacy_config->type = convertAidlRttTypeToLegacy(aidl_config.type);
+ legacy_config->peer = convertAidlRttPeerTypeToLegacy(aidl_config.peer);
+ if (!convertAidlWifiChannelInfoToLegacy(aidl_config.channel, &legacy_config->channel)) {
+ return false;
+ }
+ legacy_config->burst_period = aidl_config.burstPeriod;
+ legacy_config->num_burst = aidl_config.numBurst;
+ legacy_config->num_frames_per_burst = aidl_config.numFramesPerBurst;
+ legacy_config->num_retries_per_rtt_frame = aidl_config.numRetriesPerRttFrame;
+ legacy_config->num_retries_per_ftmr = aidl_config.numRetriesPerFtmr;
+ legacy_config->LCI_request = aidl_config.mustRequestLci;
+ legacy_config->LCR_request = aidl_config.mustRequestLcr;
+ legacy_config->burst_duration = aidl_config.burstDuration;
+ legacy_config->preamble = convertAidlRttPreambleToLegacy(aidl_config.preamble);
+ legacy_config->bw = convertAidlRttBwToLegacy(aidl_config.bw);
+ return true;
+}
+
+bool convertAidlVectorOfRttConfigToLegacy(
+ const std::vector<RttConfig>& aidl_configs,
+ std::vector<legacy_hal::wifi_rtt_config>* legacy_configs) {
+ if (!legacy_configs) {
+ return false;
+ }
+ *legacy_configs = {};
+ for (const auto& aidl_config : aidl_configs) {
+ legacy_hal::wifi_rtt_config legacy_config;
+ if (!convertAidlRttConfigToLegacy(aidl_config, &legacy_config)) {
+ return false;
+ }
+ legacy_configs->push_back(legacy_config);
+ }
+ return true;
+}
+
+bool convertAidlRttLciInformationToLegacy(const RttLciInformation& aidl_info,
+ legacy_hal::wifi_lci_information* legacy_info) {
+ if (!legacy_info) {
+ return false;
+ }
+ *legacy_info = {};
+ legacy_info->latitude = aidl_info.latitude;
+ legacy_info->longitude = aidl_info.longitude;
+ legacy_info->altitude = aidl_info.altitude;
+ legacy_info->latitude_unc = aidl_info.latitudeUnc;
+ legacy_info->longitude_unc = aidl_info.longitudeUnc;
+ legacy_info->altitude_unc = aidl_info.altitudeUnc;
+ legacy_info->motion_pattern = convertAidlRttMotionPatternToLegacy(aidl_info.motionPattern);
+ legacy_info->floor = aidl_info.floor;
+ legacy_info->height_above_floor = aidl_info.heightAboveFloor;
+ legacy_info->height_unc = aidl_info.heightUnc;
+ return true;
+}
+
+bool convertAidlRttLcrInformationToLegacy(const RttLcrInformation& aidl_info,
+ legacy_hal::wifi_lcr_information* legacy_info) {
+ if (!legacy_info) {
+ return false;
+ }
+ *legacy_info = {};
+ CHECK(aidl_info.countryCode.size() == sizeof(legacy_info->country_code));
+ memcpy(legacy_info->country_code, aidl_info.countryCode.data(), aidl_info.countryCode.size());
+ if (aidl_info.civicInfo.size() > sizeof(legacy_info->civic_info)) {
+ return false;
+ }
+ legacy_info->length = aidl_info.civicInfo.size();
+ memcpy(legacy_info->civic_info, aidl_info.civicInfo.c_str(), aidl_info.civicInfo.size());
+ return true;
+}
+
+bool convertAidlRttResponderToLegacy(const RttResponder& aidl_responder,
+ legacy_hal::wifi_rtt_responder* legacy_responder) {
+ if (!legacy_responder) {
+ return false;
+ }
+ *legacy_responder = {};
+ if (!convertAidlWifiChannelInfoToLegacy(aidl_responder.channel, &legacy_responder->channel)) {
+ return false;
+ }
+ legacy_responder->preamble = convertAidlRttPreambleToLegacy(aidl_responder.preamble);
+ return true;
+}
+
+bool convertLegacyRttResponderToAidl(const legacy_hal::wifi_rtt_responder& legacy_responder,
+ RttResponder* aidl_responder) {
+ if (!aidl_responder) {
+ return false;
+ }
+ *aidl_responder = {};
+ if (!convertLegacyWifiChannelInfoToAidl(legacy_responder.channel, &aidl_responder->channel)) {
+ return false;
+ }
+ aidl_responder->preamble = convertLegacyRttPreambleToAidl(legacy_responder.preamble);
+ return true;
+}
+
+bool convertLegacyRttCapabilitiesToAidl(
+ const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
+ RttCapabilities* aidl_capabilities) {
+ if (!aidl_capabilities) {
+ return false;
+ }
+ *aidl_capabilities = {};
+ aidl_capabilities->rttOneSidedSupported = legacy_capabilities.rtt_one_sided_supported;
+ aidl_capabilities->rttFtmSupported = legacy_capabilities.rtt_ftm_supported;
+ aidl_capabilities->lciSupported = legacy_capabilities.lci_support;
+ aidl_capabilities->lcrSupported = legacy_capabilities.lcr_support;
+ aidl_capabilities->responderSupported = legacy_capabilities.responder_supported;
+ int32_t preambleSupport = 0;
+ for (const auto flag : {legacy_hal::WIFI_RTT_PREAMBLE_LEGACY, legacy_hal::WIFI_RTT_PREAMBLE_HT,
+ legacy_hal::WIFI_RTT_PREAMBLE_VHT, legacy_hal::WIFI_RTT_PREAMBLE_HE,
+ legacy_hal::WIFI_RTT_PREAMBLE_EHT}) {
+ if (legacy_capabilities.preamble_support & flag) {
+ preambleSupport |= static_cast<std::underlying_type<RttPreamble>::type>(
+ convertLegacyRttPreambleToAidl(flag));
+ }
+ }
+ aidl_capabilities->preambleSupport = static_cast<RttPreamble>(preambleSupport);
+ int32_t bwSupport = 0;
+ for (const auto flag :
+ {legacy_hal::WIFI_RTT_BW_5, legacy_hal::WIFI_RTT_BW_10, legacy_hal::WIFI_RTT_BW_20,
+ legacy_hal::WIFI_RTT_BW_40, legacy_hal::WIFI_RTT_BW_80, legacy_hal::WIFI_RTT_BW_160,
+ legacy_hal::WIFI_RTT_BW_320}) {
+ if (legacy_capabilities.bw_support & flag) {
+ bwSupport |=
+ static_cast<std::underlying_type<RttBw>::type>(convertLegacyRttBwToAidl(flag));
+ }
+ }
+ aidl_capabilities->bwSupport = static_cast<RttBw>(bwSupport);
+ aidl_capabilities->mcVersion = legacy_capabilities.mc_version;
+ return true;
+}
+
+bool convertLegacyWifiRateInfoToAidl(const legacy_hal::wifi_rate& legacy_rate,
+ WifiRateInfo* aidl_rate) {
+ if (!aidl_rate) {
+ return false;
+ }
+ *aidl_rate = {};
+ aidl_rate->preamble = convertLegacyWifiRatePreambleToAidl(legacy_rate.preamble);
+ aidl_rate->nss = convertLegacyWifiRateNssToAidl(legacy_rate.nss);
+ aidl_rate->bw = convertLegacyWifiChannelWidthToAidl(
+ static_cast<legacy_hal::wifi_channel_width>(legacy_rate.bw));
+ aidl_rate->rateMcsIdx = legacy_rate.rateMcsIdx;
+ aidl_rate->bitRateInKbps = legacy_rate.bitrate;
+ return true;
+}
+
+bool convertLegacyRttResultToAidl(const legacy_hal::wifi_rtt_result& legacy_result,
+ RttResult* aidl_result) {
+ if (!aidl_result) {
+ return false;
+ }
+ *aidl_result = {};
+ aidl_result->addr = std::array<uint8_t, 6>();
+ CHECK(sizeof(legacy_result.addr) == aidl_result->addr.size());
+ std::copy(legacy_result.addr, legacy_result.addr + 6, std::begin(aidl_result->addr));
+ aidl_result->burstNum = legacy_result.burst_num;
+ aidl_result->measurementNumber = legacy_result.measurement_number;
+ aidl_result->successNumber = legacy_result.success_number;
+ aidl_result->numberPerBurstPeer = legacy_result.number_per_burst_peer;
+ aidl_result->status = convertLegacyRttStatusToAidl(legacy_result.status);
+ aidl_result->retryAfterDuration = legacy_result.retry_after_duration;
+ aidl_result->type = convertLegacyRttTypeToAidl(legacy_result.type);
+ aidl_result->rssi = legacy_result.rssi;
+ aidl_result->rssiSpread = legacy_result.rssi_spread;
+ if (!convertLegacyWifiRateInfoToAidl(legacy_result.tx_rate, &aidl_result->txRate)) {
+ return false;
+ }
+ if (!convertLegacyWifiRateInfoToAidl(legacy_result.rx_rate, &aidl_result->rxRate)) {
+ return false;
+ }
+ aidl_result->rtt = legacy_result.rtt;
+ aidl_result->rttSd = legacy_result.rtt_sd;
+ aidl_result->rttSpread = legacy_result.rtt_spread;
+ aidl_result->distanceInMm = legacy_result.distance_mm;
+ aidl_result->distanceSdInMm = legacy_result.distance_sd_mm;
+ aidl_result->distanceSpreadInMm = legacy_result.distance_spread_mm;
+ aidl_result->timeStampInUs = legacy_result.ts;
+ aidl_result->burstDurationInMs = legacy_result.burst_duration;
+ aidl_result->negotiatedBurstNum = legacy_result.negotiated_burst_num;
+ if (legacy_result.LCI && !convertLegacyIeToAidl(*legacy_result.LCI, &aidl_result->lci)) {
+ return false;
+ }
+ if (legacy_result.LCR && !convertLegacyIeToAidl(*legacy_result.LCR, &aidl_result->lcr)) {
+ return false;
+ }
+ return true;
+}
+
+bool convertLegacyVectorOfRttResultToAidl(
+ const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
+ std::vector<RttResult>* aidl_results) {
+ if (!aidl_results) {
+ return false;
+ }
+ *aidl_results = {};
+ for (const auto legacy_result : legacy_results) {
+ RttResult aidl_result;
+ if (!convertLegacyRttResultToAidl(*legacy_result, &aidl_result)) {
+ return false;
+ }
+ aidl_results->push_back(aidl_result);
+ }
+ return true;
+}
+
+legacy_hal::wifi_interface_type convertAidlIfaceTypeToLegacy(IfaceType aidl_interface_type) {
+ switch (aidl_interface_type) {
+ case IfaceType::STA:
+ return legacy_hal::WIFI_INTERFACE_TYPE_STA;
+ case IfaceType::AP:
+ return legacy_hal::WIFI_INTERFACE_TYPE_AP;
+ case IfaceType::P2P:
+ return legacy_hal::WIFI_INTERFACE_TYPE_P2P;
+ case IfaceType::NAN_IFACE:
+ return legacy_hal::WIFI_INTERFACE_TYPE_NAN;
+ }
+ CHECK(false);
+}
+
+legacy_hal::wifi_multi_sta_use_case convertAidlMultiStaUseCaseToLegacy(
+ IWifiChip::MultiStaUseCase use_case) {
+ switch (use_case) {
+ case IWifiChip::MultiStaUseCase::DUAL_STA_TRANSIENT_PREFER_PRIMARY:
+ return legacy_hal::WIFI_DUAL_STA_TRANSIENT_PREFER_PRIMARY;
+ case IWifiChip::MultiStaUseCase::DUAL_STA_NON_TRANSIENT_UNBIASED:
+ return legacy_hal::WIFI_DUAL_STA_NON_TRANSIENT_UNBIASED;
+ }
+ CHECK(false);
+}
+
+bool convertAidlCoexUnsafeChannelToLegacy(
+ const IWifiChip::CoexUnsafeChannel& aidl_unsafe_channel,
+ legacy_hal::wifi_coex_unsafe_channel* legacy_unsafe_channel) {
+ if (!legacy_unsafe_channel) {
+ return false;
+ }
+ *legacy_unsafe_channel = {};
+ switch (aidl_unsafe_channel.band) {
+ case WifiBand::BAND_24GHZ:
+ legacy_unsafe_channel->band = legacy_hal::WLAN_MAC_2_4_BAND;
+ break;
+ case WifiBand::BAND_5GHZ:
+ legacy_unsafe_channel->band = legacy_hal::WLAN_MAC_5_0_BAND;
+ break;
+ default:
+ return false;
+ };
+ legacy_unsafe_channel->channel = aidl_unsafe_channel.channel;
+ legacy_unsafe_channel->power_cap_dbm = aidl_unsafe_channel.powerCapDbm;
+ return true;
+}
+
+bool convertAidlVectorOfCoexUnsafeChannelToLegacy(
+ const std::vector<IWifiChip::CoexUnsafeChannel>& aidl_unsafe_channels,
+ std::vector<legacy_hal::wifi_coex_unsafe_channel>* legacy_unsafe_channels) {
+ if (!legacy_unsafe_channels) {
+ return false;
+ }
+ *legacy_unsafe_channels = {};
+ for (const auto& aidl_unsafe_channel : aidl_unsafe_channels) {
+ legacy_hal::wifi_coex_unsafe_channel legacy_unsafe_channel;
+ if (!aidl_struct_util::convertAidlCoexUnsafeChannelToLegacy(aidl_unsafe_channel,
+ &legacy_unsafe_channel)) {
+ return false;
+ }
+ legacy_unsafe_channels->push_back(legacy_unsafe_channel);
+ }
+ return true;
+}
+
+WifiAntennaMode convertLegacyAntennaConfigurationToAidl(uint32_t antenna_cfg) {
+ switch (antenna_cfg) {
+ case legacy_hal::WIFI_ANTENNA_1X1:
+ return WifiAntennaMode::WIFI_ANTENNA_MODE_1X1;
+ case legacy_hal::WIFI_ANTENNA_2X2:
+ return WifiAntennaMode::WIFI_ANTENNA_MODE_2X2;
+ case legacy_hal::WIFI_ANTENNA_3X3:
+ return WifiAntennaMode::WIFI_ANTENNA_MODE_3X3;
+ case legacy_hal::WIFI_ANTENNA_4X4:
+ return WifiAntennaMode::WIFI_ANTENNA_MODE_4X4;
+ default:
+ return WifiAntennaMode::WIFI_ANTENNA_MODE_UNSPECIFIED;
+ }
+}
+
+bool convertLegacyWifiRadioConfigurationToAidl(
+ legacy_hal::wifi_radio_configuration* radio_configuration,
+ WifiRadioConfiguration* aidl_radio_configuration) {
+ if (!aidl_radio_configuration) {
+ return false;
+ }
+ *aidl_radio_configuration = {};
+ aidl_radio_configuration->bandInfo =
+ aidl_struct_util::convertLegacyMacBandToAidlWifiBand(radio_configuration->band);
+ if (aidl_radio_configuration->bandInfo == WifiBand::BAND_UNSPECIFIED) {
+ LOG(ERROR) << "Unspecified band";
+ return false;
+ }
+ aidl_radio_configuration->antennaMode =
+ aidl_struct_util::convertLegacyAntennaConfigurationToAidl(
+ radio_configuration->antenna_cfg);
+ return true;
+}
+
+bool convertLegacyRadioCombinationsMatrixToAidl(
+ legacy_hal::wifi_radio_combination_matrix* legacy_matrix,
+ WifiRadioCombinationMatrix* aidl_matrix) {
+ if (!aidl_matrix || !legacy_matrix) {
+ return false;
+ }
+ *aidl_matrix = {};
+
+ int num_combinations = legacy_matrix->num_radio_combinations;
+ std::vector<WifiRadioCombination> radio_combinations_vec;
+ if (!num_combinations) {
+ LOG(ERROR) << "zero radio combinations";
+ return false;
+ }
+ wifi_radio_combination* l_radio_combinations_ptr = legacy_matrix->radio_combinations;
+ for (int i = 0; i < num_combinations; i++) {
+ int num_configurations = l_radio_combinations_ptr->num_radio_configurations;
+ WifiRadioCombination radioCombination;
+ std::vector<WifiRadioConfiguration> radio_configurations_vec;
+ if (!num_configurations) {
+ LOG(ERROR) << "zero radio configurations";
+ return false;
+ }
+ for (int j = 0; j < num_configurations; j++) {
+ WifiRadioConfiguration radioConfiguration;
+ wifi_radio_configuration* l_radio_configurations_ptr =
+ &l_radio_combinations_ptr->radio_configurations[j];
+ if (!aidl_struct_util::convertLegacyWifiRadioConfigurationToAidl(
+ l_radio_configurations_ptr, &radioConfiguration)) {
+ LOG(ERROR) << "Error converting wifi radio configuration";
+ return false;
+ }
+ radio_configurations_vec.push_back(radioConfiguration);
+ }
+ radioCombination.radioConfigurations = radio_configurations_vec;
+ radio_combinations_vec.push_back(radioCombination);
+ l_radio_combinations_ptr =
+ (wifi_radio_combination*)((u8*)l_radio_combinations_ptr +
+ sizeof(wifi_radio_combination) +
+ (sizeof(wifi_radio_configuration) * num_configurations));
+ }
+ aidl_matrix->radioCombinations = radio_combinations_vec;
+ return true;
+}
+
+} // namespace aidl_struct_util
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/aidl_struct_util.h b/wifi/aidl/default/aidl_struct_util.h
new file mode 100644
index 0000000..4ebfc10
--- /dev/null
+++ b/wifi/aidl/default/aidl_struct_util.h
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 AIDL_STRUCT_UTIL_H_
+#define AIDL_STRUCT_UTIL_H_
+
+#include <aidl/android/hardware/wifi/IWifiChip.h>
+#include <aidl/android/hardware/wifi/IWifiChipEventCallback.h>
+#include <aidl/android/hardware/wifi/NanBandIndex.h>
+#include <aidl/android/hardware/wifi/WifiDebugRingBufferFlags.h>
+
+#include <vector>
+
+#include "wifi_legacy_hal.h"
+
+/**
+ * This file contains a bunch of functions to convert structs from the legacy
+ * HAL to AIDL and vice versa.
+ */
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace aidl_struct_util {
+
+// Chip conversion methods.
+bool convertLegacyFeaturesToAidlChipCapabilities(uint64_t legacy_feature_set,
+ uint32_t legacy_logger_feature_set,
+ uint32_t* aidl_caps);
+bool convertLegacyDebugRingBufferStatusToAidl(
+ const legacy_hal::wifi_ring_buffer_status& legacy_status,
+ WifiDebugRingBufferStatus* aidl_status);
+bool convertLegacyVectorOfDebugRingBufferStatusToAidl(
+ const std::vector<legacy_hal::wifi_ring_buffer_status>& legacy_status_vec,
+ std::vector<WifiDebugRingBufferStatus>* aidl_status_vec);
+bool convertLegacyWakeReasonStatsToAidl(const legacy_hal::WakeReasonStats& legacy_stats,
+ WifiDebugHostWakeReasonStats* aidl_stats);
+legacy_hal::wifi_power_scenario convertAidlTxPowerScenarioToLegacy(
+ IWifiChip::TxPowerScenario aidl_scenario);
+legacy_hal::wifi_latency_mode convertAidlLatencyModeToLegacy(
+ IWifiChip::LatencyMode aidl_latency_mode);
+bool convertLegacyWifiMacInfosToAidl(
+ const std::vector<legacy_hal::WifiMacInfo>& legacy_mac_infos,
+ std::vector<IWifiChipEventCallback::RadioModeInfo>* aidl_radio_mode_infos);
+legacy_hal::wifi_interface_type convertAidlIfaceTypeToLegacy(IfaceType aidl_interface_type);
+legacy_hal::wifi_multi_sta_use_case convertAidlMultiStaUseCaseToLegacy(
+ IWifiChip::MultiStaUseCase use_case);
+bool convertAidlCoexUnsafeChannelToLegacy(
+ const IWifiChip::CoexUnsafeChannel& aidl_unsafe_channel,
+ legacy_hal::wifi_coex_unsafe_channel* legacy_unsafe_channel);
+bool convertAidlVectorOfCoexUnsafeChannelToLegacy(
+ const std::vector<IWifiChip::CoexUnsafeChannel>& aidl_unsafe_channels,
+ std::vector<legacy_hal::wifi_coex_unsafe_channel>* legacy_unsafe_channels);
+bool convertLegacyRadioCombinationsMatrixToAidl(
+ legacy_hal::wifi_radio_combination_matrix* legacy_matrix,
+ WifiRadioCombinationMatrix* aidl_matrix);
+WifiBand convertLegacyMacBandToAidlWifiBand(uint32_t band);
+WifiAntennaMode convertLegacyAntennaConfigurationToAidl(uint32_t antenna_cfg);
+
+// STA iface conversion methods.
+bool convertLegacyFeaturesToAidlStaCapabilities(uint64_t legacy_feature_set,
+ uint32_t legacy_logger_feature_set,
+ uint32_t* aidl_caps);
+bool convertLegacyApfCapabilitiesToAidl(const legacy_hal::PacketFilterCapabilities& legacy_caps,
+ StaApfPacketFilterCapabilities* aidl_caps);
+bool convertLegacyGscanCapabilitiesToAidl(const legacy_hal::wifi_gscan_capabilities& legacy_caps,
+ StaBackgroundScanCapabilities* aidl_caps);
+legacy_hal::wifi_band convertAidlWifiBandToLegacy(WifiBand band);
+bool convertAidlGscanParamsToLegacy(const StaBackgroundScanParameters& aidl_scan_params,
+ legacy_hal::wifi_scan_cmd_params* legacy_scan_params);
+// |has_ie_data| indicates whether or not the wifi_scan_result includes 802.11
+// Information Elements (IEs)
+bool convertLegacyGscanResultToAidl(const legacy_hal::wifi_scan_result& legacy_scan_result,
+ bool has_ie_data, StaScanResult* aidl_scan_result);
+// |cached_results| is assumed to not include IEs.
+bool convertLegacyVectorOfCachedGscanResultsToAidl(
+ const std::vector<legacy_hal::wifi_cached_scan_results>& legacy_cached_scan_results,
+ std::vector<StaScanData>* aidl_scan_datas);
+bool convertLegacyLinkLayerStatsToAidl(const legacy_hal::LinkLayerStats& legacy_stats,
+ StaLinkLayerStats* aidl_stats);
+bool convertLegacyRoamingCapabilitiesToAidl(
+ const legacy_hal::wifi_roaming_capabilities& legacy_caps,
+ StaRoamingCapabilities* aidl_caps);
+bool convertAidlRoamingConfigToLegacy(const StaRoamingConfig& aidl_config,
+ legacy_hal::wifi_roaming_config* legacy_config);
+legacy_hal::fw_roaming_state_t convertAidlRoamingStateToLegacy(StaRoamingState state);
+bool convertLegacyVectorOfDebugTxPacketFateToAidl(
+ const std::vector<legacy_hal::wifi_tx_report>& legacy_fates,
+ std::vector<WifiDebugTxPacketFateReport>* aidl_fates);
+bool convertLegacyVectorOfDebugRxPacketFateToAidl(
+ const std::vector<legacy_hal::wifi_rx_report>& legacy_fates,
+ std::vector<WifiDebugRxPacketFateReport>* aidl_fates);
+
+// NAN iface conversion methods.
+void convertToNanStatus(legacy_hal::NanStatusType type, const char* str, size_t max_len,
+ NanStatus* nanStatus);
+bool convertAidlNanEnableRequestToLegacy(const NanEnableRequest& aidl_request1,
+ const NanConfigRequestSupplemental& aidl_request2,
+ legacy_hal::NanEnableRequest* legacy_request);
+bool convertAidlNanConfigRequestToLegacy(const NanConfigRequest& aidl_request1,
+ const NanConfigRequestSupplemental& aidl_request2,
+ legacy_hal::NanConfigRequest* legacy_request);
+bool convertAidlNanPublishRequestToLegacy(const NanPublishRequest& aidl_request,
+ legacy_hal::NanPublishRequest* legacy_request);
+bool convertAidlNanSubscribeRequestToLegacy(const NanSubscribeRequest& aidl_request,
+ legacy_hal::NanSubscribeRequest* legacy_request);
+bool convertAidlNanTransmitFollowupRequestToLegacy(
+ const NanTransmitFollowupRequest& aidl_request,
+ legacy_hal::NanTransmitFollowupRequest* legacy_request);
+bool convertAidlNanDataPathInitiatorRequestToLegacy(
+ const NanInitiateDataPathRequest& aidl_request,
+ legacy_hal::NanDataPathInitiatorRequest* legacy_request);
+bool convertAidlNanDataPathIndicationResponseToLegacy(
+ const NanRespondToDataPathIndicationRequest& aidl_response,
+ legacy_hal::NanDataPathIndicationResponse* legacy_response);
+bool convertLegacyNanResponseHeaderToAidl(const legacy_hal::NanResponseMsg& legacy_response,
+ NanStatus* nanStatus);
+bool convertLegacyNanCapabilitiesResponseToAidl(const legacy_hal::NanCapabilities& legacy_response,
+ NanCapabilities* aidl_response);
+bool convertLegacyNanMatchIndToAidl(const legacy_hal::NanMatchInd& legacy_ind,
+ NanMatchInd* aidl_ind);
+bool convertLegacyNanFollowupIndToAidl(const legacy_hal::NanFollowupInd& legacy_ind,
+ NanFollowupReceivedInd* aidl_ind);
+bool convertLegacyNanDataPathRequestIndToAidl(const legacy_hal::NanDataPathRequestInd& legacy_ind,
+ NanDataPathRequestInd* aidl_ind);
+bool convertLegacyNanDataPathConfirmIndToAidl(const legacy_hal::NanDataPathConfirmInd& legacy_ind,
+ NanDataPathConfirmInd* aidl_ind);
+bool convertLegacyNanDataPathScheduleUpdateIndToAidl(
+ const legacy_hal::NanDataPathScheduleUpdateInd& legacy_ind,
+ NanDataPathScheduleUpdateInd* aidl_ind);
+
+// RTT controller conversion methods.
+bool convertAidlVectorOfRttConfigToLegacy(const std::vector<RttConfig>& aidl_configs,
+ std::vector<legacy_hal::wifi_rtt_config>* legacy_configs);
+bool convertAidlRttLciInformationToLegacy(const RttLciInformation& aidl_info,
+ legacy_hal::wifi_lci_information* legacy_info);
+bool convertAidlRttLcrInformationToLegacy(const RttLcrInformation& aidl_info,
+ legacy_hal::wifi_lcr_information* legacy_info);
+bool convertAidlRttResponderToLegacy(const RttResponder& aidl_responder,
+ legacy_hal::wifi_rtt_responder* legacy_responder);
+bool convertAidlWifiChannelInfoToLegacy(const WifiChannelInfo& aidl_info,
+ legacy_hal::wifi_channel_info* legacy_info);
+bool convertLegacyRttResponderToAidl(const legacy_hal::wifi_rtt_responder& legacy_responder,
+ RttResponder* aidl_responder);
+bool convertLegacyRttCapabilitiesToAidl(
+ const legacy_hal::wifi_rtt_capabilities& legacy_capabilities,
+ RttCapabilities* aidl_capabilities);
+bool convertLegacyVectorOfRttResultToAidl(
+ const std::vector<const legacy_hal::wifi_rtt_result*>& legacy_results,
+ std::vector<RttResult>* aidl_results);
+uint32_t convertAidlWifiBandToLegacyMacBand(WifiBand band);
+uint32_t convertAidlWifiIfaceModeToLegacy(uint32_t aidl_iface_mask);
+uint32_t convertAidlUsableChannelFilterToLegacy(uint32_t aidl_filter_mask);
+bool convertLegacyWifiUsableChannelsToAidl(
+ const std::vector<legacy_hal::wifi_usable_channel>& legacy_usable_channels,
+ std::vector<WifiUsableChannel>* aidl_usable_channels);
+bool convertLegacyPeerInfoStatsToAidl(const legacy_hal::WifiPeerInfo& legacy_peer_info_stats,
+ StaPeerInfo* aidl_peer_info_stats);
+bool convertLegacyWifiRateInfoToAidl(const legacy_hal::wifi_rate& legacy_rate,
+ WifiRateInfo* aidl_rate);
+} // namespace aidl_struct_util
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // AIDL_STRUCT_UTIL_H_
diff --git a/wifi/1.6/default/hidl_sync_util.cpp b/wifi/aidl/default/aidl_sync_util.cpp
similarity index 78%
rename from wifi/1.6/default/hidl_sync_util.cpp
rename to wifi/aidl/default/aidl_sync_util.cpp
index 358d95e..d81eb81 100644
--- a/wifi/1.6/default/hidl_sync_util.cpp
+++ b/wifi/aidl/default/aidl_sync_util.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,26 +14,24 @@
* limitations under the License.
*/
-#include "hidl_sync_util.h"
+#include "aidl_sync_util.h"
namespace {
std::recursive_mutex g_mutex;
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace hidl_sync_util {
+namespace aidl_sync_util {
std::unique_lock<std::recursive_mutex> acquireGlobalLock() {
return std::unique_lock<std::recursive_mutex>{g_mutex};
}
-} // namespace hidl_sync_util
-} // namespace implementation
-} // namespace V1_6
+} // namespace aidl_sync_util
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/hidl_sync_util.h b/wifi/aidl/default/aidl_sync_util.h
similarity index 71%
rename from wifi/1.6/default/hidl_sync_util.h
rename to wifi/aidl/default/aidl_sync_util.h
index 2c1c37b..a61cd3f 100644
--- a/wifi/1.6/default/hidl_sync_util.h
+++ b/wifi/aidl/default/aidl_sync_util.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,24 +14,22 @@
* limitations under the License.
*/
-#ifndef HIDL_SYNC_UTIL_H_
-#define HIDL_SYNC_UTIL_H_
+#ifndef AIDL_SYNC_UTIL_H_
+#define AIDL_SYNC_UTIL_H_
#include <mutex>
// Utility that provides a global lock to synchronize access between
-// the HIDL thread and the legacy HAL's event loop.
+// the AIDL thread and the legacy HAL's event loop.
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-namespace hidl_sync_util {
+namespace aidl_sync_util {
std::unique_lock<std::recursive_mutex> acquireGlobalLock();
-} // namespace hidl_sync_util
-} // namespace implementation
-} // namespace V1_6
+} // namespace aidl_sync_util
} // namespace wifi
} // namespace hardware
} // namespace android
-#endif // HIDL_SYNC_UTIL_H_
+} // namespace aidl
+#endif // AIDL_SYNC_UTIL_H_
diff --git a/wifi/aidl/default/android.hardware.wifi-service-lazy.rc b/wifi/aidl/default/android.hardware.wifi-service-lazy.rc
new file mode 100644
index 0000000..12d3ff7
--- /dev/null
+++ b/wifi/aidl/default/android.hardware.wifi-service-lazy.rc
@@ -0,0 +1,8 @@
+service vendor.wifi_hal_legacy /vendor/bin/hw/android.hardware.wifi-service-lazy
+ interface aidl android.hardware.wifi.IWifi/default
+ oneshot
+ disabled
+ class hal
+ capabilities NET_ADMIN NET_RAW SYS_MODULE
+ user wifi
+ group wifi gps
diff --git a/wifi/aidl/default/android.hardware.wifi-service.rc b/wifi/aidl/default/android.hardware.wifi-service.rc
new file mode 100644
index 0000000..ec8acf5
--- /dev/null
+++ b/wifi/aidl/default/android.hardware.wifi-service.rc
@@ -0,0 +1,6 @@
+service vendor.wifi_hal_legacy /vendor/bin/hw/android.hardware.wifi-service
+ interface aidl android.hardware.wifi.IWifi/default
+ class hal
+ capabilities NET_ADMIN NET_RAW SYS_MODULE
+ user wifi
+ group wifi gps
diff --git a/wifi/aidl/default/android.hardware.wifi-service.xml b/wifi/aidl/default/android.hardware.wifi-service.xml
new file mode 100644
index 0000000..5398ee7
--- /dev/null
+++ b/wifi/aidl/default/android.hardware.wifi-service.xml
@@ -0,0 +1,6 @@
+<manifest version="1.0" type="device">
+ <hal format="aidl">
+ <name>android.hardware.wifi</name>
+ <fqname>IWifi/default</fqname>
+ </hal>
+</manifest>
diff --git a/wifi/1.6/default/ringbuffer.cpp b/wifi/aidl/default/ringbuffer.cpp
similarity index 92%
rename from wifi/1.6/default/ringbuffer.cpp
rename to wifi/aidl/default/ringbuffer.cpp
index 981bf7b..9d08a73 100644
--- a/wifi/1.6/default/ringbuffer.cpp
+++ b/wifi/aidl/default/ringbuffer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,15 +14,14 @@
* limitations under the License.
*/
-#include <android-base/logging.h>
-
#include "ringbuffer.h"
+#include <android-base/logging.h>
+
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
Ringbuffer::Ringbuffer(size_t maxSize) : size_(0), maxSize_(maxSize) {}
@@ -57,8 +56,7 @@
size_ = 0;
}
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/ringbuffer.h b/wifi/aidl/default/ringbuffer.h
similarity index 90%
rename from wifi/1.6/default/ringbuffer.h
rename to wifi/aidl/default/ringbuffer.h
index c6a1e4c..80c0c11 100644
--- a/wifi/1.6/default/ringbuffer.h
+++ b/wifi/aidl/default/ringbuffer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,11 +20,10 @@
#include <list>
#include <vector>
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
/**
* Ringbuffer object used to store debug data.
@@ -53,10 +52,9 @@
size_t maxSize_;
};
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // RINGBUFFER_H_
diff --git a/wifi/aidl/default/service.cpp b/wifi/aidl/default/service.cpp
new file mode 100644
index 0000000..789a7a5
--- /dev/null
+++ b/wifi/aidl/default/service.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <android-base/logging.h>
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include <signal.h>
+
+#include "wifi.h"
+#include "wifi_feature_flags.h"
+#include "wifi_legacy_hal.h"
+#include "wifi_legacy_hal_factory.h"
+#include "wifi_mode_controller.h"
+
+using aidl::android::hardware::wifi::feature_flags::WifiFeatureFlags;
+using aidl::android::hardware::wifi::legacy_hal::WifiLegacyHal;
+using aidl::android::hardware::wifi::legacy_hal::WifiLegacyHalFactory;
+using aidl::android::hardware::wifi::mode_controller::WifiModeController;
+
+#ifdef LAZY_SERVICE
+const bool kLazyService = true;
+#else
+const bool kLazyService = false;
+#endif
+
+int main(int /*argc*/, char** argv) {
+ signal(SIGPIPE, SIG_IGN);
+ android::base::InitLogging(argv, android::base::LogdLogger(android::base::SYSTEM));
+ LOG(INFO) << "Wifi Hal is booting up...";
+
+ // Prepare the RPC-serving thread pool. Allocate 1 thread in the pool,
+ // which our main thread will join below.
+ ABinderProcess_setThreadPoolMaxThreadCount(1);
+
+ const auto iface_tool = std::make_shared<::android::wifi_system::InterfaceTool>();
+ const auto legacy_hal_factory = std::make_shared<WifiLegacyHalFactory>(iface_tool);
+
+ // Setup binder service
+ std::shared_ptr<aidl::android::hardware::wifi::Wifi> service =
+ ndk::SharedRefBase::make<aidl::android::hardware::wifi::Wifi>(
+ iface_tool, legacy_hal_factory, std::make_shared<WifiModeController>(),
+ std::make_shared<WifiFeatureFlags>());
+ std::string instance =
+ std::string() + aidl::android::hardware::wifi::Wifi::descriptor + "/default";
+ if (kLazyService) {
+ auto result =
+ AServiceManager_registerLazyService(service->asBinder().get(), instance.c_str());
+ CHECK_EQ(result, STATUS_OK) << "Failed to register lazy wifi HAL";
+ } else {
+ auto result = AServiceManager_addService(service->asBinder().get(), instance.c_str());
+ CHECK_EQ(result, STATUS_OK) << "Failed to register wifi HAL";
+ }
+
+ ABinderProcess_startThreadPool();
+ LOG(INFO) << "Joining RPC thread pool";
+ ABinderProcess_joinThreadPool();
+
+ LOG(INFO) << "Wifi Hal is terminating...";
+ return 0;
+}
diff --git a/wifi/1.6/default/tests/hidl_struct_util_unit_tests.cpp b/wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp
similarity index 69%
rename from wifi/1.6/default/tests/hidl_struct_util_unit_tests.cpp
rename to wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp
index 0dd0aa1..4a69c24 100644
--- a/wifi/1.6/default/tests/hidl_struct_util_unit_tests.cpp
+++ b/wifi/aidl/default/tests/aidl_struct_util_unit_tests.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017, The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,7 @@
#include <android-base/macros.h>
#include <gmock/gmock.h>
-#undef NAN
-#include "hidl_struct_util.h"
+#include "aidl_struct_util.h"
using testing::Test;
@@ -31,17 +30,15 @@
constexpr char kIfaceName1[] = "wlan0";
constexpr char kIfaceName2[] = "wlan1";
} // namespace
+
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
-using ::android::hardware::wifi::V1_6::WifiChannelWidthInMhz;
-class HidlStructUtilTest : public Test {};
+class AidlStructUtilTest : public Test {};
-TEST_F(HidlStructUtilTest, CanConvertLegacyWifiMacInfosToHidlWithOneMac) {
+TEST_F(AidlStructUtilTest, CanConvertLegacyWifiMacInfosToAidlWithOneMac) {
std::vector<legacy_hal::WifiMacInfo> legacy_mac_infos;
legacy_hal::WifiMacInfo legacy_mac_info1 = {
.wlan_mac_id = kMacId1,
@@ -52,24 +49,24 @@
legacy_mac_info1.iface_infos.push_back(legacy_iface_info2);
legacy_mac_infos.push_back(legacy_mac_info1);
- std::vector<V1_4::IWifiChipEventCallback::RadioModeInfo> hidl_radio_mode_infos;
- ASSERT_TRUE(hidl_struct_util::convertLegacyWifiMacInfosToHidl(legacy_mac_infos,
- &hidl_radio_mode_infos));
+ std::vector<IWifiChipEventCallback::RadioModeInfo> aidl_radio_mode_infos;
+ ASSERT_TRUE(aidl_struct_util::convertLegacyWifiMacInfosToAidl(legacy_mac_infos,
+ &aidl_radio_mode_infos));
- ASSERT_EQ(1u, hidl_radio_mode_infos.size());
- auto hidl_radio_mode_info1 = hidl_radio_mode_infos[0];
- EXPECT_EQ(legacy_mac_info1.wlan_mac_id, hidl_radio_mode_info1.radioId);
- EXPECT_EQ(V1_4::WifiBand::BAND_24GHZ_5GHZ, hidl_radio_mode_info1.bandInfo);
- ASSERT_EQ(2u, hidl_radio_mode_info1.ifaceInfos.size());
- auto hidl_iface_info1 = hidl_radio_mode_info1.ifaceInfos[0];
- EXPECT_EQ(legacy_iface_info1.name, hidl_iface_info1.name);
- EXPECT_EQ(static_cast<uint32_t>(legacy_iface_info1.channel), hidl_iface_info1.channel);
- auto hidl_iface_info2 = hidl_radio_mode_info1.ifaceInfos[1];
- EXPECT_EQ(legacy_iface_info2.name, hidl_iface_info2.name);
- EXPECT_EQ(static_cast<uint32_t>(legacy_iface_info2.channel), hidl_iface_info2.channel);
+ ASSERT_EQ(1u, aidl_radio_mode_infos.size());
+ auto aidl_radio_mode_info1 = aidl_radio_mode_infos[0];
+ EXPECT_EQ(legacy_mac_info1.wlan_mac_id, (uint32_t)aidl_radio_mode_info1.radioId);
+ EXPECT_EQ(WifiBand::BAND_24GHZ_5GHZ, aidl_radio_mode_info1.bandInfo);
+ ASSERT_EQ(2u, aidl_radio_mode_info1.ifaceInfos.size());
+ auto aidl_iface_info1 = aidl_radio_mode_info1.ifaceInfos[0];
+ EXPECT_EQ(legacy_iface_info1.name, aidl_iface_info1.name);
+ EXPECT_EQ(static_cast<int32_t>(legacy_iface_info1.channel), aidl_iface_info1.channel);
+ auto aidl_iface_info2 = aidl_radio_mode_info1.ifaceInfos[1];
+ EXPECT_EQ(legacy_iface_info2.name, aidl_iface_info2.name);
+ EXPECT_EQ(static_cast<int32_t>(legacy_iface_info2.channel), aidl_iface_info2.channel);
}
-TEST_F(HidlStructUtilTest, CanConvertLegacyWifiMacInfosToHidlWithTwoMac) {
+TEST_F(AidlStructUtilTest, CanConvertLegacyWifiMacInfosToAidlWithTwoMac) {
std::vector<legacy_hal::WifiMacInfo> legacy_mac_infos;
legacy_hal::WifiMacInfo legacy_mac_info1 = {.wlan_mac_id = kMacId1,
.mac_band = legacy_hal::WLAN_MAC_5_0_BAND};
@@ -82,40 +79,40 @@
legacy_mac_info2.iface_infos.push_back(legacy_iface_info2);
legacy_mac_infos.push_back(legacy_mac_info2);
- std::vector<V1_4::IWifiChipEventCallback::RadioModeInfo> hidl_radio_mode_infos;
- ASSERT_TRUE(hidl_struct_util::convertLegacyWifiMacInfosToHidl(legacy_mac_infos,
- &hidl_radio_mode_infos));
+ std::vector<IWifiChipEventCallback::RadioModeInfo> aidl_radio_mode_infos;
+ ASSERT_TRUE(aidl_struct_util::convertLegacyWifiMacInfosToAidl(legacy_mac_infos,
+ &aidl_radio_mode_infos));
- ASSERT_EQ(2u, hidl_radio_mode_infos.size());
+ ASSERT_EQ(2u, aidl_radio_mode_infos.size());
// Find mac info 1.
- const auto hidl_radio_mode_info1 =
- std::find_if(hidl_radio_mode_infos.begin(), hidl_radio_mode_infos.end(),
- [&legacy_mac_info1](const V1_4::IWifiChipEventCallback::RadioModeInfo& x) {
- return x.radioId == legacy_mac_info1.wlan_mac_id;
+ const auto aidl_radio_mode_info1 =
+ std::find_if(aidl_radio_mode_infos.begin(), aidl_radio_mode_infos.end(),
+ [&legacy_mac_info1](const IWifiChipEventCallback::RadioModeInfo& x) {
+ return (uint32_t)x.radioId == legacy_mac_info1.wlan_mac_id;
});
- ASSERT_NE(hidl_radio_mode_infos.end(), hidl_radio_mode_info1);
- EXPECT_EQ(V1_4::WifiBand::BAND_5GHZ, hidl_radio_mode_info1->bandInfo);
- ASSERT_EQ(1u, hidl_radio_mode_info1->ifaceInfos.size());
- auto hidl_iface_info1 = hidl_radio_mode_info1->ifaceInfos[0];
- EXPECT_EQ(legacy_iface_info1.name, hidl_iface_info1.name);
- EXPECT_EQ(static_cast<uint32_t>(legacy_iface_info1.channel), hidl_iface_info1.channel);
+ ASSERT_NE(aidl_radio_mode_infos.end(), aidl_radio_mode_info1);
+ EXPECT_EQ(WifiBand::BAND_5GHZ, aidl_radio_mode_info1->bandInfo);
+ ASSERT_EQ(1u, aidl_radio_mode_info1->ifaceInfos.size());
+ auto aidl_iface_info1 = aidl_radio_mode_info1->ifaceInfos[0];
+ EXPECT_EQ(legacy_iface_info1.name, aidl_iface_info1.name);
+ EXPECT_EQ(static_cast<int32_t>(legacy_iface_info1.channel), aidl_iface_info1.channel);
// Find mac info 2.
- const auto hidl_radio_mode_info2 =
- std::find_if(hidl_radio_mode_infos.begin(), hidl_radio_mode_infos.end(),
- [&legacy_mac_info2](const V1_4::IWifiChipEventCallback::RadioModeInfo& x) {
- return x.radioId == legacy_mac_info2.wlan_mac_id;
+ const auto aidl_radio_mode_info2 =
+ std::find_if(aidl_radio_mode_infos.begin(), aidl_radio_mode_infos.end(),
+ [&legacy_mac_info2](const IWifiChipEventCallback::RadioModeInfo& x) {
+ return (uint32_t)x.radioId == legacy_mac_info2.wlan_mac_id;
});
- ASSERT_NE(hidl_radio_mode_infos.end(), hidl_radio_mode_info2);
- EXPECT_EQ(V1_4::WifiBand::BAND_24GHZ, hidl_radio_mode_info2->bandInfo);
- ASSERT_EQ(1u, hidl_radio_mode_info2->ifaceInfos.size());
- auto hidl_iface_info2 = hidl_radio_mode_info2->ifaceInfos[0];
- EXPECT_EQ(legacy_iface_info2.name, hidl_iface_info2.name);
- EXPECT_EQ(static_cast<uint32_t>(legacy_iface_info2.channel), hidl_iface_info2.channel);
+ ASSERT_NE(aidl_radio_mode_infos.end(), aidl_radio_mode_info2);
+ EXPECT_EQ(WifiBand::BAND_24GHZ, aidl_radio_mode_info2->bandInfo);
+ ASSERT_EQ(1u, aidl_radio_mode_info2->ifaceInfos.size());
+ auto aidl_iface_info2 = aidl_radio_mode_info2->ifaceInfos[0];
+ EXPECT_EQ(legacy_iface_info2.name, aidl_iface_info2.name);
+ EXPECT_EQ(static_cast<int32_t>(legacy_iface_info2.channel), aidl_iface_info2.channel);
}
-TEST_F(HidlStructUtilTest, canConvertLegacyLinkLayerStatsToHidl) {
+TEST_F(AidlStructUtilTest, canConvertLegacyLinkLayerStatsToAidl) {
legacy_hal::LinkLayerStats legacy_stats{};
legacy_stats.radios.push_back(legacy_hal::LinkLayerRadioStats{});
legacy_stats.radios.push_back(legacy_hal::LinkLayerRadioStats{});
@@ -216,77 +213,77 @@
peer.rate_stats.push_back(rate_stat2);
}
- V1_6::StaLinkLayerStats converted{};
- hidl_struct_util::convertLegacyLinkLayerStatsToHidl(legacy_stats, &converted);
- EXPECT_EQ(legacy_stats.iface.beacon_rx, converted.iface.V1_0.beaconRx);
- EXPECT_EQ(legacy_stats.iface.rssi_mgmt, converted.iface.V1_0.avgRssiMgmt);
+ StaLinkLayerStats converted{};
+ aidl_struct_util::convertLegacyLinkLayerStatsToAidl(legacy_stats, &converted);
+ EXPECT_EQ(legacy_stats.iface.beacon_rx, (uint32_t)converted.iface.beaconRx);
+ EXPECT_EQ(legacy_stats.iface.rssi_mgmt, converted.iface.avgRssiMgmt);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].rx_mpdu,
- converted.iface.V1_0.wmeBePktStats.rxMpdu);
+ converted.iface.wmeBePktStats.rxMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].tx_mpdu,
- converted.iface.V1_0.wmeBePktStats.txMpdu);
+ converted.iface.wmeBePktStats.txMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].mpdu_lost,
- converted.iface.V1_0.wmeBePktStats.lostMpdu);
+ converted.iface.wmeBePktStats.lostMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].retries,
- converted.iface.V1_0.wmeBePktStats.retries);
+ converted.iface.wmeBePktStats.retries);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_min,
- converted.iface.wmeBeContentionTimeStats.contentionTimeMinInUsec);
+ (uint32_t)converted.iface.wmeBeContentionTimeStats.contentionTimeMinInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_max,
- converted.iface.wmeBeContentionTimeStats.contentionTimeMaxInUsec);
+ (uint32_t)converted.iface.wmeBeContentionTimeStats.contentionTimeMaxInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_time_avg,
- converted.iface.wmeBeContentionTimeStats.contentionTimeAvgInUsec);
+ (uint32_t)converted.iface.wmeBeContentionTimeStats.contentionTimeAvgInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BE].contention_num_samples,
- converted.iface.wmeBeContentionTimeStats.contentionNumSamples);
+ (uint32_t)converted.iface.wmeBeContentionTimeStats.contentionNumSamples);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].rx_mpdu,
- converted.iface.V1_0.wmeBkPktStats.rxMpdu);
+ converted.iface.wmeBkPktStats.rxMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].tx_mpdu,
- converted.iface.V1_0.wmeBkPktStats.txMpdu);
+ converted.iface.wmeBkPktStats.txMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].mpdu_lost,
- converted.iface.V1_0.wmeBkPktStats.lostMpdu);
+ converted.iface.wmeBkPktStats.lostMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].retries,
- converted.iface.V1_0.wmeBkPktStats.retries);
+ converted.iface.wmeBkPktStats.retries);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_min,
- converted.iface.wmeBkContentionTimeStats.contentionTimeMinInUsec);
+ (uint32_t)converted.iface.wmeBkContentionTimeStats.contentionTimeMinInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_max,
- converted.iface.wmeBkContentionTimeStats.contentionTimeMaxInUsec);
+ (uint32_t)converted.iface.wmeBkContentionTimeStats.contentionTimeMaxInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_time_avg,
- converted.iface.wmeBkContentionTimeStats.contentionTimeAvgInUsec);
+ (uint32_t)converted.iface.wmeBkContentionTimeStats.contentionTimeAvgInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_BK].contention_num_samples,
- converted.iface.wmeBkContentionTimeStats.contentionNumSamples);
+ (uint32_t)converted.iface.wmeBkContentionTimeStats.contentionNumSamples);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].rx_mpdu,
- converted.iface.V1_0.wmeViPktStats.rxMpdu);
+ converted.iface.wmeViPktStats.rxMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].tx_mpdu,
- converted.iface.V1_0.wmeViPktStats.txMpdu);
+ converted.iface.wmeViPktStats.txMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].mpdu_lost,
- converted.iface.V1_0.wmeViPktStats.lostMpdu);
+ converted.iface.wmeViPktStats.lostMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].retries,
- converted.iface.V1_0.wmeViPktStats.retries);
+ converted.iface.wmeViPktStats.retries);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_min,
- converted.iface.wmeViContentionTimeStats.contentionTimeMinInUsec);
+ (uint32_t)converted.iface.wmeViContentionTimeStats.contentionTimeMinInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_max,
- converted.iface.wmeViContentionTimeStats.contentionTimeMaxInUsec);
+ (uint32_t)converted.iface.wmeViContentionTimeStats.contentionTimeMaxInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_time_avg,
- converted.iface.wmeViContentionTimeStats.contentionTimeAvgInUsec);
+ (uint32_t)converted.iface.wmeViContentionTimeStats.contentionTimeAvgInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VI].contention_num_samples,
- converted.iface.wmeViContentionTimeStats.contentionNumSamples);
+ (uint32_t)converted.iface.wmeViContentionTimeStats.contentionNumSamples);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].rx_mpdu,
- converted.iface.V1_0.wmeVoPktStats.rxMpdu);
+ converted.iface.wmeVoPktStats.rxMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].tx_mpdu,
- converted.iface.V1_0.wmeVoPktStats.txMpdu);
+ converted.iface.wmeVoPktStats.txMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].mpdu_lost,
- converted.iface.V1_0.wmeVoPktStats.lostMpdu);
+ converted.iface.wmeVoPktStats.lostMpdu);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].retries,
- converted.iface.V1_0.wmeVoPktStats.retries);
+ converted.iface.wmeVoPktStats.retries);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_min,
- converted.iface.wmeVoContentionTimeStats.contentionTimeMinInUsec);
+ (uint32_t)converted.iface.wmeVoContentionTimeStats.contentionTimeMinInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_max,
- converted.iface.wmeVoContentionTimeStats.contentionTimeMaxInUsec);
+ (uint32_t)converted.iface.wmeVoContentionTimeStats.contentionTimeMaxInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_time_avg,
- converted.iface.wmeVoContentionTimeStats.contentionTimeAvgInUsec);
+ (uint32_t)converted.iface.wmeVoContentionTimeStats.contentionTimeAvgInUsec);
EXPECT_EQ(legacy_stats.iface.ac[legacy_hal::WIFI_AC_VO].contention_num_samples,
- converted.iface.wmeVoContentionTimeStats.contentionNumSamples);
+ (uint32_t)converted.iface.wmeVoContentionTimeStats.contentionNumSamples);
EXPECT_EQ(legacy_stats.iface.info.time_slicing_duty_cycle_percent,
converted.iface.timeSliceDutyCycleInPercent);
@@ -294,42 +291,43 @@
EXPECT_EQ(legacy_stats.radios.size(), converted.radios.size());
for (size_t i = 0; i < legacy_stats.radios.size(); i++) {
EXPECT_EQ(legacy_stats.radios[i].stats.radio, converted.radios[i].radioId);
- EXPECT_EQ(legacy_stats.radios[i].stats.on_time, converted.radios[i].V1_0.onTimeInMs);
- EXPECT_EQ(legacy_stats.radios[i].stats.tx_time, converted.radios[i].V1_0.txTimeInMs);
- EXPECT_EQ(legacy_stats.radios[i].stats.rx_time, converted.radios[i].V1_0.rxTimeInMs);
+ EXPECT_EQ(legacy_stats.radios[i].stats.on_time, (uint32_t)converted.radios[i].onTimeInMs);
+ EXPECT_EQ(legacy_stats.radios[i].stats.tx_time, (uint32_t)converted.radios[i].txTimeInMs);
+ EXPECT_EQ(legacy_stats.radios[i].stats.rx_time, (uint32_t)converted.radios[i].rxTimeInMs);
EXPECT_EQ(legacy_stats.radios[i].stats.on_time_scan,
- converted.radios[i].V1_0.onTimeInMsForScan);
+ (uint32_t)converted.radios[i].onTimeInMsForScan);
EXPECT_EQ(legacy_stats.radios[i].tx_time_per_levels.size(),
- converted.radios[i].V1_0.txTimeInMsPerLevel.size());
+ converted.radios[i].txTimeInMsPerLevel.size());
for (size_t j = 0; j < legacy_stats.radios[i].tx_time_per_levels.size(); j++) {
EXPECT_EQ(legacy_stats.radios[i].tx_time_per_levels[j],
- converted.radios[i].V1_0.txTimeInMsPerLevel[j]);
+ (uint32_t)converted.radios[i].txTimeInMsPerLevel[j]);
}
EXPECT_EQ(legacy_stats.radios[i].stats.on_time_nbd,
- converted.radios[i].onTimeInMsForNanScan);
+ (uint32_t)converted.radios[i].onTimeInMsForNanScan);
EXPECT_EQ(legacy_stats.radios[i].stats.on_time_gscan,
- converted.radios[i].onTimeInMsForBgScan);
+ (uint32_t)converted.radios[i].onTimeInMsForBgScan);
EXPECT_EQ(legacy_stats.radios[i].stats.on_time_roam_scan,
- converted.radios[i].onTimeInMsForRoamScan);
+ (uint32_t)converted.radios[i].onTimeInMsForRoamScan);
EXPECT_EQ(legacy_stats.radios[i].stats.on_time_pno_scan,
- converted.radios[i].onTimeInMsForPnoScan);
+ (uint32_t)converted.radios[i].onTimeInMsForPnoScan);
EXPECT_EQ(legacy_stats.radios[i].stats.on_time_hs20,
- converted.radios[i].onTimeInMsForHs20Scan);
+ (uint32_t)converted.radios[i].onTimeInMsForHs20Scan);
EXPECT_EQ(legacy_stats.radios[i].channel_stats.size(),
converted.radios[i].channelStats.size());
for (size_t k = 0; k < legacy_stats.radios[i].channel_stats.size(); k++) {
auto& legacy_channel_st = legacy_stats.radios[i].channel_stats[k];
EXPECT_EQ(WifiChannelWidthInMhz::WIDTH_20,
converted.radios[i].channelStats[k].channel.width);
- EXPECT_EQ(WifiChannelInMhz(legacy_channel_st.channel.center_freq),
+ EXPECT_EQ(legacy_channel_st.channel.center_freq,
converted.radios[i].channelStats[k].channel.centerFreq);
- EXPECT_EQ(WifiChannelInMhz(legacy_channel_st.channel.center_freq0),
+ EXPECT_EQ(legacy_channel_st.channel.center_freq0,
converted.radios[i].channelStats[k].channel.centerFreq0);
- EXPECT_EQ(WifiChannelInMhz(legacy_channel_st.channel.center_freq1),
+ EXPECT_EQ(legacy_channel_st.channel.center_freq1,
converted.radios[i].channelStats[k].channel.centerFreq1);
EXPECT_EQ(legacy_channel_st.cca_busy_time,
- converted.radios[i].channelStats[k].ccaBusyTimeInMs);
- EXPECT_EQ(legacy_channel_st.on_time, converted.radios[i].channelStats[k].onTimeInMs);
+ (uint32_t)converted.radios[i].channelStats[k].ccaBusyTimeInMs);
+ EXPECT_EQ(legacy_channel_st.on_time,
+ (uint32_t)converted.radios[i].channelStats[k].onTimeInMs);
}
}
@@ -347,35 +345,36 @@
EXPECT_EQ(legacy_stats.peers[i].rate_stats[j].rate.bw,
(uint32_t)converted.iface.peers[i].rateStats[j].rateInfo.bw);
EXPECT_EQ(legacy_stats.peers[i].rate_stats[j].rate.rateMcsIdx,
- converted.iface.peers[i].rateStats[j].rateInfo.rateMcsIdx);
+ (uint32_t)converted.iface.peers[i].rateStats[j].rateInfo.rateMcsIdx);
EXPECT_EQ(legacy_stats.peers[i].rate_stats[j].tx_mpdu,
- converted.iface.peers[i].rateStats[j].txMpdu);
+ (uint32_t)converted.iface.peers[i].rateStats[j].txMpdu);
EXPECT_EQ(legacy_stats.peers[i].rate_stats[j].rx_mpdu,
- converted.iface.peers[i].rateStats[j].rxMpdu);
+ (uint32_t)converted.iface.peers[i].rateStats[j].rxMpdu);
EXPECT_EQ(legacy_stats.peers[i].rate_stats[j].mpdu_lost,
- converted.iface.peers[i].rateStats[j].mpduLost);
+ (uint32_t)converted.iface.peers[i].rateStats[j].mpduLost);
EXPECT_EQ(legacy_stats.peers[i].rate_stats[j].retries,
- converted.iface.peers[i].rateStats[j].retries);
+ (uint32_t)converted.iface.peers[i].rateStats[j].retries);
}
}
}
-TEST_F(HidlStructUtilTest, CanConvertLegacyFeaturesToHidl) {
- using HidlChipCaps = V1_3::IWifiChip::ChipCapabilityMask;
+TEST_F(AidlStructUtilTest, CanConvertLegacyFeaturesToAidl) {
+ using AidlChipCaps = IWifiChip::ChipCapabilityMask;
- uint32_t hidle_caps;
+ uint32_t aidl_caps;
uint32_t legacy_feature_set = WIFI_FEATURE_D2D_RTT | WIFI_FEATURE_SET_LATENCY_MODE;
uint32_t legacy_logger_feature_set = legacy_hal::WIFI_LOGGER_DRIVER_DUMP_SUPPORTED;
- ASSERT_TRUE(hidl_struct_util::convertLegacyFeaturesToHidlChipCapabilities(
- legacy_feature_set, legacy_logger_feature_set, &hidle_caps));
+ ASSERT_TRUE(aidl_struct_util::convertLegacyFeaturesToAidlChipCapabilities(
+ legacy_feature_set, legacy_logger_feature_set, &aidl_caps));
- EXPECT_EQ(HidlChipCaps::DEBUG_RING_BUFFER_VENDOR_DATA |
- HidlChipCaps::DEBUG_HOST_WAKE_REASON_STATS |
- HidlChipCaps::DEBUG_ERROR_ALERTS | HidlChipCaps::D2D_RTT |
- HidlChipCaps::SET_LATENCY_MODE | HidlChipCaps::DEBUG_MEMORY_DRIVER_DUMP,
- hidle_caps);
+ EXPECT_EQ((uint32_t)AidlChipCaps::DEBUG_RING_BUFFER_VENDOR_DATA |
+ (uint32_t)AidlChipCaps::DEBUG_HOST_WAKE_REASON_STATS |
+ (uint32_t)AidlChipCaps::DEBUG_ERROR_ALERTS | (uint32_t)AidlChipCaps::D2D_RTT |
+ (uint32_t)AidlChipCaps::SET_LATENCY_MODE |
+ (uint32_t)AidlChipCaps::DEBUG_MEMORY_DRIVER_DUMP,
+ aidl_caps);
}
void insertRadioCombination(legacy_hal::wifi_radio_combination* dst_radio_combination_ptr,
@@ -390,16 +389,16 @@
legacy_hal::wifi_radio_configuration* radio_configuration) {
EXPECT_EQ(num_radio_configurations, radioCombination->radioConfigurations.size());
for (size_t i = 0; i < num_radio_configurations; i++) {
- EXPECT_EQ(hidl_struct_util::convertLegacyMacBandToHidlWifiBand(radio_configuration->band),
+ EXPECT_EQ(aidl_struct_util::convertLegacyMacBandToAidlWifiBand(radio_configuration->band),
radioCombination->radioConfigurations[i].bandInfo);
- EXPECT_EQ(hidl_struct_util::convertLegacyAntennaConfigurationToHidl(
+ EXPECT_EQ(aidl_struct_util::convertLegacyAntennaConfigurationToAidl(
radio_configuration->antenna_cfg),
radioCombination->radioConfigurations[i].antennaMode);
radio_configuration++;
}
}
-TEST_F(HidlStructUtilTest, canConvertLegacyRadioCombinationsMatrixToHidl) {
+TEST_F(AidlStructUtilTest, canConvertLegacyRadioCombinationsMatrixToAidl) {
legacy_hal::wifi_radio_configuration radio_configurations_array1[] = {
{.band = legacy_hal::WLAN_MAC_2_4_BAND, .antenna_cfg = legacy_hal::WIFI_ANTENNA_1X1},
};
@@ -461,8 +460,8 @@
sizeof(radio_configurations_array3) / sizeof(radio_configurations_array3[0]),
radio_configurations_array3);
- V1_6::WifiRadioCombinationMatrix converted_matrix{};
- hidl_struct_util::convertLegacyRadioCombinationsMatrixToHidl(legacy_matrix, &converted_matrix);
+ WifiRadioCombinationMatrix converted_matrix{};
+ aidl_struct_util::convertLegacyRadioCombinationsMatrixToAidl(legacy_matrix, &converted_matrix);
// Verify the conversion
EXPECT_EQ(legacy_matrix->num_radio_combinations, converted_matrix.radioCombinations.size());
@@ -479,8 +478,8 @@
sizeof(radio_configurations_array3) / sizeof(radio_configurations_array3[0]),
radio_configurations_array3);
}
-} // namespace implementation
-} // namespace V1_6
+
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/main.cpp b/wifi/aidl/default/tests/main.cpp
similarity index 94%
rename from wifi/1.6/default/tests/main.cpp
rename to wifi/aidl/default/tests/main.cpp
index 9aac837..767422c 100644
--- a/wifi/1.6/default/tests/main.cpp
+++ b/wifi/aidl/default/tests/main.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
diff --git a/wifi/1.6/default/tests/mock_interface_tool.cpp b/wifi/aidl/default/tests/mock_interface_tool.cpp
similarity index 86%
rename from wifi/1.6/default/tests/mock_interface_tool.cpp
rename to wifi/aidl/default/tests/mock_interface_tool.cpp
index b99a164..79f3d1e 100644
--- a/wifi/1.6/default/tests/mock_interface_tool.cpp
+++ b/wifi/aidl/default/tests/mock_interface_tool.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
#include <android-base/macros.h>
#include <gmock/gmock.h>
-#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
#include "mock_interface_tool.h"
namespace android {
diff --git a/wifi/1.6/default/tests/mock_interface_tool.h b/wifi/aidl/default/tests/mock_interface_tool.h
similarity index 95%
rename from wifi/1.6/default/tests/mock_interface_tool.h
rename to wifi/aidl/default/tests/mock_interface_tool.h
index 7ce3992..9795de8 100644
--- a/wifi/1.6/default/tests/mock_interface_tool.h
+++ b/wifi/aidl/default/tests/mock_interface_tool.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
diff --git a/wifi/1.6/default/tests/mock_wifi_feature_flags.cpp b/wifi/aidl/default/tests/mock_wifi_feature_flags.cpp
similarity index 85%
rename from wifi/1.6/default/tests/mock_wifi_feature_flags.cpp
rename to wifi/aidl/default/tests/mock_wifi_feature_flags.cpp
index d10b74c..0c4e59d 100644
--- a/wifi/1.6/default/tests/mock_wifi_feature_flags.cpp
+++ b/wifi/aidl/default/tests/mock_wifi_feature_flags.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,18 +18,16 @@
#include "mock_wifi_feature_flags.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace feature_flags {
MockWifiFeatureFlags::MockWifiFeatureFlags() {}
} // namespace feature_flags
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/mock_wifi_feature_flags.h b/wifi/aidl/default/tests/mock_wifi_feature_flags.h
similarity index 77%
rename from wifi/1.6/default/tests/mock_wifi_feature_flags.h
rename to wifi/aidl/default/tests/mock_wifi_feature_flags.h
index fbe1f7a..9143d15 100644
--- a/wifi/1.6/default/tests/mock_wifi_feature_flags.h
+++ b/wifi/aidl/default/tests/mock_wifi_feature_flags.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,30 +18,27 @@
#define MOCK_WIFI_FEATURE_FLAGS_H_
#include <gmock/gmock.h>
-#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
#include "wifi_feature_flags.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace feature_flags {
class MockWifiFeatureFlags : public WifiFeatureFlags {
public:
MockWifiFeatureFlags();
- MOCK_METHOD1(getChipModes, std::vector<V1_6::IWifiChip::ChipMode>(bool is_primary));
+ MOCK_METHOD1(getChipModes, std::vector<IWifiChip::ChipMode>(bool is_primary));
MOCK_METHOD0(isApMacRandomizationDisabled, bool());
};
} // namespace feature_flags
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // MOCK_WIFI_FEATURE_FLAGS_H_
diff --git a/wifi/1.6/default/tests/mock_wifi_iface_util.cpp b/wifi/aidl/default/tests/mock_wifi_iface_util.cpp
similarity index 68%
rename from wifi/1.6/default/tests/mock_wifi_iface_util.cpp
rename to wifi/aidl/default/tests/mock_wifi_iface_util.cpp
index 24b16cb..0f787f2 100644
--- a/wifi/1.6/default/tests/mock_wifi_iface_util.cpp
+++ b/wifi/aidl/default/tests/mock_wifi_iface_util.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,22 +18,21 @@
#include <android-base/macros.h>
#include <gmock/gmock.h>
-#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
#include "mock_wifi_iface_util.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace iface_util {
-MockWifiIfaceUtil::MockWifiIfaceUtil(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
- const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal)
+MockWifiIfaceUtil::MockWifiIfaceUtil(
+ const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal)
: WifiIfaceUtil(iface_tool, legacy_hal) {}
+
} // namespace iface_util
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/mock_wifi_iface_util.h b/wifi/aidl/default/tests/mock_wifi_iface_util.h
similarity index 79%
rename from wifi/1.6/default/tests/mock_wifi_iface_util.h
rename to wifi/aidl/default/tests/mock_wifi_iface_util.h
index 2701c36..49a8636 100644
--- a/wifi/1.6/default/tests/mock_wifi_iface_util.h
+++ b/wifi/aidl/default/tests/mock_wifi_iface_util.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,30 +21,30 @@
#include "wifi_iface_util.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace iface_util {
-class MockWifiIfaceUtil : public WifiIfaceUtil {
+class MockWifiIfaceUtil : public iface_util::WifiIfaceUtil {
public:
- MockWifiIfaceUtil(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
+ MockWifiIfaceUtil(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal);
MOCK_METHOD1(getFactoryMacAddress, std::array<uint8_t, 6>(const std::string&));
MOCK_METHOD2(setMacAddress, bool(const std::string&, const std::array<uint8_t, 6>&));
MOCK_METHOD0(getOrCreateRandomMacAddress, std::array<uint8_t, 6>());
- MOCK_METHOD2(registerIfaceEventHandlers, void(const std::string&, IfaceEventHandlers));
+ MOCK_METHOD2(registerIfaceEventHandlers,
+ void(const std::string&, iface_util::IfaceEventHandlers));
MOCK_METHOD1(unregisterIfaceEventHandlers, void(const std::string&));
MOCK_METHOD2(setUpState, bool(const std::string&, bool));
MOCK_METHOD1(ifNameToIndex, unsigned(const std::string&));
};
+
} // namespace iface_util
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // MOCK_WIFI_IFACE_UTIL_H_
diff --git a/wifi/1.6/default/tests/mock_wifi_legacy_hal.cpp b/wifi/aidl/default/tests/mock_wifi_legacy_hal.cpp
similarity index 69%
rename from wifi/1.6/default/tests/mock_wifi_legacy_hal.cpp
rename to wifi/aidl/default/tests/mock_wifi_legacy_hal.cpp
index 2c55861..33b2b1c 100644
--- a/wifi/1.6/default/tests/mock_wifi_legacy_hal.cpp
+++ b/wifi/aidl/default/tests/mock_wifi_legacy_hal.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,22 +18,20 @@
#include <android-base/macros.h>
#include <gmock/gmock.h>
-#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
#include "mock_wifi_legacy_hal.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace legacy_hal {
-MockWifiLegacyHal::MockWifiLegacyHal(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
- const wifi_hal_fn& fn, bool is_primary)
+MockWifiLegacyHal::MockWifiLegacyHal(
+ const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
+ const wifi_hal_fn& fn, bool is_primary)
: WifiLegacyHal(iface_tool, fn, is_primary) {}
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/mock_wifi_legacy_hal.h b/wifi/aidl/default/tests/mock_wifi_legacy_hal.h
similarity index 92%
rename from wifi/1.6/default/tests/mock_wifi_legacy_hal.h
rename to wifi/aidl/default/tests/mock_wifi_legacy_hal.h
index 85dbf0f..28129a9 100644
--- a/wifi/1.6/default/tests/mock_wifi_legacy_hal.h
+++ b/wifi/aidl/default/tests/mock_wifi_legacy_hal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,16 +21,15 @@
#include "wifi_legacy_hal.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace legacy_hal {
class MockWifiLegacyHal : public WifiLegacyHal {
public:
- MockWifiLegacyHal(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
+ MockWifiLegacyHal(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
const wifi_hal_fn& fn, bool is_primary);
MOCK_METHOD0(initialize, wifi_error());
MOCK_METHOD0(start, wifi_error());
@@ -62,10 +61,9 @@
MOCK_METHOD1(getSupportedFeatureSet, std::pair<wifi_error, uint64_t>(const std::string&));
};
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // MOCK_WIFI_LEGACY_HAL_H_
diff --git a/wifi/1.6/default/tests/mock_wifi_mode_controller.cpp b/wifi/aidl/default/tests/mock_wifi_mode_controller.cpp
similarity index 87%
rename from wifi/1.6/default/tests/mock_wifi_mode_controller.cpp
rename to wifi/aidl/default/tests/mock_wifi_mode_controller.cpp
index 446f829..f4cc4c4 100644
--- a/wifi/1.6/default/tests/mock_wifi_mode_controller.cpp
+++ b/wifi/aidl/default/tests/mock_wifi_mode_controller.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,17 +21,16 @@
#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
#include "mock_wifi_mode_controller.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace mode_controller {
MockWifiModeController::MockWifiModeController() : WifiModeController() {}
+
} // namespace mode_controller
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/mock_wifi_mode_controller.h b/wifi/aidl/default/tests/mock_wifi_mode_controller.h
similarity index 88%
rename from wifi/1.6/default/tests/mock_wifi_mode_controller.h
rename to wifi/aidl/default/tests/mock_wifi_mode_controller.h
index addcc81..f77f7d0 100644
--- a/wifi/1.6/default/tests/mock_wifi_mode_controller.h
+++ b/wifi/aidl/default/tests/mock_wifi_mode_controller.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,11 +21,10 @@
#include "wifi_mode_controller.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace mode_controller {
class MockWifiModeController : public WifiModeController {
@@ -37,10 +36,9 @@
MOCK_METHOD0(deinitialize, bool());
};
} // namespace mode_controller
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // MOCK_WIFI_MODE_CONTROLLER_H_
diff --git a/wifi/1.6/default/tests/ringbuffer_unit_tests.cpp b/wifi/aidl/default/tests/ringbuffer_unit_tests.cpp
similarity index 94%
rename from wifi/1.6/default/tests/ringbuffer_unit_tests.cpp
rename to wifi/aidl/default/tests/ringbuffer_unit_tests.cpp
index eb86194..c257100 100644
--- a/wifi/1.6/default/tests/ringbuffer_unit_tests.cpp
+++ b/wifi/aidl/default/tests/ringbuffer_unit_tests.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018, The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,11 +21,10 @@
using testing::Return;
using testing::Test;
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
class RingbufferTest : public Test {
public:
@@ -90,8 +89,8 @@
ASSERT_EQ(1u, buffer_.getData().size());
EXPECT_EQ(input, buffer_.getData().front());
}
-} // namespace implementation
-} // namespace V1_6
+
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/runtests.sh b/wifi/aidl/default/tests/runtests.sh
similarity index 79%
rename from wifi/1.6/default/tests/runtests.sh
rename to wifi/aidl/default/tests/runtests.sh
index 6bce3ef..1f53ab8 100755
--- a/wifi/1.6/default/tests/runtests.sh
+++ b/wifi/aidl/default/tests/runtests.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
-# Copyright(C) 2017 The Android Open Source Project
+# Copyright(C) 2022 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0(the "License");
# you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@
fi
set -e
-$ANDROID_BUILD_TOP/build/soong/soong_ui.bash --make-mode android.hardware.wifi@1.0-service-tests
+$ANDROID_BUILD_TOP/build/soong/soong_ui.bash --make-mode android.hardware.wifi-service-tests
adb root
adb sync data
-adb shell /data/nativetest64/vendor/android.hardware.wifi@1.0-service-tests/android.hardware.wifi@1.0-service-tests
+adb shell /data/nativetest64/vendor/android.hardware.wifi-service-tests/android.hardware.wifi-service-tests
diff --git a/wifi/1.6/default/tests/wifi_chip_unit_tests.cpp b/wifi/aidl/default/tests/wifi_chip_unit_tests.cpp
similarity index 66%
rename from wifi/1.6/default/tests/wifi_chip_unit_tests.cpp
rename to wifi/aidl/default/tests/wifi_chip_unit_tests.cpp
index 81117c5..e66b650 100644
--- a/wifi/1.6/default/tests/wifi_chip_unit_tests.cpp
+++ b/wifi/aidl/default/tests/wifi_chip_unit_tests.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017, The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@
#include <cutils/properties.h>
#include <gmock/gmock.h>
-#undef NAN // This is weird, NAN is defined in bionic/libc/include/math.h:38
#include "wifi_chip.h"
#include "mock_interface_tool.h"
@@ -33,28 +32,38 @@
using testing::Test;
namespace {
-using android::hardware::wifi::V1_0::ChipId;
-
-constexpr ChipId kFakeChipId = 5;
+constexpr int kFakeChipId = 5;
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
class WifiChipTest : public Test {
protected:
void setupV1IfaceCombination() {
// clang-format off
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinationsSta = {
- {{{{IfaceConcurrencyType::STA}, 1}, {{IfaceConcurrencyType::P2P}, 1}}}
+ // 1 STA + 1 P2P
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinationsSta =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 1},
+ {{IfaceConcurrencyType::P2P}, 1}
+ }
+ }
+ };
+ // 1 AP
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinationsAp =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::AP}, 1}
+ }
+ }
};
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinationsAp = {
- {{{{IfaceConcurrencyType::AP}, 1}}}
- };
- const std::vector<V1_6::IWifiChip::ChipMode> modes = {
+ const std::vector<IWifiChip::ChipMode> modes = {
{feature_flags::chip_mode_ids::kV1Sta, combinationsSta},
{feature_flags::chip_mode_ids::kV1Ap, combinationsAp}
};
@@ -64,14 +73,26 @@
void setupV1_AwareIfaceCombination() {
// clang-format off
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinationsSta = {
- {{{{IfaceConcurrencyType::STA}, 1},
- {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN}, 1}}}
+ // 1 STA + 1 of (P2P or NAN)
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinationsSta =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 1},
+ {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN_IFACE}, 1}
+ }
+ }
};
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinationsAp = {
- {{{{IfaceConcurrencyType::AP}, 1}}}
+ // 1 AP
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinationsAp =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::AP}, 1}
+ }
+ }
};
- const std::vector<V1_6::IWifiChip::ChipMode> modes = {
+ const std::vector<IWifiChip::ChipMode> modes = {
{feature_flags::chip_mode_ids::kV1Sta, combinationsSta},
{feature_flags::chip_mode_ids::kV1Ap, combinationsAp}
};
@@ -81,11 +102,17 @@
void setupV1_AwareDisabledApIfaceCombination() {
// clang-format off
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinationsSta = {
- {{{{IfaceConcurrencyType::STA}, 1},
- {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN}, 1}}}
+ // 1 STA + 1 of (P2P or NAN)
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinationsSta =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 1},
+ {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN_IFACE}, 1}
+ }
+ }
};
- const std::vector<V1_6::IWifiChip::ChipMode> modes = {
+ const std::vector<IWifiChip::ChipMode> modes = {
{feature_flags::chip_mode_ids::kV1Sta, combinationsSta}
};
// clang-format on
@@ -94,12 +121,23 @@
void setupV2_AwareIfaceCombination() {
// clang-format off
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinations = {
- {{{{IfaceConcurrencyType::STA}, 1}, {{IfaceConcurrencyType::AP}, 1}}},
- {{{{IfaceConcurrencyType::STA}, 1},
- {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN}, 1}}}
+ // (1 STA + 1 AP) or (1 STA + 1 of (P2P or NAN))
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinations =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 1},
+ {{IfaceConcurrencyType::AP}, 1}
+ }
+ },
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 1},
+ {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN_IFACE}, 1}
+ }
+ }
};
- const std::vector<V1_6::IWifiChip::ChipMode> modes = {
+ const std::vector<IWifiChip::ChipMode> modes = {
{feature_flags::chip_mode_ids::kV3, combinations}
};
// clang-format on
@@ -108,11 +146,17 @@
void setupV2_AwareDisabledApIfaceCombination() {
// clang-format off
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinations = {
- {{{{IfaceConcurrencyType::STA}, 1},
- {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN}, 1}}}
+ // 1 STA + 1 of (P2P or NAN)
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinations =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 1},
+ {{IfaceConcurrencyType::P2P, IfaceConcurrencyType::NAN_IFACE}, 1}
+ }
+ }
};
- const std::vector<V1_6::IWifiChip::ChipMode> modes = {
+ const std::vector<IWifiChip::ChipMode> modes = {
{feature_flags::chip_mode_ids::kV3, combinations}
};
// clang-format on
@@ -121,10 +165,17 @@
void setup_MultiIfaceCombination() {
// clang-format off
- const hidl_vec<IWifiChip::ChipConcurrencyCombination> combinations = {
- {{{{IfaceConcurrencyType::STA}, 3}, {{IfaceConcurrencyType::AP}, 1}}}
+ // 3 STA + 1 AP
+ const std::vector<IWifiChip::ChipConcurrencyCombination> combinations =
+ {
+ {
+ {
+ {{IfaceConcurrencyType::STA}, 3},
+ {{IfaceConcurrencyType::AP}, 1}
+ }
+ }
};
- const std::vector<V1_6::IWifiChip::ChipMode> modes = {
+ const std::vector<IWifiChip::ChipMode> modes = {
{feature_flags::chip_mode_ids::kV3, combinations}
};
// clang-format on
@@ -132,134 +183,93 @@
}
void assertNumberOfModes(uint32_t num_modes) {
- chip_->getAvailableModes_1_6([num_modes](const WifiStatus& status,
- const std::vector<WifiChip::ChipMode>& modes) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- // V2_Aware has 1 mode of operation.
- ASSERT_EQ(num_modes, modes.size());
- });
+ std::vector<IWifiChip::ChipMode> modes;
+ ASSERT_TRUE(chip_->getAvailableModes(&modes).isOk());
+ // V2_Aware has 1 mode of operation.
+ ASSERT_EQ(num_modes, modes.size());
}
void findModeAndConfigureForIfaceType(const IfaceConcurrencyType& type) {
- // This should be aligned with kInvalidModeId in wifi_chip.cpp.
- ChipModeId mode_id = UINT32_MAX;
- chip_->getAvailableModes_1_6([&mode_id, &type](
- const WifiStatus& status,
- const std::vector<WifiChip::ChipMode>& modes) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- for (const auto& mode : modes) {
- for (const auto& combination : mode.availableCombinations) {
- for (const auto& limit : combination.limits) {
- if (limit.types.end() !=
- std::find(limit.types.begin(), limit.types.end(), type)) {
- mode_id = mode.id;
- }
+ // This should be aligned with kInvalidModeId in wifi_chip.cpp
+ int32_t mode_id = INT32_MAX;
+ std::vector<IWifiChip::ChipMode> modes;
+ ASSERT_TRUE(chip_->getAvailableModes(&modes).isOk());
+
+ for (const auto& mode : modes) {
+ for (const auto& combination : mode.availableCombinations) {
+ for (const auto& limit : combination.limits) {
+ if (limit.types.end() !=
+ std::find(limit.types.begin(), limit.types.end(), type)) {
+ mode_id = mode.id;
}
}
}
- });
- ASSERT_NE(UINT32_MAX, mode_id);
+ }
- chip_->configureChip(mode_id, [](const WifiStatus& status) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- });
+ ASSERT_NE(INT32_MAX, mode_id);
+ ASSERT_TRUE(chip_->configureChip(mode_id).isOk());
}
// Returns an empty string on error.
std::string createIface(const IfaceType& type) {
std::string iface_name;
if (type == IfaceType::AP) {
- chip_->createApIface(
- [&iface_name](const WifiStatus& status, const sp<V1_0::IWifiApIface>& iface) {
- if (WifiStatusCode::SUCCESS == status.code) {
- ASSERT_NE(iface.get(), nullptr);
- iface->getName([&iface_name](const WifiStatus& status,
- const hidl_string& name) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- iface_name = name.c_str();
- });
- }
- });
- } else if (type == IfaceType::NAN) {
- chip_->createNanIface(
- [&iface_name](const WifiStatus& status,
- const sp<android::hardware::wifi::V1_0::IWifiNanIface>& iface) {
- if (WifiStatusCode::SUCCESS == status.code) {
- ASSERT_NE(iface.get(), nullptr);
- iface->getName([&iface_name](const WifiStatus& status,
- const hidl_string& name) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- iface_name = name.c_str();
- });
- }
- });
+ std::shared_ptr<IWifiApIface> iface;
+ if (!chip_->createApIface(&iface).isOk()) {
+ return "";
+ }
+ EXPECT_NE(iface.get(), nullptr);
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
+ } else if (type == IfaceType::NAN_IFACE) {
+ std::shared_ptr<IWifiNanIface> iface;
+ if (!chip_->createNanIface(&iface).isOk()) {
+ return "";
+ }
+ EXPECT_NE(iface.get(), nullptr);
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
} else if (type == IfaceType::P2P) {
- chip_->createP2pIface(
- [&iface_name](const WifiStatus& status, const sp<IWifiP2pIface>& iface) {
- if (WifiStatusCode::SUCCESS == status.code) {
- ASSERT_NE(iface.get(), nullptr);
- iface->getName([&iface_name](const WifiStatus& status,
- const hidl_string& name) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- iface_name = name.c_str();
- });
- }
- });
+ std::shared_ptr<IWifiP2pIface> iface;
+ if (!chip_->createP2pIface(&iface).isOk()) {
+ return "";
+ }
+ EXPECT_NE(iface.get(), nullptr);
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
} else if (type == IfaceType::STA) {
- chip_->createStaIface(
- [&iface_name](const WifiStatus& status, const sp<V1_0::IWifiStaIface>& iface) {
- if (WifiStatusCode::SUCCESS == status.code) {
- ASSERT_NE(iface.get(), nullptr);
- iface->getName([&iface_name](const WifiStatus& status,
- const hidl_string& name) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- iface_name = name.c_str();
- });
- }
- });
+ std::shared_ptr<IWifiStaIface> iface;
+ if (!chip_->createStaIface(&iface).isOk()) {
+ return "";
+ }
+ EXPECT_NE(iface.get(), nullptr);
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
}
return iface_name;
}
void removeIface(const IfaceType& type, const std::string& iface_name) {
if (type == IfaceType::AP) {
- chip_->removeApIface(iface_name, [](const WifiStatus& status) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- });
- } else if (type == IfaceType::NAN) {
- chip_->removeNanIface(iface_name, [](const WifiStatus& status) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- });
+ ASSERT_TRUE(chip_->removeApIface(iface_name).isOk());
+ } else if (type == IfaceType::NAN_IFACE) {
+ ASSERT_TRUE(chip_->removeNanIface(iface_name).isOk());
} else if (type == IfaceType::P2P) {
- chip_->removeP2pIface(iface_name, [](const WifiStatus& status) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- });
+ ASSERT_TRUE(chip_->removeP2pIface(iface_name).isOk());
} else if (type == IfaceType::STA) {
- chip_->removeStaIface(iface_name, [](const WifiStatus& status) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- });
+ ASSERT_TRUE(chip_->removeStaIface(iface_name).isOk());
}
}
bool createRttController() {
- bool success = false;
- chip_->createRttController_1_6(
- NULL, [&success](const WifiStatus& status, const sp<IWifiRttController>& rtt) {
- if (WifiStatusCode::SUCCESS == status.code) {
- ASSERT_NE(rtt.get(), nullptr);
- success = true;
- }
- });
- return success;
+ std::shared_ptr<IWifiRttController> rtt_controller;
+ auto status = chip_->createRttController(nullptr, &rtt_controller);
+ return status.isOk();
}
static void subsystemRestartHandler(const std::string& /*error*/) {}
- sp<WifiChip> chip_;
- ChipId chip_id_ = kFakeChipId;
+ std::shared_ptr<WifiChip> chip_;
+ int chip_id_ = kFakeChipId;
legacy_hal::wifi_hal_fn fake_func_table_;
- std::shared_ptr<NiceMock<wifi_system::MockInterfaceTool>> iface_tool_{
- new NiceMock<wifi_system::MockInterfaceTool>};
+ std::shared_ptr<NiceMock<::android::wifi_system::MockInterfaceTool>> iface_tool_{
+ new NiceMock<::android::wifi_system::MockInterfaceTool>};
std::shared_ptr<NiceMock<legacy_hal::MockWifiLegacyHal>> legacy_hal_{
new NiceMock<legacy_hal::MockWifiLegacyHal>(iface_tool_, fake_func_table_, true)};
std::shared_ptr<NiceMock<mode_controller::MockWifiModeController>> mode_controller_{
@@ -271,8 +281,8 @@
public:
void SetUp() override {
- chip_ = new WifiChip(chip_id_, true, legacy_hal_, mode_controller_, iface_util_,
- feature_flags_, subsystemRestartHandler);
+ chip_ = WifiChip::create(chip_id_, true, legacy_hal_, mode_controller_, iface_util_,
+ feature_flags_, subsystemRestartHandler);
EXPECT_CALL(*mode_controller_, changeFirmwareMode(testing::_))
.WillRepeatedly(testing::Return(true));
@@ -301,7 +311,7 @@
setupV1IfaceCombination();
WifiChipTest::SetUp();
// V1 has 2 modes of operation.
- assertNumberOfModes(2u);
+ assertNumberOfModes(2);
}
};
@@ -317,7 +327,7 @@
TEST_F(WifiChipV1IfaceCombinationTest, StaMode_CreateNan_ShouldFail) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV1IfaceCombinationTest, StaMode_CreateAp_ShouldFail) {
@@ -348,7 +358,7 @@
TEST_F(WifiChipV1IfaceCombinationTest, ApMode_CreateNan_ShouldFail) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::AP);
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
}
////////// V1 + Aware Iface Combinations ////////////
@@ -376,7 +386,7 @@
TEST_F(WifiChipV1_AwareIfaceCombinationTest, StaMode_CreateNan_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV1_AwareIfaceCombinationTest, StaMode_CreateAp_ShouldFail) {
@@ -393,37 +403,37 @@
TEST_F(WifiChipV1_AwareIfaceCombinationTest, StaMode_CreateStaNan_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV1_AwareIfaceCombinationTest, StaMode_CreateStaP2PNan_ShouldFail) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
ASSERT_FALSE(createIface(IfaceType::P2P).empty());
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV1_AwareIfaceCombinationTest, StaMode_CreateStaNan_AfterP2pRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- const auto p2p_iface_name = createIface(IfaceType::P2P);
+ std::string p2p_iface_name = createIface(IfaceType::P2P);
ASSERT_FALSE(p2p_iface_name.empty());
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
// After removing P2P iface, NAN iface creation should succeed.
removeIface(IfaceType::P2P, p2p_iface_name);
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV1_AwareIfaceCombinationTest, StaMode_CreateStaP2p_AfterNanRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- const auto nan_iface_name = createIface(IfaceType::NAN);
+ std::string nan_iface_name = createIface(IfaceType::NAN_IFACE);
ASSERT_FALSE(nan_iface_name.empty());
ASSERT_TRUE(createIface(IfaceType::P2P).empty());
// After removing NAN iface, P2P iface creation should succeed.
- removeIface(IfaceType::NAN, nan_iface_name);
+ removeIface(IfaceType::NAN_IFACE, nan_iface_name);
ASSERT_FALSE(createIface(IfaceType::P2P).empty());
}
@@ -444,7 +454,7 @@
TEST_F(WifiChipV1_AwareIfaceCombinationTest, ApMode_CreateNan_ShouldFail) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::AP);
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV1_AwareIfaceCombinationTest, RttControllerFlowStaModeNoSta) {
@@ -460,7 +470,7 @@
TEST_F(WifiChipV1_AwareIfaceCombinationTest, RttControllerFlowApToSta) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::AP);
- const auto ap_iface_name = createIface(IfaceType::AP);
+ std::string ap_iface_name = createIface(IfaceType::AP);
ASSERT_FALSE(ap_iface_name.empty());
ASSERT_FALSE(createRttController());
@@ -475,9 +485,7 @@
ASSERT_EQ(createIface(IfaceType::STA), "wlan0");
EXPECT_CALL(*legacy_hal_, selectTxPowerScenario("wlan0", testing::_))
.WillOnce(testing::Return(legacy_hal::WIFI_SUCCESS));
- chip_->selectTxPowerScenario_1_2(
- V1_2::IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF,
- [](const WifiStatus& status) { ASSERT_EQ(WifiStatusCode::SUCCESS, status.code); });
+ ASSERT_TRUE(chip_->selectTxPowerScenario(IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF).isOk());
}
TEST_F(WifiChipV1_AwareIfaceCombinationTest, SelectTxScenarioWithOnlyAp) {
@@ -485,9 +493,7 @@
ASSERT_EQ(createIface(IfaceType::AP), "wlan0");
EXPECT_CALL(*legacy_hal_, selectTxPowerScenario("wlan0", testing::_))
.WillOnce(testing::Return(legacy_hal::WIFI_SUCCESS));
- chip_->selectTxPowerScenario_1_2(
- V1_2::IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF,
- [](const WifiStatus& status) { ASSERT_EQ(WifiStatusCode::SUCCESS, status.code); });
+ ASSERT_TRUE(chip_->selectTxPowerScenario(IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF).isOk());
}
////////// V2 + Aware Iface Combinations ////////////
@@ -515,7 +521,7 @@
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateNan_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateAp_ShouldSucceed) {
@@ -543,9 +549,9 @@
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateSta_AfterStaApRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
- const auto sta_iface_name = createIface(IfaceType::STA);
+ std::string sta_iface_name = createIface(IfaceType::STA);
ASSERT_FALSE(sta_iface_name.empty());
- const auto ap_iface_name = createIface(IfaceType::AP);
+ std::string ap_iface_name = createIface(IfaceType::AP);
ASSERT_FALSE(ap_iface_name.empty());
ASSERT_TRUE(createIface(IfaceType::STA).empty());
@@ -565,44 +571,44 @@
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateStaNan_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateStaP2PNan_ShouldFail) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
ASSERT_FALSE(createIface(IfaceType::P2P).empty());
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateStaNan_AfterP2pRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- const auto p2p_iface_name = createIface(IfaceType::P2P);
+ std::string p2p_iface_name = createIface(IfaceType::P2P);
ASSERT_FALSE(p2p_iface_name.empty());
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
// After removing P2P iface, NAN iface creation should succeed.
removeIface(IfaceType::P2P, p2p_iface_name);
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateStaP2p_AfterNanRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- const auto nan_iface_name = createIface(IfaceType::NAN);
+ std::string nan_iface_name = createIface(IfaceType::NAN_IFACE);
ASSERT_FALSE(nan_iface_name.empty());
ASSERT_TRUE(createIface(IfaceType::P2P).empty());
// After removing NAN iface, P2P iface creation should succeed.
- removeIface(IfaceType::NAN, nan_iface_name);
+ removeIface(IfaceType::NAN_IFACE, nan_iface_name);
ASSERT_FALSE(createIface(IfaceType::P2P).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateApNan_ShouldFail) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::AP);
ASSERT_FALSE(createIface(IfaceType::AP).empty());
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateApP2p_ShouldFail) {
@@ -614,31 +620,31 @@
TEST_F(WifiChipV2_AwareIfaceCombinationTest, StaMode_CreateStaNan_AfterP2pRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- const auto p2p_iface_name = createIface(IfaceType::P2P);
+ std::string p2p_iface_name = createIface(IfaceType::P2P);
ASSERT_FALSE(p2p_iface_name.empty());
- ASSERT_TRUE(createIface(IfaceType::NAN).empty());
+ ASSERT_TRUE(createIface(IfaceType::NAN_IFACE).empty());
// After removing P2P iface, NAN iface creation should succeed.
removeIface(IfaceType::P2P, p2p_iface_name);
- ASSERT_FALSE(createIface(IfaceType::NAN).empty());
+ ASSERT_FALSE(createIface(IfaceType::NAN_IFACE).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, StaMode_CreateStaP2p_AfterNanRemove_ShouldSucceed) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_FALSE(createIface(IfaceType::STA).empty());
- const auto nan_iface_name = createIface(IfaceType::NAN);
+ std::string nan_iface_name = createIface(IfaceType::NAN_IFACE);
ASSERT_FALSE(nan_iface_name.empty());
ASSERT_TRUE(createIface(IfaceType::P2P).empty());
// After removing NAN iface, P2P iface creation should succeed.
- removeIface(IfaceType::NAN, nan_iface_name);
+ removeIface(IfaceType::NAN_IFACE, nan_iface_name);
ASSERT_FALSE(createIface(IfaceType::P2P).empty());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateStaAp_EnsureDifferentIfaceNames) {
findModeAndConfigureForIfaceType(IfaceConcurrencyType::AP);
- const auto sta_iface_name = createIface(IfaceType::STA);
- const auto ap_iface_name = createIface(IfaceType::AP);
+ std::string sta_iface_name = createIface(IfaceType::STA);
+ std::string ap_iface_name = createIface(IfaceType::AP);
ASSERT_FALSE(sta_iface_name.empty());
ASSERT_FALSE(ap_iface_name.empty());
ASSERT_NE(sta_iface_name, ap_iface_name);
@@ -667,9 +673,7 @@
ASSERT_EQ(createIface(IfaceType::STA), "wlan0");
EXPECT_CALL(*legacy_hal_, selectTxPowerScenario("wlan0", testing::_))
.WillOnce(testing::Return(legacy_hal::WIFI_SUCCESS));
- chip_->selectTxPowerScenario_1_2(
- V1_2::IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF,
- [](const WifiStatus& status) { ASSERT_EQ(WifiStatusCode::SUCCESS, status.code); });
+ ASSERT_TRUE(chip_->selectTxPowerScenario(IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF).isOk());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, SelectTxScenarioWithOnlyAp) {
@@ -677,9 +681,7 @@
ASSERT_EQ(createIface(IfaceType::AP), "wlan1");
EXPECT_CALL(*legacy_hal_, selectTxPowerScenario("wlan1", testing::_))
.WillOnce(testing::Return(legacy_hal::WIFI_SUCCESS));
- chip_->selectTxPowerScenario_1_2(
- V1_2::IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF,
- [](const WifiStatus& status) { ASSERT_EQ(WifiStatusCode::SUCCESS, status.code); });
+ ASSERT_TRUE(chip_->selectTxPowerScenario(IWifiChip::TxPowerScenario::ON_HEAD_CELL_OFF).isOk());
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, InvalidateAndRemoveNanOnStaRemove) {
@@ -687,35 +689,29 @@
ASSERT_EQ(createIface(IfaceType::STA), "wlan0");
// Create NAN iface
- ASSERT_EQ(createIface(IfaceType::NAN), "wlan0");
+ ASSERT_EQ(createIface(IfaceType::NAN_IFACE), "wlan0");
// We should have 1 nan iface.
- chip_->getNanIfaceNames([](const WifiStatus& status, const hidl_vec<hidl_string>& iface_names) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- ASSERT_EQ(iface_names.size(), 1u);
- ASSERT_EQ(iface_names[0], "wlan0");
- });
- // Retrieve the exact iface object.
- sp<android::hardware::wifi::V1_0::IWifiNanIface> nan_iface;
- chip_->getNanIface("wlan0",
- [&nan_iface](const WifiStatus& status,
- const sp<android::hardware::wifi::V1_0::IWifiNanIface>& iface) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- ASSERT_NE(iface.get(), nullptr);
- nan_iface = iface;
- });
+ std::vector<std::string> iface_names;
+ ASSERT_TRUE(chip_->getNanIfaceNames(&iface_names).isOk());
+ ASSERT_EQ(iface_names.size(), 1u);
+ ASSERT_EQ(iface_names[0], "wlan0");
- // Remove the STA iface.
+ // Retrieve the nan iface object.
+ std::shared_ptr<IWifiNanIface> nan_iface;
+ ASSERT_TRUE(chip_->getNanIface("wlan0", &nan_iface).isOk());
+ ASSERT_NE(nan_iface.get(), nullptr);
+
+ // Remove the STA iface. We should have 0 nan ifaces now.
removeIface(IfaceType::STA, "wlan0");
- // We should have 0 nan iface now.
- chip_->getNanIfaceNames([](const WifiStatus& status, const hidl_vec<hidl_string>& iface_names) {
- ASSERT_EQ(WifiStatusCode::SUCCESS, status.code);
- ASSERT_EQ(iface_names.size(), 0u);
- });
- // Any operation on the nan iface object should return error now.
- nan_iface->getName([](const WifiStatus& status, const std::string& /* iface_name */) {
- ASSERT_EQ(WifiStatusCode::ERROR_WIFI_IFACE_INVALID, status.code);
- });
+ ASSERT_TRUE(chip_->getNanIfaceNames(&iface_names).isOk());
+ ASSERT_EQ(iface_names.size(), 0u);
+
+ // Any operation on the nan iface object should now return an error.
+ std::string name;
+ auto status = nan_iface->getName(&name);
+ ASSERT_EQ(status.getServiceSpecificError(),
+ static_cast<int32_t>(WifiStatusCode::ERROR_WIFI_IFACE_INVALID));
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, InvalidateAndRemoveRttControllerOnStaRemove) {
@@ -723,30 +719,25 @@
ASSERT_EQ(createIface(IfaceType::STA), "wlan0");
// Create RTT controller
- sp<IWifiRttController> rtt_controller;
- chip_->createRttController_1_6(
- NULL, [&rtt_controller](const WifiStatus& status, const sp<IWifiRttController>& rtt) {
- if (WifiStatusCode::SUCCESS == status.code) {
- ASSERT_NE(rtt.get(), nullptr);
- rtt_controller = rtt;
- }
- });
+ std::shared_ptr<IWifiRttController> rtt_controller;
+ ASSERT_TRUE(chip_->createRttController(nullptr, &rtt_controller).isOk());
// Remove the STA iface.
removeIface(IfaceType::STA, "wlan0");
- // Any operation on the rtt controller object should return error now.
- rtt_controller->getBoundIface([](const WifiStatus& status, const sp<IWifiIface>& /* iface */) {
- ASSERT_EQ(WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID, status.code);
- });
+ // Any operation on the rtt controller object should now return an error.
+ std::shared_ptr<IWifiStaIface> bound_iface;
+ auto status = rtt_controller->getBoundIface(&bound_iface);
+ ASSERT_EQ(status.getServiceSpecificError(),
+ static_cast<int32_t>(WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID));
}
TEST_F(WifiChipV2_AwareIfaceCombinationTest, CreateNanWithSharedNanIface) {
property_set("wifi.aware.interface", nullptr);
findModeAndConfigureForIfaceType(IfaceConcurrencyType::STA);
ASSERT_EQ(createIface(IfaceType::STA), "wlan0");
- ASSERT_EQ(createIface(IfaceType::NAN), "wlan0");
- removeIface(IfaceType::NAN, "wlan0");
+ ASSERT_EQ(createIface(IfaceType::NAN_IFACE), "wlan0");
+ removeIface(IfaceType::NAN_IFACE, "wlan0");
EXPECT_CALL(*iface_util_, setUpState(testing::_, testing::_)).Times(0);
}
@@ -756,10 +747,10 @@
ASSERT_EQ(createIface(IfaceType::STA), "wlan0");
EXPECT_CALL(*iface_util_, ifNameToIndex("aware0")).WillOnce(testing::Return(4));
EXPECT_CALL(*iface_util_, setUpState("aware0", true)).WillOnce(testing::Return(true));
- ASSERT_EQ(createIface(IfaceType::NAN), "aware0");
+ ASSERT_EQ(createIface(IfaceType::NAN_IFACE), "aware0");
EXPECT_CALL(*iface_util_, setUpState("aware0", false)).WillOnce(testing::Return(true));
- removeIface(IfaceType::NAN, "aware0");
+ removeIface(IfaceType::NAN_IFACE, "aware0");
}
////////// V1 Iface Combinations when AP creation is disabled //////////
@@ -857,8 +848,8 @@
ASSERT_EQ(createIface(IfaceType::STA), "wlan1");
ASSERT_EQ(createIface(IfaceType::STA), "wlan3");
}
-} // namespace implementation
-} // namespace V1_6
+
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/tests/wifi_iface_util_unit_tests.cpp b/wifi/aidl/default/tests/wifi_iface_util_unit_tests.cpp
similarity index 91%
rename from wifi/1.6/default/tests/wifi_iface_util_unit_tests.cpp
rename to wifi/aidl/default/tests/wifi_iface_util_unit_tests.cpp
index cc9a334..e0db6fd 100644
--- a/wifi/1.6/default/tests/wifi_iface_util_unit_tests.cpp
+++ b/wifi/aidl/default/tests/wifi_iface_util_unit_tests.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019, The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@
#include <android-base/macros.h>
#include <gmock/gmock.h>
-#undef NAN
#include "wifi_iface_util.h"
#include "mock_interface_tool.h"
@@ -38,16 +37,16 @@
}
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace iface_util {
+
class WifiIfaceUtilTest : public Test {
protected:
- std::shared_ptr<NiceMock<wifi_system::MockInterfaceTool>> iface_tool_{
- new NiceMock<wifi_system::MockInterfaceTool>};
+ std::shared_ptr<NiceMock<::android::wifi_system::MockInterfaceTool>> iface_tool_{
+ new NiceMock<::android::wifi_system::MockInterfaceTool>};
legacy_hal::wifi_hal_fn fake_func_table_;
std::shared_ptr<NiceMock<legacy_hal::MockWifiLegacyHal>> legacy_hal_{
new NiceMock<legacy_hal::MockWifiLegacyHal>(iface_tool_, fake_func_table_, true)};
@@ -89,8 +88,7 @@
ASSERT_FALSE(callback_invoked);
}
} // namespace iface_util
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/tests/wifi_nan_iface_unit_tests.cpp b/wifi/aidl/default/tests/wifi_nan_iface_unit_tests.cpp
new file mode 100644
index 0000000..d40801f
--- /dev/null
+++ b/wifi/aidl/default/tests/wifi_nan_iface_unit_tests.cpp
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <android-base/logging.h>
+#include <android-base/macros.h>
+#include <cutils/properties.h>
+#include <gmock/gmock.h>
+
+#include "wifi_nan_iface.h"
+
+#include "mock_interface_tool.h"
+#include "mock_wifi_feature_flags.h"
+#include "mock_wifi_iface_util.h"
+#include "mock_wifi_legacy_hal.h"
+
+using testing::NiceMock;
+using testing::Return;
+using testing::Test;
+
+namespace {
+constexpr char kIfaceName[] = "mockWlan0";
+} // namespace
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+bool CaptureIfaceEventHandlers(const std::string& /* iface_name*/,
+ iface_util::IfaceEventHandlers in_iface_event_handlers,
+ iface_util::IfaceEventHandlers* out_iface_event_handlers) {
+ *out_iface_event_handlers = in_iface_event_handlers;
+ return true;
+}
+
+class MockNanIface : public WifiNanIface {
+ public:
+ MockNanIface(const std::string& ifname, bool is_dedicated_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
+ : WifiNanIface(ifname, is_dedicated_iface, legacy_hal, iface_util) {}
+
+ static std::shared_ptr<MockNanIface> createMock(
+ const std::string& ifname, bool is_dedicated_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util) {
+ std::shared_ptr<MockNanIface> ptr = ndk::SharedRefBase::make<MockNanIface>(
+ ifname, is_dedicated_iface, legacy_hal, iface_util);
+ std::weak_ptr<MockNanIface> weak_ptr_this(ptr);
+ ptr->setWeakPtr(weak_ptr_this);
+ ptr->registerCallbackHandlers();
+ return ptr;
+ }
+
+ // Override getEventCallbacks() so that we can return a mocked callback object.
+ std::set<std::shared_ptr<IWifiNanIfaceEventCallback>> getEventCallbacks() override {
+ return {callback_};
+ }
+
+ void setMockCallback(std::shared_ptr<IWifiNanIfaceEventCallback> cb) { callback_ = cb; }
+
+ private:
+ std::shared_ptr<IWifiNanIfaceEventCallback> callback_;
+};
+
+class MockNanIfaceEventCallback : public IWifiNanIfaceEventCallback {
+ public:
+ ndk::SpAIBinder asBinder() override { return ::ndk::SpAIBinder{}; }
+ bool isRemote() override { return false; }
+
+ ::ndk::ScopedAStatus getInterfaceVersion(int32_t* _aidl_return) override {
+ *_aidl_return = 1;
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus getInterfaceHash(std::string* _aidl_return) override {
+ *_aidl_return = "some_hash";
+ return ndk::ScopedAStatus::ok();
+ }
+
+ MOCK_METHOD3(notifyCapabilitiesResponse,
+ ndk::ScopedAStatus(char16_t, const NanStatus&, const NanCapabilities&));
+ MOCK_METHOD2(notifyEnableResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD2(notifyConfigResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD2(notifyDisableResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD3(notifyStartPublishResponse,
+ ndk::ScopedAStatus(char16_t, const NanStatus&, int8_t));
+ MOCK_METHOD2(notifyStopPublishResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD3(notifyStartSubscribeResponse,
+ ndk::ScopedAStatus(char16_t, const NanStatus&, int8_t));
+ MOCK_METHOD2(notifyStopSubscribeResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD2(notifyTransmitFollowupResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD2(notifyCreateDataInterfaceResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD2(notifyDeleteDataInterfaceResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD3(notifyInitiateDataPathResponse,
+ ndk::ScopedAStatus(char16_t, const NanStatus&, int32_t));
+ MOCK_METHOD2(notifyRespondToDataPathIndicationResponse,
+ ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD2(notifyTerminateDataPathResponse, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD1(eventClusterEvent, ndk::ScopedAStatus(const NanClusterEventInd&));
+ MOCK_METHOD1(eventDisabled, ndk::ScopedAStatus(const NanStatus&));
+ MOCK_METHOD2(eventPublishTerminated, ndk::ScopedAStatus(int8_t, const NanStatus&));
+ MOCK_METHOD2(eventSubscribeTerminated, ndk::ScopedAStatus(int8_t, const NanStatus&));
+ MOCK_METHOD1(eventMatch, ndk::ScopedAStatus(const NanMatchInd&));
+ MOCK_METHOD2(eventMatchExpired, ndk::ScopedAStatus(int8_t, int32_t));
+ MOCK_METHOD1(eventFollowupReceived, ndk::ScopedAStatus(const NanFollowupReceivedInd&));
+ MOCK_METHOD2(eventTransmitFollowup, ndk::ScopedAStatus(char16_t, const NanStatus&));
+ MOCK_METHOD1(eventDataPathRequest, ndk::ScopedAStatus(const NanDataPathRequestInd&));
+ MOCK_METHOD1(eventDataPathConfirm, ndk::ScopedAStatus(const NanDataPathConfirmInd&));
+ MOCK_METHOD1(eventDataPathTerminated, ndk::ScopedAStatus(int32_t));
+ MOCK_METHOD1(eventDataPathScheduleUpdate,
+ ndk::ScopedAStatus(const NanDataPathScheduleUpdateInd&));
+};
+
+class WifiNanIfaceTest : public Test {
+ protected:
+ legacy_hal::wifi_hal_fn fake_func_table_;
+ std::shared_ptr<NiceMock<::android::wifi_system::MockInterfaceTool>> iface_tool_{
+ new NiceMock<::android::wifi_system::MockInterfaceTool>};
+ std::shared_ptr<NiceMock<legacy_hal::MockWifiLegacyHal>> legacy_hal_{
+ new NiceMock<legacy_hal::MockWifiLegacyHal>(iface_tool_, fake_func_table_, true)};
+ std::shared_ptr<NiceMock<iface_util::MockWifiIfaceUtil>> iface_util_{
+ new NiceMock<iface_util::MockWifiIfaceUtil>(iface_tool_, legacy_hal_)};
+};
+
+TEST_F(WifiNanIfaceTest, IfacEventHandlers_OnStateToggleOffOn) {
+ // Ensure that event handlers are registered during nan iface creation.
+ iface_util::IfaceEventHandlers captured_iface_event_handlers = {};
+ EXPECT_CALL(*legacy_hal_, nanRegisterCallbackHandlers(testing::_, testing::_))
+ .WillOnce(testing::Return(legacy_hal::WIFI_SUCCESS));
+ EXPECT_CALL(*iface_util_, registerIfaceEventHandlers(testing::_, testing::_))
+ .WillOnce(testing::Invoke(bind(CaptureIfaceEventHandlers, std::placeholders::_1,
+ std::placeholders::_2, &captured_iface_event_handlers)));
+
+ // Create nan iface and register a callback.
+ // Note: Since we can't register a callback directly (gTest fails on
+ // AIBinder_linkToDeath), simulate the registration by overriding
+ // getEventCallbacks() to return our mock callback object.
+ std::shared_ptr<MockNanIface> mock_nan_iface =
+ MockNanIface::createMock(kIfaceName, false, legacy_hal_, iface_util_);
+ std::shared_ptr<MockNanIfaceEventCallback> mock_event_callback =
+ ndk::SharedRefBase::make<MockNanIfaceEventCallback>();
+ mock_nan_iface->setMockCallback(mock_event_callback);
+
+ // Ensure that the eventDisabled() function in the mock callback will be invoked.
+ NanStatus expected_nan_status = {NanStatusCode::UNSUPPORTED_CONCURRENCY_NAN_DISABLED, ""};
+ EXPECT_CALL(*mock_event_callback, eventDisabled(expected_nan_status)).Times(1);
+
+ // Trigger the iface state toggle callback.
+ captured_iface_event_handlers.on_state_toggle_off_on(kIfaceName);
+}
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi.cpp b/wifi/aidl/default/wifi.cpp
similarity index 60%
rename from wifi/1.6/default/wifi.cpp
rename to wifi/aidl/default/wifi.cpp
index c302ce2..e30c38a 100644
--- a/wifi/1.6/default/wifi.cpp
+++ b/wifi/aidl/default/wifi.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,26 +14,26 @@
* limitations under the License.
*/
+#include "wifi.h"
+
#include <android-base/logging.h>
-#include "hidl_return_util.h"
-#include "wifi.h"
+#include "aidl_return_util.h"
#include "wifi_status_util.h"
namespace {
// Starting Chip ID, will be assigned to primary chip
-static constexpr android::hardware::wifi::V1_0::ChipId kPrimaryChipId = 0;
+static constexpr int32_t kPrimaryChipId = 0;
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
-using hidl_return_util::validateAndCallWithLock;
+using aidl_return_util::validateAndCall;
+using aidl_return_util::validateAndCallWithLock;
-Wifi::Wifi(const std::shared_ptr<wifi_system::InterfaceTool> iface_tool,
+Wifi::Wifi(const std::shared_ptr<::android::wifi_system::InterfaceTool> iface_tool,
const std::shared_ptr<legacy_hal::WifiLegacyHalFactory> legacy_hal_factory,
const std::shared_ptr<mode_controller::WifiModeController> mode_controller,
const std::shared_ptr<feature_flags::WifiFeatureFlags> feature_flags)
@@ -48,86 +48,74 @@
return true;
}
-Return<void> Wifi::registerEventCallback(const sp<V1_0::IWifiEventCallback>& event_callback,
- registerEventCallback_cb hidl_status_cb) {
+ndk::ScopedAStatus Wifi::registerEventCallback(
+ const std::shared_ptr<IWifiEventCallback>& in_callback) {
return validateAndCall(this, WifiStatusCode::ERROR_UNKNOWN,
- &Wifi::registerEventCallbackInternal, hidl_status_cb, event_callback);
+ &Wifi::registerEventCallbackInternal, in_callback);
}
-Return<void> Wifi::registerEventCallback_1_5(const sp<V1_5::IWifiEventCallback>& event_callback,
- registerEventCallback_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_UNKNOWN,
- &Wifi::registerEventCallbackInternal_1_5, hidl_status_cb,
- event_callback);
+ndk::ScopedAStatus Wifi::isStarted(bool* _aidl_return) {
+ *_aidl_return = (run_state_ != RunState::STOPPED);
+ return ndk::ScopedAStatus::ok();
}
-Return<bool> Wifi::isStarted() {
- return run_state_ != RunState::STOPPED;
+ndk::ScopedAStatus Wifi::start() {
+ return validateAndCall(this, WifiStatusCode::ERROR_UNKNOWN, &Wifi::startInternal);
}
-Return<void> Wifi::start(start_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_UNKNOWN, &Wifi::startInternal,
- hidl_status_cb);
+ndk::ScopedAStatus Wifi::stop() {
+ return validateAndCallWithLock(this, WifiStatusCode::ERROR_UNKNOWN, &Wifi::stopInternal);
}
-Return<void> Wifi::stop(stop_cb hidl_status_cb) {
- return validateAndCallWithLock(this, WifiStatusCode::ERROR_UNKNOWN, &Wifi::stopInternal,
- hidl_status_cb);
-}
-
-Return<void> Wifi::getChipIds(getChipIds_cb hidl_status_cb) {
+ndk::ScopedAStatus Wifi::getChipIds(std::vector<int32_t>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_UNKNOWN, &Wifi::getChipIdsInternal,
- hidl_status_cb);
+ _aidl_return);
}
-Return<void> Wifi::getChip(ChipId chip_id, getChip_cb hidl_status_cb) {
+ndk::ScopedAStatus Wifi::getChip(int32_t in_chipId, std::shared_ptr<IWifiChip>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_UNKNOWN, &Wifi::getChipInternal,
- hidl_status_cb, chip_id);
+ _aidl_return, in_chipId);
}
-Return<void> Wifi::debug(const hidl_handle& handle, const hidl_vec<hidl_string>&) {
- LOG(INFO) << "-----------Debug is called----------------";
+binder_status_t Wifi::dump(int fd, const char** args, uint32_t numArgs) {
+ LOG(INFO) << "-----------Debug was called----------------";
if (chips_.size() == 0) {
- return Void();
+ LOG(INFO) << "No chips to display.";
+ return STATUS_OK;
}
- for (sp<WifiChip> chip : chips_) {
+ for (std::shared_ptr<WifiChip> chip : chips_) {
if (!chip.get()) continue;
-
- chip->debug(handle, {});
+ chip->dump(fd, args, numArgs);
}
- return Void();
+ return STATUS_OK;
}
-WifiStatus Wifi::registerEventCallbackInternal(
- const sp<V1_0::IWifiEventCallback>& event_callback __unused) {
- // Deprecated support for this callback.
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus Wifi::registerEventCallbackInternal_1_5(
- const sp<V1_5::IWifiEventCallback>& event_callback) {
+ndk::ScopedAStatus Wifi::registerEventCallbackInternal(
+ const std::shared_ptr<IWifiEventCallback>& event_callback) {
if (!event_cb_handler_.addCallback(event_callback)) {
return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-WifiStatus Wifi::startInternal() {
+ndk::ScopedAStatus Wifi::startInternal() {
if (run_state_ == RunState::STARTED) {
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
} else if (run_state_ == RunState::STOPPING) {
return createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE, "HAL is stopping");
}
- WifiStatus wifi_status = initializeModeControllerAndLegacyHal();
- if (wifi_status.code == WifiStatusCode::SUCCESS) {
+ ndk::ScopedAStatus wifi_status = initializeModeControllerAndLegacyHal();
+ if (wifi_status.isOk()) {
// Register the callback for subsystem restart
const auto& on_subsystem_restart_callback = [this](const std::string& error) {
- WifiStatus wifi_status = createWifiStatus(WifiStatusCode::ERROR_UNKNOWN, error);
+ ndk::ScopedAStatus wifi_status = createWifiStatus(WifiStatusCode::ERROR_UNKNOWN, error);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
LOG(INFO) << "Attempting to invoke onSubsystemRestart "
"callback";
- if (!callback->onSubsystemRestart(wifi_status).isOk()) {
+ WifiStatusCode errorCode =
+ static_cast<WifiStatusCode>(wifi_status.getServiceSpecificError());
+ if (!callback->onSubsystemRestart(errorCode).isOk()) {
LOG(ERROR) << "Failed to invoke onSubsystemRestart callback";
} else {
LOG(INFO) << "Succeeded to invoke onSubsystemRestart "
@@ -137,12 +125,12 @@
};
// Create the chip instance once the HAL is started.
- android::hardware::wifi::V1_0::ChipId chipId = kPrimaryChipId;
+ int32_t chipId = kPrimaryChipId;
for (auto& hal : legacy_hals_) {
chips_.push_back(
- new WifiChip(chipId, chipId == kPrimaryChipId, hal, mode_controller_,
- std::make_shared<iface_util::WifiIfaceUtil>(iface_tool_, hal),
- feature_flags_, on_subsystem_restart_callback));
+ WifiChip::create(chipId, chipId == kPrimaryChipId, hal, mode_controller_,
+ std::make_shared<iface_util::WifiIfaceUtil>(iface_tool_, hal),
+ feature_flags_, on_subsystem_restart_callback));
chipId++;
}
run_state_ = RunState::STARTED;
@@ -154,7 +142,9 @@
LOG(INFO) << "Wifi HAL started";
} else {
for (const auto& callback : event_cb_handler_.getCallbacks()) {
- if (!callback->onFailure(wifi_status).isOk()) {
+ WifiStatusCode errorCode =
+ static_cast<WifiStatusCode>(wifi_status.getServiceSpecificError());
+ if (!callback->onFailure(errorCode).isOk()) {
LOG(ERROR) << "Failed to invoke onFailure callback";
}
}
@@ -165,10 +155,10 @@
return wifi_status;
}
-WifiStatus Wifi::stopInternal(
+ndk::ScopedAStatus Wifi::stopInternal(
/* NONNULL */ std::unique_lock<std::recursive_mutex>* lock) {
if (run_state_ == RunState::STOPPED) {
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
} else if (run_state_ == RunState::STOPPING) {
return createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE, "HAL is stopping");
}
@@ -177,12 +167,12 @@
for (auto& chip : chips_) {
if (chip.get()) {
chip->invalidate();
- chip.clear();
+ chip.reset();
}
}
chips_.clear();
- WifiStatus wifi_status = stopLegacyHalAndDeinitializeModeController(lock);
- if (wifi_status.code == WifiStatusCode::SUCCESS) {
+ ndk::ScopedAStatus wifi_status = stopLegacyHalAndDeinitializeModeController(lock);
+ if (wifi_status.isOk()) {
for (const auto& callback : event_cb_handler_.getCallbacks()) {
if (!callback->onStop().isOk()) {
LOG(ERROR) << "Failed to invoke onStop callback";
@@ -191,7 +181,9 @@
LOG(INFO) << "Wifi HAL stopped";
} else {
for (const auto& callback : event_cb_handler_.getCallbacks()) {
- if (!callback->onFailure(wifi_status).isOk()) {
+ WifiStatusCode errorCode =
+ static_cast<WifiStatusCode>(wifi_status.getServiceSpecificError());
+ if (!callback->onFailure(errorCode).isOk()) {
LOG(ERROR) << "Failed to invoke onFailure callback";
}
}
@@ -202,27 +194,26 @@
return wifi_status;
}
-std::pair<WifiStatus, std::vector<ChipId>> Wifi::getChipIdsInternal() {
- std::vector<ChipId> chip_ids;
+std::pair<std::vector<int32_t>, ndk::ScopedAStatus> Wifi::getChipIdsInternal() {
+ std::vector<int32_t> chip_ids;
for (auto& chip : chips_) {
- ChipId chip_id = getChipIdFromWifiChip(chip);
- if (chip_id != UINT32_MAX) chip_ids.emplace_back(chip_id);
+ int32_t chip_id = getChipIdFromWifiChip(chip);
+ if (chip_id != INT32_MAX) chip_ids.emplace_back(chip_id);
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), std::move(chip_ids)};
+ return {std::move(chip_ids), ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, sp<V1_4::IWifiChip>> Wifi::getChipInternal(ChipId chip_id) {
+std::pair<std::shared_ptr<IWifiChip>, ndk::ScopedAStatus> Wifi::getChipInternal(int32_t chip_id) {
for (auto& chip : chips_) {
- ChipId cand_id = getChipIdFromWifiChip(chip);
- if ((cand_id != UINT32_MAX) && (cand_id == chip_id))
- return {createWifiStatus(WifiStatusCode::SUCCESS), chip};
+ int32_t cand_id = getChipIdFromWifiChip(chip);
+ if ((cand_id != INT32_MAX) && (cand_id == chip_id)) return {chip, ndk::ScopedAStatus::ok()};
}
- return {createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS), nullptr};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
-WifiStatus Wifi::initializeModeControllerAndLegacyHal() {
+ndk::ScopedAStatus Wifi::initializeModeControllerAndLegacyHal() {
if (!mode_controller_->initialize()) {
LOG(ERROR) << "Failed to initialize firmware mode controller";
return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
@@ -244,10 +235,10 @@
}
index++;
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-WifiStatus Wifi::stopLegacyHalAndDeinitializeModeController(
+ndk::ScopedAStatus Wifi::stopLegacyHalAndDeinitializeModeController(
/* NONNULL */ std::unique_lock<std::recursive_mutex>* lock) {
legacy_hal::wifi_error legacy_status = legacy_hal::WIFI_SUCCESS;
int index = 0;
@@ -272,23 +263,22 @@
LOG(ERROR) << "Failed to deinitialize firmware mode controller";
return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-ChipId Wifi::getChipIdFromWifiChip(sp<WifiChip>& chip) {
- ChipId chip_id = UINT32_MAX;
+int32_t Wifi::getChipIdFromWifiChip(std::shared_ptr<WifiChip>& chip) {
+ int32_t chip_id = INT32_MAX;
if (chip.get()) {
- chip->getId([&](WifiStatus status, uint32_t id) {
- if (status.code == WifiStatusCode::SUCCESS) {
- chip_id = id;
- }
- });
+ ndk::ScopedAStatus status = chip->getId(&chip_id);
+ if (!status.isOk()) {
+ // Reset value if operation failed.
+ chip_id = INT32_MAX;
+ }
}
-
return chip_id;
}
-} // namespace implementation
-} // namespace V1_6
+
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi.h b/wifi/aidl/default/wifi.h
new file mode 100644
index 0000000..9334524
--- /dev/null
+++ b/wifi/aidl/default/wifi.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_H_
+#define WIFI_H_
+
+#include <aidl/android/hardware/wifi/BnWifi.h>
+#include <android-base/macros.h>
+#include <utils/Looper.h>
+
+#include <functional>
+
+#include "aidl_callback_util.h"
+#include "wifi_chip.h"
+#include "wifi_feature_flags.h"
+#include "wifi_legacy_hal.h"
+#include "wifi_legacy_hal_factory.h"
+#include "wifi_mode_controller.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+/**
+ * Root AIDL interface object used to control the Wifi HAL.
+ */
+class Wifi : public BnWifi {
+ public:
+ Wifi(const std::shared_ptr<::android::wifi_system::InterfaceTool> iface_tool,
+ const std::shared_ptr<legacy_hal::WifiLegacyHalFactory> legacy_hal_factory,
+ const std::shared_ptr<mode_controller::WifiModeController> mode_controller,
+ const std::shared_ptr<feature_flags::WifiFeatureFlags> feature_flags);
+
+ bool isValid();
+
+ // AIDL methods exposed.
+ ndk::ScopedAStatus registerEventCallback(
+ const std::shared_ptr<IWifiEventCallback>& in_callback) override;
+ ndk::ScopedAStatus isStarted(bool* _aidl_return) override;
+ ndk::ScopedAStatus start() override;
+ ndk::ScopedAStatus stop() override;
+ ndk::ScopedAStatus getChipIds(std::vector<int32_t>* _aidl_return) override;
+ ndk::ScopedAStatus getChip(int32_t in_chipId,
+ std::shared_ptr<IWifiChip>* _aidl_return) override;
+ binder_status_t dump(int fd, const char** args, uint32_t numArgs) override;
+
+ private:
+ enum class RunState { STOPPED, STARTED, STOPPING };
+
+ // Corresponding worker functions for the AIDL methods.
+ ndk::ScopedAStatus registerEventCallbackInternal(
+ const std::shared_ptr<IWifiEventCallback>& event_callback __unused);
+ ndk::ScopedAStatus startInternal();
+ ndk::ScopedAStatus stopInternal(std::unique_lock<std::recursive_mutex>* lock);
+ std::pair<std::vector<int32_t>, ndk::ScopedAStatus> getChipIdsInternal();
+ std::pair<std::shared_ptr<IWifiChip>, ndk::ScopedAStatus> getChipInternal(int32_t chip_id);
+
+ ndk::ScopedAStatus initializeModeControllerAndLegacyHal();
+ ndk::ScopedAStatus stopLegacyHalAndDeinitializeModeController(
+ std::unique_lock<std::recursive_mutex>* lock);
+ int32_t getChipIdFromWifiChip(std::shared_ptr<WifiChip>& chip);
+
+ // Instance is created in this root level |IWifi| AIDL interface object
+ // and shared with all the child AIDL interface objects.
+ std::shared_ptr<::android::wifi_system::InterfaceTool> iface_tool_;
+ std::shared_ptr<legacy_hal::WifiLegacyHalFactory> legacy_hal_factory_;
+ std::shared_ptr<mode_controller::WifiModeController> mode_controller_;
+ std::vector<std::shared_ptr<legacy_hal::WifiLegacyHal>> legacy_hals_;
+ std::shared_ptr<feature_flags::WifiFeatureFlags> feature_flags_;
+ RunState run_state_;
+ std::vector<std::shared_ptr<WifiChip>> chips_;
+ aidl_callback_util::AidlCallbackHandler<IWifiEventCallback> event_cb_handler_;
+
+ DISALLOW_COPY_AND_ASSIGN(Wifi);
+};
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_H_
diff --git a/wifi/aidl/default/wifi_ap_iface.cpp b/wifi/aidl/default/wifi_ap_iface.cpp
new file mode 100644
index 0000000..6cd932d
--- /dev/null
+++ b/wifi/aidl/default/wifi_ap_iface.cpp
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "wifi_ap_iface.h"
+
+#include <android-base/logging.h>
+
+#include "aidl_return_util.h"
+#include "aidl_struct_util.h"
+#include "wifi_status_util.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+using aidl_return_util::validateAndCall;
+
+WifiApIface::WifiApIface(const std::string& ifname, const std::vector<std::string>& instances,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
+ : ifname_(ifname),
+ instances_(instances),
+ legacy_hal_(legacy_hal),
+ iface_util_(iface_util),
+ is_valid_(true) {}
+
+void WifiApIface::invalidate() {
+ legacy_hal_.reset();
+ is_valid_ = false;
+}
+
+bool WifiApIface::isValid() {
+ return is_valid_;
+}
+
+std::string WifiApIface::getName() {
+ return ifname_;
+}
+
+void WifiApIface::removeInstance(std::string instance) {
+ instances_.erase(std::remove(instances_.begin(), instances_.end(), instance), instances_.end());
+}
+
+ndk::ScopedAStatus WifiApIface::getName(std::string* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::getNameInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiApIface::setCountryCode(const std::array<uint8_t, 2>& in_code) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::setCountryCodeInternal, in_code);
+}
+
+ndk::ScopedAStatus WifiApIface::getValidFrequenciesForBand(WifiBand in_band,
+ std::vector<int32_t>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::getValidFrequenciesForBandInternal, _aidl_return, in_band);
+}
+
+ndk::ScopedAStatus WifiApIface::setMacAddress(const std::array<uint8_t, 6>& in_mac) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::setMacAddressInternal, in_mac);
+}
+
+ndk::ScopedAStatus WifiApIface::getFactoryMacAddress(std::array<uint8_t, 6>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::getFactoryMacAddressInternal, _aidl_return,
+ instances_.size() > 0 ? instances_[0] : ifname_);
+}
+
+ndk::ScopedAStatus WifiApIface::resetToFactoryMacAddress() {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::resetToFactoryMacAddressInternal);
+}
+
+ndk::ScopedAStatus WifiApIface::getBridgedInstances(std::vector<std::string>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiApIface::getBridgedInstancesInternal, _aidl_return);
+}
+
+std::pair<std::string, ndk::ScopedAStatus> WifiApIface::getNameInternal() {
+ return {ifname_, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiApIface::setCountryCodeInternal(const std::array<uint8_t, 2>& code) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->setCountryCode(
+ instances_.size() > 0 ? instances_[0] : ifname_, code);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<std::vector<int32_t>, ndk::ScopedAStatus> WifiApIface::getValidFrequenciesForBandInternal(
+ WifiBand band) {
+ static_assert(sizeof(WifiChannelWidthInMhz) == sizeof(int32_t), "Size mismatch");
+ legacy_hal::wifi_error legacy_status;
+ std::vector<uint32_t> valid_frequencies;
+ std::tie(legacy_status, valid_frequencies) = legacy_hal_.lock()->getValidFrequenciesForBand(
+ instances_.size() > 0 ? instances_[0] : ifname_,
+ aidl_struct_util::convertAidlWifiBandToLegacy(band));
+ return {std::vector<int32_t>(valid_frequencies.begin(), valid_frequencies.end()),
+ createWifiStatusFromLegacyError(legacy_status)};
+}
+
+ndk::ScopedAStatus WifiApIface::setMacAddressInternal(const std::array<uint8_t, 6>& mac) {
+ // Support random MAC up to 2 interfaces
+ if (instances_.size() == 2) {
+ int rbyte = 1;
+ for (auto const& intf : instances_) {
+ std::array<uint8_t, 6> rmac = mac;
+ // reverse the bits to avoid collision
+ rmac[rbyte] = 0xff - rmac[rbyte];
+ if (!iface_util_.lock()->setMacAddress(intf, rmac)) {
+ LOG(INFO) << "Failed to set random mac address on " << intf;
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ rbyte++;
+ }
+ }
+ // It also needs to set mac address for bridged interface, otherwise the mac
+ // address of bridged interface will be changed after one of instance
+ // down.
+ if (!iface_util_.lock()->setMacAddress(ifname_, mac)) {
+ LOG(ERROR) << "Fail to config MAC for interface " << ifname_;
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+std::pair<std::array<uint8_t, 6>, ndk::ScopedAStatus> WifiApIface::getFactoryMacAddressInternal(
+ const std::string& ifaceName) {
+ std::array<uint8_t, 6> mac = iface_util_.lock()->getFactoryMacAddress(ifaceName);
+ if (mac[0] == 0 && mac[1] == 0 && mac[2] == 0 && mac[3] == 0 && mac[4] == 0 && mac[5] == 0) {
+ return {mac, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {mac, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiApIface::resetToFactoryMacAddressInternal() {
+ std::pair<std::array<uint8_t, 6>, ndk::ScopedAStatus> getMacResult;
+ if (instances_.size() == 2) {
+ for (auto const& intf : instances_) {
+ getMacResult = getFactoryMacAddressInternal(intf);
+ LOG(DEBUG) << "Reset MAC to factory MAC on " << intf;
+ if (!getMacResult.second.isOk() ||
+ !iface_util_.lock()->setMacAddress(intf, getMacResult.first)) {
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ }
+ // We need to set mac address for bridged interface, otherwise the mac
+ // address of the bridged interface will be changed after one of the
+ // instances goes down. Thus we are generating a random MAC address for
+ // the bridged interface even if we got the request to reset the Factory
+ // MAC. This is because the bridged interface is an internal interface
+ // for the operation of bpf and other networking operations.
+ if (!iface_util_.lock()->setMacAddress(ifname_,
+ iface_util_.lock()->createRandomMacAddress())) {
+ LOG(ERROR) << "Fail to config MAC for bridged interface " << ifname_;
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ } else {
+ getMacResult = getFactoryMacAddressInternal(ifname_);
+ LOG(DEBUG) << "Reset MAC to factory MAC on " << ifname_;
+ if (!getMacResult.second.isOk() ||
+ !iface_util_.lock()->setMacAddress(ifname_, getMacResult.first)) {
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiApIface::getBridgedInstancesInternal() {
+ return {instances_, ndk::ScopedAStatus::ok()};
+}
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi_ap_iface.h b/wifi/aidl/default/wifi_ap_iface.h
new file mode 100644
index 0000000..b5673fc
--- /dev/null
+++ b/wifi/aidl/default/wifi_ap_iface.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_AP_IFACE_H_
+#define WIFI_AP_IFACE_H_
+
+#include <aidl/android/hardware/wifi/BnWifiApIface.h>
+#include <android-base/macros.h>
+
+#include "wifi_iface_util.h"
+#include "wifi_legacy_hal.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+/**
+ * AIDL interface object used to control an AP Iface instance.
+ */
+class WifiApIface : public BnWifiApIface {
+ public:
+ WifiApIface(const std::string& ifname, const std::vector<std::string>& instances,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
+ // Refer to |WifiChip::invalidate()|.
+ void invalidate();
+ bool isValid();
+ std::string getName();
+ void removeInstance(std::string instance);
+
+ // AIDL methods exposed.
+ ndk::ScopedAStatus getName(std::string* _aidl_return) override;
+ ndk::ScopedAStatus setCountryCode(const std::array<uint8_t, 2>& in_code) override;
+ ndk::ScopedAStatus getValidFrequenciesForBand(WifiBand in_band,
+ std::vector<int32_t>* _aidl_return) override;
+ ndk::ScopedAStatus setMacAddress(const std::array<uint8_t, 6>& in_mac) override;
+ ndk::ScopedAStatus getFactoryMacAddress(std::array<uint8_t, 6>* _aidl_return) override;
+ ndk::ScopedAStatus resetToFactoryMacAddress() override;
+ ndk::ScopedAStatus getBridgedInstances(std::vector<std::string>* _aidl_return) override;
+
+ private:
+ // Corresponding worker functions for the AIDL methods.
+ std::pair<std::string, ndk::ScopedAStatus> getNameInternal();
+ ndk::ScopedAStatus setCountryCodeInternal(const std::array<uint8_t, 2>& code);
+ std::pair<std::vector<int32_t>, ndk::ScopedAStatus> getValidFrequenciesForBandInternal(
+ WifiBand band);
+ ndk::ScopedAStatus setMacAddressInternal(const std::array<uint8_t, 6>& mac);
+ std::pair<std::array<uint8_t, 6>, ndk::ScopedAStatus> getFactoryMacAddressInternal(
+ const std::string& ifaceName);
+ ndk::ScopedAStatus resetToFactoryMacAddressInternal();
+ std::pair<std::vector<std::string>, ndk::ScopedAStatus> getBridgedInstancesInternal();
+
+ std::string ifname_;
+ std::vector<std::string> instances_;
+ std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
+ std::weak_ptr<iface_util::WifiIfaceUtil> iface_util_;
+ bool is_valid_;
+
+ DISALLOW_COPY_AND_ASSIGN(WifiApIface);
+};
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_AP_IFACE_H_
diff --git a/wifi/1.6/default/wifi_chip.cpp b/wifi/aidl/default/wifi_chip.cpp
similarity index 63%
rename from wifi/1.6/default/wifi_chip.cpp
rename to wifi/aidl/default/wifi_chip.cpp
index 920beb8..076f351 100644
--- a/wifi/1.6/default/wifi_chip.cpp
+++ b/wifi/aidl/default/wifi_chip.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,30 +14,27 @@
* limitations under the License.
*/
-#include <fcntl.h>
+#include "wifi_chip.h"
#include <android-base/logging.h>
#include <android-base/unique_fd.h>
#include <cutils/properties.h>
+#include <fcntl.h>
#include <net/if.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
-#include "hidl_return_util.h"
-#include "hidl_struct_util.h"
-#include "wifi_chip.h"
+#include "aidl_return_util.h"
+#include "aidl_struct_util.h"
#include "wifi_status_util.h"
#define P2P_MGMT_DEVICE_PREFIX "p2p-dev-"
namespace {
-using android::sp;
+using aidl::android::hardware::wifi::IfaceType;
+using aidl::android::hardware::wifi::IWifiChip;
+using CoexRestriction = aidl::android::hardware::wifi::IWifiChip::CoexRestriction;
using android::base::unique_fd;
-using android::hardware::hidl_string;
-using android::hardware::hidl_vec;
-using android::hardware::wifi::V1_0::ChipModeId;
-using android::hardware::wifi::V1_0::IfaceType;
-using android::hardware::wifi::V1_0::IWifiChip;
constexpr char kCpioMagic[] = "070701";
constexpr size_t kMaxBufferSizeBytes = 1024 * 1024 * 3;
@@ -50,13 +47,13 @@
constexpr char kApBridgeIfacePrefix[] = "ap_br_";
template <typename Iface>
-void invalidateAndClear(std::vector<sp<Iface>>& ifaces, sp<Iface> iface) {
+void invalidateAndClear(std::vector<std::shared_ptr<Iface>>& ifaces, std::shared_ptr<Iface> iface) {
iface->invalidate();
ifaces.erase(std::remove(ifaces.begin(), ifaces.end(), iface), ifaces.end());
}
template <typename Iface>
-void invalidateAndClearAll(std::vector<sp<Iface>>& ifaces) {
+void invalidateAndClearAll(std::vector<std::shared_ptr<Iface>>& ifaces) {
for (const auto& iface : ifaces) {
iface->invalidate();
}
@@ -64,8 +61,8 @@
}
template <typename Iface>
-std::vector<hidl_string> getNames(std::vector<sp<Iface>>& ifaces) {
- std::vector<hidl_string> names;
+std::vector<std::string> getNames(std::vector<std::shared_ptr<Iface>>& ifaces) {
+ std::vector<std::string> names;
for (const auto& iface : ifaces) {
names.emplace_back(iface->getName());
}
@@ -73,8 +70,9 @@
}
template <typename Iface>
-sp<Iface> findUsingName(std::vector<sp<Iface>>& ifaces, const std::string& name) {
- std::vector<hidl_string> names;
+std::shared_ptr<Iface> findUsingName(std::vector<std::shared_ptr<Iface>>& ifaces,
+ const std::string& name) {
+ std::vector<std::string> names;
for (const auto& iface : ifaces) {
if (name == iface->getName()) {
return iface;
@@ -169,8 +167,8 @@
}
}
-// delete files that meet either conditions:
-// 1. older than a predefined time in the wifi tombstone dir.
+// Delete files that meet either condition:
+// 1. Older than a predefined time in the wifi tombstone dir.
// 2. Files in excess to a predefined amount, starting from the oldest ones
bool removeOldFilesInternal() {
time_t now = time(0);
@@ -354,15 +352,14 @@
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
-using hidl_return_util::validateAndCallWithLock;
+using aidl_return_util::validateAndCall;
+using aidl_return_util::validateAndCallWithLock;
-WifiChip::WifiChip(ChipId chip_id, bool is_primary,
+WifiChip::WifiChip(int32_t chip_id, bool is_primary,
const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
@@ -380,6 +377,19 @@
setActiveWlanIfaceNameProperty(kNoActiveWlanIfaceNamePropertyValue);
}
+std::shared_ptr<WifiChip> WifiChip::create(
+ int32_t chip_id, bool is_primary, const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
+ const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
+ const std::weak_ptr<feature_flags::WifiFeatureFlags> feature_flags,
+ const std::function<void(const std::string&)>& handler) {
+ std::shared_ptr<WifiChip> ptr = ndk::SharedRefBase::make<WifiChip>(
+ chip_id, is_primary, legacy_hal, mode_controller, iface_util, feature_flags, handler);
+ std::weak_ptr<WifiChip> weak_ptr_this(ptr);
+ ptr->setWeakPtr(weak_ptr_this);
+ return ptr;
+}
+
void WifiChip::invalidate() {
if (!writeRingbufferFilesInternal()) {
LOG(ERROR) << "Error writing files to flash";
@@ -391,348 +401,283 @@
is_valid_ = false;
}
+void WifiChip::setWeakPtr(std::weak_ptr<WifiChip> ptr) {
+ weak_ptr_this_ = ptr;
+}
+
bool WifiChip::isValid() {
return is_valid_;
}
-std::set<sp<V1_4::IWifiChipEventCallback>> WifiChip::getEventCallbacks() {
+std::set<std::shared_ptr<IWifiChipEventCallback>> WifiChip::getEventCallbacks() {
return event_cb_handler_.getCallbacks();
}
-Return<void> WifiChip::getId(getId_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getId(int32_t* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID, &WifiChip::getIdInternal,
- hidl_status_cb);
+ _aidl_return);
}
-// Deprecated support for this callback
-Return<void> WifiChip::registerEventCallback(const sp<V1_0::IWifiChipEventCallback>& event_callback,
- registerEventCallback_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::registerEventCallback(
+ const std::shared_ptr<IWifiChipEventCallback>& event_callback) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::registerEventCallbackInternal, hidl_status_cb,
- event_callback);
+ &WifiChip::registerEventCallbackInternal, event_callback);
}
-Return<void> WifiChip::getCapabilities(getCapabilities_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getCapabilities(IWifiChip::ChipCapabilityMask* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getCapabilitiesInternal, hidl_status_cb);
+ &WifiChip::getCapabilitiesInternal, _aidl_return);
}
-Return<void> WifiChip::getAvailableModes(getAvailableModes_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getAvailableModes(std::vector<IWifiChip::ChipMode>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getAvailableModesInternal, hidl_status_cb);
+ &WifiChip::getAvailableModesInternal, _aidl_return);
}
-Return<void> WifiChip::configureChip(ChipModeId mode_id, configureChip_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::configureChip(int32_t in_modeId) {
return validateAndCallWithLock(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::configureChipInternal, hidl_status_cb, mode_id);
+ &WifiChip::configureChipInternal, in_modeId);
}
-Return<void> WifiChip::getMode(getMode_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getMode(int32_t* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getModeInternal, hidl_status_cb);
+ &WifiChip::getModeInternal, _aidl_return);
}
-Return<void> WifiChip::requestChipDebugInfo(requestChipDebugInfo_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::requestChipDebugInfo(IWifiChip::ChipDebugInfo* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::requestChipDebugInfoInternal, hidl_status_cb);
+ &WifiChip::requestChipDebugInfoInternal, _aidl_return);
}
-Return<void> WifiChip::requestDriverDebugDump(requestDriverDebugDump_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::requestDriverDebugDump(std::vector<uint8_t>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::requestDriverDebugDumpInternal, hidl_status_cb);
+ &WifiChip::requestDriverDebugDumpInternal, _aidl_return);
}
-Return<void> WifiChip::requestFirmwareDebugDump(requestFirmwareDebugDump_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::requestFirmwareDebugDump(std::vector<uint8_t>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::requestFirmwareDebugDumpInternal, hidl_status_cb);
+ &WifiChip::requestFirmwareDebugDumpInternal, _aidl_return);
}
-Return<void> WifiChip::createApIface(createApIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::createApIface(std::shared_ptr<IWifiApIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createApIfaceInternal, hidl_status_cb);
+ &WifiChip::createApIfaceInternal, _aidl_return);
}
-Return<void> WifiChip::createBridgedApIface(createBridgedApIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::createBridgedApIface(std::shared_ptr<IWifiApIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createBridgedApIfaceInternal, hidl_status_cb);
+ &WifiChip::createBridgedApIfaceInternal, _aidl_return);
}
-Return<void> WifiChip::getApIfaceNames(getApIfaceNames_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getApIfaceNames(std::vector<std::string>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getApIfaceNamesInternal, hidl_status_cb);
+ &WifiChip::getApIfaceNamesInternal, _aidl_return);
}
-Return<void> WifiChip::getApIface(const hidl_string& ifname, getApIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getApIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiApIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getApIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::getApIfaceInternal, _aidl_return, in_ifname);
}
-Return<void> WifiChip::removeApIface(const hidl_string& ifname, removeApIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::removeApIface(const std::string& in_ifname) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::removeApIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::removeApIfaceInternal, in_ifname);
}
-Return<void> WifiChip::removeIfaceInstanceFromBridgedApIface(
- const hidl_string& ifname, const hidl_string& ifInstanceName,
- removeIfaceInstanceFromBridgedApIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::removeIfaceInstanceFromBridgedApIface(
+ const std::string& in_brIfaceName, const std::string& in_ifaceInstanceName) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::removeIfaceInstanceFromBridgedApIfaceInternal, hidl_status_cb,
- ifname, ifInstanceName);
+ &WifiChip::removeIfaceInstanceFromBridgedApIfaceInternal, in_brIfaceName,
+ in_ifaceInstanceName);
}
-Return<void> WifiChip::createNanIface(createNanIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::createNanIface(std::shared_ptr<IWifiNanIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createNanIfaceInternal, hidl_status_cb);
+ &WifiChip::createNanIfaceInternal, _aidl_return);
}
-Return<void> WifiChip::getNanIfaceNames(getNanIfaceNames_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getNanIfaceNames(std::vector<std::string>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getNanIfaceNamesInternal, hidl_status_cb);
+ &WifiChip::getNanIfaceNamesInternal, _aidl_return);
}
-Return<void> WifiChip::getNanIface(const hidl_string& ifname, getNanIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getNanIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiNanIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getNanIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::getNanIfaceInternal, _aidl_return, in_ifname);
}
-Return<void> WifiChip::removeNanIface(const hidl_string& ifname, removeNanIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::removeNanIface(const std::string& in_ifname) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::removeNanIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::removeNanIfaceInternal, in_ifname);
}
-Return<void> WifiChip::createP2pIface(createP2pIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::createP2pIface(std::shared_ptr<IWifiP2pIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createP2pIfaceInternal, hidl_status_cb);
+ &WifiChip::createP2pIfaceInternal, _aidl_return);
}
-Return<void> WifiChip::getP2pIfaceNames(getP2pIfaceNames_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getP2pIfaceNames(std::vector<std::string>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getP2pIfaceNamesInternal, hidl_status_cb);
+ &WifiChip::getP2pIfaceNamesInternal, _aidl_return);
}
-Return<void> WifiChip::getP2pIface(const hidl_string& ifname, getP2pIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getP2pIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiP2pIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getP2pIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::getP2pIfaceInternal, _aidl_return, in_ifname);
}
-Return<void> WifiChip::removeP2pIface(const hidl_string& ifname, removeP2pIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::removeP2pIface(const std::string& in_ifname) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::removeP2pIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::removeP2pIfaceInternal, in_ifname);
}
-Return<void> WifiChip::createStaIface(createStaIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::createStaIface(std::shared_ptr<IWifiStaIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createStaIfaceInternal, hidl_status_cb);
+ &WifiChip::createStaIfaceInternal, _aidl_return);
}
-Return<void> WifiChip::getStaIfaceNames(getStaIfaceNames_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getStaIfaceNames(std::vector<std::string>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getStaIfaceNamesInternal, hidl_status_cb);
+ &WifiChip::getStaIfaceNamesInternal, _aidl_return);
}
-Return<void> WifiChip::getStaIface(const hidl_string& ifname, getStaIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getStaIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiStaIface>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getStaIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::getStaIfaceInternal, _aidl_return, in_ifname);
}
-Return<void> WifiChip::removeStaIface(const hidl_string& ifname, removeStaIface_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::removeStaIface(const std::string& in_ifname) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::removeStaIfaceInternal, hidl_status_cb, ifname);
+ &WifiChip::removeStaIfaceInternal, in_ifname);
}
-Return<void> WifiChip::createRttController(const sp<IWifiIface>& bound_iface,
- createRttController_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::createRttController(
+ const std::shared_ptr<IWifiStaIface>& in_boundIface,
+ std::shared_ptr<IWifiRttController>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createRttControllerInternal, hidl_status_cb, bound_iface);
+ &WifiChip::createRttControllerInternal, _aidl_return, in_boundIface);
}
-Return<void> WifiChip::getDebugRingBuffersStatus(getDebugRingBuffersStatus_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getDebugRingBuffersStatus(
+ std::vector<WifiDebugRingBufferStatus>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getDebugRingBuffersStatusInternal, hidl_status_cb);
+ &WifiChip::getDebugRingBuffersStatusInternal, _aidl_return);
}
-Return<void> WifiChip::startLoggingToDebugRingBuffer(
- const hidl_string& ring_name, WifiDebugRingBufferVerboseLevel verbose_level,
- uint32_t max_interval_in_sec, uint32_t min_data_size_in_bytes,
- startLoggingToDebugRingBuffer_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::startLoggingToDebugRingBuffer(
+ const std::string& in_ringName, WifiDebugRingBufferVerboseLevel in_verboseLevel,
+ int32_t in_maxIntervalInSec, int32_t in_minDataSizeInBytes) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::startLoggingToDebugRingBufferInternal, hidl_status_cb,
- ring_name, verbose_level, max_interval_in_sec, min_data_size_in_bytes);
+ &WifiChip::startLoggingToDebugRingBufferInternal, in_ringName,
+ in_verboseLevel, in_maxIntervalInSec, in_minDataSizeInBytes);
}
-Return<void> WifiChip::forceDumpToDebugRingBuffer(const hidl_string& ring_name,
- forceDumpToDebugRingBuffer_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::forceDumpToDebugRingBuffer(const std::string& in_ringName) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::forceDumpToDebugRingBufferInternal, hidl_status_cb,
- ring_name);
+ &WifiChip::forceDumpToDebugRingBufferInternal, in_ringName);
}
-Return<void> WifiChip::flushRingBufferToFile(flushRingBufferToFile_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::flushRingBufferToFile() {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::flushRingBufferToFileInternal, hidl_status_cb);
+ &WifiChip::flushRingBufferToFileInternal);
}
-Return<void> WifiChip::stopLoggingToDebugRingBuffer(
- stopLoggingToDebugRingBuffer_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::stopLoggingToDebugRingBuffer() {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::stopLoggingToDebugRingBufferInternal, hidl_status_cb);
+ &WifiChip::stopLoggingToDebugRingBufferInternal);
}
-Return<void> WifiChip::getDebugHostWakeReasonStats(getDebugHostWakeReasonStats_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getDebugHostWakeReasonStats(
+ WifiDebugHostWakeReasonStats* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getDebugHostWakeReasonStatsInternal, hidl_status_cb);
+ &WifiChip::getDebugHostWakeReasonStatsInternal, _aidl_return);
}
-Return<void> WifiChip::enableDebugErrorAlerts(bool enable,
- enableDebugErrorAlerts_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::enableDebugErrorAlerts(bool in_enable) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::enableDebugErrorAlertsInternal, hidl_status_cb, enable);
+ &WifiChip::enableDebugErrorAlertsInternal, in_enable);
}
-Return<void> WifiChip::selectTxPowerScenario(V1_1::IWifiChip::TxPowerScenario scenario,
- selectTxPowerScenario_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::selectTxPowerScenario(IWifiChip::TxPowerScenario in_scenario) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::selectTxPowerScenarioInternal, hidl_status_cb, scenario);
+ &WifiChip::selectTxPowerScenarioInternal, in_scenario);
}
-Return<void> WifiChip::resetTxPowerScenario(resetTxPowerScenario_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::resetTxPowerScenario() {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::resetTxPowerScenarioInternal, hidl_status_cb);
+ &WifiChip::resetTxPowerScenarioInternal);
}
-Return<void> WifiChip::setLatencyMode(LatencyMode mode, setLatencyMode_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::setLatencyMode(IWifiChip::LatencyMode in_mode) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::setLatencyModeInternal, hidl_status_cb, mode);
+ &WifiChip::setLatencyModeInternal, in_mode);
}
-Return<void> WifiChip::registerEventCallback_1_2(
- const sp<V1_2::IWifiChipEventCallback>& event_callback,
- registerEventCallback_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::registerEventCallbackInternal_1_2, hidl_status_cb,
- event_callback);
-}
-
-Return<void> WifiChip::selectTxPowerScenario_1_2(TxPowerScenario scenario,
- selectTxPowerScenario_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::selectTxPowerScenarioInternal_1_2, hidl_status_cb, scenario);
-}
-
-Return<void> WifiChip::getCapabilities_1_3(getCapabilities_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getCapabilitiesInternal_1_3, hidl_status_cb);
-}
-
-Return<void> WifiChip::getCapabilities_1_5(getCapabilities_1_5_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getCapabilitiesInternal_1_5, hidl_status_cb);
-}
-
-Return<void> WifiChip::debug(const hidl_handle& handle, const hidl_vec<hidl_string>&) {
- if (handle != nullptr && handle->numFds >= 1) {
- {
- std::unique_lock<std::mutex> lk(lock_t);
- for (const auto& item : ringbuffer_map_) {
- forceDumpToDebugRingBufferInternal(item.first);
- }
- // unique_lock unlocked here
+binder_status_t WifiChip::dump(int fd, const char**, uint32_t) {
+ {
+ std::unique_lock<std::mutex> lk(lock_t);
+ for (const auto& item : ringbuffer_map_) {
+ forceDumpToDebugRingBufferInternal(item.first);
}
- usleep(100 * 1000); // sleep for 100 milliseconds to wait for
- // ringbuffer updates.
- int fd = handle->data[0];
- if (!writeRingbufferFilesInternal()) {
- LOG(ERROR) << "Error writing files to flash";
- }
- uint32_t n_error = cpioArchiveFilesInDir(fd, kTombstoneFolderPath);
- if (n_error != 0) {
- LOG(ERROR) << n_error << " errors occured in cpio function";
- }
- fsync(fd);
- } else {
- LOG(ERROR) << "File handle error";
+ // unique_lock unlocked here
}
- return Void();
+ usleep(100 * 1000); // sleep for 100 milliseconds to wait for
+ // ringbuffer updates.
+ if (!writeRingbufferFilesInternal()) {
+ LOG(ERROR) << "Error writing files to flash";
+ }
+ uint32_t n_error = cpioArchiveFilesInDir(fd, kTombstoneFolderPath);
+ if (n_error != 0) {
+ LOG(ERROR) << n_error << " errors occurred in cpio function";
+ }
+ fsync(fd);
+ return STATUS_OK;
}
-Return<void> WifiChip::createRttController_1_4(const sp<IWifiIface>& bound_iface,
- createRttController_1_4_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::setMultiStaPrimaryConnection(const std::string& in_ifName) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createRttControllerInternal_1_4, hidl_status_cb, bound_iface);
+ &WifiChip::setMultiStaPrimaryConnectionInternal, in_ifName);
}
-Return<void> WifiChip::registerEventCallback_1_4(
- const sp<V1_4::IWifiChipEventCallback>& event_callback,
- registerEventCallback_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::setMultiStaUseCase(IWifiChip::MultiStaUseCase in_useCase) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::registerEventCallbackInternal_1_4, hidl_status_cb,
- event_callback);
+ &WifiChip::setMultiStaUseCaseInternal, in_useCase);
}
-Return<void> WifiChip::setMultiStaPrimaryConnection(
- const hidl_string& ifname, setMultiStaPrimaryConnection_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::setCoexUnsafeChannels(
+ const std::vector<IWifiChip::CoexUnsafeChannel>& in_unsafeChannels,
+ CoexRestriction in_restrictions) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::setMultiStaPrimaryConnectionInternal, hidl_status_cb, ifname);
+ &WifiChip::setCoexUnsafeChannelsInternal, in_unsafeChannels,
+ in_restrictions);
}
-Return<void> WifiChip::setMultiStaUseCase(MultiStaUseCase use_case,
- setMultiStaUseCase_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::setMultiStaUseCaseInternal, hidl_status_cb, use_case);
-}
-
-Return<void> WifiChip::setCoexUnsafeChannels(const hidl_vec<CoexUnsafeChannel>& unsafeChannels,
- hidl_bitfield<CoexRestriction> restrictions,
- setCoexUnsafeChannels_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::setCoexUnsafeChannelsInternal, hidl_status_cb, unsafeChannels,
- restrictions);
-}
-
-Return<void> WifiChip::setCountryCode(const hidl_array<int8_t, 2>& code,
- setCountryCode_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::setCountryCode(const std::array<uint8_t, 2>& in_code) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiChip::setCountryCodeInternal, hidl_status_cb, code);
+ &WifiChip::setCountryCodeInternal, in_code);
}
-Return<void> WifiChip::getUsableChannels(
- WifiBand band, hidl_bitfield<V1_5::WifiIfaceMode> ifaceModeMask,
- hidl_bitfield<V1_5::IWifiChip::UsableChannelFilter> filterMask,
- getUsableChannels_cb _hidl_cb) {
+ndk::ScopedAStatus WifiChip::getUsableChannels(WifiBand in_band, WifiIfaceMode in_ifaceModeMask,
+ UsableChannelFilter in_filterMask,
+ std::vector<WifiUsableChannel>* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getUsableChannelsInternal, _hidl_cb, band, ifaceModeMask,
- filterMask);
+ &WifiChip::getUsableChannelsInternal, _aidl_return, in_band,
+ in_ifaceModeMask, in_filterMask);
}
-Return<void> WifiChip::triggerSubsystemRestart(triggerSubsystemRestart_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::triggerSubsystemRestart() {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::triggerSubsystemRestartInternal, hidl_status_cb);
+ &WifiChip::triggerSubsystemRestartInternal);
}
-Return<void> WifiChip::createRttController_1_6(const sp<IWifiIface>& bound_iface,
- createRttController_1_6_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiChip::getSupportedRadioCombinationsMatrix(
+ WifiRadioCombinationMatrix* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::createRttControllerInternal_1_6, hidl_status_cb, bound_iface);
-}
-
-Return<void> WifiChip::getUsableChannels_1_6(
- WifiBand band, hidl_bitfield<V1_5::WifiIfaceMode> ifaceModeMask,
- hidl_bitfield<V1_6::IWifiChip::UsableChannelFilter> filterMask,
- getUsableChannels_1_6_cb _hidl_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getUsableChannelsInternal_1_6, _hidl_cb, band, ifaceModeMask,
- filterMask);
-}
-
-Return<void> WifiChip::getSupportedRadioCombinationsMatrix(
- getSupportedRadioCombinationsMatrix_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getSupportedRadioCombinationsMatrixInternal, hidl_status_cb);
-}
-
-Return<void> WifiChip::getAvailableModes_1_6(getAvailableModes_1_6_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_CHIP_INVALID,
- &WifiChip::getAvailableModesInternal_1_6, hidl_status_cb);
+ &WifiChip::getSupportedRadioCombinationsMatrixInternal, _aidl_return);
}
void WifiChip::invalidateAndRemoveAllIfaces() {
@@ -755,7 +700,7 @@
if (nan_iface->getName() == removed_iface_name) {
nan_iface->invalidate();
for (const auto& callback : event_cb_handler_.getCallbacks()) {
- if (!callback->onIfaceRemoved(IfaceType::NAN, removed_iface_name).isOk()) {
+ if (!callback->onIfaceRemoved(IfaceType::NAN_IFACE, removed_iface_name).isOk()) {
LOG(ERROR) << "Failed to invoke onIfaceRemoved callback";
}
}
@@ -776,89 +721,61 @@
}
}
-std::pair<WifiStatus, ChipId> WifiChip::getIdInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), chip_id_};
+std::pair<int32_t, ndk::ScopedAStatus> WifiChip::getIdInternal() {
+ return {chip_id_, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::registerEventCallbackInternal(
- const sp<V1_0::IWifiChipEventCallback>& /* event_callback */) {
- // Deprecated support for this callback.
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-std::pair<WifiStatus, uint32_t> WifiChip::getCapabilitiesInternal() {
- // Deprecated support for this callback.
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), 0};
-}
-
-std::pair<WifiStatus, std::vector<V1_0::IWifiChip::ChipMode>>
-WifiChip::getAvailableModesInternal() {
- // Deprecated support -- use getAvailableModes_1_6 for more granular concurrency combinations.
- std::vector<V1_0::IWifiChip::ChipMode> modes_1_0 = {};
- for (const auto& mode_1_6 : modes_) {
- std::vector<V1_0::IWifiChip::ChipIfaceCombination> combos_1_0;
- for (const auto& combo_1_6 : mode_1_6.availableCombinations) {
- std::vector<V1_0::IWifiChip::ChipIfaceCombinationLimit> limits_1_0;
- for (const auto& limit_1_6 : combo_1_6.limits) {
- std::vector<IfaceType> types_1_0;
- for (IfaceConcurrencyType type_1_6 : limit_1_6.types) {
- switch (type_1_6) {
- case IfaceConcurrencyType::STA:
- types_1_0.push_back(IfaceType::STA);
- break;
- case IfaceConcurrencyType::AP:
- types_1_0.push_back(IfaceType::AP);
- break;
- case IfaceConcurrencyType::AP_BRIDGED:
- // Ignore AP_BRIDGED
- break;
- case IfaceConcurrencyType::P2P:
- types_1_0.push_back(IfaceType::P2P);
- break;
- case IfaceConcurrencyType::NAN:
- types_1_0.push_back(IfaceType::NAN);
- break;
- }
- }
- if (types_1_0.empty()) {
- continue;
- }
- V1_0::IWifiChip::ChipIfaceCombinationLimit limit_1_0;
- limit_1_0.types = hidl_vec(types_1_0);
- limit_1_0.maxIfaces = limit_1_6.maxIfaces;
- limits_1_0.push_back(limit_1_0);
- }
- if (limits_1_0.empty()) {
- continue;
- }
- V1_0::IWifiChip::ChipIfaceCombination combo_1_0;
- combo_1_0.limits = hidl_vec(limits_1_0);
- combos_1_0.push_back(combo_1_0);
- }
- if (combos_1_0.empty()) {
- continue;
- }
- V1_0::IWifiChip::ChipMode mode_1_0;
- mode_1_0.id = mode_1_6.id;
- mode_1_0.availableCombinations = hidl_vec(combos_1_0);
- modes_1_0.push_back(mode_1_0);
+ndk::ScopedAStatus WifiChip::registerEventCallbackInternal(
+ const std::shared_ptr<IWifiChipEventCallback>& event_callback) {
+ if (!event_cb_handler_.addCallback(event_callback)) {
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), modes_1_0};
+ return ndk::ScopedAStatus::ok();
}
-WifiStatus WifiChip::configureChipInternal(
- /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock, ChipModeId mode_id) {
+std::pair<IWifiChip::ChipCapabilityMask, ndk::ScopedAStatus> WifiChip::getCapabilitiesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ uint64_t legacy_feature_set;
+ uint32_t legacy_logger_feature_set;
+ const auto ifname = getFirstActiveWlanIfaceName();
+ std::tie(legacy_status, legacy_feature_set) =
+ legacy_hal_.lock()->getSupportedFeatureSet(ifname);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {IWifiChip::ChipCapabilityMask{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ std::tie(legacy_status, legacy_logger_feature_set) =
+ legacy_hal_.lock()->getLoggerSupportedFeatureSet(ifname);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ // some devices don't support querying logger feature set
+ legacy_logger_feature_set = 0;
+ }
+ uint32_t aidl_caps;
+ if (!aidl_struct_util::convertLegacyFeaturesToAidlChipCapabilities(
+ legacy_feature_set, legacy_logger_feature_set, &aidl_caps)) {
+ return {IWifiChip::ChipCapabilityMask{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {static_cast<IWifiChip::ChipCapabilityMask>(aidl_caps), ndk::ScopedAStatus::ok()};
+}
+
+std::pair<std::vector<IWifiChip::ChipMode>, ndk::ScopedAStatus>
+WifiChip::getAvailableModesInternal() {
+ return {modes_, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiChip::configureChipInternal(
+ /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock, int32_t mode_id) {
if (!isValidModeId(mode_id)) {
return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
}
if (mode_id == current_mode_id_) {
LOG(DEBUG) << "Already in the specified mode " << mode_id;
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
- WifiStatus status = handleChipConfiguration(lock, mode_id);
- if (status.code != WifiStatusCode::SUCCESS) {
+ ndk::ScopedAStatus status = handleChipConfiguration(lock, mode_id);
+ if (!status.isOk()) {
+ WifiStatusCode errorCode = static_cast<WifiStatusCode>(status.getServiceSpecificError());
for (const auto& callback : event_cb_handler_.getCallbacks()) {
- if (!callback->onChipReconfigureFailure(status).isOk()) {
+ if (!callback->onChipReconfigureFailure(errorCode).isOk()) {
LOG(ERROR) << "Failed to invoke onChipReconfigureFailure callback";
}
}
@@ -878,24 +795,24 @@
return status;
}
-std::pair<WifiStatus, uint32_t> WifiChip::getModeInternal() {
+std::pair<int32_t, ndk::ScopedAStatus> WifiChip::getModeInternal() {
if (!isValidModeId(current_mode_id_)) {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), current_mode_id_};
+ return {current_mode_id_, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), current_mode_id_};
+ return {current_mode_id_, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, V1_4::IWifiChip::ChipDebugInfo> WifiChip::requestChipDebugInfoInternal() {
- V1_4::IWifiChip::ChipDebugInfo result;
+std::pair<IWifiChip::ChipDebugInfo, ndk::ScopedAStatus> WifiChip::requestChipDebugInfoInternal() {
+ IWifiChip::ChipDebugInfo result;
legacy_hal::wifi_error legacy_status;
std::string driver_desc;
const auto ifname = getFirstActiveWlanIfaceName();
std::tie(legacy_status, driver_desc) = legacy_hal_.lock()->getDriverVersion(ifname);
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to get driver version: " << legacyErrorToString(legacy_status);
- WifiStatus status =
+ ndk::ScopedAStatus status =
createWifiStatusFromLegacyError(legacy_status, "failed to get driver version");
- return {status, result};
+ return {std::move(result), std::move(status)};
}
result.driverDescription = driver_desc.c_str();
@@ -903,59 +820,60 @@
std::tie(legacy_status, firmware_desc) = legacy_hal_.lock()->getFirmwareVersion(ifname);
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to get firmware version: " << legacyErrorToString(legacy_status);
- WifiStatus status =
+ ndk::ScopedAStatus status =
createWifiStatusFromLegacyError(legacy_status, "failed to get firmware version");
- return {status, result};
+ return {std::move(result), std::move(status)};
}
result.firmwareDescription = firmware_desc.c_str();
- return {createWifiStatus(WifiStatusCode::SUCCESS), result};
+ return {std::move(result), ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<uint8_t>> WifiChip::requestDriverDebugDumpInternal() {
+std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> WifiChip::requestDriverDebugDumpInternal() {
legacy_hal::wifi_error legacy_status;
std::vector<uint8_t> driver_dump;
std::tie(legacy_status, driver_dump) =
legacy_hal_.lock()->requestDriverMemoryDump(getFirstActiveWlanIfaceName());
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to get driver debug dump: " << legacyErrorToString(legacy_status);
- return {createWifiStatusFromLegacyError(legacy_status), std::vector<uint8_t>()};
+ return {std::vector<uint8_t>(), createWifiStatusFromLegacyError(legacy_status)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), driver_dump};
+ return {driver_dump, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<uint8_t>> WifiChip::requestFirmwareDebugDumpInternal() {
+std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> WifiChip::requestFirmwareDebugDumpInternal() {
legacy_hal::wifi_error legacy_status;
std::vector<uint8_t> firmware_dump;
std::tie(legacy_status, firmware_dump) =
legacy_hal_.lock()->requestFirmwareMemoryDump(getFirstActiveWlanIfaceName());
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to get firmware debug dump: " << legacyErrorToString(legacy_status);
- return {createWifiStatusFromLegacyError(legacy_status), {}};
+ return {std::vector<uint8_t>(), createWifiStatusFromLegacyError(legacy_status)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), firmware_dump};
+ return {firmware_dump, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::createVirtualApInterface(const std::string& apVirtIf) {
+ndk::ScopedAStatus WifiChip::createVirtualApInterface(const std::string& apVirtIf) {
legacy_hal::wifi_error legacy_status;
legacy_status = legacy_hal_.lock()->createVirtualInterface(
- apVirtIf, hidl_struct_util::convertHidlIfaceTypeToLegacy(IfaceType::AP));
+ apVirtIf, aidl_struct_util::convertAidlIfaceTypeToLegacy(IfaceType::AP));
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to add interface: " << apVirtIf << " "
<< legacyErrorToString(legacy_status);
return createWifiStatusFromLegacyError(legacy_status);
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-sp<WifiApIface> WifiChip::newWifiApIface(std::string& ifname) {
+std::shared_ptr<WifiApIface> WifiChip::newWifiApIface(std::string& ifname) {
std::vector<std::string> ap_instances;
for (auto const& it : br_ifaces_ap_instances_) {
if (it.first == ifname) {
ap_instances = it.second;
}
}
- sp<WifiApIface> iface = new WifiApIface(ifname, ap_instances, legacy_hal_, iface_util_);
+ std::shared_ptr<WifiApIface> iface =
+ ndk::SharedRefBase::make<WifiApIface>(ifname, ap_instances, legacy_hal_, iface_util_);
ap_ifaces_.push_back(iface);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
if (!callback->onIfaceAdded(IfaceType::AP, ifname).isOk()) {
@@ -966,75 +884,77 @@
return iface;
}
-std::pair<WifiStatus, sp<V1_5::IWifiApIface>> WifiChip::createApIfaceInternal() {
+std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> WifiChip::createApIfaceInternal() {
if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::AP)) {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ return {std::shared_ptr<WifiApIface>(),
+ createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
std::string ifname = allocateApIfaceName();
- WifiStatus status = createVirtualApInterface(ifname);
- if (status.code != WifiStatusCode::SUCCESS) {
- return {status, {}};
+ ndk::ScopedAStatus status = createVirtualApInterface(ifname);
+ if (!status.isOk()) {
+ return {std::shared_ptr<WifiApIface>(), std::move(status)};
}
- sp<WifiApIface> iface = newWifiApIface(ifname);
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ std::shared_ptr<WifiApIface> iface = newWifiApIface(ifname);
+ return {iface, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, sp<V1_5::IWifiApIface>> WifiChip::createBridgedApIfaceInternal() {
+std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus>
+WifiChip::createBridgedApIfaceInternal() {
if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::AP_BRIDGED)) {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
std::vector<std::string> ap_instances = allocateBridgedApInstanceNames();
if (ap_instances.size() < 2) {
LOG(ERROR) << "Fail to allocate two instances";
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
std::string br_ifname = kApBridgeIfacePrefix + ap_instances[0];
for (int i = 0; i < 2; i++) {
- WifiStatus status = createVirtualApInterface(ap_instances[i]);
- if (status.code != WifiStatusCode::SUCCESS) {
+ ndk::ScopedAStatus status = createVirtualApInterface(ap_instances[i]);
+ if (!status.isOk()) {
if (i != 0) { // The failure happened when creating second virtual
// iface.
legacy_hal_.lock()->deleteVirtualInterface(
ap_instances.front()); // Remove the first virtual iface.
}
- return {status, {}};
+ return {nullptr, std::move(status)};
}
}
br_ifaces_ap_instances_[br_ifname] = ap_instances;
if (!iface_util_->createBridge(br_ifname)) {
LOG(ERROR) << "Failed createBridge - br_name=" << br_ifname.c_str();
- deleteApIface(br_ifname);
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ invalidateAndClearBridgedAp(br_ifname);
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
for (auto const& instance : ap_instances) {
// Bind ap instance interface to AP bridge
if (!iface_util_->addIfaceToBridge(br_ifname, instance)) {
LOG(ERROR) << "Failed add if to Bridge - if_name=" << instance.c_str();
- deleteApIface(br_ifname);
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ invalidateAndClearBridgedAp(br_ifname);
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
}
- sp<WifiApIface> iface = newWifiApIface(br_ifname);
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ std::shared_ptr<WifiApIface> iface = newWifiApIface(br_ifname);
+ return {iface, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<hidl_string>> WifiChip::getApIfaceNamesInternal() {
+std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getApIfaceNamesInternal() {
if (ap_ifaces_.empty()) {
- return {createWifiStatus(WifiStatusCode::SUCCESS), {}};
+ return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), getNames(ap_ifaces_)};
+ return {getNames(ap_ifaces_), ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, sp<V1_5::IWifiApIface>> WifiChip::getApIfaceInternal(
+std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> WifiChip::getApIfaceInternal(
const std::string& ifname) {
const auto iface = findUsingName(ap_ifaces_, ifname);
if (!iface.get()) {
- return {createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS), nullptr};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::removeApIfaceInternal(const std::string& ifname) {
+ndk::ScopedAStatus WifiChip::removeApIfaceInternal(const std::string& ifname) {
const auto iface = findUsingName(ap_ifaces_, ifname);
if (!iface.get()) {
return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
@@ -1044,7 +964,8 @@
// nan/rtt objects over AP iface. But, there is no harm to do it
// here and not make that assumption all over the place.
invalidateAndRemoveDependencies(ifname);
- deleteApIface(ifname);
+ // Clear the bridge interface and the iface instance.
+ invalidateAndClearBridgedAp(ifname);
invalidateAndClear(ap_ifaces_, iface);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
if (!callback->onIfaceRemoved(IfaceType::AP, ifname).isOk()) {
@@ -1052,10 +973,10 @@
}
}
setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-WifiStatus WifiChip::removeIfaceInstanceFromBridgedApIfaceInternal(
+ndk::ScopedAStatus WifiChip::removeIfaceInstanceFromBridgedApIfaceInternal(
const std::string& ifname, const std::string& ifInstanceName) {
const auto iface = findUsingName(ap_ifaces_, ifname);
if (!iface.get() || ifInstanceName.empty()) {
@@ -1092,12 +1013,12 @@
iface->removeInstance(ifInstanceName);
setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-std::pair<WifiStatus, sp<V1_4::IWifiNanIface>> WifiChip::createNanIfaceInternal() {
- if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::NAN)) {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+std::pair<std::shared_ptr<IWifiNanIface>, ndk::ScopedAStatus> WifiChip::createNanIfaceInternal() {
+ if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::NAN_IFACE)) {
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
bool is_dedicated_iface = true;
std::string ifname = getPredefinedNanIfaceName();
@@ -1107,77 +1028,80 @@
ifname = getFirstActiveWlanIfaceName();
is_dedicated_iface = false;
}
- sp<WifiNanIface> iface = new WifiNanIface(ifname, is_dedicated_iface, legacy_hal_, iface_util_);
+ std::shared_ptr<WifiNanIface> iface =
+ WifiNanIface::create(ifname, is_dedicated_iface, legacy_hal_, iface_util_);
nan_ifaces_.push_back(iface);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
- if (!callback->onIfaceAdded(IfaceType::NAN, ifname).isOk()) {
+ if (!callback->onIfaceAdded(IfaceType::NAN_IFACE, ifname).isOk()) {
LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
}
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<hidl_string>> WifiChip::getNanIfaceNamesInternal() {
+std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getNanIfaceNamesInternal() {
if (nan_ifaces_.empty()) {
- return {createWifiStatus(WifiStatusCode::SUCCESS), {}};
+ return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), getNames(nan_ifaces_)};
+ return {getNames(nan_ifaces_), ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, sp<V1_4::IWifiNanIface>> WifiChip::getNanIfaceInternal(
+std::pair<std::shared_ptr<IWifiNanIface>, ndk::ScopedAStatus> WifiChip::getNanIfaceInternal(
const std::string& ifname) {
const auto iface = findUsingName(nan_ifaces_, ifname);
if (!iface.get()) {
- return {createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS), nullptr};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::removeNanIfaceInternal(const std::string& ifname) {
+ndk::ScopedAStatus WifiChip::removeNanIfaceInternal(const std::string& ifname) {
const auto iface = findUsingName(nan_ifaces_, ifname);
if (!iface.get()) {
return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
}
invalidateAndClear(nan_ifaces_, iface);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
- if (!callback->onIfaceRemoved(IfaceType::NAN, ifname).isOk()) {
+ if (!callback->onIfaceRemoved(IfaceType::NAN_IFACE, ifname).isOk()) {
LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
}
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-std::pair<WifiStatus, sp<IWifiP2pIface>> WifiChip::createP2pIfaceInternal() {
+std::pair<std::shared_ptr<IWifiP2pIface>, ndk::ScopedAStatus> WifiChip::createP2pIfaceInternal() {
if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::P2P)) {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
std::string ifname = getPredefinedP2pIfaceName();
- sp<WifiP2pIface> iface = new WifiP2pIface(ifname, legacy_hal_);
+ std::shared_ptr<WifiP2pIface> iface =
+ ndk::SharedRefBase::make<WifiP2pIface>(ifname, legacy_hal_);
p2p_ifaces_.push_back(iface);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
if (!callback->onIfaceAdded(IfaceType::P2P, ifname).isOk()) {
LOG(ERROR) << "Failed to invoke onIfaceAdded callback";
}
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<hidl_string>> WifiChip::getP2pIfaceNamesInternal() {
+std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getP2pIfaceNamesInternal() {
if (p2p_ifaces_.empty()) {
- return {createWifiStatus(WifiStatusCode::SUCCESS), {}};
+ return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), getNames(p2p_ifaces_)};
+ return {getNames(p2p_ifaces_), ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, sp<IWifiP2pIface>> WifiChip::getP2pIfaceInternal(const std::string& ifname) {
+std::pair<std::shared_ptr<IWifiP2pIface>, ndk::ScopedAStatus> WifiChip::getP2pIfaceInternal(
+ const std::string& ifname) {
const auto iface = findUsingName(p2p_ifaces_, ifname);
if (!iface.get()) {
- return {createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS), nullptr};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::removeP2pIfaceInternal(const std::string& ifname) {
+ndk::ScopedAStatus WifiChip::removeP2pIfaceInternal(const std::string& ifname) {
const auto iface = findUsingName(p2p_ifaces_, ifname);
if (!iface.get()) {
return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
@@ -1188,22 +1112,23 @@
LOG(ERROR) << "Failed to invoke onIfaceRemoved callback";
}
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-std::pair<WifiStatus, sp<V1_6::IWifiStaIface>> WifiChip::createStaIfaceInternal() {
+std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> WifiChip::createStaIfaceInternal() {
if (!canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::STA)) {
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
}
std::string ifname = allocateStaIfaceName();
legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->createVirtualInterface(
- ifname, hidl_struct_util::convertHidlIfaceTypeToLegacy(IfaceType::STA));
+ ifname, aidl_struct_util::convertAidlIfaceTypeToLegacy(IfaceType::STA));
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to add interface: " << ifname << " "
<< legacyErrorToString(legacy_status);
- return {createWifiStatusFromLegacyError(legacy_status), {}};
+ return {nullptr, createWifiStatusFromLegacyError(legacy_status)};
}
- sp<WifiStaIface> iface = new WifiStaIface(ifname, legacy_hal_, iface_util_);
+ std::shared_ptr<WifiStaIface> iface =
+ ndk::SharedRefBase::make<WifiStaIface>(ifname, legacy_hal_, iface_util_);
sta_ifaces_.push_back(iface);
for (const auto& callback : event_cb_handler_.getCallbacks()) {
if (!callback->onIfaceAdded(IfaceType::STA, ifname).isOk()) {
@@ -1211,26 +1136,26 @@
}
}
setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<hidl_string>> WifiChip::getStaIfaceNamesInternal() {
+std::pair<std::vector<std::string>, ndk::ScopedAStatus> WifiChip::getStaIfaceNamesInternal() {
if (sta_ifaces_.empty()) {
- return {createWifiStatus(WifiStatusCode::SUCCESS), {}};
+ return {std::vector<std::string>(), ndk::ScopedAStatus::ok()};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), getNames(sta_ifaces_)};
+ return {getNames(sta_ifaces_), ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, sp<V1_6::IWifiStaIface>> WifiChip::getStaIfaceInternal(
+std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> WifiChip::getStaIfaceInternal(
const std::string& ifname) {
const auto iface = findUsingName(sta_ifaces_, ifname);
if (!iface.get()) {
- return {createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS), nullptr};
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), iface};
+ return {iface, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::removeStaIfaceInternal(const std::string& ifname) {
+ndk::ScopedAStatus WifiChip::removeStaIfaceInternal(const std::string& ifname) {
const auto iface = findUsingName(sta_ifaces_, ifname);
if (!iface.get()) {
return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
@@ -1249,37 +1174,47 @@
}
}
setActiveWlanIfaceNameProperty(getFirstActiveWlanIfaceName());
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-std::pair<WifiStatus, sp<V1_0::IWifiRttController>> WifiChip::createRttControllerInternal(
- const sp<IWifiIface>& /*bound_iface*/) {
- LOG(ERROR) << "createRttController is not supported on this HAL";
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
+std::pair<std::shared_ptr<IWifiRttController>, ndk::ScopedAStatus>
+WifiChip::createRttControllerInternal(const std::shared_ptr<IWifiStaIface>& bound_iface) {
+ if (sta_ifaces_.size() == 0 &&
+ !canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::STA)) {
+ LOG(ERROR) << "createRttControllerInternal: Chip cannot support STAs "
+ "(and RTT by extension)";
+ return {nullptr, createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE)};
+ }
+ std::shared_ptr<WifiRttController> rtt =
+ WifiRttController::create(getFirstActiveWlanIfaceName(), bound_iface, legacy_hal_);
+ rtt_controllers_.emplace_back(rtt);
+ return {rtt, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<WifiDebugRingBufferStatus>>
+std::pair<std::vector<WifiDebugRingBufferStatus>, ndk::ScopedAStatus>
WifiChip::getDebugRingBuffersStatusInternal() {
legacy_hal::wifi_error legacy_status;
std::vector<legacy_hal::wifi_ring_buffer_status> legacy_ring_buffer_status_vec;
std::tie(legacy_status, legacy_ring_buffer_status_vec) =
legacy_hal_.lock()->getRingBuffersStatus(getFirstActiveWlanIfaceName());
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
+ return {std::vector<WifiDebugRingBufferStatus>(),
+ createWifiStatusFromLegacyError(legacy_status)};
}
- std::vector<WifiDebugRingBufferStatus> hidl_ring_buffer_status_vec;
- if (!hidl_struct_util::convertLegacyVectorOfDebugRingBufferStatusToHidl(
- legacy_ring_buffer_status_vec, &hidl_ring_buffer_status_vec)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
+ std::vector<WifiDebugRingBufferStatus> aidl_ring_buffer_status_vec;
+ if (!aidl_struct_util::convertLegacyVectorOfDebugRingBufferStatusToAidl(
+ legacy_ring_buffer_status_vec, &aidl_ring_buffer_status_vec)) {
+ return {std::vector<WifiDebugRingBufferStatus>(),
+ createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_ring_buffer_status_vec};
+ return {aidl_ring_buffer_status_vec, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::startLoggingToDebugRingBufferInternal(
- const hidl_string& ring_name, WifiDebugRingBufferVerboseLevel verbose_level,
+ndk::ScopedAStatus WifiChip::startLoggingToDebugRingBufferInternal(
+ const std::string& ring_name, WifiDebugRingBufferVerboseLevel verbose_level,
uint32_t max_interval_in_sec, uint32_t min_data_size_in_bytes) {
- WifiStatus status = registerDebugRingBufferCallback();
- if (status.code != WifiStatusCode::SUCCESS) {
+ ndk::ScopedAStatus status = registerDebugRingBufferCallback();
+ if (!status.isOk()) {
return status;
}
legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startRingBufferLogging(
@@ -1290,16 +1225,16 @@
std::pair<std::string, Ringbuffer>(ring_name, Ringbuffer(kMaxBufferSizeBytes)));
// if verbose logging enabled, turn up HAL daemon logging as well.
if (verbose_level < WifiDebugRingBufferVerboseLevel::VERBOSE) {
- android::base::SetMinimumLogSeverity(android::base::DEBUG);
+ ::android::base::SetMinimumLogSeverity(::android::base::DEBUG);
} else {
- android::base::SetMinimumLogSeverity(android::base::VERBOSE);
+ ::android::base::SetMinimumLogSeverity(::android::base::VERBOSE);
}
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::forceDumpToDebugRingBufferInternal(const hidl_string& ring_name) {
- WifiStatus status = registerDebugRingBufferCallback();
- if (status.code != WifiStatusCode::SUCCESS) {
+ndk::ScopedAStatus WifiChip::forceDumpToDebugRingBufferInternal(const std::string& ring_name) {
+ ndk::ScopedAStatus status = registerDebugRingBufferCallback();
+ if (!status.isOk()) {
return status;
}
legacy_hal::wifi_error legacy_status =
@@ -1308,15 +1243,15 @@
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::flushRingBufferToFileInternal() {
+ndk::ScopedAStatus WifiChip::flushRingBufferToFileInternal() {
if (!writeRingbufferFilesInternal()) {
LOG(ERROR) << "Error writing files to flash";
return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-WifiStatus WifiChip::stopLoggingToDebugRingBufferInternal() {
+ndk::ScopedAStatus WifiChip::stopLoggingToDebugRingBufferInternal() {
legacy_hal::wifi_error legacy_status =
legacy_hal_.lock()->deregisterRingBufferCallbackHandler(getFirstActiveWlanIfaceName());
if (legacy_status == legacy_hal::WIFI_SUCCESS) {
@@ -1325,29 +1260,29 @@
return createWifiStatusFromLegacyError(legacy_status);
}
-std::pair<WifiStatus, WifiDebugHostWakeReasonStats>
+std::pair<WifiDebugHostWakeReasonStats, ndk::ScopedAStatus>
WifiChip::getDebugHostWakeReasonStatsInternal() {
legacy_hal::wifi_error legacy_status;
legacy_hal::WakeReasonStats legacy_stats;
std::tie(legacy_status, legacy_stats) =
legacy_hal_.lock()->getWakeReasonStats(getFirstActiveWlanIfaceName());
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
+ return {WifiDebugHostWakeReasonStats{}, createWifiStatusFromLegacyError(legacy_status)};
}
- WifiDebugHostWakeReasonStats hidl_stats;
- if (!hidl_struct_util::convertLegacyWakeReasonStatsToHidl(legacy_stats, &hidl_stats)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
+ WifiDebugHostWakeReasonStats aidl_stats;
+ if (!aidl_struct_util::convertLegacyWakeReasonStatsToAidl(legacy_stats, &aidl_stats)) {
+ return {WifiDebugHostWakeReasonStats{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_stats};
+ return {aidl_stats, ndk::ScopedAStatus::ok()};
}
-WifiStatus WifiChip::enableDebugErrorAlertsInternal(bool enable) {
+ndk::ScopedAStatus WifiChip::enableDebugErrorAlertsInternal(bool enable) {
legacy_hal::wifi_error legacy_status;
if (enable) {
- android::wp<WifiChip> weak_ptr_this(this);
+ std::weak_ptr<WifiChip> weak_ptr_this = weak_ptr_this_;
const auto& on_alert_callback = [weak_ptr_this](int32_t error_code,
std::vector<uint8_t> debug_data) {
- const auto shared_ptr_this = weak_ptr_this.promote();
+ const auto shared_ptr_this = weak_ptr_this.lock();
if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
LOG(ERROR) << "Callback invoked on an invalid object";
return;
@@ -1367,106 +1302,51 @@
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::selectTxPowerScenarioInternal(V1_1::IWifiChip::TxPowerScenario scenario) {
+ndk::ScopedAStatus WifiChip::selectTxPowerScenarioInternal(IWifiChip::TxPowerScenario scenario) {
auto legacy_status = legacy_hal_.lock()->selectTxPowerScenario(
getFirstActiveWlanIfaceName(),
- hidl_struct_util::convertHidlTxPowerScenarioToLegacy(scenario));
+ aidl_struct_util::convertAidlTxPowerScenarioToLegacy(scenario));
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::resetTxPowerScenarioInternal() {
+ndk::ScopedAStatus WifiChip::resetTxPowerScenarioInternal() {
auto legacy_status = legacy_hal_.lock()->resetTxPowerScenario(getFirstActiveWlanIfaceName());
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::setLatencyModeInternal(LatencyMode mode) {
+ndk::ScopedAStatus WifiChip::setLatencyModeInternal(IWifiChip::LatencyMode mode) {
auto legacy_status = legacy_hal_.lock()->setLatencyMode(
- getFirstActiveWlanIfaceName(), hidl_struct_util::convertHidlLatencyModeToLegacy(mode));
+ getFirstActiveWlanIfaceName(), aidl_struct_util::convertAidlLatencyModeToLegacy(mode));
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::registerEventCallbackInternal_1_2(
- const sp<V1_2::IWifiChipEventCallback>& /* event_callback */) {
- // Deprecated support for this callback.
- return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
-}
-
-WifiStatus WifiChip::selectTxPowerScenarioInternal_1_2(TxPowerScenario scenario) {
- auto legacy_status = legacy_hal_.lock()->selectTxPowerScenario(
- getFirstActiveWlanIfaceName(),
- hidl_struct_util::convertHidlTxPowerScenarioToLegacy_1_2(scenario));
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, uint32_t> WifiChip::getCapabilitiesInternal_1_3() {
- // Deprecated support for this callback.
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), 0};
-}
-
-std::pair<WifiStatus, uint32_t> WifiChip::getCapabilitiesInternal_1_5() {
- legacy_hal::wifi_error legacy_status;
- uint64_t legacy_feature_set;
- uint32_t legacy_logger_feature_set;
- const auto ifname = getFirstActiveWlanIfaceName();
- std::tie(legacy_status, legacy_feature_set) =
- legacy_hal_.lock()->getSupportedFeatureSet(ifname);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), 0};
- }
- std::tie(legacy_status, legacy_logger_feature_set) =
- legacy_hal_.lock()->getLoggerSupportedFeatureSet(ifname);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- // some devices don't support querying logger feature set
- legacy_logger_feature_set = 0;
- }
- uint32_t hidl_caps;
- if (!hidl_struct_util::convertLegacyFeaturesToHidlChipCapabilities(
- legacy_feature_set, legacy_logger_feature_set, &hidl_caps)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), 0};
- }
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_caps};
-}
-
-std::pair<WifiStatus, sp<V1_4::IWifiRttController>> WifiChip::createRttControllerInternal_1_4(
- const sp<IWifiIface>& /*bound_iface*/) {
- LOG(ERROR) << "createRttController_1_4 is not supported on this HAL";
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-WifiStatus WifiChip::registerEventCallbackInternal_1_4(
- const sp<V1_4::IWifiChipEventCallback>& event_callback) {
- if (!event_cb_handler_.addCallback(event_callback)) {
- return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
- }
- return createWifiStatus(WifiStatusCode::SUCCESS);
-}
-
-WifiStatus WifiChip::setMultiStaPrimaryConnectionInternal(const std::string& ifname) {
+ndk::ScopedAStatus WifiChip::setMultiStaPrimaryConnectionInternal(const std::string& ifname) {
auto legacy_status = legacy_hal_.lock()->multiStaSetPrimaryConnection(ifname);
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::setMultiStaUseCaseInternal(MultiStaUseCase use_case) {
+ndk::ScopedAStatus WifiChip::setMultiStaUseCaseInternal(IWifiChip::MultiStaUseCase use_case) {
auto legacy_status = legacy_hal_.lock()->multiStaSetUseCase(
- hidl_struct_util::convertHidlMultiStaUseCaseToLegacy(use_case));
+ aidl_struct_util::convertAidlMultiStaUseCaseToLegacy(use_case));
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::setCoexUnsafeChannelsInternal(std::vector<CoexUnsafeChannel> unsafe_channels,
- uint32_t restrictions) {
+ndk::ScopedAStatus WifiChip::setCoexUnsafeChannelsInternal(
+ std::vector<IWifiChip::CoexUnsafeChannel> unsafe_channels, CoexRestriction restrictions) {
std::vector<legacy_hal::wifi_coex_unsafe_channel> legacy_unsafe_channels;
- if (!hidl_struct_util::convertHidlVectorOfCoexUnsafeChannelToLegacy(unsafe_channels,
+ if (!aidl_struct_util::convertAidlVectorOfCoexUnsafeChannelToLegacy(unsafe_channels,
&legacy_unsafe_channels)) {
return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
}
+ uint32_t aidl_restrictions = static_cast<uint32_t>(restrictions);
uint32_t legacy_restrictions = 0;
- if (restrictions & CoexRestriction::WIFI_DIRECT) {
+ if (aidl_restrictions & static_cast<uint32_t>(CoexRestriction::WIFI_DIRECT)) {
legacy_restrictions |= legacy_hal::wifi_coex_restriction::WIFI_DIRECT;
}
- if (restrictions & CoexRestriction::SOFTAP) {
+ if (aidl_restrictions & static_cast<uint32_t>(CoexRestriction::SOFTAP)) {
legacy_restrictions |= legacy_hal::wifi_coex_restriction::SOFTAP;
}
- if (restrictions & CoexRestriction::WIFI_AWARE) {
+ if (aidl_restrictions & static_cast<uint32_t>(CoexRestriction::WIFI_AWARE)) {
legacy_restrictions |= legacy_hal::wifi_coex_restriction::WIFI_AWARE;
}
auto legacy_status =
@@ -1474,57 +1354,34 @@
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::setCountryCodeInternal(const std::array<int8_t, 2>& code) {
+ndk::ScopedAStatus WifiChip::setCountryCodeInternal(const std::array<uint8_t, 2>& code) {
auto legacy_status = legacy_hal_.lock()->setCountryCode(getFirstActiveWlanIfaceName(), code);
return createWifiStatusFromLegacyError(legacy_status);
}
-std::pair<WifiStatus, std::vector<V1_5::WifiUsableChannel>> WifiChip::getUsableChannelsInternal(
- WifiBand /*band*/, uint32_t /*ifaceModeMask*/, uint32_t /*filterMask*/) {
- LOG(ERROR) << "getUsableChannels is not supported on this HAL";
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED), {}};
-}
-
-WifiStatus WifiChip::triggerSubsystemRestartInternal() {
- auto legacy_status = legacy_hal_.lock()->triggerSubsystemRestart();
- return createWifiStatusFromLegacyError(legacy_status);
-}
-
-std::pair<WifiStatus, sp<V1_6::IWifiRttController>> WifiChip::createRttControllerInternal_1_6(
- const sp<IWifiIface>& bound_iface) {
- if (sta_ifaces_.size() == 0 &&
- !canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType::STA)) {
- LOG(ERROR) << "createRttControllerInternal_1_6: Chip cannot support STAs "
- "(and RTT by extension)";
- return {createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE), {}};
- }
- sp<WifiRttController> rtt =
- new WifiRttController(getFirstActiveWlanIfaceName(), bound_iface, legacy_hal_);
- rtt_controllers_.emplace_back(rtt);
- return {createWifiStatus(WifiStatusCode::SUCCESS), rtt};
-}
-
-std::pair<WifiStatus, std::vector<V1_6::WifiUsableChannel>> WifiChip::getUsableChannelsInternal_1_6(
- WifiBand band, uint32_t ifaceModeMask, uint32_t filterMask) {
+std::pair<std::vector<WifiUsableChannel>, ndk::ScopedAStatus> WifiChip::getUsableChannelsInternal(
+ WifiBand band, WifiIfaceMode ifaceModeMask, UsableChannelFilter filterMask) {
legacy_hal::wifi_error legacy_status;
std::vector<legacy_hal::wifi_usable_channel> legacy_usable_channels;
std::tie(legacy_status, legacy_usable_channels) = legacy_hal_.lock()->getUsableChannels(
- hidl_struct_util::convertHidlWifiBandToLegacyMacBand(band),
- hidl_struct_util::convertHidlWifiIfaceModeToLegacy(ifaceModeMask),
- hidl_struct_util::convertHidlUsableChannelFilterToLegacy(filterMask));
+ aidl_struct_util::convertAidlWifiBandToLegacyMacBand(band),
+ aidl_struct_util::convertAidlWifiIfaceModeToLegacy(
+ static_cast<uint32_t>(ifaceModeMask)),
+ aidl_struct_util::convertAidlUsableChannelFilterToLegacy(
+ static_cast<uint32_t>(filterMask)));
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- return {createWifiStatusFromLegacyError(legacy_status), {}};
+ return {std::vector<WifiUsableChannel>(), createWifiStatusFromLegacyError(legacy_status)};
}
- std::vector<V1_6::WifiUsableChannel> hidl_usable_channels;
- if (!hidl_struct_util::convertLegacyWifiUsableChannelsToHidl(legacy_usable_channels,
- &hidl_usable_channels)) {
- return {createWifiStatus(WifiStatusCode::ERROR_UNKNOWN), {}};
+ std::vector<WifiUsableChannel> aidl_usable_channels;
+ if (!aidl_struct_util::convertLegacyWifiUsableChannelsToAidl(legacy_usable_channels,
+ &aidl_usable_channels)) {
+ return {std::vector<WifiUsableChannel>(), createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_usable_channels};
+ return {aidl_usable_channels, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, V1_6::WifiRadioCombinationMatrix>
+std::pair<WifiRadioCombinationMatrix, ndk::ScopedAStatus>
WifiChip::getSupportedRadioCombinationsMatrixInternal() {
legacy_hal::wifi_error legacy_status;
legacy_hal::wifi_radio_combination_matrix* legacy_matrix;
@@ -1534,25 +1391,25 @@
if (legacy_status != legacy_hal::WIFI_SUCCESS) {
LOG(ERROR) << "Failed to get SupportedRadioCombinations matrix from legacy HAL: "
<< legacyErrorToString(legacy_status);
- return {createWifiStatusFromLegacyError(legacy_status), {}};
+ return {WifiRadioCombinationMatrix{}, createWifiStatusFromLegacyError(legacy_status)};
}
- V1_6::WifiRadioCombinationMatrix hidl_matrix;
- if (!hidl_struct_util::convertLegacyRadioCombinationsMatrixToHidl(legacy_matrix,
- &hidl_matrix)) {
- LOG(ERROR) << "Failed convertLegacyRadioCombinationsMatrixToHidl() ";
- return {createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS), {}};
+ WifiRadioCombinationMatrix aidl_matrix;
+ if (!aidl_struct_util::convertLegacyRadioCombinationsMatrixToAidl(legacy_matrix,
+ &aidl_matrix)) {
+ LOG(ERROR) << "Failed convertLegacyRadioCombinationsMatrixToAidl() ";
+ return {WifiRadioCombinationMatrix(), createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS)};
}
- return {createWifiStatus(WifiStatusCode::SUCCESS), hidl_matrix};
+ return {aidl_matrix, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::vector<V1_6::IWifiChip::ChipMode>>
-WifiChip::getAvailableModesInternal_1_6() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), modes_};
+ndk::ScopedAStatus WifiChip::triggerSubsystemRestartInternal() {
+ auto legacy_status = legacy_hal_.lock()->triggerSubsystemRestart();
+ return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::handleChipConfiguration(
- /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock, ChipModeId mode_id) {
+ndk::ScopedAStatus WifiChip::handleChipConfiguration(
+ /* NONNULL */ std::unique_lock<std::recursive_mutex>* lock, int32_t mode_id) {
// If the chip is already configured in a different mode, stop
// the legacy HAL and then start it after firmware mode change.
if (isValidModeId(current_mode_id_)) {
@@ -1581,41 +1438,41 @@
}
// Every time the HAL is restarted, we need to register the
// radio mode change callback.
- WifiStatus status = registerRadioModeChangeCallback();
- if (status.code != WifiStatusCode::SUCCESS) {
- // This probably is not a critical failure?
+ ndk::ScopedAStatus status = registerRadioModeChangeCallback();
+ if (!status.isOk()) {
+ // This is probably not a critical failure?
LOG(ERROR) << "Failed to register radio mode change callback";
}
// Extract and save the version information into property.
- std::pair<WifiStatus, V1_4::IWifiChip::ChipDebugInfo> version_info;
+ std::pair<IWifiChip::ChipDebugInfo, ndk::ScopedAStatus> version_info;
version_info = WifiChip::requestChipDebugInfoInternal();
- if (WifiStatusCode::SUCCESS == version_info.first.code) {
+ if (version_info.second.isOk()) {
property_set("vendor.wlan.firmware.version",
- version_info.second.firmwareDescription.c_str());
- property_set("vendor.wlan.driver.version", version_info.second.driverDescription.c_str());
+ version_info.first.firmwareDescription.c_str());
+ property_set("vendor.wlan.driver.version", version_info.first.driverDescription.c_str());
}
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
-WifiStatus WifiChip::registerDebugRingBufferCallback() {
+ndk::ScopedAStatus WifiChip::registerDebugRingBufferCallback() {
if (debug_ring_buffer_cb_registered_) {
- return createWifiStatus(WifiStatusCode::SUCCESS);
+ return ndk::ScopedAStatus::ok();
}
- android::wp<WifiChip> weak_ptr_this(this);
+ std::weak_ptr<WifiChip> weak_ptr_this = weak_ptr_this_;
const auto& on_ring_buffer_data_callback =
[weak_ptr_this](const std::string& name, const std::vector<uint8_t>& data,
const legacy_hal::wifi_ring_buffer_status& status) {
- const auto shared_ptr_this = weak_ptr_this.promote();
+ const auto shared_ptr_this = weak_ptr_this.lock();
if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
LOG(ERROR) << "Callback invoked on an invalid object";
return;
}
- WifiDebugRingBufferStatus hidl_status;
+ WifiDebugRingBufferStatus aidl_status;
Ringbuffer::AppendStatus appendstatus;
- if (!hidl_struct_util::convertLegacyDebugRingBufferStatusToHidl(status,
- &hidl_status)) {
+ if (!aidl_struct_util::convertLegacyDebugRingBufferStatusToAidl(status,
+ &aidl_status)) {
LOG(ERROR) << "Error converting ring buffer status";
return;
}
@@ -1636,7 +1493,6 @@
shared_ptr_this->writeRingbufferFilesInternal();
return;
}
-
};
legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->registerRingBufferCallbackHandler(
getFirstActiveWlanIfaceName(), on_ring_buffer_data_callback);
@@ -1647,25 +1503,24 @@
return createWifiStatusFromLegacyError(legacy_status);
}
-WifiStatus WifiChip::registerRadioModeChangeCallback() {
- android::wp<WifiChip> weak_ptr_this(this);
+ndk::ScopedAStatus WifiChip::registerRadioModeChangeCallback() {
+ std::weak_ptr<WifiChip> weak_ptr_this = weak_ptr_this_;
const auto& on_radio_mode_change_callback =
[weak_ptr_this](const std::vector<legacy_hal::WifiMacInfo>& mac_infos) {
- const auto shared_ptr_this = weak_ptr_this.promote();
+ const auto shared_ptr_this = weak_ptr_this.lock();
if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
LOG(ERROR) << "Callback invoked on an invalid object";
return;
}
- std::vector<V1_4::IWifiChipEventCallback::RadioModeInfo> hidl_radio_mode_infos;
- if (!hidl_struct_util::convertLegacyWifiMacInfosToHidl(mac_infos,
- &hidl_radio_mode_infos)) {
+ std::vector<IWifiChipEventCallback::RadioModeInfo> aidl_radio_mode_infos;
+ if (!aidl_struct_util::convertLegacyWifiMacInfosToAidl(mac_infos,
+ &aidl_radio_mode_infos)) {
LOG(ERROR) << "Error converting wifi mac info";
return;
}
for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
- if (!callback->onRadioModeChange_1_4(hidl_radio_mode_infos).isOk()) {
- LOG(ERROR) << "Failed to invoke onRadioModeChange_1_4"
- << " callback on: " << toString(callback);
+ if (!callback->onRadioModeChange(aidl_radio_mode_infos).isOk()) {
+ LOG(ERROR) << "Failed to invoke onRadioModeChange callback";
}
}
};
@@ -1675,11 +1530,11 @@
return createWifiStatusFromLegacyError(legacy_status);
}
-std::vector<V1_6::IWifiChip::ChipConcurrencyCombination>
+std::vector<IWifiChip::ChipConcurrencyCombination>
WifiChip::getCurrentModeConcurrencyCombinations() {
if (!isValidModeId(current_mode_id_)) {
LOG(ERROR) << "Chip not configured in a mode yet";
- return {};
+ return std::vector<IWifiChip::ChipConcurrencyCombination>();
}
for (const auto& mode : modes_) {
if (mode.id == current_mode_id_) {
@@ -1687,7 +1542,7 @@
}
}
CHECK(0) << "Expected to find concurrency combinations for current mode!";
- return {};
+ return std::vector<IWifiChip::ChipConcurrencyCombination>();
}
// Returns a map indexed by IfaceConcurrencyType with the number of ifaces currently
@@ -1707,7 +1562,7 @@
}
iface_counts[IfaceConcurrencyType::AP] = num_ap;
iface_counts[IfaceConcurrencyType::AP_BRIDGED] = num_ap_bridged;
- iface_counts[IfaceConcurrencyType::NAN] = nan_ifaces_.size();
+ iface_counts[IfaceConcurrencyType::NAN_IFACE] = nan_ifaces_.size();
iface_counts[IfaceConcurrencyType::P2P] = p2p_ifaces_.size();
iface_counts[IfaceConcurrencyType::STA] = sta_ifaces_.size();
return iface_counts;
@@ -1718,10 +1573,10 @@
// of each concurrency type in the combination.
// This method is a port of HalDeviceManager.expandConcurrencyCombos() from framework.
std::vector<std::map<IfaceConcurrencyType, size_t>> WifiChip::expandConcurrencyCombinations(
- const V1_6::IWifiChip::ChipConcurrencyCombination& combination) {
- uint32_t num_expanded_combos = 1;
+ const IWifiChip::ChipConcurrencyCombination& combination) {
+ int32_t num_expanded_combos = 1;
for (const auto& limit : combination.limits) {
- for (uint32_t i = 0; i < limit.maxIfaces; i++) {
+ for (int32_t i = 0; i < limit.maxIfaces; i++) {
num_expanded_combos *= limit.types.size();
}
}
@@ -1731,17 +1586,17 @@
std::vector<std::map<IfaceConcurrencyType, size_t>> expanded_combos;
expanded_combos.resize(num_expanded_combos);
for (auto& expanded_combo : expanded_combos) {
- for (const auto type :
- {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED, IfaceConcurrencyType::NAN,
- IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
+ for (const auto type : {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED,
+ IfaceConcurrencyType::NAN_IFACE, IfaceConcurrencyType::P2P,
+ IfaceConcurrencyType::STA}) {
expanded_combo[type] = 0;
}
}
- uint32_t span = num_expanded_combos;
+ int32_t span = num_expanded_combos;
for (const auto& limit : combination.limits) {
- for (uint32_t i = 0; i < limit.maxIfaces; i++) {
+ for (int32_t i = 0; i < limit.maxIfaces; i++) {
span /= limit.types.size();
- for (uint32_t k = 0; k < num_expanded_combos; ++k) {
+ for (int32_t k = 0; k < num_expanded_combos; ++k) {
const auto iface_type = limit.types[(k / span) % limit.types.size()];
expanded_combos[k][iface_type]++;
}
@@ -1757,8 +1612,8 @@
// Check if we have space for 1 more iface of |type| in this combo
for (const auto type :
- {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED, IfaceConcurrencyType::NAN,
- IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
+ {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED,
+ IfaceConcurrencyType::NAN_IFACE, IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
size_t num_ifaces_needed = current_combo.at(type);
if (type == requested_type) {
num_ifaces_needed++;
@@ -1802,8 +1657,8 @@
const std::map<IfaceConcurrencyType, size_t>& req_combo) {
// Check if we have space for 1 more |type| in this combo
for (const auto type :
- {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED, IfaceConcurrencyType::NAN,
- IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
+ {IfaceConcurrencyType::AP, IfaceConcurrencyType::AP_BRIDGED,
+ IfaceConcurrencyType::NAN_IFACE, IfaceConcurrencyType::P2P, IfaceConcurrencyType::STA}) {
if (req_combo.count(type) == 0) {
// Concurrency type not in the req_combo.
continue;
@@ -1816,6 +1671,7 @@
}
return true;
}
+
// This method does the following:
// a) Enumerate all possible concurrency combos by expanding the current
// ChipConcurrencyCombination.
@@ -1851,7 +1707,7 @@
return canCurrentModeSupportConcurrencyCombo(req_iface_combo);
}
-bool WifiChip::isValidModeId(ChipModeId mode_id) {
+bool WifiChip::isValidModeId(int32_t mode_id) {
for (const auto& mode : modes_) {
if (mode.id == mode_id) {
return true;
@@ -2017,28 +1873,21 @@
br_ifaces_ap_instances_.clear();
}
-void WifiChip::deleteApIface(const std::string& if_name) {
- if (if_name.empty()) return;
- // delete bridged interfaces if have
+void WifiChip::invalidateAndClearBridgedAp(const std::string& br_name) {
+ if (br_name.empty()) return;
+ // delete managed interfaces
for (auto const& it : br_ifaces_ap_instances_) {
- if (it.first == if_name) {
+ if (it.first == br_name) {
for (auto const& iface : it.second) {
- iface_util_->removeIfaceFromBridge(if_name, iface);
+ iface_util_->removeIfaceFromBridge(br_name, iface);
legacy_hal_.lock()->deleteVirtualInterface(iface);
}
- iface_util_->deleteBridge(if_name);
- br_ifaces_ap_instances_.erase(if_name);
- // ifname is bridged AP, return here.
- return;
+ iface_util_->deleteBridge(br_name);
+ br_ifaces_ap_instances_.erase(br_name);
+ break;
}
}
-
- // No bridged AP case, delete AP iface
- legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->deleteVirtualInterface(if_name);
- if (legacy_status != legacy_hal::WIFI_SUCCESS) {
- LOG(ERROR) << "Failed to remove interface: " << if_name << " "
- << legacyErrorToString(legacy_status);
- }
+ return;
}
bool WifiChip::findUsingNameFromBridgedApInstances(const std::string& name) {
@@ -2055,8 +1904,7 @@
return false;
}
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi_chip.h b/wifi/aidl/default/wifi_chip.h
new file mode 100644
index 0000000..59eaa4a
--- /dev/null
+++ b/wifi/aidl/default/wifi_chip.h
@@ -0,0 +1,287 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_CHIP_H_
+#define WIFI_CHIP_H_
+
+#include <aidl/android/hardware/wifi/BnWifiChip.h>
+#include <aidl/android/hardware/wifi/IWifiRttController.h>
+#include <android-base/macros.h>
+
+#include <list>
+#include <map>
+#include <mutex>
+
+#include "aidl_callback_util.h"
+#include "ringbuffer.h"
+#include "wifi_ap_iface.h"
+#include "wifi_feature_flags.h"
+#include "wifi_legacy_hal.h"
+#include "wifi_mode_controller.h"
+#include "wifi_nan_iface.h"
+#include "wifi_p2p_iface.h"
+#include "wifi_rtt_controller.h"
+#include "wifi_sta_iface.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+/**
+ * AIDL interface object used to control a Wifi HAL chip instance.
+ * Since there is only a single chip instance used today, there is no
+ * identifying handle information stored here.
+ */
+class WifiChip : public BnWifiChip {
+ public:
+ WifiChip(int32_t chip_id, bool is_primary,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
+ const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
+ const std::weak_ptr<feature_flags::WifiFeatureFlags> feature_flags,
+ const std::function<void(const std::string&)>& subsystemCallbackHandler);
+
+ // Factory method - use instead of default constructor.
+ static std::shared_ptr<WifiChip> create(
+ int32_t chip_id, bool is_primary,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<mode_controller::WifiModeController> mode_controller,
+ const std::shared_ptr<iface_util::WifiIfaceUtil> iface_util,
+ const std::weak_ptr<feature_flags::WifiFeatureFlags> feature_flags,
+ const std::function<void(const std::string&)>& subsystemCallbackHandler);
+
+ // AIDL does not provide a built-in mechanism to let the server invalidate
+ // an AIDL interface object after creation. If any client process holds onto
+ // a reference to the object in their context, any method calls on that
+ // reference will continue to be directed to the server.
+ //
+ // However Wifi HAL needs to control the lifetime of these objects. So, add
+ // a public |invalidate| method to |WifiChip| and its child objects. This
+ // will be used to mark an object invalid when either:
+ // a) Wifi HAL is stopped, or
+ // b) Wifi Chip is reconfigured.
+ //
+ // All AIDL method implementations should check if the object is still
+ // marked valid before processing them.
+ void invalidate();
+ bool isValid();
+ std::set<std::shared_ptr<IWifiChipEventCallback>> getEventCallbacks();
+
+ // AIDL methods exposed.
+ ndk::ScopedAStatus getId(int32_t* _aidl_return) override;
+ ndk::ScopedAStatus registerEventCallback(
+ const std::shared_ptr<IWifiChipEventCallback>& in_callback) override;
+ ndk::ScopedAStatus getCapabilities(IWifiChip::ChipCapabilityMask* _aidl_return) override;
+ ndk::ScopedAStatus getAvailableModes(std::vector<IWifiChip::ChipMode>* _aidl_return) override;
+ ndk::ScopedAStatus configureChip(int32_t in_modeId) override;
+ ndk::ScopedAStatus getMode(int32_t* _aidl_return) override;
+ ndk::ScopedAStatus requestChipDebugInfo(IWifiChip::ChipDebugInfo* _aidl_return) override;
+ ndk::ScopedAStatus requestDriverDebugDump(std::vector<uint8_t>* _aidl_return) override;
+ ndk::ScopedAStatus requestFirmwareDebugDump(std::vector<uint8_t>* _aidl_return) override;
+ ndk::ScopedAStatus createApIface(std::shared_ptr<IWifiApIface>* _aidl_return) override;
+ ndk::ScopedAStatus createBridgedApIface(std::shared_ptr<IWifiApIface>* _aidl_return) override;
+ ndk::ScopedAStatus getApIfaceNames(std::vector<std::string>* _aidl_return) override;
+ ndk::ScopedAStatus getApIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiApIface>* _aidl_return) override;
+ ndk::ScopedAStatus removeApIface(const std::string& in_ifname) override;
+ ndk::ScopedAStatus removeIfaceInstanceFromBridgedApIface(
+ const std::string& in_brIfaceName, const std::string& in_ifaceInstanceName) override;
+ ndk::ScopedAStatus createNanIface(std::shared_ptr<IWifiNanIface>* _aidl_return) override;
+ ndk::ScopedAStatus getNanIfaceNames(std::vector<std::string>* _aidl_return) override;
+ ndk::ScopedAStatus getNanIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiNanIface>* _aidl_return) override;
+ ndk::ScopedAStatus removeNanIface(const std::string& in_ifname) override;
+ ndk::ScopedAStatus createP2pIface(std::shared_ptr<IWifiP2pIface>* _aidl_return) override;
+ ndk::ScopedAStatus getP2pIfaceNames(std::vector<std::string>* _aidl_return) override;
+ ndk::ScopedAStatus getP2pIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiP2pIface>* _aidl_return) override;
+ ndk::ScopedAStatus removeP2pIface(const std::string& in_ifname) override;
+ ndk::ScopedAStatus createStaIface(std::shared_ptr<IWifiStaIface>* _aidl_return) override;
+ ndk::ScopedAStatus getStaIfaceNames(std::vector<std::string>* _aidl_return) override;
+ ndk::ScopedAStatus getStaIface(const std::string& in_ifname,
+ std::shared_ptr<IWifiStaIface>* _aidl_return) override;
+ ndk::ScopedAStatus removeStaIface(const std::string& in_ifname) override;
+ ndk::ScopedAStatus createRttController(
+ const std::shared_ptr<IWifiStaIface>& in_boundIface,
+ std::shared_ptr<IWifiRttController>* _aidl_return) override;
+ ndk::ScopedAStatus getDebugRingBuffersStatus(
+ std::vector<WifiDebugRingBufferStatus>* _aidl_return) override;
+ ndk::ScopedAStatus startLoggingToDebugRingBuffer(
+ const std::string& in_ringName, WifiDebugRingBufferVerboseLevel in_verboseLevel,
+ int32_t in_maxIntervalInSec, int32_t in_minDataSizeInBytes) override;
+ ndk::ScopedAStatus forceDumpToDebugRingBuffer(const std::string& in_ringName) override;
+ ndk::ScopedAStatus flushRingBufferToFile() override;
+ ndk::ScopedAStatus stopLoggingToDebugRingBuffer() override;
+ ndk::ScopedAStatus getDebugHostWakeReasonStats(
+ WifiDebugHostWakeReasonStats* _aidl_return) override;
+ ndk::ScopedAStatus enableDebugErrorAlerts(bool in_enable) override;
+ ndk::ScopedAStatus selectTxPowerScenario(IWifiChip::TxPowerScenario in_scenario) override;
+ ndk::ScopedAStatus resetTxPowerScenario() override;
+ ndk::ScopedAStatus setLatencyMode(IWifiChip::LatencyMode in_mode) override;
+ ndk::ScopedAStatus setMultiStaPrimaryConnection(const std::string& in_ifName) override;
+ ndk::ScopedAStatus setMultiStaUseCase(IWifiChip::MultiStaUseCase in_useCase) override;
+ ndk::ScopedAStatus setCoexUnsafeChannels(
+ const std::vector<IWifiChip::CoexUnsafeChannel>& in_unsafeChannels,
+ CoexRestriction in_restrictions) override;
+ ndk::ScopedAStatus setCountryCode(const std::array<uint8_t, 2>& in_code) override;
+ ndk::ScopedAStatus getUsableChannels(WifiBand in_band, WifiIfaceMode in_ifaceModeMask,
+ UsableChannelFilter in_filterMask,
+ std::vector<WifiUsableChannel>* _aidl_return) override;
+ ndk::ScopedAStatus triggerSubsystemRestart() override;
+ ndk::ScopedAStatus getSupportedRadioCombinationsMatrix(
+ WifiRadioCombinationMatrix* _aidl_return) override;
+ binder_status_t dump(int fd, const char** args, uint32_t numArgs) override;
+
+ private:
+ void invalidateAndRemoveAllIfaces();
+ // When a STA iface is removed any dependent NAN-ifaces/RTT-controllers are
+ // invalidated & removed.
+ void invalidateAndRemoveDependencies(const std::string& removed_iface_name);
+
+ // Corresponding worker functions for the AIDL methods.
+ std::pair<int32_t, ndk::ScopedAStatus> getIdInternal();
+ ndk::ScopedAStatus registerEventCallbackInternal(
+ const std::shared_ptr<IWifiChipEventCallback>& event_callback);
+ std::pair<IWifiChip::ChipCapabilityMask, ndk::ScopedAStatus> getCapabilitiesInternal();
+ std::pair<std::vector<IWifiChip::ChipMode>, ndk::ScopedAStatus> getAvailableModesInternal();
+ ndk::ScopedAStatus configureChipInternal(std::unique_lock<std::recursive_mutex>* lock,
+ int32_t mode_id);
+ std::pair<int32_t, ndk::ScopedAStatus> getModeInternal();
+ std::pair<IWifiChip::ChipDebugInfo, ndk::ScopedAStatus> requestChipDebugInfoInternal();
+ std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> requestDriverDebugDumpInternal();
+ std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> requestFirmwareDebugDumpInternal();
+ std::shared_ptr<WifiApIface> newWifiApIface(std::string& ifname);
+ ndk::ScopedAStatus createVirtualApInterface(const std::string& apVirtIf);
+ std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> createApIfaceInternal();
+ std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> createBridgedApIfaceInternal();
+ std::pair<std::vector<std::string>, ndk::ScopedAStatus> getApIfaceNamesInternal();
+ std::pair<std::shared_ptr<IWifiApIface>, ndk::ScopedAStatus> getApIfaceInternal(
+ const std::string& ifname);
+ ndk::ScopedAStatus removeApIfaceInternal(const std::string& ifname);
+ ndk::ScopedAStatus removeIfaceInstanceFromBridgedApIfaceInternal(
+ const std::string& brIfaceName, const std::string& ifInstanceName);
+ std::pair<std::shared_ptr<IWifiNanIface>, ndk::ScopedAStatus> createNanIfaceInternal();
+ std::pair<std::vector<std::string>, ndk::ScopedAStatus> getNanIfaceNamesInternal();
+ std::pair<std::shared_ptr<IWifiNanIface>, ndk::ScopedAStatus> getNanIfaceInternal(
+ const std::string& ifname);
+ ndk::ScopedAStatus removeNanIfaceInternal(const std::string& ifname);
+ std::pair<std::shared_ptr<IWifiP2pIface>, ndk::ScopedAStatus> createP2pIfaceInternal();
+ std::pair<std::vector<std::string>, ndk::ScopedAStatus> getP2pIfaceNamesInternal();
+ std::pair<std::shared_ptr<IWifiP2pIface>, ndk::ScopedAStatus> getP2pIfaceInternal(
+ const std::string& ifname);
+ ndk::ScopedAStatus removeP2pIfaceInternal(const std::string& ifname);
+ std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> createStaIfaceInternal();
+ std::pair<std::vector<std::string>, ndk::ScopedAStatus> getStaIfaceNamesInternal();
+ std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> getStaIfaceInternal(
+ const std::string& ifname);
+ ndk::ScopedAStatus removeStaIfaceInternal(const std::string& ifname);
+ std::pair<std::shared_ptr<IWifiRttController>, ndk::ScopedAStatus> createRttControllerInternal(
+ const std::shared_ptr<IWifiStaIface>& bound_iface);
+ std::pair<std::vector<WifiDebugRingBufferStatus>, ndk::ScopedAStatus>
+ getDebugRingBuffersStatusInternal();
+ ndk::ScopedAStatus startLoggingToDebugRingBufferInternal(
+ const std::string& ring_name, WifiDebugRingBufferVerboseLevel verbose_level,
+ uint32_t max_interval_in_sec, uint32_t min_data_size_in_bytes);
+ ndk::ScopedAStatus forceDumpToDebugRingBufferInternal(const std::string& ring_name);
+ ndk::ScopedAStatus flushRingBufferToFileInternal();
+ ndk::ScopedAStatus stopLoggingToDebugRingBufferInternal();
+ std::pair<WifiDebugHostWakeReasonStats, ndk::ScopedAStatus>
+ getDebugHostWakeReasonStatsInternal();
+ ndk::ScopedAStatus enableDebugErrorAlertsInternal(bool enable);
+ ndk::ScopedAStatus selectTxPowerScenarioInternal(IWifiChip::TxPowerScenario scenario);
+ ndk::ScopedAStatus resetTxPowerScenarioInternal();
+ ndk::ScopedAStatus setLatencyModeInternal(IWifiChip::LatencyMode mode);
+ ndk::ScopedAStatus setMultiStaPrimaryConnectionInternal(const std::string& ifname);
+ ndk::ScopedAStatus setMultiStaUseCaseInternal(IWifiChip::MultiStaUseCase use_case);
+ ndk::ScopedAStatus setCoexUnsafeChannelsInternal(
+ std::vector<IWifiChip::CoexUnsafeChannel> unsafe_channels,
+ CoexRestriction restrictions);
+ ndk::ScopedAStatus setCountryCodeInternal(const std::array<uint8_t, 2>& in_code);
+ std::pair<std::vector<WifiUsableChannel>, ndk::ScopedAStatus> getUsableChannelsInternal(
+ WifiBand band, WifiIfaceMode ifaceModeMask, UsableChannelFilter filterMask);
+ ndk::ScopedAStatus handleChipConfiguration(std::unique_lock<std::recursive_mutex>* lock,
+ int32_t mode_id);
+ ndk::ScopedAStatus registerDebugRingBufferCallback();
+ ndk::ScopedAStatus registerRadioModeChangeCallback();
+
+ std::vector<ChipConcurrencyCombination> getCurrentModeConcurrencyCombinations();
+ std::map<IfaceConcurrencyType, size_t> getCurrentConcurrencyCombination();
+ std::vector<std::map<IfaceConcurrencyType, size_t>> expandConcurrencyCombinations(
+ const ChipConcurrencyCombination& combination);
+ bool canExpandedConcurrencyComboSupportConcurrencyTypeWithCurrentTypes(
+ const std::map<IfaceConcurrencyType, size_t>& expanded_combo,
+ IfaceConcurrencyType requested_type);
+ bool canCurrentModeSupportConcurrencyTypeWithCurrentTypes(IfaceConcurrencyType requested_type);
+ bool canExpandedConcurrencyComboSupportConcurrencyCombo(
+ const std::map<IfaceConcurrencyType, size_t>& expanded_combo,
+ const std::map<IfaceConcurrencyType, size_t>& req_combo);
+ bool canCurrentModeSupportConcurrencyCombo(
+ const std::map<IfaceConcurrencyType, size_t>& req_combo);
+ bool canCurrentModeSupportConcurrencyType(IfaceConcurrencyType requested_type);
+
+ bool isValidModeId(int32_t mode_id);
+ bool isStaApConcurrencyAllowedInCurrentMode();
+ bool isDualStaConcurrencyAllowedInCurrentMode();
+ uint32_t startIdxOfApIface();
+ std::string getFirstActiveWlanIfaceName();
+ std::string allocateApOrStaIfaceName(IfaceType type, uint32_t start_idx);
+ std::string allocateApIfaceName();
+ std::vector<std::string> allocateBridgedApInstanceNames();
+ std::string allocateStaIfaceName();
+ bool writeRingbufferFilesInternal();
+ std::string getWlanIfaceNameWithType(IfaceType type, unsigned idx);
+ void invalidateAndClearBridgedApAll();
+ void invalidateAndClearBridgedAp(const std::string& br_name);
+ bool findUsingNameFromBridgedApInstances(const std::string& name);
+ ndk::ScopedAStatus triggerSubsystemRestartInternal();
+ std::pair<WifiRadioCombinationMatrix, ndk::ScopedAStatus>
+ getSupportedRadioCombinationsMatrixInternal();
+ void setWeakPtr(std::weak_ptr<WifiChip> ptr);
+
+ int32_t chip_id_;
+ std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
+ std::weak_ptr<mode_controller::WifiModeController> mode_controller_;
+ std::shared_ptr<iface_util::WifiIfaceUtil> iface_util_;
+ std::vector<std::shared_ptr<WifiApIface>> ap_ifaces_;
+ std::vector<std::shared_ptr<WifiNanIface>> nan_ifaces_;
+ std::vector<std::shared_ptr<WifiP2pIface>> p2p_ifaces_;
+ std::vector<std::shared_ptr<WifiStaIface>> sta_ifaces_;
+ std::vector<std::shared_ptr<WifiRttController>> rtt_controllers_;
+ std::map<std::string, Ringbuffer> ringbuffer_map_;
+ bool is_valid_;
+ // Members pertaining to chip configuration.
+ int32_t current_mode_id_;
+ std::mutex lock_t;
+ std::vector<IWifiChip::ChipMode> modes_;
+ // The legacy ring buffer callback API has only a global callback
+ // registration mechanism. Use this to check if we have already
+ // registered a callback.
+ bool debug_ring_buffer_cb_registered_;
+ aidl_callback_util::AidlCallbackHandler<IWifiChipEventCallback> event_cb_handler_;
+ std::weak_ptr<WifiChip> weak_ptr_this_;
+
+ const std::function<void(const std::string&)> subsystemCallbackHandler_;
+ std::map<std::string, std::vector<std::string>> br_ifaces_ap_instances_;
+ DISALLOW_COPY_AND_ASSIGN(WifiChip);
+};
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_CHIP_H_
diff --git a/wifi/aidl/default/wifi_feature_flags.cpp b/wifi/aidl/default/wifi_feature_flags.cpp
new file mode 100644
index 0000000..3c9f042
--- /dev/null
+++ b/wifi/aidl/default/wifi_feature_flags.cpp
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 <string>
+
+#include <android-base/logging.h>
+#include <cutils/properties.h>
+
+#include "wifi_feature_flags.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+namespace feature_flags {
+
+/* The chip may either have a single mode supporting any number of combinations,
+ * or a fixed dual-mode (so it involves firmware loading to switch between
+ * modes) setting. If there is a need to support more modes, it needs to be
+ * implemented manually in WiFi HAL (see changeFirmwareMode in
+ * WifiChip::handleChipConfiguration).
+ *
+ * Supported combinations are defined in device's makefile, for example:
+ * WIFI_HAL_INTERFACE_COMBINATIONS := {{{STA, AP}, 1}, {{P2P, NAN}, 1}},
+ * WIFI_HAL_INTERFACE_COMBINATIONS += {{{STA}, 1}, {{AP}, 2}}
+ * What this means:
+ * Interface concurrency combination 1: 1 STA or AP and 1 P2P or NAN concurrent iface
+ * operations.
+ * Interface concurrency combination 2: 1 STA and 2 AP concurrent iface operations.
+ *
+ * For backward compatibility, the following makefile flags can be used to
+ * generate combinations list:
+ * - WIFI_HIDL_FEATURE_DUAL_INTERFACE
+ * - WIFI_HIDL_FEATURE_DISABLE_AP
+ * - WIFI_HIDL_FEATURE_AWARE
+ * However, they are ignored if WIFI_HAL_INTERFACE_COMBINATIONS was provided.
+ * With WIFI_HIDL_FEATURE_DUAL_INTERFACE flag set, there is a single mode with
+ * two concurrency combinations:
+ * Interface Concurrency Combination 1: Will support 1 STA and 1 P2P or NAN (optional)
+ * concurrent iface operations.
+ * Interface Concurrency Combination 2: Will support 1 STA and 1 AP concurrent
+ * iface operations.
+ *
+ * The only dual-mode configuration supported is for alternating STA and AP
+ * mode, that may involve firmware reloading. In such case, there are 2 separate
+ * modes of operation with 1 concurrency combination each:
+ * Mode 1 (STA mode): Will support 1 STA and 1 P2P or NAN (optional)
+ * concurrent iface operations.
+ * Mode 2 (AP mode): Will support 1 AP iface operation.
+ *
+ * If Aware is enabled, the concurrency combination will be modified to support either
+ * P2P or NAN in place of just P2P.
+ */
+// clang-format off
+#ifdef WIFI_HAL_INTERFACE_COMBINATIONS
+constexpr int kMainModeId = chip_mode_ids::kV3;
+#elif defined(WIFI_HIDL_FEATURE_DUAL_INTERFACE)
+// former V2 (fixed dual interface) setup expressed as V3
+constexpr int kMainModeId = chip_mode_ids::kV3;
+# ifdef WIFI_HIDL_FEATURE_DISABLE_AP
+# ifdef WIFI_HIDL_FEATURE_AWARE
+// 1 STA + 1 of (P2P or NAN)
+# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P, NAN}, 1}}
+# else
+// 1 STA + 1 P2P
+# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P}, 1}}
+# endif
+# else
+# ifdef WIFI_HIDL_FEATURE_AWARE
+// (1 STA + 1 AP) or (1 STA + 1 of (P2P or NAN))
+# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{AP}, 1}},\
+ {{{STA}, 1}, {{P2P, NAN}, 1}}
+# else
+// (1 STA + 1 AP) or (1 STA + 1 P2P)
+# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{AP}, 1}},\
+ {{{STA}, 1}, {{P2P}, 1}}
+# endif
+# endif
+#else
+// V1 (fixed single interface, dual-mode chip)
+constexpr int kMainModeId = chip_mode_ids::kV1Sta;
+# ifdef WIFI_HIDL_FEATURE_AWARE
+// 1 STA + 1 of (P2P or NAN)
+# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P, NAN}, 1}}
+# else
+// 1 STA + 1 P2P
+# define WIFI_HAL_INTERFACE_COMBINATIONS {{{STA}, 1}, {{P2P}, 1}}
+# endif
+
+# ifndef WIFI_HIDL_FEATURE_DISABLE_AP
+# define WIFI_HAL_INTERFACE_COMBINATIONS_AP {{{AP}, 1}}
+# endif
+#endif
+// clang-format on
+
+// Convert from the legacy format (used by the WIFI_HAL_INTERFACE_COMBINATIONS
+// config variable) to a list of ChipConcurrencyCombination objects.
+std::vector<IWifiChip::ChipConcurrencyCombination> legacyToChipConcurrencyComboList(
+ std::vector<std::vector<IWifiChip::ChipConcurrencyCombinationLimit>> legacyLimits) {
+ std::vector<IWifiChip::ChipConcurrencyCombination> combos;
+ for (auto& legacyLimit : legacyLimits) {
+ IWifiChip::ChipConcurrencyCombination combo = {legacyLimit};
+ combos.push_back(combo);
+ }
+ return combos;
+}
+
+#define STA IfaceConcurrencyType::STA
+#define AP IfaceConcurrencyType::AP
+#define AP_BRIDGED IfaceConcurrencyType::AP_BRIDGED
+#define P2P IfaceConcurrencyType::P2P
+#define NAN IfaceConcurrencyType::NAN_IFACE
+static const std::vector<IWifiChip::ChipMode> kChipModesPrimary{
+ {kMainModeId, legacyToChipConcurrencyComboList({WIFI_HAL_INTERFACE_COMBINATIONS})},
+#ifdef WIFI_HAL_INTERFACE_COMBINATIONS_AP
+ {chip_mode_ids::kV1Ap,
+ legacyToChipConcurrencyComboList({WIFI_HAL_INTERFACE_COMBINATIONS_AP})},
+#endif
+};
+
+static const std::vector<IWifiChip::ChipMode> kChipModesSecondary{
+#ifdef WIFI_HAL_INTERFACE_COMBINATIONS_SECONDARY_CHIP
+ {chip_mode_ids::kV3,
+ legacyToChipConcurrencyComboList({WIFI_HAL_INTERFACE_COMBINATIONS_SECONDARY_CHIP})},
+#endif
+};
+
+constexpr char kDebugPresetInterfaceCombinationIdxProperty[] =
+ "persist.vendor.debug.wifi.hal.preset_interface_combination_idx";
+// List of pre-defined concurrency combinations that can be enabled at runtime via
+// setting the property: "kDebugPresetInterfaceCombinationIdxProperty" to the
+// corresponding index value.
+static const std::vector<std::pair<std::string, std::vector<IWifiChip::ChipMode>>> kDebugChipModes{
+ // Legacy combination - No STA/AP concurrencies.
+ // 0 - (1 AP) or (1 STA + 1 of (P2P or NAN))
+ {"No STA/AP Concurrency",
+ {{kMainModeId,
+ legacyToChipConcurrencyComboList({{{{AP}, 1}}, {{{STA}, 1}, {{P2P, NAN}, 1}}})}}},
+
+ // STA + AP concurrency
+ // 1 - (1 STA + 1 AP) or (1 STA + 1 of (P2P or NAN))
+ {"STA + AP Concurrency",
+ {{kMainModeId, legacyToChipConcurrencyComboList(
+ {{{{STA}, 1}, {{AP}, 1}}, {{{STA}, 1}, {{P2P, NAN}, 1}}})}}},
+
+ // STA + STA concurrency
+ // 2 - (1 STA + 1 AP) or (2 STA + 1 of (P2P or NAN))
+ {"Dual STA Concurrency",
+ {{kMainModeId, legacyToChipConcurrencyComboList(
+ {{{{STA}, 1}, {{AP}, 1}}, {{{STA}, 2}, {{P2P, NAN}, 1}}})}}},
+
+ // AP + AP + STA concurrency
+ // 3 - (1 STA + 2 AP) or (1 STA + 1 of (P2P or NAN))
+ {"Dual AP Concurrency",
+ {{kMainModeId, legacyToChipConcurrencyComboList(
+ {{{{STA}, 1}, {{AP}, 2}}, {{{STA}, 1}, {{P2P, NAN}, 1}}})}}},
+
+ // STA + STA concurrency and AP + AP + STA concurrency
+ // 4 - (1 STA + 2 AP) or (2 STA + 1 of (P2P or NAN))
+ {"Dual STA & Dual AP Concurrency",
+ {{kMainModeId, legacyToChipConcurrencyComboList(
+ {{{{STA}, 1}, {{AP}, 2}}, {{{STA}, 2}, {{P2P, NAN}, 1}}})}}},
+
+ // STA + STA concurrency
+ // 5 - (1 STA + 1 AP (bridged or single) | P2P | NAN), or (2 STA))
+ {"Dual STA or STA plus single other interface",
+ {{kMainModeId, legacyToChipConcurrencyComboList(
+ {{{{STA}, 1}, {{P2P, NAN, AP, AP_BRIDGED}, 1}}, {{{STA}, 2}}})}}}};
+
+#undef STA
+#undef AP
+#undef AP_BRIDGED
+#undef P2P
+#undef NAN
+
+#ifdef WIFI_HIDL_FEATURE_DISABLE_AP_MAC_RANDOMIZATION
+#pragma message \
+ "WIFI_HIDL_FEATURE_DISABLE_AP_MAC_RANDOMIZATION is deprecated; override " \
+ "'config_wifi_ap_randomization_supported' in " \
+ "frameworks/base/core/res/res/values/config.xml in the device overlay " \
+ "instead"
+#endif // WIFI_HIDL_FEATURE_DISABLE_AP_MAC_RANDOMIZATION
+
+WifiFeatureFlags::WifiFeatureFlags() {}
+
+std::vector<IWifiChip::ChipMode> WifiFeatureFlags::getChipModesForPrimary() {
+ std::array<char, PROPERTY_VALUE_MAX> buffer;
+ auto res = property_get(kDebugPresetInterfaceCombinationIdxProperty, buffer.data(), nullptr);
+ // Debug property not set, use the device preset concurrency combination.
+ if (res <= 0) return kChipModesPrimary;
+
+ // Debug property set, use one of the debug preset concurrency combination.
+ unsigned long idx = std::stoul(buffer.data());
+ if (idx >= kDebugChipModes.size()) {
+ LOG(ERROR) << "Invalid index set in property: "
+ << kDebugPresetInterfaceCombinationIdxProperty;
+ return kChipModesPrimary;
+ }
+ std::string name;
+ std::vector<IWifiChip::ChipMode> chip_modes;
+ std::tie(name, chip_modes) = kDebugChipModes[idx];
+ LOG(INFO) << "Using debug chip mode: <" << name
+ << "> set via property: " << kDebugPresetInterfaceCombinationIdxProperty;
+ return chip_modes;
+}
+
+std::vector<IWifiChip::ChipMode> WifiFeatureFlags::getChipModes(bool is_primary) {
+ return (is_primary) ? getChipModesForPrimary() : kChipModesSecondary;
+}
+
+} // namespace feature_flags
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_feature_flags.h b/wifi/aidl/default/wifi_feature_flags.h
similarity index 67%
rename from wifi/1.6/default/wifi_feature_flags.h
rename to wifi/aidl/default/wifi_feature_flags.h
index 1635341..af1b6a6 100644
--- a/wifi/1.6/default/wifi_feature_flags.h
+++ b/wifi/aidl/default/wifi_feature_flags.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,24 +17,23 @@
#ifndef WIFI_FEATURE_FLAGS_H_
#define WIFI_FEATURE_FLAGS_H_
-#include <android/hardware/wifi/1.6/IWifiChip.h>
+#include <aidl/android/hardware/wifi/IWifiChip.h>
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace feature_flags {
namespace chip_mode_ids {
// These mode ID's should be unique (even across combo versions). Refer to
-// handleChipConfiguration() for it's usage.
-constexpr V1_0::ChipModeId kInvalid = UINT32_MAX;
+// handleChipConfiguration() for its usage.
+constexpr uint32_t kInvalid = UINT32_MAX;
// Mode ID's for V1
-constexpr V1_0::ChipModeId kV1Sta = 0;
-constexpr V1_0::ChipModeId kV1Ap = 1;
+constexpr uint32_t kV1Sta = 0;
+constexpr uint32_t kV1Ap = 1;
// Mode ID for V3
-constexpr V1_0::ChipModeId kV3 = 3;
+constexpr uint32_t kV3 = 3;
} // namespace chip_mode_ids
class WifiFeatureFlags {
@@ -42,17 +41,16 @@
WifiFeatureFlags();
virtual ~WifiFeatureFlags() = default;
- virtual std::vector<V1_6::IWifiChip::ChipMode> getChipModes(bool is_primary);
+ virtual std::vector<IWifiChip::ChipMode> getChipModes(bool is_primary);
private:
- std::vector<V1_6::IWifiChip::ChipMode> getChipModesForPrimary();
+ std::vector<IWifiChip::ChipMode> getChipModesForPrimary();
};
} // namespace feature_flags
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_FEATURE_FLAGS_H_
diff --git a/wifi/1.6/default/wifi_iface_util.cpp b/wifi/aidl/default/wifi_iface_util.cpp
similarity index 95%
rename from wifi/1.6/default/wifi_iface_util.cpp
rename to wifi/aidl/default/wifi_iface_util.cpp
index d55e4f8..f788217 100644
--- a/wifi/1.6/default/wifi_iface_util.cpp
+++ b/wifi/aidl/default/wifi_iface_util.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,33 +14,32 @@
* limitations under the License.
*/
+#include <android-base/logging.h>
+#include <android-base/macros.h>
#include <net/if.h>
+#include <private/android_filesystem_config.h>
+
#include <cstddef>
#include <iostream>
#include <limits>
#include <random>
-#include <android-base/logging.h>
-#include <android-base/macros.h>
-#include <private/android_filesystem_config.h>
-
-#undef NAN
#include "wifi_iface_util.h"
namespace {
// Constants to set the local bit & clear the multicast bit.
constexpr uint8_t kMacAddressMulticastMask = 0x01;
constexpr uint8_t kMacAddressLocallyAssignedMask = 0x02;
+
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace iface_util {
-WifiIfaceUtil::WifiIfaceUtil(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
+WifiIfaceUtil::WifiIfaceUtil(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal)
: iface_tool_(iface_tool),
legacy_hal_(legacy_hal),
@@ -169,8 +168,7 @@
}
} // namespace iface_util
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_iface_util.h b/wifi/aidl/default/wifi_iface_util.h
similarity index 89%
rename from wifi/1.6/default/wifi_iface_util.h
rename to wifi/aidl/default/wifi_iface_util.h
index c5db5de..a3236a5 100644
--- a/wifi/1.6/default/wifi_iface_util.h
+++ b/wifi/aidl/default/wifi_iface_util.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,17 +17,15 @@
#ifndef WIFI_IFACE_UTIL_H_
#define WIFI_IFACE_UTIL_H_
+#include <aidl/android/hardware/wifi/IWifi.h>
#include <wifi_system/interface_tool.h>
-#include <android/hardware/wifi/1.0/IWifi.h>
-
#include "wifi_legacy_hal.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace iface_util {
// Iface event handlers.
@@ -42,7 +40,7 @@
*/
class WifiIfaceUtil {
public:
- WifiIfaceUtil(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
+ WifiIfaceUtil(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal);
virtual ~WifiIfaceUtil() = default;
@@ -71,17 +69,16 @@
virtual std::array<uint8_t, 6> createRandomMacAddress();
private:
- std::weak_ptr<wifi_system::InterfaceTool> iface_tool_;
+ std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool_;
std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
std::unique_ptr<std::array<uint8_t, 6>> random_mac_address_;
std::map<std::string, IfaceEventHandlers> event_handlers_map_;
};
} // namespace iface_util
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_IFACE_UTIL_H_
diff --git a/wifi/1.6/default/wifi_legacy_hal.cpp b/wifi/aidl/default/wifi_legacy_hal.cpp
similarity index 94%
rename from wifi/1.6/default/wifi_legacy_hal.cpp
rename to wifi/aidl/default/wifi_legacy_hal.cpp
index 43cb7c4..43e73ca 100644
--- a/wifi/1.6/default/wifi_legacy_hal.cpp
+++ b/wifi/aidl/default/wifi_legacy_hal.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,15 +14,16 @@
* limitations under the License.
*/
-#include <array>
-#include <chrono>
+#include "wifi_legacy_hal.h"
#include <android-base/logging.h>
#include <cutils/properties.h>
#include <net/if.h>
-#include "hidl_sync_util.h"
-#include "wifi_legacy_hal.h"
+#include <array>
+#include <chrono>
+
+#include "aidl_sync_util.h"
#include "wifi_legacy_hal_stubs.h"
namespace {
@@ -38,7 +39,7 @@
static constexpr uint32_t kMaxRingBuffers = 10;
static constexpr uint32_t kMaxWifiUsableChannels = 256;
static constexpr uint32_t kMaxSupportedRadioCombinationsMatrixLength = 256;
-// need a long timeout (1000ms) for chips that unload their driver.
+// Need a long timeout (1000ms) for chips that unload their driver.
static constexpr uint32_t kMaxStopCompleteWaitMs = 1000;
static constexpr char kDriverPropName[] = "wlan.driver.status";
@@ -51,11 +52,10 @@
}
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace legacy_hal {
// Legacy HAL functions accept "C" style function pointers, so use global
@@ -65,7 +65,7 @@
// Callback to be invoked once |stop| is complete
std::function<void(wifi_handle handle)> on_stop_complete_internal_callback;
void onAsyncStopComplete(wifi_handle handle) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_stop_complete_internal_callback) {
on_stop_complete_internal_callback(handle);
// Invalidate this callback since we don't want this firing again.
@@ -92,7 +92,7 @@
// Callback to be invoked for Gscan events.
std::function<void(wifi_request_id, wifi_scan_event)> on_gscan_event_internal_callback;
void onAsyncGscanEvent(wifi_request_id id, wifi_scan_event event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_gscan_event_internal_callback) {
on_gscan_event_internal_callback(id, event);
}
@@ -103,7 +103,7 @@
on_gscan_full_result_internal_callback;
void onAsyncGscanFullResult(wifi_request_id id, wifi_scan_result* result,
uint32_t buckets_scanned) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_gscan_full_result_internal_callback) {
on_gscan_full_result_internal_callback(id, result, buckets_scanned);
}
@@ -123,7 +123,7 @@
std::function<void((wifi_request_id, uint8_t*, int8_t))>
on_rssi_threshold_breached_internal_callback;
void onAsyncRssiThresholdBreached(wifi_request_id id, uint8_t* bssid, int8_t rssi) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_rssi_threshold_breached_internal_callback) {
on_rssi_threshold_breached_internal_callback(id, bssid, rssi);
}
@@ -134,7 +134,7 @@
on_ring_buffer_data_internal_callback;
void onAsyncRingBufferData(char* ring_name, char* buffer, int buffer_size,
wifi_ring_buffer_status* status) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_ring_buffer_data_internal_callback) {
on_ring_buffer_data_internal_callback(ring_name, buffer, buffer_size, status);
}
@@ -143,7 +143,7 @@
// Callback to be invoked for error alert indication.
std::function<void(wifi_request_id, char*, int, int)> on_error_alert_internal_callback;
void onAsyncErrorAlert(wifi_request_id id, char* buffer, int buffer_size, int err_code) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_error_alert_internal_callback) {
on_error_alert_internal_callback(id, buffer, buffer_size, err_code);
}
@@ -153,7 +153,7 @@
std::function<void(wifi_request_id, uint32_t, wifi_mac_info*)>
on_radio_mode_change_internal_callback;
void onAsyncRadioModeChange(wifi_request_id id, uint32_t num_macs, wifi_mac_info* mac_infos) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_radio_mode_change_internal_callback) {
on_radio_mode_change_internal_callback(id, num_macs, mac_infos);
}
@@ -162,7 +162,7 @@
// Callback to be invoked to report subsystem restart
std::function<void(const char*)> on_subsystem_restart_internal_callback;
void onAsyncSubsystemRestart(const char* error) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_subsystem_restart_internal_callback) {
on_subsystem_restart_internal_callback(error);
}
@@ -172,7 +172,7 @@
std::function<void(wifi_request_id, unsigned num_results, wifi_rtt_result* rtt_results[])>
on_rtt_results_internal_callback;
void onAsyncRttResults(wifi_request_id id, unsigned num_results, wifi_rtt_result* rtt_results[]) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_rtt_results_internal_callback) {
on_rtt_results_internal_callback(id, num_results, rtt_results);
on_rtt_results_internal_callback = nullptr;
@@ -184,37 +184,37 @@
// callbacks.
// So, handle all of them here directly to avoid adding an unnecessary layer.
std::function<void(transaction_id, const NanResponseMsg&)> on_nan_notify_response_user_callback;
-void onAysncNanNotifyResponse(transaction_id id, NanResponseMsg* msg) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanNotifyResponse(transaction_id id, NanResponseMsg* msg) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_notify_response_user_callback && msg) {
on_nan_notify_response_user_callback(id, *msg);
}
}
std::function<void(const NanPublishRepliedInd&)> on_nan_event_publish_replied_user_callback;
-void onAysncNanEventPublishReplied(NanPublishRepliedInd* /* event */) {
- LOG(ERROR) << "onAysncNanEventPublishReplied triggered";
+void onAsyncNanEventPublishReplied(NanPublishRepliedInd* /* event */) {
+ LOG(ERROR) << "onAsyncNanEventPublishReplied triggered";
}
std::function<void(const NanPublishTerminatedInd&)> on_nan_event_publish_terminated_user_callback;
-void onAysncNanEventPublishTerminated(NanPublishTerminatedInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventPublishTerminated(NanPublishTerminatedInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_publish_terminated_user_callback && event) {
on_nan_event_publish_terminated_user_callback(*event);
}
}
std::function<void(const NanMatchInd&)> on_nan_event_match_user_callback;
-void onAysncNanEventMatch(NanMatchInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventMatch(NanMatchInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_match_user_callback && event) {
on_nan_event_match_user_callback(*event);
}
}
std::function<void(const NanMatchExpiredInd&)> on_nan_event_match_expired_user_callback;
-void onAysncNanEventMatchExpired(NanMatchExpiredInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventMatchExpired(NanMatchExpiredInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_match_expired_user_callback && event) {
on_nan_event_match_expired_user_callback(*event);
}
@@ -222,95 +222,95 @@
std::function<void(const NanSubscribeTerminatedInd&)>
on_nan_event_subscribe_terminated_user_callback;
-void onAysncNanEventSubscribeTerminated(NanSubscribeTerminatedInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventSubscribeTerminated(NanSubscribeTerminatedInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_subscribe_terminated_user_callback && event) {
on_nan_event_subscribe_terminated_user_callback(*event);
}
}
std::function<void(const NanFollowupInd&)> on_nan_event_followup_user_callback;
-void onAysncNanEventFollowup(NanFollowupInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventFollowup(NanFollowupInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_followup_user_callback && event) {
on_nan_event_followup_user_callback(*event);
}
}
std::function<void(const NanDiscEngEventInd&)> on_nan_event_disc_eng_event_user_callback;
-void onAysncNanEventDiscEngEvent(NanDiscEngEventInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventDiscEngEvent(NanDiscEngEventInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_disc_eng_event_user_callback && event) {
on_nan_event_disc_eng_event_user_callback(*event);
}
}
std::function<void(const NanDisabledInd&)> on_nan_event_disabled_user_callback;
-void onAysncNanEventDisabled(NanDisabledInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventDisabled(NanDisabledInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_disabled_user_callback && event) {
on_nan_event_disabled_user_callback(*event);
}
}
std::function<void(const NanTCAInd&)> on_nan_event_tca_user_callback;
-void onAysncNanEventTca(NanTCAInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventTca(NanTCAInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_tca_user_callback && event) {
on_nan_event_tca_user_callback(*event);
}
}
std::function<void(const NanBeaconSdfPayloadInd&)> on_nan_event_beacon_sdf_payload_user_callback;
-void onAysncNanEventBeaconSdfPayload(NanBeaconSdfPayloadInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventBeaconSdfPayload(NanBeaconSdfPayloadInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_beacon_sdf_payload_user_callback && event) {
on_nan_event_beacon_sdf_payload_user_callback(*event);
}
}
std::function<void(const NanDataPathRequestInd&)> on_nan_event_data_path_request_user_callback;
-void onAysncNanEventDataPathRequest(NanDataPathRequestInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventDataPathRequest(NanDataPathRequestInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_data_path_request_user_callback && event) {
on_nan_event_data_path_request_user_callback(*event);
}
}
std::function<void(const NanDataPathConfirmInd&)> on_nan_event_data_path_confirm_user_callback;
-void onAysncNanEventDataPathConfirm(NanDataPathConfirmInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventDataPathConfirm(NanDataPathConfirmInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_data_path_confirm_user_callback && event) {
on_nan_event_data_path_confirm_user_callback(*event);
}
}
std::function<void(const NanDataPathEndInd&)> on_nan_event_data_path_end_user_callback;
-void onAysncNanEventDataPathEnd(NanDataPathEndInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventDataPathEnd(NanDataPathEndInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_data_path_end_user_callback && event) {
on_nan_event_data_path_end_user_callback(*event);
}
}
std::function<void(const NanTransmitFollowupInd&)> on_nan_event_transmit_follow_up_user_callback;
-void onAysncNanEventTransmitFollowUp(NanTransmitFollowupInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventTransmitFollowUp(NanTransmitFollowupInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_transmit_follow_up_user_callback && event) {
on_nan_event_transmit_follow_up_user_callback(*event);
}
}
std::function<void(const NanRangeRequestInd&)> on_nan_event_range_request_user_callback;
-void onAysncNanEventRangeRequest(NanRangeRequestInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventRangeRequest(NanRangeRequestInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_range_request_user_callback && event) {
on_nan_event_range_request_user_callback(*event);
}
}
std::function<void(const NanRangeReportInd&)> on_nan_event_range_report_user_callback;
-void onAysncNanEventRangeReport(NanRangeReportInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+void onAsyncNanEventRangeReport(NanRangeReportInd* event) {
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_range_report_user_callback && event) {
on_nan_event_range_report_user_callback(*event);
}
@@ -318,7 +318,7 @@
std::function<void(const NanDataPathScheduleUpdateInd&)> on_nan_event_schedule_update_user_callback;
void onAsyncNanEventScheduleUpdate(NanDataPathScheduleUpdateInd* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_nan_event_schedule_update_user_callback && event) {
on_nan_event_schedule_update_user_callback(*event);
}
@@ -327,7 +327,7 @@
// Callbacks for the various TWT operations.
std::function<void(const TwtSetupResponse&)> on_twt_event_setup_response_callback;
void onAsyncTwtEventSetupResponse(TwtSetupResponse* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_twt_event_setup_response_callback && event) {
on_twt_event_setup_response_callback(*event);
}
@@ -335,7 +335,7 @@
std::function<void(const TwtTeardownCompletion&)> on_twt_event_teardown_completion_callback;
void onAsyncTwtEventTeardownCompletion(TwtTeardownCompletion* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_twt_event_teardown_completion_callback && event) {
on_twt_event_teardown_completion_callback(*event);
}
@@ -343,7 +343,7 @@
std::function<void(const TwtInfoFrameReceived&)> on_twt_event_info_frame_received_callback;
void onAsyncTwtEventInfoFrameReceived(TwtInfoFrameReceived* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_twt_event_info_frame_received_callback && event) {
on_twt_event_info_frame_received_callback(*event);
}
@@ -351,7 +351,7 @@
std::function<void(const TwtDeviceNotify&)> on_twt_event_device_notify_callback;
void onAsyncTwtEventDeviceNotify(TwtDeviceNotify* event) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_twt_event_device_notify_callback && event) {
on_twt_event_device_notify_callback(*event);
}
@@ -360,7 +360,7 @@
// Callback to report current CHRE NAN state
std::function<void(chre_nan_rtt_state)> on_chre_nan_rtt_internal_callback;
void onAsyncChreNanRttState(chre_nan_rtt_state state) {
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (on_chre_nan_rtt_internal_callback) {
on_chre_nan_rtt_internal_callback(state);
}
@@ -376,7 +376,7 @@
// End of the free-standing "C" style callbacks.
-WifiLegacyHal::WifiLegacyHal(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool,
+WifiLegacyHal::WifiLegacyHal(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
const wifi_hal_fn& fn, bool is_primary)
: global_func_table_(fn),
global_handle_(nullptr),
@@ -769,7 +769,7 @@
if (!bssid_ptr) {
return;
}
- std::array<uint8_t, 6> bssid_arr;
+ std::array<uint8_t, ETH_ALEN> bssid_arr;
// |bssid_ptr| pointer is assumed to have 6 bytes for the mac
// address.
std::copy(bssid_ptr, bssid_ptr + 6, std::begin(bssid_arr));
@@ -820,12 +820,12 @@
return global_func_table_.wifi_configure_nd_offload(getIfaceHandle(iface_name), enable);
}
-wifi_error WifiLegacyHal::startSendingOffloadedPacket(const std::string& iface_name,
- uint32_t cmd_id, uint16_t ether_type,
+wifi_error WifiLegacyHal::startSendingOffloadedPacket(const std::string& iface_name, int32_t cmd_id,
+ uint16_t ether_type,
const std::vector<uint8_t>& ip_packet_data,
const std::array<uint8_t, 6>& src_address,
const std::array<uint8_t, 6>& dst_address,
- uint32_t period_in_ms) {
+ int32_t period_in_ms) {
std::vector<uint8_t> ip_packet_data_internal(ip_packet_data);
std::vector<uint8_t> src_address_internal(src_address.data(),
src_address.data() + src_address.size());
@@ -1120,14 +1120,15 @@
wifi_error WifiLegacyHal::cancelRttRangeRequest(
const std::string& iface_name, wifi_request_id id,
- const std::vector<std::array<uint8_t, 6>>& mac_addrs) {
+ const std::vector<std::array<uint8_t, ETH_ALEN>>& mac_addrs) {
if (!on_rtt_results_internal_callback) {
return WIFI_ERROR_NOT_AVAILABLE;
}
- static_assert(sizeof(mac_addr) == sizeof(std::array<uint8_t, 6>), "MAC address size mismatch");
+ static_assert(sizeof(mac_addr) == sizeof(std::array<uint8_t, ETH_ALEN>),
+ "MAC address size mismatch");
// TODO: How do we handle partial cancels (i.e only a subset of enabled mac
// addressed are cancelled).
- std::vector<std::array<uint8_t, 6>> mac_addrs_internal(mac_addrs);
+ std::vector<std::array<uint8_t, ETH_ALEN>> mac_addrs_internal(mac_addrs);
wifi_error status = global_func_table_.wifi_rtt_range_cancel(
id, getIfaceHandle(iface_name), mac_addrs.size(),
reinterpret_cast<mac_addr*>(mac_addrs_internal.data()));
@@ -1202,14 +1203,14 @@
return global_func_table_.wifi_nan_register_handler(
getIfaceHandle(iface_name),
- {onAysncNanNotifyResponse, onAysncNanEventPublishReplied,
- onAysncNanEventPublishTerminated, onAysncNanEventMatch, onAysncNanEventMatchExpired,
- onAysncNanEventSubscribeTerminated, onAysncNanEventFollowup,
- onAysncNanEventDiscEngEvent, onAysncNanEventDisabled, onAysncNanEventTca,
- onAysncNanEventBeaconSdfPayload, onAysncNanEventDataPathRequest,
- onAysncNanEventDataPathConfirm, onAysncNanEventDataPathEnd,
- onAysncNanEventTransmitFollowUp, onAysncNanEventRangeRequest,
- onAysncNanEventRangeReport, onAsyncNanEventScheduleUpdate});
+ {onAsyncNanNotifyResponse, onAsyncNanEventPublishReplied,
+ onAsyncNanEventPublishTerminated, onAsyncNanEventMatch, onAsyncNanEventMatchExpired,
+ onAsyncNanEventSubscribeTerminated, onAsyncNanEventFollowup,
+ onAsyncNanEventDiscEngEvent, onAsyncNanEventDisabled, onAsyncNanEventTca,
+ onAsyncNanEventBeaconSdfPayload, onAsyncNanEventDataPathRequest,
+ onAsyncNanEventDataPathConfirm, onAsyncNanEventDataPathEnd,
+ onAsyncNanEventTransmitFollowUp, onAsyncNanEventRangeRequest,
+ onAsyncNanEventRangeReport, onAsyncNanEventScheduleUpdate});
}
wifi_error WifiLegacyHal::nanEnableRequest(const std::string& iface_name, transaction_id id,
@@ -1340,7 +1341,7 @@
}
wifi_error WifiLegacyHal::setCountryCode(const std::string& iface_name,
- std::array<int8_t, 2> code) {
+ const std::array<uint8_t, 2> code) {
std::string code_str(code.data(), code.data() + code.size());
return global_func_table_.wifi_set_country_code(getIfaceHandle(iface_name), code_str.c_str());
}
@@ -1384,7 +1385,7 @@
void WifiLegacyHal::runEventLoop() {
LOG(DEBUG) << "Starting legacy HAL event loop";
global_func_table_.wifi_event_loop(global_handle_);
- const auto lock = hidl_sync_util::acquireGlobalLock();
+ const auto lock = aidl_sync_util::acquireGlobalLock();
if (!awaiting_event_loop_termination_) {
LOG(FATAL) << "Legacy HAL event loop terminated, but HAL was not stopping";
}
@@ -1647,8 +1648,7 @@
}
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_legacy_hal.h b/wifi/aidl/default/wifi_legacy_hal.h
similarity index 97%
rename from wifi/1.6/default/wifi_legacy_hal.h
rename to wifi/aidl/default/wifi_legacy_hal.h
index 1fd784a..cd8c0b1 100644
--- a/wifi/1.6/default/wifi_legacy_hal.h
+++ b/wifi/aidl/default/wifi_legacy_hal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,22 +17,22 @@
#ifndef WIFI_LEGACY_HAL_H_
#define WIFI_LEGACY_HAL_H_
-#include <condition_variable>
-#include <functional>
-#include <map>
-#include <thread>
-#include <vector>
-
#include <hardware_legacy/wifi_hal.h>
#include <wifi_system/interface_tool.h>
+#include <condition_variable>
+#include <functional>
+#include <map>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
// This is in a separate namespace to prevent typename conflicts between
-// the legacy HAL types and the HIDL interface types.
+// the legacy HAL types and the AIDL interface types.
namespace legacy_hal {
// Import all the types defined inside the legacy HAL header files into this
// namespace.
@@ -411,7 +411,7 @@
// Invoked when the rssi value breaches the thresholds set.
using on_rssi_threshold_breached_callback =
- std::function<void(wifi_request_id, std::array<uint8_t, 6>, int8_t)>;
+ std::function<void(wifi_request_id, std::array<uint8_t, ETH_ALEN>, int8_t)>;
// Callback for RTT range request results.
// Rtt results contain IE info and are hence passed by reference, to
@@ -481,8 +481,8 @@
*/
class WifiLegacyHal {
public:
- WifiLegacyHal(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool, const wifi_hal_fn& fn,
- bool is_primary);
+ WifiLegacyHal(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool,
+ const wifi_hal_fn& fn, bool is_primary);
virtual ~WifiLegacyHal() = default;
// Initialize the legacy HAL function table.
@@ -521,7 +521,7 @@
// |on_results_user_callback| on success.
// b) |WIFI_SCAN_FAILED| scan event or failure to retrieve cached scan
// results
- // triggers the externally provided |on_failure_user_callback|.
+ // Triggers the externally provided |on_failure_user_callback|.
// c) Full scan result event triggers the externally provided
// |on_full_result_user_callback|.
wifi_error startGscan(const std::string& iface_name, wifi_request_id id,
@@ -547,12 +547,12 @@
wifi_error configureRoaming(const std::string& iface_name, const wifi_roaming_config& config);
wifi_error enableFirmwareRoaming(const std::string& iface_name, fw_roaming_state_t state);
wifi_error configureNdOffload(const std::string& iface_name, bool enable);
- wifi_error startSendingOffloadedPacket(const std::string& iface_name, uint32_t cmd_id,
+ wifi_error startSendingOffloadedPacket(const std::string& iface_name, int32_t cmd_id,
uint16_t ether_type,
const std::vector<uint8_t>& ip_packet_data,
const std::array<uint8_t, 6>& src_address,
const std::array<uint8_t, 6>& dst_address,
- uint32_t period_in_ms);
+ int32_t period_in_ms);
wifi_error stopSendingOffloadedPacket(const std::string& iface_name, uint32_t cmd_id);
virtual wifi_error selectTxPowerScenario(const std::string& iface_name,
wifi_power_scenario scenario);
@@ -591,7 +591,7 @@
const std::vector<wifi_rtt_config>& rtt_configs,
const on_rtt_results_callback& on_results_callback);
wifi_error cancelRttRangeRequest(const std::string& iface_name, wifi_request_id id,
- const std::vector<std::array<uint8_t, 6>>& mac_addrs);
+ const std::vector<std::array<uint8_t, ETH_ALEN>>& mac_addrs);
std::pair<wifi_error, wifi_rtt_capabilities> getRttCapabilities(const std::string& iface_name);
std::pair<wifi_error, wifi_rtt_responder> getRttResponderInfo(const std::string& iface_name);
wifi_error enableRttResponder(const std::string& iface_name, wifi_request_id id,
@@ -638,9 +638,9 @@
const NanDataPathIndicationResponse& msg);
wifi_error nanDataEnd(const std::string& iface_name, transaction_id id, uint32_t ndpInstanceId);
// AP functions.
- wifi_error setCountryCode(const std::string& iface_name, std::array<int8_t, 2> code);
+ wifi_error setCountryCode(const std::string& iface_name, const std::array<uint8_t, 2> code);
- // interface functions.
+ // Interface functions.
virtual wifi_error createVirtualInterface(const std::string& ifname,
wifi_interface_type iftype);
virtual wifi_error deleteVirtualInterface(const std::string& ifname);
@@ -721,8 +721,8 @@
std::condition_variable_any stop_wait_cv_;
// Flag to indicate if the legacy HAL has been started.
bool is_started_;
- std::weak_ptr<wifi_system::InterfaceTool> iface_tool_;
- // flag to indicate if this HAL is for the primary chip. This is used
+ std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool_;
+ // Flag to indicate if this HAL is for the primary chip. This is used
// in order to avoid some hard-coded behavior used with older HALs,
// such as bring wlan0 interface up/down on start/stop HAL.
// it may be removed once vendor HALs are updated.
@@ -730,10 +730,9 @@
};
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_LEGACY_HAL_H_
diff --git a/wifi/1.6/default/wifi_legacy_hal_factory.cpp b/wifi/aidl/default/wifi_legacy_hal_factory.cpp
similarity index 97%
rename from wifi/1.6/default/wifi_legacy_hal_factory.cpp
rename to wifi/aidl/default/wifi_legacy_hal_factory.cpp
index 147bf4d..60f81ed 100644
--- a/wifi/1.6/default/wifi_legacy_hal_factory.cpp
+++ b/wifi/aidl/default/wifi_legacy_hal_factory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-#include <dirent.h>
-#include <sys/stat.h>
-#include <sys/types.h>
+#include "wifi_legacy_hal_factory.h"
#include <android-base/logging.h>
+#include <dirent.h>
#include <dlfcn.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
+#include <sys/stat.h>
+#include <sys/types.h>
-#include "wifi_legacy_hal_factory.h"
#include "wifi_legacy_hal_stubs.h"
namespace {
@@ -59,15 +59,14 @@
}
}; // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace legacy_hal {
WifiLegacyHalFactory::WifiLegacyHalFactory(
- const std::weak_ptr<wifi_system::InterfaceTool> iface_tool)
+ const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool)
: iface_tool_(iface_tool) {}
std::vector<std::shared_ptr<WifiLegacyHal>> WifiLegacyHalFactory::getHals() {
@@ -247,8 +246,7 @@
}
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_legacy_hal_factory.h b/wifi/aidl/default/wifi_legacy_hal_factory.h
similarity index 82%
rename from wifi/1.6/default/wifi_legacy_hal_factory.h
rename to wifi/aidl/default/wifi_legacy_hal_factory.h
index 9f4423e..e7b287a 100644
--- a/wifi/1.6/default/wifi_legacy_hal_factory.h
+++ b/wifi/aidl/default/wifi_legacy_hal_factory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2020 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,20 +21,19 @@
#include "wifi_legacy_hal.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
// This is in a separate namespace to prevent typename conflicts between
-// the legacy HAL types and the HIDL interface types.
+// the legacy HAL types and the AIDL interface types.
namespace legacy_hal {
/**
* Class that creates WifiLegacyHal objects for vendor HALs in the system.
*/
class WifiLegacyHalFactory {
public:
- WifiLegacyHalFactory(const std::weak_ptr<wifi_system::InterfaceTool> iface_tool);
+ WifiLegacyHalFactory(const std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool);
virtual ~WifiLegacyHalFactory() = default;
std::vector<std::shared_ptr<WifiLegacyHal>> getHals();
@@ -51,16 +50,15 @@
bool initLinkedHalFunctionTable(wifi_hal_fn* hal_fn);
bool loadVendorHalLib(const std::string& path, wifi_hal_lib_desc& desc);
- std::weak_ptr<wifi_system::InterfaceTool> iface_tool_;
+ std::weak_ptr<::android::wifi_system::InterfaceTool> iface_tool_;
std::vector<wifi_hal_lib_desc> descs_;
std::vector<std::shared_ptr<WifiLegacyHal>> legacy_hals_;
};
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_LEGACY_HAL_FACTORY_H_
diff --git a/wifi/1.6/default/wifi_legacy_hal_stubs.cpp b/wifi/aidl/default/wifi_legacy_hal_stubs.cpp
similarity index 97%
rename from wifi/1.6/default/wifi_legacy_hal_stubs.cpp
rename to wifi/aidl/default/wifi_legacy_hal_stubs.cpp
index 8f8527a..cff7f69 100644
--- a/wifi/1.6/default/wifi_legacy_hal_stubs.cpp
+++ b/wifi/aidl/default/wifi_legacy_hal_stubs.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,11 +17,10 @@
#include "wifi_legacy_hal_stubs.h"
// TODO: Remove these stubs from HalTool in libwifi-system.
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace legacy_hal {
template <typename>
struct stubFunction;
@@ -170,9 +169,9 @@
populateStubFor(&hal_fn->wifi_get_cached_scan_results);
return true;
}
+
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_legacy_hal_stubs.h b/wifi/aidl/default/wifi_legacy_hal_stubs.h
similarity index 86%
rename from wifi/1.6/default/wifi_legacy_hal_stubs.h
rename to wifi/aidl/default/wifi_legacy_hal_stubs.h
index c9a03bf..603ecf2 100644
--- a/wifi/1.6/default/wifi_legacy_hal_stubs.h
+++ b/wifi/aidl/default/wifi_legacy_hal_stubs.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,19 +19,17 @@
#include <hardware_legacy/wifi_hal.h>
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace legacy_hal {
bool initHalFuncTableWithStubs(wifi_hal_fn* hal_fn);
} // namespace legacy_hal
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_LEGACY_HAL_STUBS_H_
diff --git a/wifi/1.6/default/wifi_mode_controller.cpp b/wifi/aidl/default/wifi_mode_controller.cpp
similarity index 90%
rename from wifi/1.6/default/wifi_mode_controller.cpp
rename to wifi/aidl/default/wifi_mode_controller.cpp
index 4b8ac7d..07cb072 100644
--- a/wifi/1.6/default/wifi_mode_controller.cpp
+++ b/wifi/aidl/default/wifi_mode_controller.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,16 +14,16 @@
* limitations under the License.
*/
+#include "wifi_mode_controller.h"
+
#include <android-base/logging.h>
#include <android-base/macros.h>
#include <private/android_filesystem_config.h>
-#include "wifi_mode_controller.h"
-
-using android::hardware::wifi::V1_0::IfaceType;
+namespace {
+using aidl::android::hardware::wifi::IfaceType;
using android::wifi_hal::DriverTool;
-namespace {
int convertIfaceTypeToFirmwareMode(IfaceType type) {
int mode;
switch (type) {
@@ -33,7 +33,7 @@
case IfaceType::P2P:
mode = DriverTool::kFirmwareModeP2p;
break;
- case IfaceType::NAN:
+ case IfaceType::NAN_IFACE:
// NAN is exposed in STA mode currently.
mode = DriverTool::kFirmwareModeSta;
break;
@@ -45,11 +45,10 @@
}
} // namespace
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace mode_controller {
WifiModeController::WifiModeController() : driver_tool_(new DriverTool) {}
@@ -81,9 +80,9 @@
}
return true;
}
+
} // namespace mode_controller
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_mode_controller.h b/wifi/aidl/default/wifi_mode_controller.h
similarity index 84%
rename from wifi/1.6/default/wifi_mode_controller.h
rename to wifi/aidl/default/wifi_mode_controller.h
index fee2b66..1a9fb1a 100644
--- a/wifi/1.6/default/wifi_mode_controller.h
+++ b/wifi/aidl/default/wifi_mode_controller.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,17 +17,14 @@
#ifndef WIFI_MODE_CONTROLLER_H_
#define WIFI_MODE_CONTROLLER_H_
+#include <aidl/android/hardware/wifi/IWifi.h>
#include <wifi_hal/driver_tool.h>
-#include <android/hardware/wifi/1.0/IWifi.h>
-
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
namespace mode_controller {
-using namespace android::hardware::wifi::V1_0;
/**
* Class that encapsulates all firmware mode configuration.
@@ -50,14 +47,13 @@
virtual bool deinitialize();
private:
- std::unique_ptr<wifi_hal::DriverTool> driver_tool_;
+ std::unique_ptr<::android::wifi_hal::DriverTool> driver_tool_;
};
} // namespace mode_controller
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_MODE_CONTROLLER_H_
diff --git a/wifi/aidl/default/wifi_nan_iface.cpp b/wifi/aidl/default/wifi_nan_iface.cpp
new file mode 100644
index 0000000..9edef09
--- /dev/null
+++ b/wifi/aidl/default/wifi_nan_iface.cpp
@@ -0,0 +1,751 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "wifi_nan_iface.h"
+
+#include <android-base/logging.h>
+
+#include "aidl_return_util.h"
+#include "aidl_struct_util.h"
+#include "wifi_status_util.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+using aidl_return_util::validateAndCall;
+
+WifiNanIface::WifiNanIface(const std::string& ifname, bool is_dedicated_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
+ : ifname_(ifname),
+ is_dedicated_iface_(is_dedicated_iface),
+ legacy_hal_(legacy_hal),
+ iface_util_(iface_util),
+ is_valid_(true) {}
+
+std::shared_ptr<WifiNanIface> WifiNanIface::create(
+ const std::string& ifname, bool is_dedicated_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util) {
+ std::shared_ptr<WifiNanIface> ptr = ndk::SharedRefBase::make<WifiNanIface>(
+ ifname, is_dedicated_iface, legacy_hal, iface_util);
+ if (is_dedicated_iface) {
+ // If using a dedicated iface, set the iface up first.
+ if (!iface_util.lock()->setUpState(ifname, true)) {
+ // Fatal failure, invalidate the iface object.
+ ptr->invalidate();
+ return nullptr;
+ }
+ }
+ std::weak_ptr<WifiNanIface> weak_ptr_this(ptr);
+ ptr->setWeakPtr(weak_ptr_this);
+ ptr->registerCallbackHandlers();
+ return ptr;
+}
+
+void WifiNanIface::registerCallbackHandlers() {
+ // Register all the callbacks here. These should be valid for the lifetime
+ // of the object. Whenever the mode changes legacy HAL will remove
+ // all of these callbacks.
+ legacy_hal::NanCallbackHandlers callback_handlers;
+ std::weak_ptr<WifiNanIface> weak_ptr_this = weak_ptr_this_;
+
+ // Callback for response.
+ callback_handlers.on_notify_response = [weak_ptr_this](legacy_hal::transaction_id id,
+ const legacy_hal::NanResponseMsg& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanStatus nanStatus;
+ if (!aidl_struct_util::convertLegacyNanResponseHeaderToAidl(msg, &nanStatus)) {
+ LOG(ERROR) << "Failed to convert nan response header";
+ return;
+ }
+
+ switch (msg.response_type) {
+ case legacy_hal::NAN_RESPONSE_ENABLED: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyEnableResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_DISABLED: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyDisableResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_PUBLISH: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyStartPublishResponse(id, nanStatus,
+ msg.body.publish_response.publish_id)
+ .isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_PUBLISH_CANCEL: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyStopPublishResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_TRANSMIT_FOLLOWUP: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyTransmitFollowupResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_SUBSCRIBE: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyStartSubscribeResponse(
+ id, nanStatus, msg.body.subscribe_response.subscribe_id)
+ .isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_SUBSCRIBE_CANCEL: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyStopSubscribeResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_CONFIG: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyConfigResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_GET_CAPABILITIES: {
+ NanCapabilities aidl_struct;
+ if (!aidl_struct_util::convertLegacyNanCapabilitiesResponseToAidl(
+ msg.body.nan_capabilities, &aidl_struct)) {
+ LOG(ERROR) << "Failed to convert nan capabilities response";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyCapabilitiesResponse(id, nanStatus, aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_DP_INTERFACE_CREATE: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyCreateDataInterfaceResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_DP_INTERFACE_DELETE: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyDeleteDataInterfaceResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_DP_INITIATOR_RESPONSE: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyInitiateDataPathResponse(
+ id, nanStatus,
+ msg.body.data_request_response.ndp_instance_id)
+ .isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_DP_RESPONDER_RESPONSE: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyRespondToDataPathIndicationResponse(id, nanStatus)
+ .isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_DP_END: {
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->notifyTerminateDataPathResponse(id, nanStatus).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ break;
+ }
+ case legacy_hal::NAN_RESPONSE_BEACON_SDF_PAYLOAD:
+ /* fall through */
+ case legacy_hal::NAN_RESPONSE_TCA:
+ /* fall through */
+ case legacy_hal::NAN_RESPONSE_STATS:
+ /* fall through */
+ case legacy_hal::NAN_RESPONSE_ERROR:
+ /* fall through */
+ default:
+ LOG(ERROR) << "Unknown or unhandled response type: " << msg.response_type;
+ return;
+ }
+ };
+
+ callback_handlers.on_event_disc_eng_event = [weak_ptr_this](
+ const legacy_hal::NanDiscEngEventInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanClusterEventInd aidl_struct;
+ // event types defined identically - hence can be cast
+ aidl_struct.eventType = (NanClusterEventType)msg.event_type;
+ aidl_struct.addr = std::array<uint8_t, 6>();
+ std::copy(msg.data.mac_addr.addr, msg.data.mac_addr.addr + 6, std::begin(aidl_struct.addr));
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventClusterEvent(aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_disabled = [weak_ptr_this](const legacy_hal::NanDisabledInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanStatus status;
+ aidl_struct_util::convertToNanStatus(msg.reason, msg.nan_reason, sizeof(msg.nan_reason),
+ &status);
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventDisabled(status).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_publish_terminated =
+ [weak_ptr_this](const legacy_hal::NanPublishTerminatedInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanStatus status;
+ aidl_struct_util::convertToNanStatus(msg.reason, msg.nan_reason,
+ sizeof(msg.nan_reason), &status);
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventPublishTerminated(msg.publish_id, status).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_subscribe_terminated =
+ [weak_ptr_this](const legacy_hal::NanSubscribeTerminatedInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanStatus status;
+ aidl_struct_util::convertToNanStatus(msg.reason, msg.nan_reason,
+ sizeof(msg.nan_reason), &status);
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventSubscribeTerminated(msg.subscribe_id, status).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_match = [weak_ptr_this](const legacy_hal::NanMatchInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanMatchInd aidl_struct;
+ if (!aidl_struct_util::convertLegacyNanMatchIndToAidl(msg, &aidl_struct)) {
+ LOG(ERROR) << "Failed to convert nan capabilities response";
+ return;
+ }
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventMatch(aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_match_expired = [weak_ptr_this](
+ const legacy_hal::NanMatchExpiredInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventMatchExpired(msg.publish_subscribe_id, msg.requestor_instance_id)
+ .isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_followup = [weak_ptr_this](const legacy_hal::NanFollowupInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanFollowupReceivedInd aidl_struct;
+ if (!aidl_struct_util::convertLegacyNanFollowupIndToAidl(msg, &aidl_struct)) {
+ LOG(ERROR) << "Failed to convert nan capabilities response";
+ return;
+ }
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventFollowupReceived(aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_transmit_follow_up =
+ [weak_ptr_this](const legacy_hal::NanTransmitFollowupInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanStatus status;
+ aidl_struct_util::convertToNanStatus(msg.reason, msg.nan_reason,
+ sizeof(msg.nan_reason), &status);
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventTransmitFollowup(msg.id, status).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_data_path_request =
+ [weak_ptr_this](const legacy_hal::NanDataPathRequestInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanDataPathRequestInd aidl_struct;
+ if (!aidl_struct_util::convertLegacyNanDataPathRequestIndToAidl(msg,
+ &aidl_struct)) {
+ LOG(ERROR) << "Failed to convert nan capabilities response";
+ return;
+ }
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventDataPathRequest(aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_data_path_confirm =
+ [weak_ptr_this](const legacy_hal::NanDataPathConfirmInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanDataPathConfirmInd aidl_struct;
+ if (!aidl_struct_util::convertLegacyNanDataPathConfirmIndToAidl(msg,
+ &aidl_struct)) {
+ LOG(ERROR) << "Failed to convert nan capabilities response";
+ return;
+ }
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventDataPathConfirm(aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ callback_handlers.on_event_data_path_end =
+ [weak_ptr_this](const legacy_hal::NanDataPathEndInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ for (int i = 0; i < msg.num_ndp_instances; ++i) {
+ if (!callback->eventDataPathTerminated(msg.ndp_instance_id[i]).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ }
+ };
+
+ callback_handlers.on_event_beacon_sdf_payload =
+ [](const legacy_hal::NanBeaconSdfPayloadInd& /* msg */) {
+ LOG(ERROR) << "on_event_beacon_sdf_payload - should not be called";
+ };
+
+ callback_handlers.on_event_range_request = [](const legacy_hal::NanRangeRequestInd& /* msg */) {
+ LOG(ERROR) << "on_event_range_request - should not be called";
+ };
+
+ callback_handlers.on_event_range_report = [](const legacy_hal::NanRangeReportInd& /* msg */) {
+ LOG(ERROR) << "on_event_range_report - should not be called";
+ };
+
+ callback_handlers.on_event_schedule_update =
+ [weak_ptr_this](const legacy_hal::NanDataPathScheduleUpdateInd& msg) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ NanDataPathScheduleUpdateInd aidl_struct;
+ if (!aidl_struct_util::convertLegacyNanDataPathScheduleUpdateIndToAidl(
+ msg, &aidl_struct)) {
+ LOG(ERROR) << "Failed to convert nan capabilities response";
+ return;
+ }
+
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventDataPathScheduleUpdate(aidl_struct).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanRegisterCallbackHandlers(ifname_, callback_handlers);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ LOG(ERROR) << "Failed to register nan callbacks. Invalidating object";
+ invalidate();
+ }
+
+ // Register for iface state toggle events.
+ iface_util::IfaceEventHandlers event_handlers = {};
+ event_handlers.on_state_toggle_off_on = [weak_ptr_this](const std::string& /* iface_name */) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ // Tell framework that NAN has been disabled.
+ NanStatus status = {NanStatusCode::UNSUPPORTED_CONCURRENCY_NAN_DISABLED, ""};
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->eventDisabled(status).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+ iface_util_.lock()->registerIfaceEventHandlers(ifname_, event_handlers);
+}
+
+void WifiNanIface::setWeakPtr(std::weak_ptr<WifiNanIface> ptr) {
+ weak_ptr_this_ = ptr;
+}
+
+void WifiNanIface::invalidate() {
+ if (!isValid()) {
+ return;
+ }
+ // send commands to HAL to actually disable and destroy interfaces
+ legacy_hal_.lock()->nanDisableRequest(ifname_, 0xFFFF);
+ legacy_hal_.lock()->nanDataInterfaceDelete(ifname_, 0xFFFE, "aware_data0");
+ legacy_hal_.lock()->nanDataInterfaceDelete(ifname_, 0xFFFD, "aware_data1");
+ iface_util_.lock()->unregisterIfaceEventHandlers(ifname_);
+ legacy_hal_.reset();
+ event_cb_handler_.invalidate();
+ is_valid_ = false;
+ if (is_dedicated_iface_) {
+ // If using a dedicated iface, set the iface down.
+ iface_util_.lock()->setUpState(ifname_, false);
+ }
+}
+
+bool WifiNanIface::isValid() {
+ return is_valid_;
+}
+
+std::string WifiNanIface::getName() {
+ return ifname_;
+}
+
+std::set<std::shared_ptr<IWifiNanIfaceEventCallback>> WifiNanIface::getEventCallbacks() {
+ LOG(ERROR) << "Using original getEventCallbacks";
+ return event_cb_handler_.getCallbacks();
+}
+
+ndk::ScopedAStatus WifiNanIface::getName(std::string* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::getNameInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiNanIface::registerEventCallback(
+ const std::shared_ptr<IWifiNanIfaceEventCallback>& callback) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::registerEventCallbackInternal, callback);
+}
+
+ndk::ScopedAStatus WifiNanIface::getCapabilitiesRequest(char16_t in_cmdId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::getCapabilitiesRequestInternal, in_cmdId);
+}
+
+ndk::ScopedAStatus WifiNanIface::enableRequest(char16_t in_cmdId, const NanEnableRequest& in_msg1,
+ const NanConfigRequestSupplemental& in_msg2) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::enableRequestInternal, in_cmdId, in_msg1, in_msg2);
+}
+
+ndk::ScopedAStatus WifiNanIface::configRequest(char16_t in_cmdId, const NanConfigRequest& in_msg1,
+ const NanConfigRequestSupplemental& in_msg2) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::configRequestInternal, in_cmdId, in_msg1, in_msg2);
+}
+
+ndk::ScopedAStatus WifiNanIface::disableRequest(char16_t in_cmdId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::disableRequestInternal, in_cmdId);
+}
+
+ndk::ScopedAStatus WifiNanIface::startPublishRequest(char16_t in_cmdId,
+ const NanPublishRequest& in_msg) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::startPublishRequestInternal, in_cmdId, in_msg);
+}
+
+ndk::ScopedAStatus WifiNanIface::stopPublishRequest(char16_t in_cmdId, int8_t in_sessionId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::stopPublishRequestInternal, in_cmdId, in_sessionId);
+}
+
+ndk::ScopedAStatus WifiNanIface::startSubscribeRequest(char16_t in_cmdId,
+ const NanSubscribeRequest& in_msg) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::startSubscribeRequestInternal, in_cmdId, in_msg);
+}
+
+ndk::ScopedAStatus WifiNanIface::stopSubscribeRequest(char16_t in_cmdId, int8_t in_sessionId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::stopSubscribeRequestInternal, in_cmdId, in_sessionId);
+}
+
+ndk::ScopedAStatus WifiNanIface::transmitFollowupRequest(char16_t in_cmdId,
+ const NanTransmitFollowupRequest& in_msg) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::transmitFollowupRequestInternal, in_cmdId, in_msg);
+}
+
+ndk::ScopedAStatus WifiNanIface::createDataInterfaceRequest(char16_t in_cmdId,
+ const std::string& in_ifaceName) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::createDataInterfaceRequestInternal, in_cmdId,
+ in_ifaceName);
+}
+
+ndk::ScopedAStatus WifiNanIface::deleteDataInterfaceRequest(char16_t in_cmdId,
+ const std::string& in_ifaceName) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::deleteDataInterfaceRequestInternal, in_cmdId,
+ in_ifaceName);
+}
+
+ndk::ScopedAStatus WifiNanIface::initiateDataPathRequest(char16_t in_cmdId,
+ const NanInitiateDataPathRequest& in_msg) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::initiateDataPathRequestInternal, in_cmdId, in_msg);
+}
+
+ndk::ScopedAStatus WifiNanIface::respondToDataPathIndicationRequest(
+ char16_t in_cmdId, const NanRespondToDataPathIndicationRequest& in_msg) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::respondToDataPathIndicationRequestInternal, in_cmdId,
+ in_msg);
+}
+
+ndk::ScopedAStatus WifiNanIface::terminateDataPathRequest(char16_t in_cmdId,
+ int32_t in_ndpInstanceId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiNanIface::terminateDataPathRequestInternal, in_cmdId,
+ in_ndpInstanceId);
+}
+
+std::pair<std::string, ndk::ScopedAStatus> WifiNanIface::getNameInternal() {
+ return {ifname_, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiNanIface::registerEventCallbackInternal(
+ const std::shared_ptr<IWifiNanIfaceEventCallback>& callback) {
+ if (!event_cb_handler_.addCallback(callback)) {
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus WifiNanIface::getCapabilitiesRequestInternal(char16_t cmd_id) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->nanGetCapabilities(ifname_, cmd_id);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::enableRequestInternal(char16_t cmd_id,
+ const NanEnableRequest& msg1,
+ const NanConfigRequestSupplemental& msg2) {
+ legacy_hal::NanEnableRequest legacy_msg;
+ if (!aidl_struct_util::convertAidlNanEnableRequestToLegacy(msg1, msg2, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanEnableRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::configRequestInternal(char16_t cmd_id,
+ const NanConfigRequest& msg1,
+ const NanConfigRequestSupplemental& msg2) {
+ legacy_hal::NanConfigRequest legacy_msg;
+ if (!aidl_struct_util::convertAidlNanConfigRequestToLegacy(msg1, msg2, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanConfigRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::disableRequestInternal(char16_t cmd_id) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->nanDisableRequest(ifname_, cmd_id);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::startPublishRequestInternal(char16_t cmd_id,
+ const NanPublishRequest& msg) {
+ legacy_hal::NanPublishRequest legacy_msg;
+ if (!aidl_struct_util::convertAidlNanPublishRequestToLegacy(msg, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanPublishRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::stopPublishRequestInternal(char16_t cmd_id, int8_t sessionId) {
+ legacy_hal::NanPublishCancelRequest legacy_msg;
+ legacy_msg.publish_id = sessionId;
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanPublishCancelRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::startSubscribeRequestInternal(char16_t cmd_id,
+ const NanSubscribeRequest& msg) {
+ legacy_hal::NanSubscribeRequest legacy_msg;
+ if (!aidl_struct_util::convertAidlNanSubscribeRequestToLegacy(msg, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanSubscribeRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::stopSubscribeRequestInternal(char16_t cmd_id, int8_t sessionId) {
+ legacy_hal::NanSubscribeCancelRequest legacy_msg;
+ legacy_msg.subscribe_id = sessionId;
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanSubscribeCancelRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::transmitFollowupRequestInternal(
+ char16_t cmd_id, const NanTransmitFollowupRequest& msg) {
+ legacy_hal::NanTransmitFollowupRequest legacy_msg;
+ if (!aidl_struct_util::convertAidlNanTransmitFollowupRequestToLegacy(msg, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanTransmitFollowupRequest(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiNanIface::createDataInterfaceRequestInternal(char16_t cmd_id,
+ const std::string& iface_name) {
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanDataInterfaceCreate(ifname_, cmd_id, iface_name);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+ndk::ScopedAStatus WifiNanIface::deleteDataInterfaceRequestInternal(char16_t cmd_id,
+ const std::string& iface_name) {
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanDataInterfaceDelete(ifname_, cmd_id, iface_name);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+ndk::ScopedAStatus WifiNanIface::initiateDataPathRequestInternal(
+ char16_t cmd_id, const NanInitiateDataPathRequest& msg) {
+ legacy_hal::NanDataPathInitiatorRequest legacy_msg;
+ if (!aidl_struct_util::convertAidlNanDataPathInitiatorRequestToLegacy(msg, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanDataRequestInitiator(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+ndk::ScopedAStatus WifiNanIface::respondToDataPathIndicationRequestInternal(
+ char16_t cmd_id, const NanRespondToDataPathIndicationRequest& msg) {
+ legacy_hal::NanDataPathIndicationResponse legacy_msg;
+ if (!aidl_struct_util::convertAidlNanDataPathIndicationResponseToLegacy(msg, &legacy_msg)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanDataIndicationResponse(ifname_, cmd_id, legacy_msg);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+ndk::ScopedAStatus WifiNanIface::terminateDataPathRequestInternal(char16_t cmd_id,
+ int32_t ndpInstanceId) {
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->nanDataEnd(ifname_, cmd_id, ndpInstanceId);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi_nan_iface.h b/wifi/aidl/default/wifi_nan_iface.h
new file mode 100644
index 0000000..1018905
--- /dev/null
+++ b/wifi/aidl/default/wifi_nan_iface.h
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_NAN_IFACE_H_
+#define WIFI_NAN_IFACE_H_
+
+#include <aidl/android/hardware/wifi/BnWifiNanIface.h>
+#include <aidl/android/hardware/wifi/IWifiNanIfaceEventCallback.h>
+#include <android-base/macros.h>
+
+#include "aidl_callback_util.h"
+#include "wifi_iface_util.h"
+#include "wifi_legacy_hal.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+/**
+ * AIDL interface object used to control a NAN Iface instance.
+ */
+class WifiNanIface : public BnWifiNanIface {
+ public:
+ WifiNanIface(const std::string& ifname, bool is_dedicated_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
+
+ // Factory method - use instead of default constructor.
+ static std::shared_ptr<WifiNanIface> create(
+ const std::string& ifname, bool is_dedicated_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
+
+ // Refer to |WifiChip::invalidate()|.
+ void invalidate();
+ bool isValid();
+ std::string getName();
+
+ // AIDL methods exposed.
+ ndk::ScopedAStatus getName(std::string* _aidl_return) override;
+ ndk::ScopedAStatus registerEventCallback(
+ const std::shared_ptr<IWifiNanIfaceEventCallback>& in_callback) override;
+ ndk::ScopedAStatus getCapabilitiesRequest(char16_t in_cmdId) override;
+ ndk::ScopedAStatus enableRequest(char16_t in_cmdId, const NanEnableRequest& in_msg1,
+ const NanConfigRequestSupplemental& in_msg2) override;
+ ndk::ScopedAStatus configRequest(char16_t in_cmdId, const NanConfigRequest& in_msg1,
+ const NanConfigRequestSupplemental& in_msg2) override;
+ ndk::ScopedAStatus disableRequest(char16_t in_cmdId) override;
+ ndk::ScopedAStatus startPublishRequest(char16_t in_cmdId,
+ const NanPublishRequest& in_msg) override;
+ ndk::ScopedAStatus stopPublishRequest(char16_t in_cmdId, int8_t in_sessionId) override;
+ ndk::ScopedAStatus startSubscribeRequest(char16_t in_cmdId,
+ const NanSubscribeRequest& in_msg) override;
+ ndk::ScopedAStatus stopSubscribeRequest(char16_t in_cmdId, int8_t in_sessionId) override;
+ ndk::ScopedAStatus transmitFollowupRequest(char16_t in_cmdId,
+ const NanTransmitFollowupRequest& in_msg) override;
+ ndk::ScopedAStatus createDataInterfaceRequest(char16_t in_cmdId,
+ const std::string& in_ifaceName) override;
+ ndk::ScopedAStatus deleteDataInterfaceRequest(char16_t in_cmdId,
+ const std::string& in_ifaceName) override;
+ ndk::ScopedAStatus initiateDataPathRequest(char16_t in_cmdId,
+ const NanInitiateDataPathRequest& in_msg) override;
+ ndk::ScopedAStatus respondToDataPathIndicationRequest(
+ char16_t in_cmdId, const NanRespondToDataPathIndicationRequest& in_msg) override;
+ ndk::ScopedAStatus terminateDataPathRequest(char16_t in_cmdId,
+ int32_t in_ndpInstanceId) override;
+
+ protected:
+ // Accessible to child class in the gTest suite.
+ void setWeakPtr(std::weak_ptr<WifiNanIface> ptr);
+ void registerCallbackHandlers();
+
+ private:
+ // Corresponding worker functions for the AIDL methods.
+ std::pair<std::string, ndk::ScopedAStatus> getNameInternal();
+ ndk::ScopedAStatus registerEventCallbackInternal(
+ const std::shared_ptr<IWifiNanIfaceEventCallback>& callback);
+ ndk::ScopedAStatus getCapabilitiesRequestInternal(char16_t cmd_id);
+ ndk::ScopedAStatus enableRequestInternal(char16_t cmd_id, const NanEnableRequest& msg1,
+ const NanConfigRequestSupplemental& msg2);
+ ndk::ScopedAStatus configRequestInternal(char16_t cmd_id, const NanConfigRequest& msg1,
+ const NanConfigRequestSupplemental& msg2);
+ ndk::ScopedAStatus disableRequestInternal(char16_t cmd_id);
+ ndk::ScopedAStatus startPublishRequestInternal(char16_t cmd_id, const NanPublishRequest& msg);
+ ndk::ScopedAStatus stopPublishRequestInternal(char16_t cmd_id, int8_t sessionId);
+ ndk::ScopedAStatus startSubscribeRequestInternal(char16_t cmd_id,
+ const NanSubscribeRequest& msg);
+ ndk::ScopedAStatus stopSubscribeRequestInternal(char16_t cmd_id, int8_t sessionId);
+ ndk::ScopedAStatus transmitFollowupRequestInternal(char16_t cmd_id,
+ const NanTransmitFollowupRequest& msg);
+ ndk::ScopedAStatus createDataInterfaceRequestInternal(char16_t cmd_id,
+ const std::string& iface_name);
+ ndk::ScopedAStatus deleteDataInterfaceRequestInternal(char16_t cmd_id,
+ const std::string& iface_name);
+ ndk::ScopedAStatus initiateDataPathRequestInternal(char16_t cmd_id,
+ const NanInitiateDataPathRequest& msg);
+ ndk::ScopedAStatus respondToDataPathIndicationRequestInternal(
+ char16_t cmd_id, const NanRespondToDataPathIndicationRequest& msg);
+ ndk::ScopedAStatus terminateDataPathRequestInternal(char16_t cmd_id, int32_t ndpInstanceId);
+
+ // Overridden in the gTest suite.
+ virtual std::set<std::shared_ptr<IWifiNanIfaceEventCallback>> getEventCallbacks();
+
+ std::string ifname_;
+ bool is_dedicated_iface_;
+ std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
+ std::weak_ptr<iface_util::WifiIfaceUtil> iface_util_;
+ bool is_valid_;
+ std::weak_ptr<WifiNanIface> weak_ptr_this_;
+ aidl_callback_util::AidlCallbackHandler<IWifiNanIfaceEventCallback> event_cb_handler_;
+
+ DISALLOW_COPY_AND_ASSIGN(WifiNanIface);
+};
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_NAN_IFACE_H_
diff --git a/wifi/1.6/default/wifi_p2p_iface.cpp b/wifi/aidl/default/wifi_p2p_iface.cpp
similarity index 60%
rename from wifi/1.6/default/wifi_p2p_iface.cpp
rename to wifi/aidl/default/wifi_p2p_iface.cpp
index d4b1fca..48ec6d6 100644
--- a/wifi/1.6/default/wifi_p2p_iface.cpp
+++ b/wifi/aidl/default/wifi_p2p_iface.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,18 +14,18 @@
* limitations under the License.
*/
+#include "wifi_p2p_iface.h"
+
#include <android-base/logging.h>
-#include "hidl_return_util.h"
-#include "wifi_p2p_iface.h"
+#include "aidl_return_util.h"
#include "wifi_status_util.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using hidl_return_util::validateAndCall;
+using aidl_return_util::validateAndCall;
WifiP2pIface::WifiP2pIface(const std::string& ifname,
const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal)
@@ -44,26 +44,16 @@
return ifname_;
}
-Return<void> WifiP2pIface::getName(getName_cb hidl_status_cb) {
+ndk::ScopedAStatus WifiP2pIface::getName(std::string* _aidl_return) {
return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiP2pIface::getNameInternal, hidl_status_cb);
+ &WifiP2pIface::getNameInternal, _aidl_return);
}
-Return<void> WifiP2pIface::getType(getType_cb hidl_status_cb) {
- return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
- &WifiP2pIface::getTypeInternal, hidl_status_cb);
+std::pair<std::string, ndk::ScopedAStatus> WifiP2pIface::getNameInternal() {
+ return {ifname_, ndk::ScopedAStatus::ok()};
}
-std::pair<WifiStatus, std::string> WifiP2pIface::getNameInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), ifname_};
-}
-
-std::pair<WifiStatus, IfaceType> WifiP2pIface::getTypeInternal() {
- return {createWifiStatus(WifiStatusCode::SUCCESS), IfaceType::P2P};
-}
-
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/1.6/default/wifi_p2p_iface.h b/wifi/aidl/default/wifi_p2p_iface.h
similarity index 64%
rename from wifi/1.6/default/wifi_p2p_iface.h
rename to wifi/aidl/default/wifi_p2p_iface.h
index 0089443..d17470e 100644
--- a/wifi/1.6/default/wifi_p2p_iface.h
+++ b/wifi/aidl/default/wifi_p2p_iface.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,22 +17,20 @@
#ifndef WIFI_P2P_IFACE_H_
#define WIFI_P2P_IFACE_H_
+#include <aidl/android/hardware/wifi/BnWifiP2pIface.h>
#include <android-base/macros.h>
-#include <android/hardware/wifi/1.0/IWifiP2pIface.h>
#include "wifi_legacy_hal.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
-using namespace android::hardware::wifi::V1_0;
/**
- * HIDL interface object used to control a P2P Iface instance.
+ * AIDL interface object used to control a P2P Iface instance.
*/
-class WifiP2pIface : public V1_0::IWifiP2pIface {
+class WifiP2pIface : public BnWifiP2pIface {
public:
WifiP2pIface(const std::string& ifname,
const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal);
@@ -41,14 +39,12 @@
bool isValid();
std::string getName();
- // HIDL methods exposed.
- Return<void> getName(getName_cb hidl_status_cb) override;
- Return<void> getType(getType_cb hidl_status_cb) override;
+ // AIDL methods exposed.
+ ndk::ScopedAStatus getName(std::string* _aidl_return) override;
private:
- // Corresponding worker functions for the HIDL methods.
- std::pair<WifiStatus, std::string> getNameInternal();
- std::pair<WifiStatus, IfaceType> getTypeInternal();
+ // Corresponding worker functions for the AIDL methods.
+ std::pair<std::string, ndk::ScopedAStatus> getNameInternal();
std::string ifname_;
std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
@@ -57,10 +53,9 @@
DISALLOW_COPY_AND_ASSIGN(WifiP2pIface);
};
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
#endif // WIFI_P2P_IFACE_H_
diff --git a/wifi/aidl/default/wifi_rtt_controller.cpp b/wifi/aidl/default/wifi_rtt_controller.cpp
new file mode 100644
index 0000000..856c3cd
--- /dev/null
+++ b/wifi/aidl/default/wifi_rtt_controller.cpp
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "wifi_rtt_controller.h"
+
+#include <android-base/logging.h>
+
+#include "aidl_return_util.h"
+#include "aidl_struct_util.h"
+#include "wifi_status_util.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+using aidl_return_util::validateAndCall;
+
+WifiRttController::WifiRttController(const std::string& iface_name,
+ const std::shared_ptr<IWifiStaIface>& bound_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal)
+ : ifname_(iface_name), bound_iface_(bound_iface), legacy_hal_(legacy_hal), is_valid_(true) {}
+
+std::shared_ptr<WifiRttController> WifiRttController::create(
+ const std::string& iface_name, const std::shared_ptr<IWifiStaIface>& bound_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal) {
+ std::shared_ptr<WifiRttController> ptr =
+ ndk::SharedRefBase::make<WifiRttController>(iface_name, bound_iface, legacy_hal);
+ std::weak_ptr<WifiRttController> weak_ptr_this(ptr);
+ ptr->setWeakPtr(weak_ptr_this);
+ return ptr;
+}
+
+void WifiRttController::invalidate() {
+ legacy_hal_.reset();
+ event_callbacks_.clear();
+ is_valid_ = false;
+};
+
+bool WifiRttController::isValid() {
+ return is_valid_;
+}
+
+void WifiRttController::setWeakPtr(std::weak_ptr<WifiRttController> ptr) {
+ weak_ptr_this_ = ptr;
+}
+
+std::vector<std::shared_ptr<IWifiRttControllerEventCallback>>
+WifiRttController::getEventCallbacks() {
+ return event_callbacks_;
+}
+
+std::string WifiRttController::getIfaceName() {
+ return ifname_;
+}
+
+ndk::ScopedAStatus WifiRttController::getBoundIface(std::shared_ptr<IWifiStaIface>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::getBoundIfaceInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiRttController::registerEventCallback(
+ const std::shared_ptr<IWifiRttControllerEventCallback>& callback) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::registerEventCallbackInternal, callback);
+}
+
+ndk::ScopedAStatus WifiRttController::rangeRequest(int32_t in_cmdId,
+ const std::vector<RttConfig>& in_rttConfigs) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::rangeRequestInternal, in_cmdId, in_rttConfigs);
+}
+
+ndk::ScopedAStatus WifiRttController::rangeCancel(int32_t in_cmdId,
+ const std::vector<MacAddress>& in_addrs) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::rangeCancelInternal, in_cmdId, in_addrs);
+}
+
+ndk::ScopedAStatus WifiRttController::getCapabilities(RttCapabilities* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::getCapabilitiesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiRttController::setLci(int32_t in_cmdId, const RttLciInformation& in_lci) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::setLciInternal, in_cmdId, in_lci);
+}
+
+ndk::ScopedAStatus WifiRttController::setLcr(int32_t in_cmdId, const RttLcrInformation& in_lcr) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::setLcrInternal, in_cmdId, in_lcr);
+}
+
+ndk::ScopedAStatus WifiRttController::getResponderInfo(RttResponder* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::getResponderInfoInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiRttController::enableResponder(int32_t in_cmdId,
+ const WifiChannelInfo& in_channelHint,
+ int32_t in_maxDurationInSeconds,
+ const RttResponder& in_info) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::enableResponderInternal, in_cmdId, in_channelHint,
+ in_maxDurationInSeconds, in_info);
+}
+
+ndk::ScopedAStatus WifiRttController::disableResponder(int32_t in_cmdId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_RTT_CONTROLLER_INVALID,
+ &WifiRttController::disableResponderInternal, in_cmdId);
+}
+
+std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus>
+WifiRttController::getBoundIfaceInternal() {
+ return {bound_iface_, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiRttController::registerEventCallbackInternal(
+ const std::shared_ptr<IWifiRttControllerEventCallback>& callback) {
+ event_callbacks_.emplace_back(callback);
+ return ndk::ScopedAStatus::ok();
+}
+
+ndk::ScopedAStatus WifiRttController::rangeRequestInternal(
+ int32_t cmd_id, const std::vector<RttConfig>& rtt_configs) {
+ std::vector<legacy_hal::wifi_rtt_config> legacy_configs;
+ if (!aidl_struct_util::convertAidlVectorOfRttConfigToLegacy(rtt_configs, &legacy_configs)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ std::weak_ptr<WifiRttController> weak_ptr_this = weak_ptr_this_;
+ const auto& on_results_callback =
+ [weak_ptr_this](legacy_hal::wifi_request_id id,
+ const std::vector<const legacy_hal::wifi_rtt_result*>& results) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ std::vector<RttResult> aidl_results;
+ if (!aidl_struct_util::convertLegacyVectorOfRttResultToAidl(results,
+ &aidl_results)) {
+ LOG(ERROR) << "Failed to convert rtt results to AIDL structs";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->onResults(id, aidl_results).isOk()) {
+ LOG(ERROR) << "Failed to invoke the callback";
+ }
+ }
+ };
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startRttRangeRequest(
+ ifname_, cmd_id, legacy_configs, on_results_callback);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiRttController::rangeCancelInternal(int32_t cmd_id,
+ const std::vector<MacAddress>& addrs) {
+ std::vector<std::array<uint8_t, ETH_ALEN>> legacy_addrs;
+ for (const auto& addr : addrs) {
+ std::array<uint8_t, ETH_ALEN> addr_array;
+ std::copy_n(addr.data.begin(), ETH_ALEN, addr_array.begin());
+ legacy_addrs.push_back(addr_array);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->cancelRttRangeRequest(ifname_, cmd_id, legacy_addrs);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<RttCapabilities, ndk::ScopedAStatus> WifiRttController::getCapabilitiesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ legacy_hal::wifi_rtt_capabilities legacy_caps;
+ std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getRttCapabilities(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {RttCapabilities{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ RttCapabilities aidl_caps;
+ if (!aidl_struct_util::convertLegacyRttCapabilitiesToAidl(legacy_caps, &aidl_caps)) {
+ return {RttCapabilities{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_caps, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiRttController::setLciInternal(int32_t cmd_id, const RttLciInformation& lci) {
+ legacy_hal::wifi_lci_information legacy_lci;
+ if (!aidl_struct_util::convertAidlRttLciInformationToLegacy(lci, &legacy_lci)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->setRttLci(ifname_, cmd_id, legacy_lci);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiRttController::setLcrInternal(int32_t cmd_id, const RttLcrInformation& lcr) {
+ legacy_hal::wifi_lcr_information legacy_lcr;
+ if (!aidl_struct_util::convertAidlRttLcrInformationToLegacy(lcr, &legacy_lcr)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->setRttLcr(ifname_, cmd_id, legacy_lcr);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<RttResponder, ndk::ScopedAStatus> WifiRttController::getResponderInfoInternal() {
+ legacy_hal::wifi_error legacy_status;
+ legacy_hal::wifi_rtt_responder legacy_responder;
+ std::tie(legacy_status, legacy_responder) = legacy_hal_.lock()->getRttResponderInfo(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {RttResponder{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ RttResponder aidl_responder;
+ if (!aidl_struct_util::convertLegacyRttResponderToAidl(legacy_responder, &aidl_responder)) {
+ return {RttResponder{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_responder, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiRttController::enableResponderInternal(int32_t cmd_id,
+ const WifiChannelInfo& channel_hint,
+ int32_t max_duration_seconds,
+ const RttResponder& info) {
+ legacy_hal::wifi_channel_info legacy_channel_info;
+ if (!aidl_struct_util::convertAidlWifiChannelInfoToLegacy(channel_hint, &legacy_channel_info)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_rtt_responder legacy_responder;
+ if (!aidl_struct_util::convertAidlRttResponderToLegacy(info, &legacy_responder)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->enableRttResponder(
+ ifname_, cmd_id, legacy_channel_info, max_duration_seconds, legacy_responder);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiRttController::disableResponderInternal(int32_t cmd_id) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->disableRttResponder(ifname_, cmd_id);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi_rtt_controller.h b/wifi/aidl/default/wifi_rtt_controller.h
new file mode 100644
index 0000000..db690c3
--- /dev/null
+++ b/wifi/aidl/default/wifi_rtt_controller.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_RTT_CONTROLLER_H_
+#define WIFI_RTT_CONTROLLER_H_
+
+#include <aidl/android/hardware/wifi/BnWifiRttController.h>
+#include <aidl/android/hardware/wifi/IWifiRttControllerEventCallback.h>
+#include <aidl/android/hardware/wifi/IWifiStaIface.h>
+#include <android-base/macros.h>
+
+#include "wifi_legacy_hal.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+/**
+ * AIDL interface object used to control all RTT operations.
+ */
+class WifiRttController : public BnWifiRttController {
+ public:
+ WifiRttController(const std::string& iface_name,
+ const std::shared_ptr<IWifiStaIface>& bound_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal);
+ // Factory method - use instead of default constructor.
+ static std::shared_ptr<WifiRttController> create(
+ const std::string& iface_name, const std::shared_ptr<IWifiStaIface>& bound_iface,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal);
+
+ // Refer to |WifiChip::invalidate()|.
+ void invalidate();
+ bool isValid();
+ std::vector<std::shared_ptr<IWifiRttControllerEventCallback>> getEventCallbacks();
+ std::string getIfaceName();
+
+ // AIDL methods exposed.
+ ndk::ScopedAStatus getBoundIface(std::shared_ptr<IWifiStaIface>* _aidl_return) override;
+ ndk::ScopedAStatus registerEventCallback(
+ const std::shared_ptr<IWifiRttControllerEventCallback>& callback) override;
+ ndk::ScopedAStatus rangeRequest(int32_t in_cmdId,
+ const std::vector<RttConfig>& in_rttConfigs) override;
+ ndk::ScopedAStatus rangeCancel(int32_t in_cmdId,
+ const std::vector<MacAddress>& in_addrs) override;
+ ndk::ScopedAStatus getCapabilities(RttCapabilities* _aidl_return) override;
+ ndk::ScopedAStatus setLci(int32_t in_cmdId, const RttLciInformation& in_lci) override;
+ ndk::ScopedAStatus setLcr(int32_t in_cmdId, const RttLcrInformation& in_lcr) override;
+ ndk::ScopedAStatus getResponderInfo(RttResponder* _aidl_return) override;
+ ndk::ScopedAStatus enableResponder(int32_t in_cmdId, const WifiChannelInfo& in_channelHint,
+ int32_t in_maxDurationInSeconds,
+ const RttResponder& in_info) override;
+ ndk::ScopedAStatus disableResponder(int32_t in_cmdId) override;
+
+ private:
+ // Corresponding worker functions for the AIDL methods.
+ std::pair<std::shared_ptr<IWifiStaIface>, ndk::ScopedAStatus> getBoundIfaceInternal();
+ ndk::ScopedAStatus registerEventCallbackInternal(
+ const std::shared_ptr<IWifiRttControllerEventCallback>& callback);
+ ndk::ScopedAStatus rangeRequestInternal(int32_t cmd_id,
+ const std::vector<RttConfig>& rtt_configs);
+ ndk::ScopedAStatus rangeCancelInternal(int32_t cmd_id, const std::vector<MacAddress>& addrs);
+ std::pair<RttCapabilities, ndk::ScopedAStatus> getCapabilitiesInternal();
+ ndk::ScopedAStatus setLciInternal(int32_t cmd_id, const RttLciInformation& lci);
+ ndk::ScopedAStatus setLcrInternal(int32_t cmd_id, const RttLcrInformation& lcr);
+ std::pair<RttResponder, ndk::ScopedAStatus> getResponderInfoInternal();
+ ndk::ScopedAStatus enableResponderInternal(int32_t cmd_id, const WifiChannelInfo& channel_hint,
+ int32_t max_duration_seconds,
+ const RttResponder& info);
+ ndk::ScopedAStatus disableResponderInternal(int32_t cmd_id);
+
+ void setWeakPtr(std::weak_ptr<WifiRttController> ptr);
+
+ std::string ifname_;
+ std::shared_ptr<IWifiStaIface> bound_iface_;
+ std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
+ std::vector<std::shared_ptr<IWifiRttControllerEventCallback>> event_callbacks_;
+ std::weak_ptr<WifiRttController> weak_ptr_this_;
+ bool is_valid_;
+
+ DISALLOW_COPY_AND_ASSIGN(WifiRttController);
+};
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_RTT_CONTROLLER_H_
diff --git a/wifi/aidl/default/wifi_sta_iface.cpp b/wifi/aidl/default/wifi_sta_iface.cpp
new file mode 100644
index 0000000..ce90349
--- /dev/null
+++ b/wifi/aidl/default/wifi_sta_iface.cpp
@@ -0,0 +1,558 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "wifi_sta_iface.h"
+
+#include <android-base/logging.h>
+
+#include "aidl_return_util.h"
+#include "aidl_struct_util.h"
+#include "wifi_status_util.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+using aidl_return_util::validateAndCall;
+
+WifiStaIface::WifiStaIface(const std::string& ifname,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util)
+ : ifname_(ifname), legacy_hal_(legacy_hal), iface_util_(iface_util), is_valid_(true) {
+ // Turn on DFS channel usage for STA iface.
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->setDfsFlag(ifname_, true);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ LOG(ERROR) << "Failed to set DFS flag; DFS channels may be unavailable.";
+ }
+}
+
+std::shared_ptr<WifiStaIface> WifiStaIface::create(
+ const std::string& ifname, const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util) {
+ std::shared_ptr<WifiStaIface> ptr =
+ ndk::SharedRefBase::make<WifiStaIface>(ifname, legacy_hal, iface_util);
+ std::weak_ptr<WifiStaIface> weak_ptr_this(ptr);
+ ptr->setWeakPtr(weak_ptr_this);
+ return ptr;
+}
+
+void WifiStaIface::invalidate() {
+ legacy_hal_.reset();
+ event_cb_handler_.invalidate();
+ is_valid_ = false;
+}
+
+void WifiStaIface::setWeakPtr(std::weak_ptr<WifiStaIface> ptr) {
+ weak_ptr_this_ = ptr;
+}
+
+bool WifiStaIface::isValid() {
+ return is_valid_;
+}
+
+std::string WifiStaIface::getName() {
+ return ifname_;
+}
+
+std::set<std::shared_ptr<IWifiStaIfaceEventCallback>> WifiStaIface::getEventCallbacks() {
+ return event_cb_handler_.getCallbacks();
+}
+
+ndk::ScopedAStatus WifiStaIface::getName(std::string* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getNameInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::registerEventCallback(
+ const std::shared_ptr<IWifiStaIfaceEventCallback>& in_callback) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::registerEventCallbackInternal, in_callback);
+}
+
+ndk::ScopedAStatus WifiStaIface::getCapabilities(
+ IWifiStaIface::StaIfaceCapabilityMask* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getCapabilitiesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::getApfPacketFilterCapabilities(
+ StaApfPacketFilterCapabilities* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getApfPacketFilterCapabilitiesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::installApfPacketFilter(const std::vector<uint8_t>& in_program) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::installApfPacketFilterInternal, in_program);
+}
+
+ndk::ScopedAStatus WifiStaIface::readApfPacketFilterData(std::vector<uint8_t>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::readApfPacketFilterDataInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::getBackgroundScanCapabilities(
+ StaBackgroundScanCapabilities* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getBackgroundScanCapabilitiesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::getValidFrequenciesForBand(WifiBand in_band,
+ std::vector<int32_t>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getValidFrequenciesForBandInternal, _aidl_return,
+ in_band);
+}
+
+ndk::ScopedAStatus WifiStaIface::startBackgroundScan(int32_t in_cmdId,
+ const StaBackgroundScanParameters& in_params) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::startBackgroundScanInternal, in_cmdId, in_params);
+}
+
+ndk::ScopedAStatus WifiStaIface::stopBackgroundScan(int32_t in_cmdId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::stopBackgroundScanInternal, in_cmdId);
+}
+
+ndk::ScopedAStatus WifiStaIface::enableLinkLayerStatsCollection(bool in_debug) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::enableLinkLayerStatsCollectionInternal, in_debug);
+}
+
+ndk::ScopedAStatus WifiStaIface::disableLinkLayerStatsCollection() {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::disableLinkLayerStatsCollectionInternal);
+}
+
+ndk::ScopedAStatus WifiStaIface::getLinkLayerStats(StaLinkLayerStats* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getLinkLayerStatsInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::startRssiMonitoring(int32_t in_cmdId, int32_t in_maxRssi,
+ int32_t in_minRssi) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::startRssiMonitoringInternal, in_cmdId, in_maxRssi,
+ in_minRssi);
+}
+
+ndk::ScopedAStatus WifiStaIface::stopRssiMonitoring(int32_t in_cmdId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::stopRssiMonitoringInternal, in_cmdId);
+}
+
+ndk::ScopedAStatus WifiStaIface::getRoamingCapabilities(StaRoamingCapabilities* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getRoamingCapabilitiesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::configureRoaming(const StaRoamingConfig& in_config) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::configureRoamingInternal, in_config);
+}
+
+ndk::ScopedAStatus WifiStaIface::setRoamingState(StaRoamingState in_state) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::setRoamingStateInternal, in_state);
+}
+
+ndk::ScopedAStatus WifiStaIface::enableNdOffload(bool in_enable) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::enableNdOffloadInternal, in_enable);
+}
+
+ndk::ScopedAStatus WifiStaIface::startSendingKeepAlivePackets(
+ int32_t in_cmdId, const std::vector<uint8_t>& in_ipPacketData, char16_t in_etherType,
+ const std::array<uint8_t, 6>& in_srcAddress, const std::array<uint8_t, 6>& in_dstAddress,
+ int32_t in_periodInMs) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::startSendingKeepAlivePacketsInternal, in_cmdId,
+ in_ipPacketData, in_etherType, in_srcAddress, in_dstAddress,
+ in_periodInMs);
+}
+
+ndk::ScopedAStatus WifiStaIface::stopSendingKeepAlivePackets(int32_t in_cmdId) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::stopSendingKeepAlivePacketsInternal, in_cmdId);
+}
+
+ndk::ScopedAStatus WifiStaIface::startDebugPacketFateMonitoring() {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::startDebugPacketFateMonitoringInternal);
+}
+
+ndk::ScopedAStatus WifiStaIface::getDebugTxPacketFates(
+ std::vector<WifiDebugTxPacketFateReport>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getDebugTxPacketFatesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::getDebugRxPacketFates(
+ std::vector<WifiDebugRxPacketFateReport>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getDebugRxPacketFatesInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::setMacAddress(const std::array<uint8_t, 6>& in_mac) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::setMacAddressInternal, in_mac);
+}
+
+ndk::ScopedAStatus WifiStaIface::getFactoryMacAddress(std::array<uint8_t, 6>* _aidl_return) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::getFactoryMacAddressInternal, _aidl_return);
+}
+
+ndk::ScopedAStatus WifiStaIface::setScanMode(bool in_enable) {
+ return validateAndCall(this, WifiStatusCode::ERROR_WIFI_IFACE_INVALID,
+ &WifiStaIface::setScanModeInternal, in_enable);
+}
+
+std::pair<std::string, ndk::ScopedAStatus> WifiStaIface::getNameInternal() {
+ return {ifname_, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiStaIface::registerEventCallbackInternal(
+ const std::shared_ptr<IWifiStaIfaceEventCallback>& callback) {
+ if (!event_cb_handler_.addCallback(callback)) {
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+std::pair<IWifiStaIface::StaIfaceCapabilityMask, ndk::ScopedAStatus>
+WifiStaIface::getCapabilitiesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ uint64_t legacy_feature_set;
+ std::tie(legacy_status, legacy_feature_set) =
+ legacy_hal_.lock()->getSupportedFeatureSet(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {IWifiStaIface::StaIfaceCapabilityMask{},
+ createWifiStatusFromLegacyError(legacy_status)};
+ }
+ uint32_t legacy_logger_feature_set;
+ std::tie(legacy_status, legacy_logger_feature_set) =
+ legacy_hal_.lock()->getLoggerSupportedFeatureSet(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ // some devices don't support querying logger feature set
+ legacy_logger_feature_set = 0;
+ }
+ uint32_t aidl_caps;
+ if (!aidl_struct_util::convertLegacyFeaturesToAidlStaCapabilities(
+ legacy_feature_set, legacy_logger_feature_set, &aidl_caps)) {
+ return {IWifiStaIface::StaIfaceCapabilityMask{},
+ createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {static_cast<IWifiStaIface::StaIfaceCapabilityMask>(aidl_caps),
+ ndk::ScopedAStatus::ok()};
+}
+
+std::pair<StaApfPacketFilterCapabilities, ndk::ScopedAStatus>
+WifiStaIface::getApfPacketFilterCapabilitiesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ legacy_hal::PacketFilterCapabilities legacy_caps;
+ std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getPacketFilterCapabilities(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {StaApfPacketFilterCapabilities{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ StaApfPacketFilterCapabilities aidl_caps;
+ if (!aidl_struct_util::convertLegacyApfCapabilitiesToAidl(legacy_caps, &aidl_caps)) {
+ return {StaApfPacketFilterCapabilities{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_caps, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiStaIface::installApfPacketFilterInternal(
+ const std::vector<uint8_t>& program) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->setPacketFilter(ifname_, program);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<std::vector<uint8_t>, ndk::ScopedAStatus>
+WifiStaIface::readApfPacketFilterDataInternal() {
+ const std::pair<legacy_hal::wifi_error, std::vector<uint8_t>> legacy_status_and_data =
+ legacy_hal_.lock()->readApfPacketFilterData(ifname_);
+ return {std::move(legacy_status_and_data.second),
+ createWifiStatusFromLegacyError(legacy_status_and_data.first)};
+}
+
+std::pair<StaBackgroundScanCapabilities, ndk::ScopedAStatus>
+WifiStaIface::getBackgroundScanCapabilitiesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ legacy_hal::wifi_gscan_capabilities legacy_caps;
+ std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getGscanCapabilities(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {StaBackgroundScanCapabilities{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ StaBackgroundScanCapabilities aidl_caps;
+ if (!aidl_struct_util::convertLegacyGscanCapabilitiesToAidl(legacy_caps, &aidl_caps)) {
+ return {StaBackgroundScanCapabilities{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_caps, ndk::ScopedAStatus::ok()};
+}
+
+std::pair<std::vector<int32_t>, ndk::ScopedAStatus>
+WifiStaIface::getValidFrequenciesForBandInternal(WifiBand band) {
+ static_assert(sizeof(WifiChannelWidthInMhz) == sizeof(int32_t), "Size mismatch");
+ legacy_hal::wifi_error legacy_status;
+ std::vector<uint32_t> valid_frequencies;
+ std::tie(legacy_status, valid_frequencies) = legacy_hal_.lock()->getValidFrequenciesForBand(
+ ifname_, aidl_struct_util::convertAidlWifiBandToLegacy(band));
+ return {std::vector<int32_t>(valid_frequencies.begin(), valid_frequencies.end()),
+ createWifiStatusFromLegacyError(legacy_status)};
+}
+
+ndk::ScopedAStatus WifiStaIface::startBackgroundScanInternal(
+ int32_t cmd_id, const StaBackgroundScanParameters& params) {
+ legacy_hal::wifi_scan_cmd_params legacy_params;
+ if (!aidl_struct_util::convertAidlGscanParamsToLegacy(params, &legacy_params)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ std::weak_ptr<WifiStaIface> weak_ptr_this = weak_ptr_this_;
+ const auto& on_failure_callback = [weak_ptr_this](legacy_hal::wifi_request_id id) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->onBackgroundScanFailure(id).isOk()) {
+ LOG(ERROR) << "Failed to invoke onBackgroundScanFailure callback";
+ }
+ }
+ };
+ const auto& on_results_callback =
+ [weak_ptr_this](legacy_hal::wifi_request_id id,
+ const std::vector<legacy_hal::wifi_cached_scan_results>& results) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ std::vector<StaScanData> aidl_scan_datas;
+ if (!aidl_struct_util::convertLegacyVectorOfCachedGscanResultsToAidl(
+ results, &aidl_scan_datas)) {
+ LOG(ERROR) << "Failed to convert scan results to AIDL structs";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->onBackgroundScanResults(id, aidl_scan_datas).isOk()) {
+ LOG(ERROR) << "Failed to invoke onBackgroundScanResults callback";
+ }
+ }
+ };
+ const auto& on_full_result_callback = [weak_ptr_this](
+ legacy_hal::wifi_request_id id,
+ const legacy_hal::wifi_scan_result* result,
+ uint32_t buckets_scanned) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ StaScanResult aidl_scan_result;
+ if (!aidl_struct_util::convertLegacyGscanResultToAidl(*result, true, &aidl_scan_result)) {
+ LOG(ERROR) << "Failed to convert full scan results to AIDL structs";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->onBackgroundFullScanResult(id, buckets_scanned, aidl_scan_result)
+ .isOk()) {
+ LOG(ERROR) << "Failed to invoke onBackgroundFullScanResult callback";
+ }
+ }
+ };
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->startGscan(ifname_, cmd_id, legacy_params, on_failure_callback,
+ on_results_callback, on_full_result_callback);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::stopBackgroundScanInternal(int32_t cmd_id) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->stopGscan(ifname_, cmd_id);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::enableLinkLayerStatsCollectionInternal(bool debug) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->enableLinkLayerStats(ifname_, debug);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::disableLinkLayerStatsCollectionInternal() {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->disableLinkLayerStats(ifname_);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<StaLinkLayerStats, ndk::ScopedAStatus> WifiStaIface::getLinkLayerStatsInternal() {
+ legacy_hal::wifi_error legacy_status;
+ legacy_hal::LinkLayerStats legacy_stats;
+ std::tie(legacy_status, legacy_stats) = legacy_hal_.lock()->getLinkLayerStats(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {StaLinkLayerStats{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ StaLinkLayerStats aidl_stats;
+ if (!aidl_struct_util::convertLegacyLinkLayerStatsToAidl(legacy_stats, &aidl_stats)) {
+ return {StaLinkLayerStats{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_stats, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiStaIface::startRssiMonitoringInternal(int32_t cmd_id, int32_t max_rssi,
+ int32_t min_rssi) {
+ std::weak_ptr<WifiStaIface> weak_ptr_this = weak_ptr_this_;
+ const auto& on_threshold_breached_callback =
+ [weak_ptr_this](legacy_hal::wifi_request_id id, std::array<uint8_t, ETH_ALEN> bssid,
+ int8_t rssi) {
+ const auto shared_ptr_this = weak_ptr_this.lock();
+ if (!shared_ptr_this.get() || !shared_ptr_this->isValid()) {
+ LOG(ERROR) << "Callback invoked on an invalid object";
+ return;
+ }
+ for (const auto& callback : shared_ptr_this->getEventCallbacks()) {
+ if (!callback->onRssiThresholdBreached(id, bssid, rssi).isOk()) {
+ LOG(ERROR) << "Failed to invoke onRssiThresholdBreached callback";
+ }
+ }
+ };
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startRssiMonitoring(
+ ifname_, cmd_id, max_rssi, min_rssi, on_threshold_breached_callback);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::stopRssiMonitoringInternal(int32_t cmd_id) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->stopRssiMonitoring(ifname_, cmd_id);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<StaRoamingCapabilities, ndk::ScopedAStatus>
+WifiStaIface::getRoamingCapabilitiesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ legacy_hal::wifi_roaming_capabilities legacy_caps;
+ std::tie(legacy_status, legacy_caps) = legacy_hal_.lock()->getRoamingCapabilities(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {StaRoamingCapabilities{}, createWifiStatusFromLegacyError(legacy_status)};
+ }
+ StaRoamingCapabilities aidl_caps;
+ if (!aidl_struct_util::convertLegacyRoamingCapabilitiesToAidl(legacy_caps, &aidl_caps)) {
+ return {StaRoamingCapabilities{}, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_caps, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiStaIface::configureRoamingInternal(const StaRoamingConfig& config) {
+ legacy_hal::wifi_roaming_config legacy_config;
+ if (!aidl_struct_util::convertAidlRoamingConfigToLegacy(config, &legacy_config)) {
+ return createWifiStatus(WifiStatusCode::ERROR_INVALID_ARGS);
+ }
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->configureRoaming(ifname_, legacy_config);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::setRoamingStateInternal(StaRoamingState state) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->enableFirmwareRoaming(
+ ifname_, aidl_struct_util::convertAidlRoamingStateToLegacy(state));
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::enableNdOffloadInternal(bool enable) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->configureNdOffload(ifname_, enable);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::startSendingKeepAlivePacketsInternal(
+ int32_t cmd_id, const std::vector<uint8_t>& ip_packet_data, char16_t ether_type,
+ const std::array<uint8_t, 6>& src_address, const std::array<uint8_t, 6>& dst_address,
+ int32_t period_in_ms) {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startSendingOffloadedPacket(
+ ifname_, cmd_id, ether_type, ip_packet_data, src_address, dst_address, period_in_ms);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::stopSendingKeepAlivePacketsInternal(int32_t cmd_id) {
+ legacy_hal::wifi_error legacy_status =
+ legacy_hal_.lock()->stopSendingOffloadedPacket(ifname_, cmd_id);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+ndk::ScopedAStatus WifiStaIface::startDebugPacketFateMonitoringInternal() {
+ legacy_hal::wifi_error legacy_status = legacy_hal_.lock()->startPktFateMonitoring(ifname_);
+ return createWifiStatusFromLegacyError(legacy_status);
+}
+
+std::pair<std::vector<WifiDebugTxPacketFateReport>, ndk::ScopedAStatus>
+WifiStaIface::getDebugTxPacketFatesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ std::vector<legacy_hal::wifi_tx_report> legacy_fates;
+ std::tie(legacy_status, legacy_fates) = legacy_hal_.lock()->getTxPktFates(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {std::vector<WifiDebugTxPacketFateReport>(),
+ createWifiStatusFromLegacyError(legacy_status)};
+ }
+ std::vector<WifiDebugTxPacketFateReport> aidl_fates;
+ if (!aidl_struct_util::convertLegacyVectorOfDebugTxPacketFateToAidl(legacy_fates,
+ &aidl_fates)) {
+ return {std::vector<WifiDebugTxPacketFateReport>(),
+ createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_fates, ndk::ScopedAStatus::ok()};
+}
+
+std::pair<std::vector<WifiDebugRxPacketFateReport>, ndk::ScopedAStatus>
+WifiStaIface::getDebugRxPacketFatesInternal() {
+ legacy_hal::wifi_error legacy_status;
+ std::vector<legacy_hal::wifi_rx_report> legacy_fates;
+ std::tie(legacy_status, legacy_fates) = legacy_hal_.lock()->getRxPktFates(ifname_);
+ if (legacy_status != legacy_hal::WIFI_SUCCESS) {
+ return {std::vector<WifiDebugRxPacketFateReport>(),
+ createWifiStatusFromLegacyError(legacy_status)};
+ }
+ std::vector<WifiDebugRxPacketFateReport> aidl_fates;
+ if (!aidl_struct_util::convertLegacyVectorOfDebugRxPacketFateToAidl(legacy_fates,
+ &aidl_fates)) {
+ return {std::vector<WifiDebugRxPacketFateReport>(),
+ createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {aidl_fates, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiStaIface::setMacAddressInternal(const std::array<uint8_t, 6>& mac) {
+ bool status = iface_util_.lock()->setMacAddress(ifname_, mac);
+ if (!status) {
+ return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN);
+ }
+ return ndk::ScopedAStatus::ok();
+}
+
+std::pair<std::array<uint8_t, 6>, ndk::ScopedAStatus> WifiStaIface::getFactoryMacAddressInternal() {
+ std::array<uint8_t, 6> mac = iface_util_.lock()->getFactoryMacAddress(ifname_);
+ if (mac[0] == 0 && mac[1] == 0 && mac[2] == 0 && mac[3] == 0 && mac[4] == 0 && mac[5] == 0) {
+ return {mac, createWifiStatus(WifiStatusCode::ERROR_UNKNOWN)};
+ }
+ return {mac, ndk::ScopedAStatus::ok()};
+}
+
+ndk::ScopedAStatus WifiStaIface::setScanModeInternal(bool enable) {
+ // OEM's need to implement this on their devices if needed.
+ LOG(WARNING) << "setScanModeInternal(" << enable << ") not supported";
+ return createWifiStatus(WifiStatusCode::ERROR_NOT_SUPPORTED);
+}
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi_sta_iface.h b/wifi/aidl/default/wifi_sta_iface.h
new file mode 100644
index 0000000..8ac3470
--- /dev/null
+++ b/wifi/aidl/default/wifi_sta_iface.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_STA_IFACE_H_
+#define WIFI_STA_IFACE_H_
+
+#include <aidl/android/hardware/wifi/BnWifiStaIface.h>
+#include <aidl/android/hardware/wifi/IWifiStaIfaceEventCallback.h>
+#include <android-base/macros.h>
+
+#include "aidl_callback_util.h"
+#include "wifi_iface_util.h"
+#include "wifi_legacy_hal.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+
+/**
+ * AIDL interface object used to control a STA Iface instance.
+ */
+class WifiStaIface : public BnWifiStaIface {
+ public:
+ WifiStaIface(const std::string& ifname,
+ const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
+
+ // Factory method - use instead of default constructor.
+ static std::shared_ptr<WifiStaIface> create(
+ const std::string& ifname, const std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal,
+ const std::weak_ptr<iface_util::WifiIfaceUtil> iface_util);
+
+ // Refer to |WifiChip::invalidate()|.
+ void invalidate();
+ bool isValid();
+ std::set<std::shared_ptr<IWifiStaIfaceEventCallback>> getEventCallbacks();
+ std::string getName();
+
+ // AIDL methods exposed.
+ ndk::ScopedAStatus getName(std::string* _aidl_return) override;
+ ndk::ScopedAStatus registerEventCallback(
+ const std::shared_ptr<IWifiStaIfaceEventCallback>& in_callback) override;
+ ndk::ScopedAStatus getCapabilities(
+ IWifiStaIface::StaIfaceCapabilityMask* _aidl_return) override;
+ ndk::ScopedAStatus getApfPacketFilterCapabilities(
+ StaApfPacketFilterCapabilities* _aidl_return) override;
+ ndk::ScopedAStatus installApfPacketFilter(const std::vector<uint8_t>& in_program) override;
+ ndk::ScopedAStatus readApfPacketFilterData(std::vector<uint8_t>* _aidl_return) override;
+ ndk::ScopedAStatus getBackgroundScanCapabilities(
+ StaBackgroundScanCapabilities* _aidl_return) override;
+ ndk::ScopedAStatus getValidFrequenciesForBand(WifiBand in_band,
+ std::vector<int32_t>* _aidl_return) override;
+ ndk::ScopedAStatus startBackgroundScan(int32_t in_cmdId,
+ const StaBackgroundScanParameters& in_params) override;
+ ndk::ScopedAStatus stopBackgroundScan(int32_t in_cmdId) override;
+ ndk::ScopedAStatus enableLinkLayerStatsCollection(bool in_debug) override;
+ ndk::ScopedAStatus disableLinkLayerStatsCollection() override;
+ ndk::ScopedAStatus getLinkLayerStats(StaLinkLayerStats* _aidl_return) override;
+ ndk::ScopedAStatus startRssiMonitoring(int32_t in_cmdId, int32_t in_maxRssi,
+ int32_t in_minRssi) override;
+ ndk::ScopedAStatus stopRssiMonitoring(int32_t in_cmdId) override;
+ ndk::ScopedAStatus getRoamingCapabilities(StaRoamingCapabilities* _aidl_return) override;
+ ndk::ScopedAStatus configureRoaming(const StaRoamingConfig& in_config) override;
+ ndk::ScopedAStatus setRoamingState(StaRoamingState in_state) override;
+ ndk::ScopedAStatus enableNdOffload(bool in_enable) override;
+ ndk::ScopedAStatus startSendingKeepAlivePackets(int32_t in_cmdId,
+ const std::vector<uint8_t>& in_ipPacketData,
+ char16_t in_etherType,
+ const std::array<uint8_t, 6>& in_srcAddress,
+ const std::array<uint8_t, 6>& in_dstAddress,
+ int32_t in_periodInMs) override;
+ ndk::ScopedAStatus stopSendingKeepAlivePackets(int32_t in_cmdId) override;
+ ndk::ScopedAStatus startDebugPacketFateMonitoring() override;
+ ndk::ScopedAStatus getDebugTxPacketFates(
+ std::vector<WifiDebugTxPacketFateReport>* _aidl_return) override;
+ ndk::ScopedAStatus getDebugRxPacketFates(
+ std::vector<WifiDebugRxPacketFateReport>* _aidl_return) override;
+ ndk::ScopedAStatus setMacAddress(const std::array<uint8_t, 6>& in_mac) override;
+ ndk::ScopedAStatus getFactoryMacAddress(std::array<uint8_t, 6>* _aidl_return) override;
+ ndk::ScopedAStatus setScanMode(bool in_enable) override;
+
+ private:
+ // Corresponding worker functions for the AIDL methods.
+ std::pair<std::string, ndk::ScopedAStatus> getNameInternal();
+ ndk::ScopedAStatus registerEventCallbackInternal(
+ const std::shared_ptr<IWifiStaIfaceEventCallback>& callback);
+ std::pair<IWifiStaIface::StaIfaceCapabilityMask, ndk::ScopedAStatus> getCapabilitiesInternal();
+ std::pair<StaApfPacketFilterCapabilities, ndk::ScopedAStatus>
+ getApfPacketFilterCapabilitiesInternal();
+ ndk::ScopedAStatus installApfPacketFilterInternal(const std::vector<uint8_t>& program);
+ std::pair<std::vector<uint8_t>, ndk::ScopedAStatus> readApfPacketFilterDataInternal();
+ std::pair<StaBackgroundScanCapabilities, ndk::ScopedAStatus>
+ getBackgroundScanCapabilitiesInternal();
+ std::pair<std::vector<int32_t>, ndk::ScopedAStatus> getValidFrequenciesForBandInternal(
+ WifiBand band);
+ ndk::ScopedAStatus startBackgroundScanInternal(int32_t cmd_id,
+ const StaBackgroundScanParameters& params);
+ ndk::ScopedAStatus stopBackgroundScanInternal(int32_t cmd_id);
+ ndk::ScopedAStatus enableLinkLayerStatsCollectionInternal(bool debug);
+ ndk::ScopedAStatus disableLinkLayerStatsCollectionInternal();
+ std::pair<StaLinkLayerStats, ndk::ScopedAStatus> getLinkLayerStatsInternal();
+ ndk::ScopedAStatus startRssiMonitoringInternal(int32_t cmd_id, int32_t max_rssi,
+ int32_t min_rssi);
+ ndk::ScopedAStatus stopRssiMonitoringInternal(int32_t cmd_id);
+ std::pair<StaRoamingCapabilities, ndk::ScopedAStatus> getRoamingCapabilitiesInternal();
+ ndk::ScopedAStatus configureRoamingInternal(const StaRoamingConfig& config);
+ ndk::ScopedAStatus setRoamingStateInternal(StaRoamingState state);
+ ndk::ScopedAStatus enableNdOffloadInternal(bool enable);
+ ndk::ScopedAStatus startSendingKeepAlivePacketsInternal(
+ int32_t cmd_id, const std::vector<uint8_t>& ip_packet_data, char16_t ether_type,
+ const std::array<uint8_t, 6>& src_address, const std::array<uint8_t, 6>& dst_address,
+ int32_t period_in_ms);
+ ndk::ScopedAStatus stopSendingKeepAlivePacketsInternal(int32_t cmd_id);
+ ndk::ScopedAStatus startDebugPacketFateMonitoringInternal();
+ std::pair<std::vector<WifiDebugTxPacketFateReport>, ndk::ScopedAStatus>
+ getDebugTxPacketFatesInternal();
+ std::pair<std::vector<WifiDebugRxPacketFateReport>, ndk::ScopedAStatus>
+ getDebugRxPacketFatesInternal();
+ ndk::ScopedAStatus setMacAddressInternal(const std::array<uint8_t, 6>& mac);
+ std::pair<std::array<uint8_t, 6>, ndk::ScopedAStatus> getFactoryMacAddressInternal();
+ ndk::ScopedAStatus setScanModeInternal(bool enable);
+
+ void setWeakPtr(std::weak_ptr<WifiStaIface> ptr);
+
+ std::string ifname_;
+ std::weak_ptr<legacy_hal::WifiLegacyHal> legacy_hal_;
+ std::weak_ptr<iface_util::WifiIfaceUtil> iface_util_;
+ std::weak_ptr<WifiStaIface> weak_ptr_this_;
+ bool is_valid_;
+ aidl_callback_util::AidlCallbackHandler<IWifiStaIfaceEventCallback> event_cb_handler_;
+
+ DISALLOW_COPY_AND_ASSIGN(WifiStaIface);
+};
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_STA_IFACE_H_
diff --git a/wifi/1.6/default/wifi_status_util.cpp b/wifi/aidl/default/wifi_status_util.cpp
similarity index 79%
rename from wifi/1.6/default/wifi_status_util.cpp
rename to wifi/aidl/default/wifi_status_util.cpp
index 3b18e53..25ecd71 100644
--- a/wifi/1.6/default/wifi_status_util.cpp
+++ b/wifi/aidl/default/wifi_status_util.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,10 @@
#include "wifi_status_util.h"
+namespace aidl {
namespace android {
namespace hardware {
namespace wifi {
-namespace V1_6 {
-namespace implementation {
std::string legacyErrorToString(legacy_hal::wifi_error error) {
switch (error) {
@@ -51,16 +50,21 @@
}
}
-WifiStatus createWifiStatus(WifiStatusCode code, const std::string& description) {
- return {code, description};
+ndk::ScopedAStatus createWifiStatus(WifiStatusCode code, const std::string& description) {
+ return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(static_cast<int32_t>(code),
+ description.c_str());
}
-WifiStatus createWifiStatus(WifiStatusCode code) {
- return createWifiStatus(code, "");
+ndk::ScopedAStatus createWifiStatus(WifiStatusCode code) {
+ return ndk::ScopedAStatus::fromServiceSpecificError(static_cast<int32_t>(code));
}
-WifiStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error, const std::string& desc) {
+ndk::ScopedAStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error,
+ const std::string& desc) {
switch (error) {
+ case legacy_hal::WIFI_ERROR_NONE:
+ return ndk::ScopedAStatus::ok();
+
case legacy_hal::WIFI_ERROR_UNINITIALIZED:
case legacy_hal::WIFI_ERROR_NOT_AVAILABLE:
return createWifiStatus(WifiStatusCode::ERROR_NOT_AVAILABLE, desc);
@@ -84,9 +88,6 @@
case legacy_hal::WIFI_ERROR_BUSY:
return createWifiStatus(WifiStatusCode::ERROR_BUSY);
- case legacy_hal::WIFI_ERROR_NONE:
- return createWifiStatus(WifiStatusCode::SUCCESS, desc);
-
case legacy_hal::WIFI_ERROR_UNKNOWN:
return createWifiStatus(WifiStatusCode::ERROR_UNKNOWN, "unknown");
@@ -95,12 +96,11 @@
}
}
-WifiStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error) {
+ndk::ScopedAStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error) {
return createWifiStatusFromLegacyError(error, "");
}
-} // namespace implementation
-} // namespace V1_6
} // namespace wifi
} // namespace hardware
} // namespace android
+} // namespace aidl
diff --git a/wifi/aidl/default/wifi_status_util.h b/wifi/aidl/default/wifi_status_util.h
new file mode 100644
index 0000000..633811d
--- /dev/null
+++ b/wifi/aidl/default/wifi_status_util.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 WIFI_STATUS_UTIL_H_
+#define WIFI_STATUS_UTIL_H_
+
+#include <aidl/android/hardware/wifi/IWifi.h>
+
+#include "wifi_legacy_hal.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace wifi {
+using ::aidl::android::hardware::wifi::WifiStatusCode;
+
+std::string legacyErrorToString(legacy_hal::wifi_error error);
+ndk::ScopedAStatus createWifiStatus(WifiStatusCode code, const std::string& description);
+ndk::ScopedAStatus createWifiStatus(WifiStatusCode code);
+ndk::ScopedAStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error,
+ const std::string& description);
+ndk::ScopedAStatus createWifiStatusFromLegacyError(legacy_hal::wifi_error error);
+
+} // namespace wifi
+} // namespace hardware
+} // namespace android
+} // namespace aidl
+
+#endif // WIFI_STATUS_UTIL_H_
diff --git a/wifi/aidl/vts/functional/Android.bp b/wifi/aidl/vts/functional/Android.bp
new file mode 100644
index 0000000..1277182
--- /dev/null
+++ b/wifi/aidl/vts/functional/Android.bp
@@ -0,0 +1,169 @@
+//
+// Copyright (C) 2022 The Android Open Source Project
+//
+// 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.
+//
+
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "hardware_interfaces_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_test {
+ name: "VtsHalWifiChipTargetTest",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ ],
+ srcs: [
+ "wifi_chip_aidl_test.cpp",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbinder_ndk",
+ "libvndksupport",
+ ],
+ static_libs: [
+ "VtsHalWifiTargetTestUtil",
+ "android.hardware.wifi-V1-ndk",
+ "libwifi-system-iface",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
+
+cc_test {
+ name: "VtsHalWifiStaIfaceTargetTest",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ ],
+ srcs: [
+ "wifi_sta_iface_aidl_test.cpp",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbinder_ndk",
+ "libvndksupport",
+ ],
+ static_libs: [
+ "VtsHalWifiTargetTestUtil",
+ "android.hardware.wifi-V1-ndk",
+ "libwifi-system-iface",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
+
+cc_test {
+ name: "VtsHalWifiApIfaceTargetTest",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ ],
+ srcs: [
+ "wifi_ap_iface_aidl_test.cpp",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbinder_ndk",
+ "libvndksupport",
+ ],
+ static_libs: [
+ "VtsHalWifiTargetTestUtil",
+ "android.hardware.wifi-V1-ndk",
+ "libwifi-system-iface",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
+
+cc_test {
+ name: "VtsHalWifiNanIfaceTargetTest",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ ],
+ srcs: [
+ "wifi_nan_iface_aidl_test.cpp",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbinder_ndk",
+ "libvndksupport",
+ ],
+ static_libs: [
+ "VtsHalWifiTargetTestUtil",
+ "android.hardware.wifi-V1-ndk",
+ "libwifi-system-iface",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
+
+cc_test {
+ name: "VtsHalWifiRttControllerTargetTest",
+ defaults: [
+ "VtsHalTargetTestDefaults",
+ "use_libaidlvintf_gtest_helper_static",
+ ],
+ srcs: [
+ "wifi_rtt_controller_aidl_test.cpp",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbinder_ndk",
+ "libvndksupport",
+ ],
+ static_libs: [
+ "VtsHalWifiTargetTestUtil",
+ "android.hardware.wifi-V1-ndk",
+ "libwifi-system-iface",
+ ],
+ test_suites: [
+ "general-tests",
+ "vts",
+ ],
+}
+
+cc_library_static {
+ name: "VtsHalWifiTargetTestUtil",
+ defaults: ["VtsHalTargetTestDefaults"],
+ srcs: [
+ "wifi_aidl_test_utils.cpp",
+ ],
+ export_include_dirs: [
+ ".",
+ ],
+ shared_libs: [
+ "libbinder",
+ "libbinder_ndk",
+ "libnativehelper",
+ ],
+ static_libs: [
+ "android.hardware.wifi-V1-ndk",
+ "libwifi-system-iface",
+ ],
+}
diff --git a/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp b/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp
new file mode 100644
index 0000000..6722f36
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_aidl_test_utils.cpp
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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 "wifi_aidl_test_utils.h"
+
+using ::android::wifi_system::InterfaceTool;
+
+namespace {
+bool findAnyModeSupportingConcurrencyType(IfaceConcurrencyType desired_type,
+ const std::vector<IWifiChip::ChipMode>& modes,
+ int* mode_id) {
+ for (const auto& mode : modes) {
+ for (const auto& combination : mode.availableCombinations) {
+ for (const auto& iface_limit : combination.limits) {
+ const auto& iface_types = iface_limit.types;
+ if (std::find(iface_types.begin(), iface_types.end(), desired_type) !=
+ iface_types.end()) {
+ *mode_id = mode.id;
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+bool configureChipToSupportConcurrencyTypeInternal(const std::shared_ptr<IWifiChip>& wifi_chip,
+ IfaceConcurrencyType type,
+ int* configured_mode_id) {
+ if (!configured_mode_id) {
+ return false;
+ }
+ std::vector<IWifiChip::ChipMode> chip_modes;
+ auto status = wifi_chip->getAvailableModes(&chip_modes);
+ if (!status.isOk()) {
+ return false;
+ }
+ if (!findAnyModeSupportingConcurrencyType(type, chip_modes, configured_mode_id)) {
+ return false;
+ }
+ if (!wifi_chip->configureChip(*configured_mode_id).isOk()) {
+ return false;
+ }
+ return true;
+}
+
+bool configureChipToSupportConcurrencyTypeInternal(const std::shared_ptr<IWifiChip>& wifi_chip,
+ IfaceConcurrencyType type) {
+ int mode_id;
+ return configureChipToSupportConcurrencyTypeInternal(wifi_chip, type, &mode_id);
+}
+} // namespace
+
+bool checkStatusCode(ndk::ScopedAStatus* status, WifiStatusCode expected_code) {
+ if (status == nullptr) {
+ return false;
+ }
+ return status->getServiceSpecificError() == static_cast<int32_t>(expected_code);
+}
+
+std::shared_ptr<IWifi> getWifi(const char* instance_name) {
+ return IWifi::fromBinder(ndk::SpAIBinder(AServiceManager_waitForService(instance_name)));
+}
+
+std::shared_ptr<IWifiChip> getWifiChip(const char* instance_name) {
+ std::shared_ptr<IWifi> wifi = getWifi(instance_name);
+ if (!wifi.get()) {
+ return nullptr;
+ }
+
+ const int retry_interval_ms = 2;
+ const int max_retries = 5;
+ int retry_count = 0;
+ auto status = wifi->start();
+ while (retry_count < max_retries && !status.isOk()) {
+ retry_count++;
+ usleep(retry_interval_ms * 1000);
+ status = wifi->start();
+ }
+ if (!status.isOk()) {
+ return nullptr;
+ }
+
+ std::vector<int> chip_ids = {};
+ status = wifi->getChipIds(&chip_ids);
+ if (!status.isOk() || chip_ids.size() == 0) {
+ return nullptr;
+ }
+ std::shared_ptr<IWifiChip> chip;
+ status = wifi->getChip(chip_ids[0], &chip);
+ if (!status.isOk()) {
+ return nullptr;
+ }
+ return chip;
+}
+
+void setupStaIface(const std::shared_ptr<IWifiStaIface>& iface) {
+ std::string iface_name;
+ auto status = iface->getName(&iface_name);
+ if (status.isOk()) {
+ InterfaceTool iface_tool;
+ iface_tool.SetUpState(iface_name.c_str(), true);
+ }
+}
+
+void setupNanIface(const std::shared_ptr<IWifiNanIface>& iface) {
+ std::string iface_name;
+ auto status = iface->getName(&iface_name);
+ if (status.isOk()) {
+ InterfaceTool iface_tool;
+ iface_tool.SetUpState(iface_name.c_str(), true);
+ }
+}
+
+std::shared_ptr<IWifiStaIface> getWifiStaIface(const char* instance_name) {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(instance_name);
+ if (!wifi_chip.get()) {
+ return nullptr;
+ }
+ if (!configureChipToSupportConcurrencyTypeInternal(wifi_chip, IfaceConcurrencyType::STA)) {
+ return nullptr;
+ }
+ std::shared_ptr<IWifiStaIface> iface;
+ auto status = wifi_chip->createStaIface(&iface);
+ if (!status.isOk()) {
+ return nullptr;
+ }
+ setupStaIface(iface);
+ return iface;
+}
+
+std::shared_ptr<IWifiNanIface> getWifiNanIface(const char* instance_name) {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(instance_name);
+ if (!wifi_chip.get()) {
+ return nullptr;
+ }
+ if (!configureChipToSupportConcurrencyTypeInternal(wifi_chip,
+ IfaceConcurrencyType::NAN_IFACE)) {
+ return nullptr;
+ }
+ std::shared_ptr<IWifiNanIface> iface;
+ auto status = wifi_chip->createNanIface(&iface);
+ if (!status.isOk()) {
+ return nullptr;
+ }
+ setupNanIface(iface);
+ return iface;
+}
+
+std::shared_ptr<IWifiApIface> getWifiApIface(const char* instance_name) {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(instance_name);
+ if (!wifi_chip.get()) {
+ return nullptr;
+ }
+ if (!configureChipToSupportConcurrencyTypeInternal(wifi_chip, IfaceConcurrencyType::AP)) {
+ return nullptr;
+ }
+ std::shared_ptr<IWifiApIface> iface;
+ auto status = wifi_chip->createApIface(&iface);
+ if (!status.isOk()) {
+ return nullptr;
+ }
+ return iface;
+}
+
+std::shared_ptr<IWifiApIface> getBridgedWifiApIface(std::shared_ptr<IWifiChip> wifi_chip) {
+ if (!wifi_chip.get()) {
+ return nullptr;
+ }
+ int mode_id;
+ std::shared_ptr<IWifiApIface> iface;
+ configureChipToSupportConcurrencyTypeInternal(wifi_chip, IfaceConcurrencyType::AP, &mode_id);
+ auto status = wifi_chip->createBridgedApIface(&iface);
+ if (!status.isOk()) {
+ return nullptr;
+ }
+ return iface;
+}
+
+std::shared_ptr<IWifiApIface> getBridgedWifiApIface(const char* instance_name) {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(instance_name);
+ return getBridgedWifiApIface(wifi_chip);
+}
+
+bool configureChipToSupportConcurrencyType(const std::shared_ptr<IWifiChip>& wifi_chip,
+ IfaceConcurrencyType type, int* configured_mode_id) {
+ return configureChipToSupportConcurrencyTypeInternal(wifi_chip, type, configured_mode_id);
+}
+
+void stopWifiService(const char* instance_name) {
+ std::shared_ptr<IWifi> wifi = getWifi(instance_name);
+ if (wifi != nullptr) {
+ wifi->stop();
+ }
+}
+
+int32_t getChipCapabilities(const std::shared_ptr<IWifiChip>& wifi_chip) {
+ IWifiChip::ChipCapabilityMask caps = {};
+ if (wifi_chip->getCapabilities(&caps).isOk()) {
+ return static_cast<int32_t>(caps);
+ }
+ return 0;
+}
diff --git a/wifi/aidl/vts/functional/wifi_aidl_test_utils.h b/wifi/aidl/vts/functional/wifi_aidl_test_utils.h
new file mode 100644
index 0000000..ad16603
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_aidl_test_utils.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#pragma once
+
+#include <VtsCoreUtil.h>
+
+#include <aidl/android/hardware/wifi/IWifi.h>
+#include <aidl/android/hardware/wifi/IWifiChip.h>
+#include <android/binder_manager.h>
+#include <wifi_system/interface_tool.h>
+
+using aidl::android::hardware::wifi::IfaceConcurrencyType;
+using aidl::android::hardware::wifi::IWifi;
+using aidl::android::hardware::wifi::IWifiApIface;
+using aidl::android::hardware::wifi::IWifiChip;
+using aidl::android::hardware::wifi::IWifiNanIface;
+using aidl::android::hardware::wifi::IWifiStaIface;
+using aidl::android::hardware::wifi::WifiStatusCode;
+
+// Helper functions to obtain references to the various AIDL interface objects.
+std::shared_ptr<IWifi> getWifi(const char* instance_name);
+std::shared_ptr<IWifiChip> getWifiChip(const char* instance_name);
+std::shared_ptr<IWifiStaIface> getWifiStaIface(const char* instance_name);
+std::shared_ptr<IWifiNanIface> getWifiNanIface(const char* instance_name);
+std::shared_ptr<IWifiApIface> getWifiApIface(const char* instance_name);
+std::shared_ptr<IWifiApIface> getBridgedWifiApIface(const char* instance_name);
+std::shared_ptr<IWifiApIface> getBridgedWifiApIface(std::shared_ptr<IWifiChip> wifi_chip);
+// Configure the chip in a mode to support the creation of the provided iface type.
+bool configureChipToSupportConcurrencyType(const std::shared_ptr<IWifiChip>& wifi_chip,
+ IfaceConcurrencyType type, int* configured_mode_id);
+// Used to trigger IWifi.stop() at the end of every test.
+void stopWifiService(const char* instance_name);
+int32_t getChipCapabilities(const std::shared_ptr<IWifiChip>& wifi_chip);
+bool checkStatusCode(ndk::ScopedAStatus* status, WifiStatusCode expected_code);
diff --git a/wifi/aidl/vts/functional/wifi_ap_iface_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_ap_iface_aidl_test.cpp
new file mode 100644
index 0000000..0eaf660
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_ap_iface_aidl_test.cpp
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Staache 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 <vector>
+
+#include <VtsCoreUtil.h>
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/wifi/BnWifi.h>
+#include <android/binder_manager.h>
+#include <android/binder_status.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::IWifiApIface;
+using aidl::android::hardware::wifi::WifiBand;
+
+class WifiApIfaceAidlTest : public testing::TestWithParam<std::string> {
+ public:
+ void SetUp() override {
+ isBridgedSupport_ = testing::checkSubstringInCommandOutput(
+ "/system/bin/cmd wifi get-softap-supported-features",
+ "wifi_softap_bridged_ap_supported");
+ stopWifiService(getInstanceName());
+ }
+
+ void TearDown() override { stopWifiService(getInstanceName()); }
+
+ protected:
+ bool isBridgedSupport_ = false;
+ const char* getInstanceName() { return GetParam().c_str(); }
+};
+
+/*
+ * SetMacAddress
+ */
+TEST_P(WifiApIfaceAidlTest, SetMacAddress) {
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+ std::array<uint8_t, 6> mac = {0x12, 0x22, 0x33, 0x52, 0x10, 0x44};
+ EXPECT_TRUE(wifi_ap_iface->setMacAddress(mac).isOk());
+}
+
+/*
+ * SetCountryCode
+ */
+TEST_P(WifiApIfaceAidlTest, SetCountryCode) {
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+
+ const std::array<uint8_t, 2> country_code = {0x55, 0x53};
+ EXPECT_TRUE(wifi_ap_iface->setCountryCode(country_code).isOk());
+}
+
+/*
+ * GetValidFrequenciesForBand
+ * Ensures that we can retrieve valid frequencies for the 2.4 GHz band.
+ */
+TEST_P(WifiApIfaceAidlTest, GetValidFrequenciesForBand) {
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+
+ std::vector<int32_t> freqs;
+ EXPECT_TRUE(wifi_ap_iface->getValidFrequenciesForBand(WifiBand::BAND_24GHZ, &freqs).isOk());
+ EXPECT_NE(freqs.size(), 0);
+}
+
+/*
+ * GetFactoryMacAddress
+ */
+TEST_P(WifiApIfaceAidlTest, GetFactoryMacAddress) {
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+
+ std::array<uint8_t, 6> mac;
+ EXPECT_TRUE(wifi_ap_iface->getFactoryMacAddress(&mac).isOk());
+ std::array<uint8_t, 6> all_zero_mac = {0, 0, 0, 0, 0, 0};
+ EXPECT_NE(mac, all_zero_mac);
+}
+
+/**
+ * GetBridgedInstances - non-bridged mode
+ */
+TEST_P(WifiApIfaceAidlTest, GetBridgedInstances) {
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+
+ std::vector<std::string> instances;
+ EXPECT_TRUE(wifi_ap_iface->getBridgedInstances(&instances).isOk());
+ EXPECT_EQ(instances.size(), 0);
+}
+
+/**
+ * GetBridgedInstances - bridged AP mode.
+ */
+TEST_P(WifiApIfaceAidlTest, GetBridgedInstances_Bridged) {
+ if (!isBridgedSupport_) {
+ GTEST_SKIP() << "Missing Bridged AP support";
+ }
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getBridgedWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+
+ std::vector<std::string> instances;
+ EXPECT_TRUE(wifi_ap_iface->getBridgedInstances(&instances).isOk());
+ EXPECT_EQ(instances.size(), 2);
+}
+
+/**
+ * ResetToFactoryMacAddress - non-bridged mode
+ */
+TEST_P(WifiApIfaceAidlTest, ResetToFactoryMacAddress) {
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+ EXPECT_TRUE(wifi_ap_iface->resetToFactoryMacAddress().isOk());
+}
+
+/**
+ * ResetToFactoryMacAddress - bridged AP mode
+ */
+TEST_P(WifiApIfaceAidlTest, ResetToFactoryMacAddress_Bridged) {
+ if (!isBridgedSupport_) {
+ GTEST_SKIP() << "Missing Bridged AP support";
+ }
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getBridgedWifiApIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+ EXPECT_TRUE(wifi_ap_iface->resetToFactoryMacAddress().isOk());
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(WifiApIfaceAidlTest);
+INSTANTIATE_TEST_SUITE_P(WifiTest, WifiApIfaceAidlTest,
+ testing::ValuesIn(android::getAidlHalInstanceNames(IWifi::descriptor)),
+ android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
+ android::ProcessState::self()->startThreadPool();
+ return RUN_ALL_TESTS();
+}
diff --git a/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp
new file mode 100644
index 0000000..0806ed2
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_chip_aidl_test.cpp
@@ -0,0 +1,889 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Staache 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 <numeric>
+#include <vector>
+
+#include <VtsCoreUtil.h>
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/wifi/BnWifi.h>
+#include <aidl/android/hardware/wifi/BnWifiChipEventCallback.h>
+#include <android/binder_manager.h>
+#include <android/binder_status.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::BnWifiChipEventCallback;
+using aidl::android::hardware::wifi::IfaceType;
+using aidl::android::hardware::wifi::IWifiApIface;
+using aidl::android::hardware::wifi::IWifiChip;
+using aidl::android::hardware::wifi::IWifiNanIface;
+using aidl::android::hardware::wifi::IWifiP2pIface;
+using aidl::android::hardware::wifi::IWifiRttController;
+using aidl::android::hardware::wifi::WifiBand;
+using aidl::android::hardware::wifi::WifiDebugHostWakeReasonStats;
+using aidl::android::hardware::wifi::WifiDebugRingBufferStatus;
+using aidl::android::hardware::wifi::WifiDebugRingBufferVerboseLevel;
+using aidl::android::hardware::wifi::WifiIfaceMode;
+using aidl::android::hardware::wifi::WifiRadioCombinationMatrix;
+using aidl::android::hardware::wifi::WifiStatusCode;
+using aidl::android::hardware::wifi::WifiUsableChannel;
+
+class WifiChipAidlTest : public testing::TestWithParam<std::string> {
+ public:
+ void SetUp() override {
+ stopWifiService(getInstanceName());
+ wifi_chip_ = getWifiChip(getInstanceName());
+ ASSERT_NE(nullptr, wifi_chip_.get());
+ }
+
+ void TearDown() override { stopWifiService(getInstanceName()); }
+
+ protected:
+ int configureChipForConcurrencyType(IfaceConcurrencyType type) {
+ int mode_id;
+ EXPECT_TRUE(configureChipToSupportConcurrencyType(wifi_chip_, type, &mode_id));
+ return mode_id;
+ }
+
+ std::shared_ptr<IWifiStaIface> configureChipForStaAndGetIface() {
+ std::shared_ptr<IWifiStaIface> iface;
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ EXPECT_TRUE(wifi_chip_->createStaIface(&iface).isOk());
+ EXPECT_NE(nullptr, iface.get());
+ return iface;
+ }
+
+ std::shared_ptr<IWifiP2pIface> configureChipForP2pAndGetIface() {
+ std::shared_ptr<IWifiP2pIface> iface;
+ configureChipForConcurrencyType(IfaceConcurrencyType::P2P);
+ EXPECT_TRUE(wifi_chip_->createP2pIface(&iface).isOk());
+ EXPECT_NE(nullptr, iface.get());
+ return iface;
+ }
+
+ std::shared_ptr<IWifiApIface> configureChipForApAndGetIface() {
+ std::shared_ptr<IWifiApIface> iface;
+ configureChipForConcurrencyType(IfaceConcurrencyType::AP);
+ EXPECT_TRUE(wifi_chip_->createApIface(&iface).isOk());
+ EXPECT_NE(nullptr, iface.get());
+ return iface;
+ }
+
+ std::shared_ptr<IWifiNanIface> configureChipForNanAndGetIface() {
+ std::shared_ptr<IWifiNanIface> iface;
+ configureChipForConcurrencyType(IfaceConcurrencyType::NAN_IFACE);
+ EXPECT_TRUE(wifi_chip_->createNanIface(&iface).isOk());
+ EXPECT_NE(nullptr, iface.get());
+ return iface;
+ }
+
+ std::string getStaIfaceName(const std::shared_ptr<IWifiStaIface>& iface) {
+ std::string iface_name;
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
+ return iface_name;
+ }
+
+ std::string getP2pIfaceName(const std::shared_ptr<IWifiP2pIface>& iface) {
+ std::string iface_name;
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
+ return iface_name;
+ }
+
+ std::string getApIfaceName(const std::shared_ptr<IWifiApIface>& iface) {
+ std::string iface_name;
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
+ return iface_name;
+ }
+
+ std::string getNanIfaceName(const std::shared_ptr<IWifiNanIface>& iface) {
+ std::string iface_name;
+ EXPECT_TRUE(iface->getName(&iface_name).isOk());
+ return iface_name;
+ }
+
+ std::vector<std::shared_ptr<IWifiStaIface>> create2StaIfacesIfPossible() {
+ std::shared_ptr<IWifiStaIface> iface1 = configureChipForStaAndGetIface();
+
+ // Try create a create second iface.
+ std::shared_ptr<IWifiStaIface> iface2;
+ bool add_second_success = wifi_chip_->createStaIface(&iface2).isOk();
+ if (!add_second_success) {
+ return {iface1};
+ }
+ EXPECT_NE(nullptr, iface2.get());
+ return {iface1, iface2};
+ }
+
+ bool hasAnyRingBufferCapabilities(int32_t caps) {
+ return caps &
+ (static_cast<int32_t>(
+ IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_CONNECT_EVENT) |
+ static_cast<int32_t>(IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_POWER_EVENT) |
+ static_cast<int32_t>(
+ IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_WAKELOCK_EVENT) |
+ static_cast<int32_t>(IWifiChip::ChipCapabilityMask::DEBUG_RING_BUFFER_VENDOR_DATA));
+ }
+
+ const char* getInstanceName() { return GetParam().c_str(); }
+
+ std::shared_ptr<IWifiChip> wifi_chip_;
+};
+
+class WifiChipEventCallback : public BnWifiChipEventCallback {
+ public:
+ WifiChipEventCallback() = default;
+
+ ::ndk::ScopedAStatus onChipReconfigureFailure(WifiStatusCode /* status */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus onChipReconfigured(int /* modeId */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus onDebugErrorAlert(int /* errorCode */,
+ const std::vector<uint8_t>& /* debugData */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus onDebugRingBufferDataAvailable(
+ const WifiDebugRingBufferStatus& /* status */,
+ const std::vector<uint8_t>& /* data */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus onIfaceAdded(IfaceType /* type */,
+ const std::string& /* name */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus onIfaceRemoved(IfaceType /* type */,
+ const std::string& /* name */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus onRadioModeChange(
+ const std::vector<RadioModeInfo>& /* radioModeInfos */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+/*
+ * RegisterEventCallback
+ *
+ * Note: it is not feasible to test the invocation of the callback function,
+ * since events are triggered internally in the HAL implementation and cannot be
+ * triggered from the test case.
+ */
+TEST_P(WifiChipAidlTest, RegisterEventCallback) {
+ std::shared_ptr<WifiChipEventCallback> callback =
+ ndk::SharedRefBase::make<WifiChipEventCallback>();
+ ASSERT_NE(nullptr, callback.get());
+ EXPECT_TRUE(wifi_chip_->registerEventCallback(callback).isOk());
+}
+
+/*
+ * GetCapabilities
+ */
+TEST_P(WifiChipAidlTest, GetCapabilities) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ EXPECT_NE(static_cast<int32_t>(caps), 0);
+}
+
+/*
+ * GetId
+ */
+TEST_P(WifiChipAidlTest, GetId) {
+ int id;
+ EXPECT_TRUE(wifi_chip_->getId(&id).isOk());
+}
+
+/*
+ * GetAvailableModes
+ */
+TEST_P(WifiChipAidlTest, GetAvailableModes) {
+ std::vector<IWifiChip::ChipMode> modes;
+ EXPECT_TRUE(wifi_chip_->getAvailableModes(&modes).isOk());
+ EXPECT_NE(modes.size(), 0);
+}
+
+/*
+ * GetMode
+ */
+TEST_P(WifiChipAidlTest, GetMode) {
+ int expected_mode = configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int retrieved_mode;
+ EXPECT_TRUE(wifi_chip_->getMode(&retrieved_mode).isOk());
+ EXPECT_EQ(retrieved_mode, expected_mode);
+}
+
+/*
+ * GetUsableChannels
+ */
+TEST_P(WifiChipAidlTest, GetUsableChannels) {
+ WifiBand band = WifiBand::BAND_24GHZ_5GHZ_6GHZ;
+ uint32_t ifaceModeMask = static_cast<uint32_t>(WifiIfaceMode::IFACE_MODE_P2P_CLIENT) |
+ static_cast<uint32_t>(WifiIfaceMode::IFACE_MODE_P2P_GO);
+ uint32_t filterMask =
+ static_cast<uint32_t>(IWifiChip::UsableChannelFilter::CELLULAR_COEXISTENCE) |
+ static_cast<uint32_t>(IWifiChip::UsableChannelFilter::CONCURRENCY);
+
+ std::vector<WifiUsableChannel> channels;
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ auto status = wifi_chip_->getUsableChannels(
+ band, static_cast<WifiIfaceMode>(ifaceModeMask),
+ static_cast<IWifiChip::UsableChannelFilter>(filterMask), &channels);
+ if (checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ GTEST_SKIP() << "getUsableChannels() is not supported by vendor.";
+ }
+ EXPECT_TRUE(status.isOk());
+}
+
+/*
+ * GetSupportedRadioCombinationsMatrix
+ */
+TEST_P(WifiChipAidlTest, GetSupportedRadioCombinationsMatrix) {
+ WifiRadioCombinationMatrix combination_matrix = {};
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ auto status = wifi_chip_->getSupportedRadioCombinationsMatrix(&combination_matrix);
+ if (checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ GTEST_SKIP() << "Skipping this test since getSupportedRadioCombinationsMatrix() "
+ "is not supported by vendor.";
+ }
+ EXPECT_TRUE(status.isOk());
+}
+
+/*
+ * SetCountryCode
+ */
+TEST_P(WifiChipAidlTest, SetCountryCode) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ std::array<uint8_t, 2> country_code = {0x55, 0x53};
+ EXPECT_TRUE(wifi_chip_->setCountryCode(country_code).isOk());
+}
+
+/*
+ * SetLatencyMode_normal
+ * Tests the setLatencyMode() API with Latency mode NORMAL.
+ */
+TEST_P(WifiChipAidlTest, SetLatencyMode_normal) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ auto status = wifi_chip_->setLatencyMode(IWifiChip::LatencyMode::NORMAL);
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::SET_LATENCY_MODE)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * SetLatencyMode_low
+ * Tests the setLatencyMode() API with Latency mode LOW.
+ */
+TEST_P(WifiChipAidlTest, SetLatencyMode_low) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ auto status = wifi_chip_->setLatencyMode(IWifiChip::LatencyMode::LOW);
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::SET_LATENCY_MODE)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * SetMultiStaPrimaryConnection
+ *
+ * Only runs if the device supports 2 STA ifaces.
+ */
+TEST_P(WifiChipAidlTest, SetMultiStaPrimaryConnection) {
+ auto ifaces = create2StaIfacesIfPossible();
+ if (ifaces.size() < 2) {
+ GTEST_SKIP() << "Device does not support more than 1 STA concurrently";
+ }
+
+ auto status = wifi_chip_->setMultiStaPrimaryConnection(getStaIfaceName(ifaces[0]));
+ if (!status.isOk()) {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * SetMultiStaUseCase
+ *
+ * Only runs if the device supports 2 STA ifaces.
+ */
+TEST_P(WifiChipAidlTest, setMultiStaUseCase) {
+ auto ifaces = create2StaIfacesIfPossible();
+ if (ifaces.size() < 2) {
+ GTEST_SKIP() << "Device does not support more than 1 STA concurrently";
+ }
+
+ auto status = wifi_chip_->setMultiStaUseCase(
+ IWifiChip::MultiStaUseCase::DUAL_STA_TRANSIENT_PREFER_PRIMARY);
+ if (!status.isOk()) {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * SetCoexUnsafeChannels
+ */
+TEST_P(WifiChipAidlTest, SetCoexUnsafeChannels) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+
+ // Test with an empty vector of CoexUnsafeChannels.
+ std::vector<IWifiChip::CoexUnsafeChannel> vec;
+ IWifiChip::CoexRestriction restrictions = static_cast<IWifiChip::CoexRestriction>(0);
+ auto status = wifi_chip_->setCoexUnsafeChannels(vec, restrictions);
+ if (!status.isOk()) {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+
+ // Test with a non-empty vector of CoexUnsafeChannels.
+ IWifiChip::CoexUnsafeChannel unsafeChannel24Ghz;
+ unsafeChannel24Ghz.band = WifiBand::BAND_24GHZ;
+ unsafeChannel24Ghz.channel = 6;
+ vec.push_back(unsafeChannel24Ghz);
+ IWifiChip::CoexUnsafeChannel unsafeChannel5Ghz;
+ unsafeChannel5Ghz.band = WifiBand::BAND_5GHZ;
+ unsafeChannel5Ghz.channel = 36;
+ vec.push_back(unsafeChannel5Ghz);
+ restrictions = static_cast<IWifiChip::CoexRestriction>(
+ static_cast<int32_t>(IWifiChip::CoexRestriction::WIFI_AWARE) |
+ static_cast<int32_t>(IWifiChip::CoexRestriction::SOFTAP) |
+ static_cast<int32_t>(IWifiChip::CoexRestriction::WIFI_DIRECT));
+
+ status = wifi_chip_->setCoexUnsafeChannels(vec, restrictions);
+ if (!status.isOk()) {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * SelectTxPowerScenario - Body
+ */
+TEST_P(WifiChipAidlTest, SelectTxPowerScenario_body) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ int32_t expected_caps =
+ static_cast<int32_t>(IWifiChip::ChipCapabilityMask::SET_TX_POWER_LIMIT) |
+ static_cast<int32_t>(IWifiChip::ChipCapabilityMask::USE_BODY_HEAD_SAR);
+ auto status = wifi_chip_->selectTxPowerScenario(IWifiChip::TxPowerScenario::ON_BODY_CELL_OFF);
+ if (caps & expected_caps) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * SelectTxPowerScenario - Voice Call
+ */
+TEST_P(WifiChipAidlTest, SelectTxPowerScenario_voiceCall) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ auto status = wifi_chip_->selectTxPowerScenario(IWifiChip::TxPowerScenario::VOICE_CALL);
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::SET_TX_POWER_LIMIT)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * ResetTxPowerScenario
+ */
+TEST_P(WifiChipAidlTest, ResetTxPowerScenario) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ auto status = wifi_chip_->resetTxPowerScenario();
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::SET_TX_POWER_LIMIT)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * ConfigureChip
+ */
+TEST_P(WifiChipAidlTest, ConfigureChip) {
+ std::vector<IWifiChip::ChipMode> modes;
+ EXPECT_TRUE(wifi_chip_->getAvailableModes(&modes).isOk());
+ EXPECT_NE(modes.size(), 0);
+ for (const auto& mode : modes) {
+ // configureChip() requires a fresh IWifiChip object.
+ wifi_chip_ = getWifiChip(getInstanceName());
+ ASSERT_NE(nullptr, wifi_chip_.get());
+ EXPECT_TRUE(wifi_chip_->configureChip(mode.id).isOk());
+ stopWifiService(getInstanceName());
+ // Sleep for 5 milliseconds between each wifi state toggle.
+ usleep(5000);
+ }
+}
+
+/*
+ * RequestChipDebugInfo
+ */
+TEST_P(WifiChipAidlTest, RequestChipDebugInfo) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ IWifiChip::ChipDebugInfo debug_info = {};
+ EXPECT_TRUE(wifi_chip_->requestChipDebugInfo(&debug_info).isOk());
+ EXPECT_NE(debug_info.driverDescription.size(), 0);
+ EXPECT_NE(debug_info.firmwareDescription.size(), 0);
+}
+
+/*
+ * RequestFirmwareDebugDump
+ */
+TEST_P(WifiChipAidlTest, RequestFirmwareDebugDump) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ std::vector<uint8_t> debug_dump;
+ auto status = wifi_chip_->requestFirmwareDebugDump(&debug_dump);
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::DEBUG_MEMORY_FIRMWARE_DUMP)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * RequestDriverDebugDump
+ */
+TEST_P(WifiChipAidlTest, RequestDriverDebugDump) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ std::vector<uint8_t> debug_dump;
+ auto status = wifi_chip_->requestDriverDebugDump(&debug_dump);
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::DEBUG_MEMORY_DRIVER_DUMP)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * GetDebugRingBuffersStatus
+ */
+TEST_P(WifiChipAidlTest, GetDebugRingBuffersStatus) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ std::vector<WifiDebugRingBufferStatus> ring_buffer_status;
+ auto status = wifi_chip_->getDebugRingBuffersStatus(&ring_buffer_status);
+ if (hasAnyRingBufferCapabilities(caps)) {
+ EXPECT_TRUE(status.isOk());
+ ASSERT_NE(ring_buffer_status.size(), 0);
+ for (const auto& ring_buffer : ring_buffer_status) {
+ EXPECT_NE(ring_buffer.ringName.size(), 0);
+ }
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * GetDebugHostWakeReasonStats
+ */
+TEST_P(WifiChipAidlTest, GetDebugHostWakeReasonStats) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ WifiDebugHostWakeReasonStats wake_reason_stats = {};
+ auto status = wifi_chip_->getDebugHostWakeReasonStats(&wake_reason_stats);
+ if (caps & static_cast<int32_t>(IWifiChip::ChipCapabilityMask::DEBUG_HOST_WAKE_REASON_STATS)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * StartLoggingToDebugRingBuffer
+ */
+TEST_P(WifiChipAidlTest, StartLoggingToDebugRingBuffer) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ std::string ring_name;
+ std::vector<WifiDebugRingBufferStatus> ring_buffer_status;
+ auto status = wifi_chip_->getDebugRingBuffersStatus(&ring_buffer_status);
+
+ if (hasAnyRingBufferCapabilities(caps)) {
+ EXPECT_TRUE(status.isOk());
+ ASSERT_NE(ring_buffer_status.size(), 0);
+ ring_name = ring_buffer_status[0].ringName;
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+
+ status = wifi_chip_->startLoggingToDebugRingBuffer(
+ ring_name, WifiDebugRingBufferVerboseLevel::VERBOSE, 5, 1024);
+ if (hasAnyRingBufferCapabilities(caps)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * ForceDumpToDebugRingBuffer
+ */
+TEST_P(WifiChipAidlTest, ForceDumpToDebugRingBuffer) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+ int32_t caps = getChipCapabilities(wifi_chip_);
+ std::string ring_name;
+ std::vector<WifiDebugRingBufferStatus> ring_buffer_status;
+ auto status = wifi_chip_->getDebugRingBuffersStatus(&ring_buffer_status);
+
+ if (hasAnyRingBufferCapabilities(caps)) {
+ EXPECT_TRUE(status.isOk());
+ ASSERT_NE(ring_buffer_status.size(), 0);
+ ring_name = ring_buffer_status[0].ringName;
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+
+ status = wifi_chip_->forceDumpToDebugRingBuffer(ring_name);
+ if (hasAnyRingBufferCapabilities(caps)) {
+ EXPECT_TRUE(status.isOk());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/*
+ * CreateStaIface
+ * Configures the chip in STA mode and creates an iface.
+ */
+TEST_P(WifiChipAidlTest, CreateStaIface) {
+ configureChipForStaAndGetIface();
+}
+
+/*
+ * CreateApIface
+ */
+TEST_P(WifiChipAidlTest, CreateApIface) {
+ configureChipForApAndGetIface();
+}
+
+/*
+ * CreateNanIface
+ */
+TEST_P(WifiChipAidlTest, CreateNanIface) {
+ configureChipForNanAndGetIface();
+}
+
+/*
+ * CreateP2pIface
+ */
+TEST_P(WifiChipAidlTest, CreateP2pIface) {
+ configureChipForNanAndGetIface();
+}
+
+/*
+ * GetStaIfaceNames
+ * Configures the chip in STA mode and ensures that the iface name list is
+ * empty before creating the iface. Then create the iface and ensure that
+ * iface name is returned in the iface name list.
+ */
+TEST_P(WifiChipAidlTest, GetStaIfaceNames) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::STA);
+
+ std::vector<std::string> iface_names;
+ EXPECT_TRUE(wifi_chip_->getP2pIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+
+ std::shared_ptr<IWifiStaIface> iface;
+ EXPECT_TRUE(wifi_chip_->createStaIface(&iface).isOk());
+ ASSERT_NE(nullptr, iface.get());
+
+ std::string iface_name = getStaIfaceName(iface);
+ EXPECT_TRUE(wifi_chip_->getStaIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 1);
+ EXPECT_EQ(iface_name, iface_names[0]);
+
+ EXPECT_TRUE(wifi_chip_->removeStaIface(iface_name).isOk());
+ EXPECT_TRUE(wifi_chip_->getStaIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+}
+
+/*
+ * GetP2pIfaceNames
+ */
+TEST_P(WifiChipAidlTest, GetP2pIfaceNames) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::P2P);
+
+ std::vector<std::string> iface_names;
+ EXPECT_TRUE(wifi_chip_->getP2pIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+
+ std::shared_ptr<IWifiP2pIface> iface;
+ EXPECT_TRUE(wifi_chip_->createP2pIface(&iface).isOk());
+ ASSERT_NE(nullptr, iface.get());
+
+ std::string iface_name = getP2pIfaceName(iface);
+ EXPECT_TRUE(wifi_chip_->getP2pIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 1);
+ EXPECT_EQ(iface_name, iface_names[0]);
+
+ EXPECT_TRUE(wifi_chip_->removeP2pIface(iface_name).isOk());
+ EXPECT_TRUE(wifi_chip_->getP2pIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+}
+
+/*
+ * GetApIfaceNames
+ */
+TEST_P(WifiChipAidlTest, GetApIfaceNames) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::AP);
+
+ std::vector<std::string> iface_names;
+ EXPECT_TRUE(wifi_chip_->getApIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+
+ std::shared_ptr<IWifiApIface> iface;
+ EXPECT_TRUE(wifi_chip_->createApIface(&iface).isOk());
+ ASSERT_NE(nullptr, iface.get());
+
+ std::string iface_name = getApIfaceName(iface);
+ EXPECT_TRUE(wifi_chip_->getApIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 1);
+ EXPECT_EQ(iface_name, iface_names[0]);
+
+ EXPECT_TRUE(wifi_chip_->removeApIface(iface_name).isOk());
+ EXPECT_TRUE(wifi_chip_->getApIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+}
+
+/*
+ * GetNanIfaceNames
+ */
+TEST_P(WifiChipAidlTest, GetNanIfaceNames) {
+ configureChipForConcurrencyType(IfaceConcurrencyType::NAN_IFACE);
+
+ std::vector<std::string> iface_names;
+ EXPECT_TRUE(wifi_chip_->getNanIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+
+ std::shared_ptr<IWifiNanIface> iface;
+ EXPECT_TRUE(wifi_chip_->createNanIface(&iface).isOk());
+ ASSERT_NE(nullptr, iface.get());
+
+ std::string iface_name = getNanIfaceName(iface);
+ EXPECT_TRUE(wifi_chip_->getNanIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 1);
+ EXPECT_EQ(iface_name, iface_names[0]);
+
+ EXPECT_TRUE(wifi_chip_->removeNanIface(iface_name).isOk());
+ EXPECT_TRUE(wifi_chip_->getNanIfaceNames(&iface_names).isOk());
+ EXPECT_EQ(iface_names.size(), 0);
+}
+
+/*
+ * GetStaIface
+ * Configures the chip in STA mode and creates an iface. Then retrieves
+ * the iface object using its name and ensures that any other name
+ * doesn't retrieve a valid iface object.
+ */
+TEST_P(WifiChipAidlTest, GetStaIface) {
+ std::shared_ptr<IWifiStaIface> iface = configureChipForStaAndGetIface();
+ std::string iface_name = getStaIfaceName(iface);
+
+ std::shared_ptr<IWifiStaIface> retrieved_iface;
+ EXPECT_TRUE(wifi_chip_->getStaIface(iface_name, &retrieved_iface).isOk());
+ EXPECT_NE(nullptr, retrieved_iface.get());
+
+ std::string invalid_name = iface_name + "0";
+ std::shared_ptr<IWifiStaIface> invalid_iface;
+ auto status = wifi_chip_->getStaIface(invalid_name, &invalid_iface);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_EQ(nullptr, invalid_iface.get());
+}
+
+/*
+ * GetP2pIface
+ */
+TEST_P(WifiChipAidlTest, GetP2pIface) {
+ std::shared_ptr<IWifiP2pIface> iface = configureChipForP2pAndGetIface();
+ std::string iface_name = getP2pIfaceName(iface);
+
+ std::shared_ptr<IWifiP2pIface> retrieved_iface;
+ EXPECT_TRUE(wifi_chip_->getP2pIface(iface_name, &retrieved_iface).isOk());
+ EXPECT_NE(nullptr, retrieved_iface.get());
+
+ std::string invalid_name = iface_name + "0";
+ std::shared_ptr<IWifiP2pIface> invalid_iface;
+ auto status = wifi_chip_->getP2pIface(invalid_name, &invalid_iface);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_EQ(nullptr, invalid_iface.get());
+}
+
+/*
+ * GetApIface
+ */
+TEST_P(WifiChipAidlTest, GetApIface) {
+ std::shared_ptr<IWifiApIface> iface = configureChipForApAndGetIface();
+ std::string iface_name = getApIfaceName(iface);
+
+ std::shared_ptr<IWifiApIface> retrieved_iface;
+ EXPECT_TRUE(wifi_chip_->getApIface(iface_name, &retrieved_iface).isOk());
+ EXPECT_NE(nullptr, retrieved_iface.get());
+
+ std::string invalid_name = iface_name + "0";
+ std::shared_ptr<IWifiApIface> invalid_iface;
+ auto status = wifi_chip_->getApIface(invalid_name, &invalid_iface);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_EQ(nullptr, invalid_iface.get());
+}
+
+/*
+ * GetNanIface
+ */
+TEST_P(WifiChipAidlTest, GetNanIface) {
+ std::shared_ptr<IWifiNanIface> iface = configureChipForNanAndGetIface();
+ std::string iface_name = getNanIfaceName(iface);
+
+ std::shared_ptr<IWifiNanIface> retrieved_iface;
+ EXPECT_TRUE(wifi_chip_->getNanIface(iface_name, &retrieved_iface).isOk());
+ EXPECT_NE(nullptr, retrieved_iface.get());
+
+ std::string invalid_name = iface_name + "0";
+ std::shared_ptr<IWifiNanIface> invalid_iface;
+ auto status = wifi_chip_->getNanIface(invalid_name, &invalid_iface);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_EQ(nullptr, invalid_iface.get());
+}
+
+/*
+ * RemoveStaIface
+ * Configures the chip in STA mode and creates an iface. Then removes
+ * the iface object using the correct name and ensures that any other
+ * name doesn't remove the iface.
+ */
+TEST_P(WifiChipAidlTest, RemoveStaIface) {
+ std::shared_ptr<IWifiStaIface> iface = configureChipForStaAndGetIface();
+ std::string iface_name = getStaIfaceName(iface);
+
+ std::string invalid_name = iface_name + "0";
+ auto status = wifi_chip_->removeStaIface(invalid_name);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_TRUE(wifi_chip_->removeStaIface(iface_name).isOk());
+
+ // No such iface exists now, so this should return failure.
+ EXPECT_FALSE(wifi_chip_->removeStaIface(iface_name).isOk());
+}
+
+/*
+ * RemoveP2pIface
+ */
+TEST_P(WifiChipAidlTest, RemoveP2pIface) {
+ std::shared_ptr<IWifiP2pIface> iface = configureChipForP2pAndGetIface();
+ std::string iface_name = getP2pIfaceName(iface);
+
+ std::string invalid_name = iface_name + "0";
+ auto status = wifi_chip_->removeP2pIface(invalid_name);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_TRUE(wifi_chip_->removeP2pIface(iface_name).isOk());
+
+ // No such iface exists now, so this should return failure.
+ EXPECT_FALSE(wifi_chip_->removeP2pIface(iface_name).isOk());
+}
+
+/*
+ * RemoveApIface
+ */
+TEST_P(WifiChipAidlTest, RemoveApIface) {
+ std::shared_ptr<IWifiApIface> iface = configureChipForApAndGetIface();
+ std::string iface_name = getApIfaceName(iface);
+
+ std::string invalid_name = iface_name + "0";
+ auto status = wifi_chip_->removeApIface(invalid_name);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_TRUE(wifi_chip_->removeApIface(iface_name).isOk());
+
+ // No such iface exists now, so this should return failure.
+ EXPECT_FALSE(wifi_chip_->removeApIface(iface_name).isOk());
+}
+
+/*
+ * RemoveNanIface
+ */
+TEST_P(WifiChipAidlTest, RemoveNanIface) {
+ std::shared_ptr<IWifiNanIface> iface = configureChipForNanAndGetIface();
+ std::string iface_name = getNanIfaceName(iface);
+
+ std::string invalid_name = iface_name + "0";
+ auto status = wifi_chip_->removeNanIface(invalid_name);
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ EXPECT_TRUE(wifi_chip_->removeNanIface(iface_name).isOk());
+
+ // No such iface exists now, so this should return failure.
+ EXPECT_FALSE(wifi_chip_->removeNanIface(iface_name).isOk());
+}
+
+/*
+ * CreateRttController
+ */
+TEST_P(WifiChipAidlTest, CreateRttController) {
+ std::shared_ptr<IWifiStaIface> iface = configureChipForStaAndGetIface();
+ std::shared_ptr<IWifiRttController> rtt_controller;
+ auto status = wifi_chip_->createRttController(iface, &rtt_controller);
+ if (status.isOk()) {
+ EXPECT_NE(nullptr, rtt_controller.get());
+ } else {
+ EXPECT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+ }
+}
+
+/**
+ * CreateBridgedApIface & RemoveIfaceInstanceFromBridgedApIface
+ */
+TEST_P(WifiChipAidlTest, CreateBridgedApIfaceAndremoveIfaceInstanceFromBridgedApIfaceTest) {
+ bool isBridgedSupport = testing::checkSubstringInCommandOutput(
+ "/system/bin/cmd wifi get-softap-supported-features",
+ "wifi_softap_bridged_ap_supported");
+ if (!isBridgedSupport) {
+ GTEST_SKIP() << "Missing Bridged AP support";
+ }
+
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(getInstanceName());
+ ASSERT_NE(nullptr, wifi_chip.get());
+ std::shared_ptr<IWifiApIface> wifi_ap_iface = getBridgedWifiApIface(wifi_chip);
+ ASSERT_NE(nullptr, wifi_ap_iface.get());
+
+ std::string br_name;
+ std::vector<std::string> instances;
+ EXPECT_TRUE(wifi_ap_iface->getName(&br_name).isOk());
+ EXPECT_TRUE(wifi_ap_iface->getBridgedInstances(&instances).isOk());
+ EXPECT_EQ(instances.size(), 2);
+
+ std::vector<std::string> instances_after_remove;
+ EXPECT_TRUE(wifi_chip->removeIfaceInstanceFromBridgedApIface(br_name, instances[0]).isOk());
+ EXPECT_TRUE(wifi_ap_iface->getBridgedInstances(&instances_after_remove).isOk());
+ EXPECT_EQ(instances_after_remove.size(), 1);
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(WifiChipAidlTest);
+INSTANTIATE_TEST_SUITE_P(WifiTest, WifiChipAidlTest,
+ testing::ValuesIn(android::getAidlHalInstanceNames(IWifi::descriptor)),
+ android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
+ android::ProcessState::self()->startThreadPool();
+ return RUN_ALL_TESTS();
+}
diff --git a/wifi/aidl/vts/functional/wifi_nan_iface_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_nan_iface_aidl_test.cpp
new file mode 100644
index 0000000..457d57a
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_nan_iface_aidl_test.cpp
@@ -0,0 +1,627 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Staache 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 <vector>
+
+#include <VtsCoreUtil.h>
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/wifi/BnWifi.h>
+#include <aidl/android/hardware/wifi/BnWifiNanIfaceEventCallback.h>
+#include <aidl/android/hardware/wifi/NanBandIndex.h>
+#include <android/binder_manager.h>
+#include <android/binder_status.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::BnWifiNanIfaceEventCallback;
+using aidl::android::hardware::wifi::IWifiNanIface;
+using aidl::android::hardware::wifi::NanBandIndex;
+using aidl::android::hardware::wifi::NanBandSpecificConfig;
+using aidl::android::hardware::wifi::NanCapabilities;
+using aidl::android::hardware::wifi::NanClusterEventInd;
+using aidl::android::hardware::wifi::NanConfigRequest;
+using aidl::android::hardware::wifi::NanConfigRequestSupplemental;
+using aidl::android::hardware::wifi::NanDataPathConfirmInd;
+using aidl::android::hardware::wifi::NanDataPathRequestInd;
+using aidl::android::hardware::wifi::NanDataPathScheduleUpdateInd;
+using aidl::android::hardware::wifi::NanDataPathSecurityType;
+using aidl::android::hardware::wifi::NanEnableRequest;
+using aidl::android::hardware::wifi::NanFollowupReceivedInd;
+using aidl::android::hardware::wifi::NanInitiateDataPathRequest;
+using aidl::android::hardware::wifi::NanMatchAlg;
+using aidl::android::hardware::wifi::NanMatchInd;
+using aidl::android::hardware::wifi::NanPublishRequest;
+using aidl::android::hardware::wifi::NanPublishType;
+using aidl::android::hardware::wifi::NanRespondToDataPathIndicationRequest;
+using aidl::android::hardware::wifi::NanStatus;
+using aidl::android::hardware::wifi::NanStatusCode;
+using aidl::android::hardware::wifi::NanTxType;
+
+#define TIMEOUT_PERIOD 10
+
+class WifiNanIfaceAidlTest : public testing::TestWithParam<std::string> {
+ public:
+ void SetUp() override {
+ if (!::testing::deviceSupportsFeature("android.hardware.wifi.aware"))
+ GTEST_SKIP() << "Skipping this test since NAN is not supported.";
+ stopWifiService(getInstanceName());
+
+ wifi_nan_iface_ = getWifiNanIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_nan_iface_.get());
+ std::shared_ptr<WifiNanIfaceEventCallback> callback =
+ ndk::SharedRefBase::make<WifiNanIfaceEventCallback>(*this);
+ EXPECT_TRUE(wifi_nan_iface_->registerEventCallback(callback).isOk());
+ }
+
+ void TearDown() override { stopWifiService(getInstanceName()); }
+
+ // Used as a mechanism to inform the test about data/event callbacks.
+ inline void notify() {
+ std::unique_lock<std::mutex> lock(mtx_);
+ count_++;
+ cv_.notify_one();
+ }
+
+ enum CallbackType {
+ INVALID = -2,
+ ANY_CALLBACK = -1,
+
+ NOTIFY_CAPABILITIES_RESPONSE = 0,
+ NOTIFY_ENABLE_RESPONSE,
+ NOTIFY_CONFIG_RESPONSE,
+ NOTIFY_DISABLE_RESPONSE,
+ NOTIFY_START_PUBLISH_RESPONSE,
+ NOTIFY_STOP_PUBLISH_RESPONSE,
+ NOTIFY_START_SUBSCRIBE_RESPONSE,
+ NOTIFY_STOP_SUBSCRIBE_RESPONSE,
+ NOTIFY_TRANSMIT_FOLLOWUP_RESPONSE,
+ NOTIFY_CREATE_DATA_INTERFACE_RESPONSE,
+ NOTIFY_DELETE_DATA_INTERFACE_RESPONSE,
+ NOTIFY_INITIATE_DATA_PATH_RESPONSE,
+ NOTIFY_RESPOND_TO_DATA_PATH_INDICATION_RESPONSE,
+ NOTIFY_TERMINATE_DATA_PATH_RESPONSE,
+
+ EVENT_CLUSTER_EVENT,
+ EVENT_DISABLED,
+ EVENT_PUBLISH_TERMINATED,
+ EVENT_SUBSCRIBE_TERMINATED,
+ EVENT_MATCH,
+ EVENT_MATCH_EXPIRED,
+ EVENT_FOLLOWUP_RECEIVED,
+ EVENT_TRANSMIT_FOLLOWUP,
+ EVENT_DATA_PATH_REQUEST,
+ EVENT_DATA_PATH_CONFIRM,
+ EVENT_DATA_PATH_TERMINATED,
+ EVENT_DATA_PATH_SCHEDULE_UPDATE,
+ };
+
+ // Test code calls this function to wait for data/event callback.
+ // Must set callbackType = INVALID before calling this function.
+ inline std::cv_status wait(CallbackType waitForCallbackType) {
+ std::unique_lock<std::mutex> lock(mtx_);
+ EXPECT_NE(INVALID, waitForCallbackType);
+
+ std::cv_status status = std::cv_status::no_timeout;
+ auto now = std::chrono::system_clock::now();
+ while (count_ == 0) {
+ status = cv_.wait_until(lock, now + std::chrono::seconds(TIMEOUT_PERIOD));
+ if (status == std::cv_status::timeout) return status;
+ if (waitForCallbackType != ANY_CALLBACK && callback_type_ != INVALID &&
+ callback_type_ != waitForCallbackType) {
+ count_--;
+ }
+ }
+ count_--;
+ return status;
+ }
+
+ class WifiNanIfaceEventCallback : public BnWifiNanIfaceEventCallback {
+ public:
+ WifiNanIfaceEventCallback(WifiNanIfaceAidlTest& parent) : parent_(parent){};
+
+ ::ndk::ScopedAStatus eventClusterEvent(const NanClusterEventInd& event) override {
+ parent_.callback_type_ = EVENT_CLUSTER_EVENT;
+ parent_.nan_cluster_event_ind_ = event;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventDataPathConfirm(const NanDataPathConfirmInd& event) override {
+ parent_.callback_type_ = EVENT_DATA_PATH_CONFIRM;
+ parent_.nan_data_path_confirm_ind_ = event;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventDataPathRequest(const NanDataPathRequestInd& event) override {
+ parent_.callback_type_ = EVENT_DATA_PATH_REQUEST;
+ parent_.nan_data_path_request_ind_ = event;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventDataPathScheduleUpdate(
+ const NanDataPathScheduleUpdateInd& event) override {
+ parent_.callback_type_ = EVENT_DATA_PATH_SCHEDULE_UPDATE;
+ parent_.nan_data_path_schedule_update_ind_ = event;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventDataPathTerminated(int32_t ndpInstanceId) override {
+ parent_.callback_type_ = EVENT_DATA_PATH_TERMINATED;
+ parent_.ndp_instance_id_ = ndpInstanceId;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventDisabled(const NanStatus& status) override {
+ parent_.callback_type_ = EVENT_DISABLED;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventFollowupReceived(const NanFollowupReceivedInd& event) override {
+ parent_.callback_type_ = EVENT_FOLLOWUP_RECEIVED;
+ parent_.nan_followup_received_ind_ = event;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventMatch(const NanMatchInd& event) override {
+ parent_.callback_type_ = EVENT_MATCH;
+ parent_.nan_match_ind_ = event;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventMatchExpired(int8_t discoverySessionId, int32_t peerId) override {
+ parent_.callback_type_ = EVENT_MATCH_EXPIRED;
+ parent_.session_id_ = discoverySessionId;
+ parent_.peer_id_ = peerId;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventPublishTerminated(int8_t sessionId,
+ const NanStatus& status) override {
+ parent_.callback_type_ = EVENT_PUBLISH_TERMINATED;
+ parent_.session_id_ = sessionId;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventSubscribeTerminated(int8_t sessionId,
+ const NanStatus& status) override {
+ parent_.callback_type_ = EVENT_SUBSCRIBE_TERMINATED;
+ parent_.session_id_ = sessionId;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus eventTransmitFollowup(char16_t id, const NanStatus& status) override {
+ parent_.callback_type_ = EVENT_TRANSMIT_FOLLOWUP;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyCapabilitiesResponse(
+ char16_t id, const NanStatus& status,
+ const NanCapabilities& capabilities) override {
+ parent_.callback_type_ = NOTIFY_CAPABILITIES_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.capabilities_ = capabilities;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyConfigResponse(char16_t id, const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_CONFIG_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyCreateDataInterfaceResponse(char16_t id,
+ const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_CREATE_DATA_INTERFACE_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyDeleteDataInterfaceResponse(char16_t id,
+ const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_DELETE_DATA_INTERFACE_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyDisableResponse(char16_t id, const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_DISABLE_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyEnableResponse(char16_t id, const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_ENABLE_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyInitiateDataPathResponse(char16_t id, const NanStatus& status,
+ int32_t ndpInstanceId) override {
+ parent_.callback_type_ = NOTIFY_INITIATE_DATA_PATH_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.ndp_instance_id_ = ndpInstanceId;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyRespondToDataPathIndicationResponse(
+ char16_t id, const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_RESPOND_TO_DATA_PATH_INDICATION_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyStartPublishResponse(char16_t id, const NanStatus& status,
+ int8_t sessionId) override {
+ parent_.callback_type_ = NOTIFY_START_PUBLISH_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.session_id_ = sessionId;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyStartSubscribeResponse(char16_t id, const NanStatus& status,
+ int8_t sessionId) override {
+ parent_.callback_type_ = NOTIFY_START_SUBSCRIBE_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.session_id_ = sessionId;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyStopPublishResponse(char16_t id,
+ const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_STOP_PUBLISH_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyStopSubscribeResponse(char16_t id,
+ const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_STOP_SUBSCRIBE_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyTerminateDataPathResponse(char16_t id,
+ const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_TERMINATE_DATA_PATH_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+ ::ndk::ScopedAStatus notifyTransmitFollowupResponse(char16_t id,
+ const NanStatus& status) override {
+ parent_.callback_type_ = NOTIFY_TRANSMIT_FOLLOWUP_RESPONSE;
+ parent_.id_ = id;
+ parent_.status_ = status;
+ parent_.notify();
+ return ndk::ScopedAStatus::ok();
+ }
+
+ private:
+ WifiNanIfaceAidlTest& parent_;
+ };
+
+ protected:
+ std::shared_ptr<IWifiNanIface> wifi_nan_iface_;
+ CallbackType callback_type_;
+ uint16_t id_;
+ uint8_t session_id_;
+ uint32_t ndp_instance_id_;
+ uint32_t peer_id_;
+ NanCapabilities capabilities_;
+ NanClusterEventInd nan_cluster_event_ind_;
+ NanDataPathConfirmInd nan_data_path_confirm_ind_;
+ NanDataPathRequestInd nan_data_path_request_ind_;
+ NanDataPathScheduleUpdateInd nan_data_path_schedule_update_ind_;
+ NanFollowupReceivedInd nan_followup_received_ind_;
+ NanMatchInd nan_match_ind_;
+ NanStatus status_;
+
+ const char* getInstanceName() { return GetParam().c_str(); }
+
+ private:
+ // synchronization objects
+ std::mutex mtx_;
+ std::condition_variable cv_;
+ int count_ = 0;
+};
+
+/*
+ * FailOnIfaceInvalid
+ * Ensure that API calls to an interface fail with code ERROR_WIFI_IFACE_INVALID
+ * after wifi is disabled.
+ */
+TEST_P(WifiNanIfaceAidlTest, FailOnIfaceInvalid) {
+ stopWifiService(getInstanceName());
+ sleep(5); // Ensure that all chips/interfaces are invalidated.
+ auto status = wifi_nan_iface_->getCapabilitiesRequest(0);
+ ASSERT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_WIFI_IFACE_INVALID));
+}
+
+/*
+ * EnableRequest - Invalid Args
+ */
+TEST_P(WifiNanIfaceAidlTest, EnableRequest_InvalidArgs) {
+ uint16_t inputCmdId = 10;
+ callback_type_ = INVALID;
+ NanEnableRequest nanEnableRequest = {};
+ NanConfigRequestSupplemental nanConfigRequestSupp = {};
+ auto status =
+ wifi_nan_iface_->enableRequest(inputCmdId, nanEnableRequest, nanConfigRequestSupp);
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_TRUE(status.isOk());
+
+ // Wait for a callback.
+ ASSERT_EQ(std::cv_status::no_timeout, wait(NOTIFY_ENABLE_RESPONSE));
+ ASSERT_EQ(NOTIFY_ENABLE_RESPONSE, callback_type_);
+ ASSERT_EQ(id_, inputCmdId);
+ ASSERT_EQ(status_.status, NanStatusCode::INVALID_ARGS);
+ }
+}
+
+/*
+ * ConfigRequest - Invalid Args
+ */
+TEST_P(WifiNanIfaceAidlTest, ConfigRequest_InvalidArgs) {
+ uint16_t inputCmdId = 10;
+ callback_type_ = INVALID;
+ NanConfigRequest nanConfigRequest = {};
+ NanConfigRequestSupplemental nanConfigRequestSupp = {};
+ auto status =
+ wifi_nan_iface_->configRequest(inputCmdId, nanConfigRequest, nanConfigRequestSupp);
+
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_TRUE(status.isOk());
+
+ // Wait for a callback.
+ ASSERT_EQ(std::cv_status::no_timeout, wait(NOTIFY_CONFIG_RESPONSE));
+ ASSERT_EQ(NOTIFY_CONFIG_RESPONSE, callback_type_);
+ ASSERT_EQ(id_, inputCmdId);
+ ASSERT_EQ(status_.status, NanStatusCode::INVALID_ARGS);
+ }
+}
+
+/*
+ * EnableRequest - Invalid Args in Shim Conversion
+ */
+TEST_P(WifiNanIfaceAidlTest, EnableRequest_InvalidShimArgs) {
+ uint16_t inputCmdId = 10;
+ NanEnableRequest nanEnableRequest = {};
+ nanEnableRequest.configParams.numberOfPublishServiceIdsInBeacon = -15; // must be > 0
+ NanConfigRequestSupplemental nanConfigRequestSupp = {};
+ auto status =
+ wifi_nan_iface_->enableRequest(inputCmdId, nanEnableRequest, nanConfigRequestSupp);
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ }
+}
+
+/*
+ * ConfigRequest - Invalid Args in Shim Conversion
+ */
+TEST_P(WifiNanIfaceAidlTest, ConfigRequest_InvalidShimArgs) {
+ uint16_t inputCmdId = 10;
+ NanConfigRequest nanConfigRequest = {};
+ nanConfigRequest.numberOfPublishServiceIdsInBeacon = -15; // must be > 0
+ NanConfigRequestSupplemental nanConfigRequestSupp = {};
+ auto status =
+ wifi_nan_iface_->configRequest(inputCmdId, nanConfigRequest, nanConfigRequestSupp);
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_TRUE(checkStatusCode(&status, WifiStatusCode::ERROR_INVALID_ARGS));
+ }
+}
+
+/*
+ * NotifyCapabilitiesResponse
+ */
+TEST_P(WifiNanIfaceAidlTest, NotifyCapabilitiesResponse) {
+ uint16_t inputCmdId = 10;
+ callback_type_ = INVALID;
+ EXPECT_TRUE(wifi_nan_iface_->getCapabilitiesRequest(inputCmdId).isOk());
+
+ // Wait for a callback.
+ ASSERT_EQ(std::cv_status::no_timeout, wait(NOTIFY_CAPABILITIES_RESPONSE));
+ ASSERT_EQ(NOTIFY_CAPABILITIES_RESPONSE, callback_type_);
+ ASSERT_EQ(id_, inputCmdId);
+ ASSERT_EQ(status_.status, NanStatusCode::SUCCESS);
+
+ // Check for reasonable capability values.
+ EXPECT_GT(capabilities_.maxConcurrentClusters, 0);
+ EXPECT_GT(capabilities_.maxPublishes, 0);
+ EXPECT_GT(capabilities_.maxSubscribes, 0);
+ EXPECT_EQ(capabilities_.maxServiceNameLen, 255);
+ EXPECT_EQ(capabilities_.maxMatchFilterLen, 255);
+ EXPECT_GT(capabilities_.maxTotalMatchFilterLen, 255);
+ EXPECT_EQ(capabilities_.maxServiceSpecificInfoLen, 255);
+ EXPECT_GE(capabilities_.maxExtendedServiceSpecificInfoLen, 255);
+ EXPECT_GT(capabilities_.maxNdiInterfaces, 0);
+ EXPECT_GT(capabilities_.maxNdpSessions, 0);
+ EXPECT_GT(capabilities_.maxAppInfoLen, 0);
+ EXPECT_GT(capabilities_.maxQueuedTransmitFollowupMsgs, 0);
+ EXPECT_GT(capabilities_.maxSubscribeInterfaceAddresses, 0);
+ EXPECT_NE(static_cast<int32_t>(capabilities_.supportedCipherSuites), 0);
+}
+
+/*
+ * StartPublishRequest
+ */
+TEST_P(WifiNanIfaceAidlTest, StartPublishRequest) {
+ uint16_t inputCmdId = 10;
+ NanBandSpecificConfig config24 = {};
+ config24.rssiClose = 60;
+ config24.rssiMiddle = 70;
+ config24.rssiCloseProximity = 60;
+ config24.dwellTimeMs = 200;
+ config24.scanPeriodSec = 20;
+ config24.validDiscoveryWindowIntervalVal = false;
+ config24.discoveryWindowIntervalVal = 0;
+
+ NanBandSpecificConfig config5 = {};
+ config5.rssiClose = 60;
+ config5.rssiMiddle = 75;
+ config5.rssiCloseProximity = 60;
+ config5.dwellTimeMs = 200;
+ config5.scanPeriodSec = 20;
+ config5.validDiscoveryWindowIntervalVal = false;
+ config5.discoveryWindowIntervalVal = 0;
+
+ NanEnableRequest req = {};
+ req.operateInBand[static_cast<int32_t>(NanBandIndex::NAN_BAND_24GHZ)] = true;
+ req.operateInBand[static_cast<int32_t>(NanBandIndex::NAN_BAND_5GHZ)] = false;
+ req.hopCountMax = 2;
+ req.configParams.masterPref = 0;
+ req.configParams.disableDiscoveryAddressChangeIndication = true;
+ req.configParams.disableStartedClusterIndication = true;
+ req.configParams.disableJoinedClusterIndication = true;
+ req.configParams.includePublishServiceIdsInBeacon = true;
+ req.configParams.numberOfPublishServiceIdsInBeacon = 0;
+ req.configParams.includeSubscribeServiceIdsInBeacon = true;
+ req.configParams.numberOfSubscribeServiceIdsInBeacon = 0;
+ req.configParams.rssiWindowSize = 8;
+ req.configParams.macAddressRandomizationIntervalSec = 1800;
+ req.configParams.bandSpecificConfig[static_cast<int32_t>(NanBandIndex::NAN_BAND_24GHZ)] =
+ config24;
+ req.configParams.bandSpecificConfig[static_cast<int32_t>(NanBandIndex::NAN_BAND_5GHZ)] =
+ config5;
+
+ req.debugConfigs.validClusterIdVals = true;
+ req.debugConfigs.clusterIdTopRangeVal = 65535;
+ req.debugConfigs.clusterIdBottomRangeVal = 0;
+ req.debugConfigs.validIntfAddrVal = false;
+ req.debugConfigs.validOuiVal = false;
+ req.debugConfigs.ouiVal = 0;
+ req.debugConfigs.validRandomFactorForceVal = false;
+ req.debugConfigs.randomFactorForceVal = 0;
+ req.debugConfigs.validHopCountForceVal = false;
+ req.debugConfigs.hopCountForceVal = 0;
+ req.debugConfigs.validDiscoveryChannelVal = false;
+ req.debugConfigs.discoveryChannelMhzVal[static_cast<int32_t>(NanBandIndex::NAN_BAND_24GHZ)] = 0;
+ req.debugConfigs.discoveryChannelMhzVal[static_cast<int32_t>(NanBandIndex::NAN_BAND_5GHZ)] = 0;
+ req.debugConfigs.validUseBeaconsInBandVal = false;
+ req.debugConfigs.useBeaconsInBandVal[static_cast<int32_t>(NanBandIndex::NAN_BAND_24GHZ)] = true;
+ req.debugConfigs.useBeaconsInBandVal[static_cast<int32_t>(NanBandIndex::NAN_BAND_5GHZ)] = true;
+ req.debugConfigs.validUseSdfInBandVal = false;
+ req.debugConfigs.useSdfInBandVal[static_cast<int32_t>(NanBandIndex::NAN_BAND_24GHZ)] = true;
+ req.debugConfigs.useSdfInBandVal[static_cast<int32_t>(NanBandIndex::NAN_BAND_5GHZ)] = true;
+
+ NanConfigRequestSupplemental nanConfigRequestSupp = {};
+ nanConfigRequestSupp.discoveryBeaconIntervalMs = 20;
+ nanConfigRequestSupp.numberOfSpatialStreamsInDiscovery = 0;
+ nanConfigRequestSupp.enableDiscoveryWindowEarlyTermination = false;
+
+ callback_type_ = INVALID;
+ auto status = wifi_nan_iface_->enableRequest(inputCmdId, req, nanConfigRequestSupp);
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_TRUE(status.isOk());
+
+ // Wait for a callback.
+ ASSERT_EQ(std::cv_status::no_timeout, wait(NOTIFY_ENABLE_RESPONSE));
+ ASSERT_EQ(NOTIFY_ENABLE_RESPONSE, callback_type_);
+ ASSERT_EQ(id_, inputCmdId);
+ ASSERT_EQ(status_.status, NanStatusCode::SUCCESS);
+ }
+
+ NanPublishRequest nanPublishRequest = {};
+ nanPublishRequest.baseConfigs.sessionId = 0;
+ nanPublishRequest.baseConfigs.ttlSec = 0;
+ nanPublishRequest.baseConfigs.discoveryWindowPeriod = 1;
+ nanPublishRequest.baseConfigs.discoveryCount = 0;
+ nanPublishRequest.baseConfigs.serviceName = {97};
+ nanPublishRequest.baseConfigs.discoveryMatchIndicator = NanMatchAlg::MATCH_NEVER;
+ nanPublishRequest.baseConfigs.useRssiThreshold = false;
+ nanPublishRequest.baseConfigs.disableDiscoveryTerminationIndication = false;
+ nanPublishRequest.baseConfigs.disableMatchExpirationIndication = true;
+ nanPublishRequest.baseConfigs.disableFollowupReceivedIndication = false;
+ nanPublishRequest.baseConfigs.securityConfig.securityType = NanDataPathSecurityType::OPEN;
+ nanPublishRequest.autoAcceptDataPathRequests = false;
+ nanPublishRequest.publishType = NanPublishType::UNSOLICITED;
+ nanPublishRequest.txType = NanTxType::BROADCAST;
+
+ status = wifi_nan_iface_->startPublishRequest(inputCmdId + 1, nanPublishRequest);
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_TRUE(status.isOk());
+
+ // Wait for a callback.
+ ASSERT_EQ(std::cv_status::no_timeout, wait(NOTIFY_START_PUBLISH_RESPONSE));
+ ASSERT_EQ(NOTIFY_START_PUBLISH_RESPONSE, callback_type_);
+ ASSERT_EQ(id_, inputCmdId + 1);
+ ASSERT_EQ(status_.status, NanStatusCode::SUCCESS);
+ }
+}
+
+/*
+ * RespondToDataPathIndicationRequest - Invalid Args
+ */
+TEST_P(WifiNanIfaceAidlTest, RespondToDataPathIndicationRequest_InvalidArgs) {
+ uint16_t inputCmdId = 10;
+ callback_type_ = INVALID;
+ NanRespondToDataPathIndicationRequest nanRespondToDataPathIndicationRequest = {};
+ nanRespondToDataPathIndicationRequest.ifaceName = "AwareInterfaceNameTooLong";
+ auto status = wifi_nan_iface_->respondToDataPathIndicationRequest(
+ inputCmdId, nanRespondToDataPathIndicationRequest);
+
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_EQ(status.getServiceSpecificError(),
+ static_cast<int32_t>(WifiStatusCode::ERROR_INVALID_ARGS));
+ }
+}
+
+/*
+ * InitiateDataPathRequest - Invalid Args
+ */
+TEST_P(WifiNanIfaceAidlTest, InitiateDataPathRequest_InvalidArgs) {
+ uint16_t inputCmdId = 10;
+ callback_type_ = INVALID;
+ NanInitiateDataPathRequest nanInitiateDataPathRequest = {};
+ nanInitiateDataPathRequest.ifaceName = "AwareInterfaceNameTooLong";
+ auto status = wifi_nan_iface_->initiateDataPathRequest(inputCmdId, nanInitiateDataPathRequest);
+
+ if (!checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ ASSERT_EQ(status.getServiceSpecificError(),
+ static_cast<int32_t>(WifiStatusCode::ERROR_INVALID_ARGS));
+ }
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(WifiNanIfaceAidlTest);
+INSTANTIATE_TEST_SUITE_P(WifiTest, WifiNanIfaceAidlTest,
+ testing::ValuesIn(android::getAidlHalInstanceNames(IWifi::descriptor)),
+ android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
+ android::ProcessState::self()->startThreadPool();
+ return RUN_ALL_TESTS();
+}
diff --git a/wifi/aidl/vts/functional/wifi_rtt_controller_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_rtt_controller_aidl_test.cpp
new file mode 100644
index 0000000..d763fe6
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_rtt_controller_aidl_test.cpp
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Staache 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 <vector>
+
+#include <VtsCoreUtil.h>
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/wifi/BnWifi.h>
+#include <aidl/android/hardware/wifi/BnWifiRttControllerEventCallback.h>
+#include <android/binder_manager.h>
+#include <android/binder_status.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::BnWifiRttControllerEventCallback;
+using aidl::android::hardware::wifi::IWifiRttController;
+using aidl::android::hardware::wifi::RttBw;
+using aidl::android::hardware::wifi::RttCapabilities;
+using aidl::android::hardware::wifi::RttConfig;
+using aidl::android::hardware::wifi::RttPeerType;
+using aidl::android::hardware::wifi::RttPreamble;
+using aidl::android::hardware::wifi::RttResponder;
+using aidl::android::hardware::wifi::RttResult;
+using aidl::android::hardware::wifi::RttType;
+using aidl::android::hardware::wifi::WifiChannelInfo;
+using aidl::android::hardware::wifi::WifiChannelWidthInMhz;
+using aidl::android::hardware::wifi::WifiStatusCode;
+
+class WifiRttControllerAidlTest : public testing::TestWithParam<std::string> {
+ public:
+ void SetUp() override {
+ if (!::testing::deviceSupportsFeature("android.hardware.wifi.rtt"))
+ GTEST_SKIP() << "Skipping this test since RTT is not supported.";
+ stopWifiService(getInstanceName());
+ wifi_rtt_controller_ = getWifiRttController();
+ ASSERT_NE(nullptr, wifi_rtt_controller_.get());
+
+ // Check RTT support before we run the test.
+ RttCapabilities caps = {};
+ auto status = wifi_rtt_controller_->getCapabilities(&caps);
+ if (checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED)) {
+ GTEST_SKIP() << "Skipping this test since RTT is not supported.";
+ }
+ }
+
+ void TearDown() override { stopWifiService(getInstanceName()); }
+
+ protected:
+ std::shared_ptr<IWifiRttController> getWifiRttController() {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(getInstanceName());
+ EXPECT_NE(nullptr, wifi_chip.get());
+
+ std::shared_ptr<IWifiStaIface> wifi_sta_iface = getWifiStaIface(getInstanceName());
+ EXPECT_NE(nullptr, wifi_sta_iface.get());
+
+ std::shared_ptr<IWifiRttController> rtt_controller;
+ EXPECT_TRUE(wifi_chip->createRttController(wifi_sta_iface, &rtt_controller).isOk());
+ EXPECT_NE(nullptr, rtt_controller.get());
+ return rtt_controller;
+ }
+
+ std::shared_ptr<IWifiRttController> wifi_rtt_controller_;
+
+ private:
+ const char* getInstanceName() { return GetParam().c_str(); }
+};
+
+class WifiRttControllerEventCallback : public BnWifiRttControllerEventCallback {
+ public:
+ WifiRttControllerEventCallback() = default;
+
+ ::ndk::ScopedAStatus onResults(int /* cmdId */,
+ const std::vector<RttResult>& /* results */) override {
+ return ndk::ScopedAStatus::ok();
+ }
+};
+
+/*
+ * RegisterEventCallback
+ *
+ * Note: it is not feasible to test the invocation of the callback function,
+ * since events are triggered internally in the HAL implementation and cannot be
+ * triggered from the test case.
+ */
+TEST_P(WifiRttControllerAidlTest, RegisterEventCallback) {
+ std::shared_ptr<WifiRttControllerEventCallback> callback =
+ ndk::SharedRefBase::make<WifiRttControllerEventCallback>();
+ ASSERT_NE(nullptr, callback.get());
+ EXPECT_TRUE(wifi_rtt_controller_->registerEventCallback(callback).isOk());
+}
+
+/*
+ * GetCapabilities
+ */
+TEST_P(WifiRttControllerAidlTest, GetCapabilities) {
+ RttCapabilities caps = {};
+ EXPECT_TRUE(wifi_rtt_controller_->getCapabilities(&caps).isOk());
+}
+
+/*
+ * GetResponderInfo
+ */
+TEST_P(WifiRttControllerAidlTest, GetResponderInfo) {
+ RttResponder responder = {};
+ EXPECT_TRUE(wifi_rtt_controller_->getResponderInfo(&responder).isOk());
+}
+
+/*
+ * EnableResponder
+ */
+TEST_P(WifiRttControllerAidlTest, EnableResponder) {
+ int cmdId = 55;
+ WifiChannelInfo channelInfo;
+ channelInfo.width = WifiChannelWidthInMhz::WIDTH_80;
+ channelInfo.centerFreq = 5660;
+ channelInfo.centerFreq0 = 5660;
+ channelInfo.centerFreq1 = 0;
+
+ RttResponder responder = {};
+ EXPECT_TRUE(wifi_rtt_controller_->getResponderInfo(&responder).isOk());
+ EXPECT_TRUE(wifi_rtt_controller_->enableResponder(cmdId, channelInfo, 10, responder).isOk());
+}
+
+/*
+ * Request2SidedRangeMeasurement
+ * Tests the two sided ranging - 802.11mc FTM protocol.
+ */
+TEST_P(WifiRttControllerAidlTest, Request2SidedRangeMeasurement) {
+ RttCapabilities caps = {};
+ EXPECT_TRUE(wifi_rtt_controller_->getCapabilities(&caps).isOk());
+ if (!caps.rttFtmSupported) {
+ GTEST_SKIP() << "Skipping two sided RTT since driver/fw does not support";
+ }
+
+ RttConfig config;
+ config.addr = {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}};
+ config.type = RttType::TWO_SIDED;
+ config.peer = RttPeerType::AP;
+ config.channel.width = WifiChannelWidthInMhz::WIDTH_80;
+ config.channel.centerFreq = 5180;
+ config.channel.centerFreq0 = 5210;
+ config.channel.centerFreq1 = 0;
+ config.bw = RttBw::BW_20MHZ;
+ config.preamble = RttPreamble::HT;
+ config.mustRequestLci = false;
+ config.mustRequestLcr = false;
+ config.burstPeriod = 0;
+ config.numBurst = 0;
+ config.numFramesPerBurst = 8;
+ config.numRetriesPerRttFrame = 0;
+ config.numRetriesPerFtmr = 0;
+ config.burstDuration = 9;
+
+ int cmdId = 55;
+ std::vector<RttConfig> configs = {config};
+ EXPECT_TRUE(wifi_rtt_controller_->rangeRequest(cmdId, configs).isOk());
+
+ // Sleep for 2 seconds to wait for driver/firmware to complete RTT.
+ sleep(2);
+}
+
+/*
+ * RangeRequest
+ */
+TEST_P(WifiRttControllerAidlTest, RangeRequest) {
+ RttCapabilities caps = {};
+ EXPECT_TRUE(wifi_rtt_controller_->getCapabilities(&caps).isOk());
+ if (!caps.rttOneSidedSupported) {
+ GTEST_SKIP() << "Skipping one sided RTT since driver/fw does not support";
+ }
+
+ // Get the highest supported preamble.
+ int preamble = 1;
+ int caps_preamble_support = static_cast<int>(caps.preambleSupport);
+ caps_preamble_support >>= 1;
+ while (caps_preamble_support != 0) {
+ caps_preamble_support >>= 1;
+ preamble <<= 1;
+ }
+
+ RttConfig config;
+ config.addr = {{0x00, 0x01, 0x02, 0x03, 0x04, 0x05}};
+ config.type = RttType::ONE_SIDED;
+ config.peer = RttPeerType::AP;
+ config.channel.width = WifiChannelWidthInMhz::WIDTH_80;
+ config.channel.centerFreq = 5765;
+ config.channel.centerFreq0 = 5775;
+ config.channel.centerFreq1 = 0;
+ config.bw = RttBw::BW_80MHZ;
+ config.preamble = static_cast<RttPreamble>(preamble);
+ config.mustRequestLci = false;
+ config.mustRequestLcr = false;
+ config.burstPeriod = 0;
+ config.numBurst = 0;
+ config.numFramesPerBurst = 8;
+ config.numRetriesPerRttFrame = 3;
+ config.numRetriesPerFtmr = 3;
+ config.burstDuration = 9;
+
+ int cmdId = 55;
+ std::vector<RttConfig> configs = {config};
+ EXPECT_TRUE(wifi_rtt_controller_->rangeRequest(cmdId, configs).isOk());
+
+ // Sleep for 2 seconds to wait for driver/firmware to complete RTT.
+ sleep(2);
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(WifiRttControllerAidlTest);
+INSTANTIATE_TEST_SUITE_P(WifiTest, WifiRttControllerAidlTest,
+ testing::ValuesIn(android::getAidlHalInstanceNames(IWifi::descriptor)),
+ android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
+ android::ProcessState::self()->startThreadPool();
+ return RUN_ALL_TESTS();
+}
diff --git a/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp b/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp
new file mode 100644
index 0000000..ef7e274
--- /dev/null
+++ b/wifi/aidl/vts/functional/wifi_sta_iface_aidl_test.cpp
@@ -0,0 +1,282 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Staache 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 <vector>
+
+#include <VtsCoreUtil.h>
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <aidl/android/hardware/wifi/BnWifi.h>
+#include <android/binder_manager.h>
+#include <android/binder_status.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::IWifi;
+using aidl::android::hardware::wifi::IWifiStaIface;
+using aidl::android::hardware::wifi::MacAddress;
+using aidl::android::hardware::wifi::Ssid;
+using aidl::android::hardware::wifi::StaApfPacketFilterCapabilities;
+using aidl::android::hardware::wifi::StaBackgroundScanCapabilities;
+using aidl::android::hardware::wifi::StaLinkLayerStats;
+using aidl::android::hardware::wifi::StaRoamingCapabilities;
+using aidl::android::hardware::wifi::StaRoamingConfig;
+using aidl::android::hardware::wifi::StaRoamingState;
+using aidl::android::hardware::wifi::WifiBand;
+using aidl::android::hardware::wifi::WifiDebugRxPacketFateReport;
+using aidl::android::hardware::wifi::WifiDebugTxPacketFateReport;
+using aidl::android::hardware::wifi::WifiStatusCode;
+
+class WifiStaIfaceAidlTest : public testing::TestWithParam<std::string> {
+ public:
+ void SetUp() override {
+ stopWifiService(getInstanceName());
+ wifi_sta_iface_ = getWifiStaIface(getInstanceName());
+ ASSERT_NE(nullptr, wifi_sta_iface_.get());
+ }
+
+ void TearDown() override { stopWifiService(getInstanceName()); }
+
+ protected:
+ bool isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask expected) {
+ IWifiStaIface::StaIfaceCapabilityMask caps = {};
+ EXPECT_TRUE(wifi_sta_iface_->getCapabilities(&caps).isOk());
+ return static_cast<uint32_t>(caps) & static_cast<uint32_t>(expected);
+ }
+
+ ndk::ScopedAStatus createStaIface(std::shared_ptr<IWifiStaIface>* sta_iface) {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(getInstanceName());
+ EXPECT_NE(nullptr, wifi_chip.get());
+ return wifi_chip->createStaIface(sta_iface);
+ }
+
+ std::shared_ptr<IWifiStaIface> wifi_sta_iface_;
+
+ private:
+ const char* getInstanceName() { return GetParam().c_str(); }
+};
+
+/*
+ * GetFactoryMacAddress
+ * Ensures that calls to getFactoryMacAddress will retrieve a non-zero MAC.
+ */
+TEST_P(WifiStaIfaceAidlTest, GetFactoryMacAddress) {
+ std::array<uint8_t, 6> mac;
+ EXPECT_TRUE(wifi_sta_iface_->getFactoryMacAddress(&mac).isOk());
+ std::array<uint8_t, 6> all_zero_mac = {0, 0, 0, 0, 0, 0};
+ EXPECT_NE(mac, all_zero_mac);
+}
+
+/*
+ * GetCapabilities
+ */
+TEST_P(WifiStaIfaceAidlTest, GetCapabilities) {
+ IWifiStaIface::StaIfaceCapabilityMask caps = {};
+ EXPECT_TRUE(wifi_sta_iface_->getCapabilities(&caps).isOk());
+ EXPECT_NE(static_cast<int32_t>(caps), 0);
+}
+
+/*
+ * GetApfPacketFilterCapabilities
+ */
+TEST_P(WifiStaIfaceAidlTest, GetApfPacketFilterCapabilities) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::APF)) {
+ GTEST_SKIP() << "APF packet filter capabilities are not supported.";
+ }
+ StaApfPacketFilterCapabilities apf_caps = {};
+ EXPECT_TRUE(wifi_sta_iface_->getApfPacketFilterCapabilities(&apf_caps).isOk());
+}
+
+/*
+ * GetBackgroundScanCapabilities
+ */
+TEST_P(WifiStaIfaceAidlTest, GetBackgroundScanCapabilities) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::BACKGROUND_SCAN)) {
+ GTEST_SKIP() << "Background scan capabilities are not supported.";
+ }
+ StaBackgroundScanCapabilities caps = {};
+ EXPECT_TRUE(wifi_sta_iface_->getBackgroundScanCapabilities(&caps).isOk());
+}
+
+/*
+ * GetValidFrequenciesForBand
+ * Ensures that we can retrieve valid frequencies for the 2.4 GHz band.
+ */
+TEST_P(WifiStaIfaceAidlTest, GetValidFrequenciesForBand) {
+ std::vector<int> freqs;
+ EXPECT_TRUE(wifi_sta_iface_->getValidFrequenciesForBand(WifiBand::BAND_24GHZ, &freqs).isOk());
+ EXPECT_NE(freqs.size(), 0);
+}
+
+/*
+ * GetLinkLayerStats
+ * Ensures that calls to getLinkLayerStats will retrieve a non-empty
+ * StaLinkLayerStats after link layer stats collection is enabled.
+ */
+TEST_P(WifiStaIfaceAidlTest, GetLinkLayerStats) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::LINK_LAYER_STATS)) {
+ GTEST_SKIP() << "Skipping this test since link layer stats are not supported.";
+ }
+
+ // Enable link layer stats collection.
+ EXPECT_TRUE(wifi_sta_iface_->enableLinkLayerStatsCollection(true).isOk());
+
+ // Retrieve link layer stats.
+ StaLinkLayerStats link_layer_stats = {};
+ EXPECT_TRUE(wifi_sta_iface_->getLinkLayerStats(&link_layer_stats).isOk());
+ EXPECT_GT(link_layer_stats.timeStampInMs, 0);
+
+ // Try to create a 2nd iface. If successful, it should fill the duty cycle field.
+ std::shared_ptr<IWifiStaIface> iface;
+ auto status = createStaIface(&iface);
+ if (status.isOk()) {
+ EXPECT_GT(link_layer_stats.iface.timeSliceDutyCycleInPercent, 0);
+ }
+
+ // Disable link layer stats collection.
+ EXPECT_TRUE(wifi_sta_iface_->disableLinkLayerStatsCollection().isOk());
+}
+
+/*
+ * SetMacAddress
+ * Ensures that calls to setMacAddress will return successfully.
+ */
+TEST_P(WifiStaIfaceAidlTest, SetMacAddress) {
+ std::array<uint8_t, 6> mac = {0x12, 0x22, 0x33, 0x52, 0x10, 0x41};
+ EXPECT_TRUE(wifi_sta_iface_->setMacAddress(mac).isOk());
+}
+
+/*
+ * SetScanMode
+ */
+TEST_P(WifiStaIfaceAidlTest, SetScanMode) {
+ auto status = wifi_sta_iface_->setScanMode(true);
+ EXPECT_TRUE(status.isOk() || checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+
+ status = wifi_sta_iface_->setScanMode(false);
+ EXPECT_TRUE(status.isOk() || checkStatusCode(&status, WifiStatusCode::ERROR_NOT_SUPPORTED));
+}
+
+/*
+ * LinkLayerStatsCollection
+ */
+TEST_P(WifiStaIfaceAidlTest, LinkLayerStatsCollection) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::LINK_LAYER_STATS)) {
+ GTEST_SKIP() << "Link layer stats collection is not supported.";
+ }
+
+ // Enable link layer stats collection.
+ EXPECT_TRUE(wifi_sta_iface_->enableLinkLayerStatsCollection(true).isOk());
+
+ // Retrieve link layer stats.
+ StaLinkLayerStats link_layer_stats = {};
+ EXPECT_TRUE(wifi_sta_iface_->getLinkLayerStats(&link_layer_stats).isOk());
+
+ // Disable link layer stats collection.
+ EXPECT_TRUE(wifi_sta_iface_->disableLinkLayerStatsCollection().isOk());
+}
+
+/*
+ * RSSIMonitoring
+ * Ensures that calls to startRssiMonitoring and stopRssiMonitoring will fail
+ * if the device is not connected to an AP.
+ */
+TEST_P(WifiStaIfaceAidlTest, RSSIMonitoring) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::RSSI_MONITOR)) {
+ GTEST_SKIP() << "RSSI monitoring is not supported.";
+ }
+
+ const int cmd = 1;
+ const int maxRssi = -50;
+ const int minRssi = -90;
+ // Expected to fail because device is not connected to an AP.
+ EXPECT_FALSE(wifi_sta_iface_->startRssiMonitoring(cmd, maxRssi, minRssi).isOk());
+ EXPECT_FALSE(wifi_sta_iface_->stopRssiMonitoring(cmd).isOk());
+}
+
+/*
+ * RoamingControl
+ */
+TEST_P(WifiStaIfaceAidlTest, RoamingControl) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::CONTROL_ROAMING)) {
+ GTEST_SKIP() << "Roaming control is not supported.";
+ }
+
+ // Retrieve roaming capabilities.
+ StaRoamingCapabilities caps = {};
+ EXPECT_TRUE(wifi_sta_iface_->getRoamingCapabilities(&caps).isOk());
+
+ // Set up roaming configuration based on roaming capabilities.
+ StaRoamingConfig roaming_config = {};
+ if (caps.maxBlocklistSize > 0) {
+ MacAddress block_list_entry;
+ block_list_entry.data = std::array<uint8_t, 6>{{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}};
+ roaming_config.bssidBlocklist = {block_list_entry};
+ }
+ if (caps.maxAllowlistSize > 0) {
+ Ssid allow_list_entry = {};
+ allow_list_entry.data = std::array<uint8_t, 32>{{0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC}};
+ roaming_config.ssidAllowlist = {allow_list_entry};
+ }
+
+ // Configure roaming.
+ EXPECT_TRUE(wifi_sta_iface_->configureRoaming(roaming_config).isOk());
+
+ // Enable roaming.
+ EXPECT_TRUE(wifi_sta_iface_->setRoamingState(StaRoamingState::ENABLED).isOk());
+}
+
+/*
+ * EnableNDOffload
+ */
+TEST_P(WifiStaIfaceAidlTest, EnableNDOffload) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::ND_OFFLOAD)) {
+ GTEST_SKIP() << "ND offload is not supported.";
+ }
+ EXPECT_TRUE(wifi_sta_iface_->enableNdOffload(true).isOk());
+}
+
+/*
+ * PacketFateMonitoring
+ */
+TEST_P(WifiStaIfaceAidlTest, PacketFateMonitoring) {
+ if (!isCapabilitySupported(IWifiStaIface::StaIfaceCapabilityMask::DEBUG_PACKET_FATE)) {
+ GTEST_SKIP() << "Packet fate monitoring is not supported.";
+ }
+
+ // Start packet fate monitoring.
+ EXPECT_TRUE(wifi_sta_iface_->startDebugPacketFateMonitoring().isOk());
+
+ // Retrieve packets.
+ std::vector<WifiDebugRxPacketFateReport> rx_reports;
+ std::vector<WifiDebugTxPacketFateReport> tx_reports;
+ EXPECT_TRUE(wifi_sta_iface_->getDebugRxPacketFates(&rx_reports).isOk());
+ EXPECT_TRUE(wifi_sta_iface_->getDebugTxPacketFates(&tx_reports).isOk());
+}
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(WifiStaIfaceAidlTest);
+INSTANTIATE_TEST_SUITE_P(WifiTest, WifiStaIfaceAidlTest,
+ testing::ValuesIn(android::getAidlHalInstanceNames(IWifi::descriptor)),
+ android::PrintInstanceNameToString);
+
+int main(int argc, char** argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
+ android::ProcessState::self()->startThreadPool();
+ return RUN_ALL_TESTS();
+}
diff --git a/wifi/apex/Android.bp b/wifi/apex/Android.bp
index 0afb96b..e1fefb9 100644
--- a/wifi/apex/Android.bp
+++ b/wifi/apex/Android.bp
@@ -15,7 +15,7 @@
genrule {
name: "gen-android.hardware.wifi.rc",
- srcs: [":default-android.hardware.wifi@1.0-service.rc"],
+ srcs: [":default-android.hardware.wifi-service.rc"],
out: ["com.android.hardware.wifi-service.rc"],
cmd: "sed -e 's@/vendor/bin/@/apex/com.android.hardware.wifi/bin/@' $(in) > $(out)",
}
@@ -28,7 +28,7 @@
prebuilt_etc {
name: "com.android.hardware.wifi.xml",
- src: ":default-android.hardware.wifi@1.0-service.xml",
+ src: ":default-android.hardware.wifi-service.xml",
installable: false,
}
@@ -43,13 +43,13 @@
updatable: false,
soc_specific: true,
binaries: [
- "android.hardware.wifi@1.0-service",
+ "android.hardware.wifi-service",
],
prebuilts: [
"com.android.hardware.wifi.rc",
"com.android.hardware.wifi.xml",
],
overrides: [
- "android.hardware.wifi@1.0-service",
+ "android.hardware.wifi-service",
],
}
diff --git a/wifi/apex/file_contexts b/wifi/apex/file_contexts
index 812d51d..6368729 100644
--- a/wifi/apex/file_contexts
+++ b/wifi/apex/file_contexts
@@ -1,3 +1,3 @@
(/.*)? u:object_r:vendor_file:s0
-/bin/hw/android\.hardware\.wifi@1.0-service u:object_r:hal_wifi_default_exec:s0
+/bin/hw/android\.hardware\.wifi-service u:object_r:hal_wifi_default_exec:s0
diff --git a/wifi/hostapd/aidl/vts/functional/Android.bp b/wifi/hostapd/aidl/vts/functional/Android.bp
index e61d397..a9fdec8 100644
--- a/wifi/hostapd/aidl/vts/functional/Android.bp
+++ b/wifi/hostapd/aidl/vts/functional/Android.bp
@@ -20,20 +20,10 @@
"libvndksupport",
],
static_libs: [
+ "android.hardware.wifi-V1-ndk",
"android.hardware.wifi.hostapd-V1-ndk",
- "VtsHalWifiV1_0TargetTestUtil",
- "VtsHalWifiV1_5TargetTestUtil",
- "VtsHalWifiHostapdV1_0TargetTestUtil",
- "android.hardware.wifi.hostapd@1.0",
- "android.hardware.wifi.hostapd@1.1",
- "android.hardware.wifi.hostapd@1.2",
- "android.hardware.wifi.hostapd@1.3",
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
+ "libwifi-system-iface",
+ "VtsHalWifiTargetTestUtil",
],
test_suites: [
"general-tests",
diff --git a/wifi/hostapd/aidl/vts/functional/VtsHalHostapdTargetTest.cpp b/wifi/hostapd/aidl/vts/functional/VtsHalHostapdTargetTest.cpp
index bd2649f..65ffa7b 100644
--- a/wifi/hostapd/aidl/vts/functional/VtsHalHostapdTargetTest.cpp
+++ b/wifi/hostapd/aidl/vts/functional/VtsHalHostapdTargetTest.cpp
@@ -13,8 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-#include <android/hardware/wifi/1.0/IWifi.h>
-#include <android/hardware/wifi/hostapd/1.3/IHostapd.h>
+#include <aidl/android/hardware/wifi/IWifi.h>
#include <VtsCoreUtil.h>
#include <aidl/Gtest.h>
@@ -24,12 +23,11 @@
#include <android/binder_manager.h>
#include <binder/IServiceManager.h>
#include <binder/ProcessState.h>
-#include <hidl/ServiceManagement.h>
-#include <hostapd_hidl_call_util.h>
-#include <hostapd_hidl_test_utils.h>
-#include <wifi_hidl_test_utils.h>
-#include <wifi_hidl_test_utils_1_5.h>
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::IWifi;
+using aidl::android::hardware::wifi::IWifiApIface;
using aidl::android::hardware::wifi::hostapd::BandMask;
using aidl::android::hardware::wifi::hostapd::BnHostapdCallback;
using aidl::android::hardware::wifi::hostapd::ChannelBandwidth;
@@ -44,6 +42,8 @@
using android::ProcessState;
namespace {
+const std::string kWifiInstanceNameStr = std::string() + IWifi::descriptor + "/default";
+const char* kWifiInstanceName = kWifiInstanceNameStr.c_str();
const unsigned char kNwSsid[] = {'t', 'e', 's', 't', '1', '2', '3', '4', '5'};
const std::string kPassphrase = "test12345";
const std::string kInvalidMinPassphrase = "test";
@@ -75,17 +75,13 @@
"/system/bin/cmd wifi get-softap-supported-features",
"wifi_softap_wpa3_sae_supported");
isBridgedSupport = testing::checkSubstringInCommandOutput(
- "/system/bin/cmd wifi get-softap-supported-features",
- "wifi_softap_bridged_ap_supported");
- const std::vector<std::string> instances = android::hardware::getAllHalInstanceNames(
- ::android::hardware::wifi::V1_0::IWifi::descriptor);
- EXPECT_NE(0, instances.size());
- wifiInstanceName = instances[0];
+ "/system/bin/cmd wifi get-softap-supported-features",
+ "wifi_softap_bridged_ap_supported");
}
virtual void TearDown() override {
- if (getWifi(wifiInstanceName) != nullptr) {
- stopWifi(wifiInstanceName);
+ if (getWifi(kWifiInstanceName) != nullptr) {
+ stopWifiService(kWifiInstanceName);
}
hostapd->terminate();
// Wait 3 seconds to allow terminate to complete
@@ -93,24 +89,23 @@
}
std::shared_ptr<IHostapd> hostapd;
- std::string wifiInstanceName;
bool isAcsSupport;
bool isWpa3SaeSupport;
bool isBridgedSupport;
std::string setupApIfaceAndGetName(bool isBridged) {
- android::sp<::android::hardware::wifi::V1_0::IWifiApIface> wifi_ap_iface;
+ std::shared_ptr<IWifiApIface> wifi_ap_iface;
if (isBridged) {
- wifi_ap_iface = getBridgedWifiApIface_1_5(wifiInstanceName);
+ wifi_ap_iface = getBridgedWifiApIface(kWifiInstanceName);
} else {
- wifi_ap_iface = getWifiApIface_1_5(wifiInstanceName);
+ wifi_ap_iface = getWifiApIface(kWifiInstanceName);
}
EXPECT_NE(nullptr, wifi_ap_iface.get());
- const auto& status_and_name = HIDL_INVOKE(wifi_ap_iface, getName);
- EXPECT_EQ(android::hardware::wifi::V1_0::WifiStatusCode::SUCCESS,
- status_and_name.first.code);
- return status_and_name.second;
+ std::string ap_iface_name;
+ auto status = wifi_ap_iface->getName(&ap_iface_name);
+ EXPECT_TRUE(status.isOk());
+ return ap_iface_name;
}
IfaceParams getIfaceParamsWithoutAcs(std::string iface_name) {
diff --git a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl
index 25a09b4..c7dd584 100644
--- a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl
+++ b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl
@@ -63,4 +63,5 @@
oneway void onWpsEventSuccess();
oneway void onQosPolicyReset();
oneway void onQosPolicyRequest(in int qosPolicyRequestId, in android.hardware.wifi.supplicant.QosPolicyData[] qosPolicyData);
+ oneway void onStateChangedWithAkm(in android.hardware.wifi.supplicant.StaIfaceCallbackState newState, in byte[] bssid, in int id, in byte[] ssid, in boolean filsHlpSent, in android.hardware.wifi.supplicant.KeyMgmtMask keyMgmtMask);
}
diff --git a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl
index 0b3cb81..0bdec34 100644
--- a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl
+++ b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl
@@ -127,6 +127,7 @@
void setWepKey(in int keyIdx, in byte[] wepKey);
void setWepTxKeyIdx(in int keyIdx);
void setRoamingConsortiumSelection(in byte[] selectedRcoi);
+ void setMinimumTlsVersionEapPhase1Param(android.hardware.wifi.supplicant.TlsVersion tlsVersion);
const int SSID_MAX_LEN_IN_BYTES = 32;
const int PSK_PASSPHRASE_MIN_LEN_IN_BYTES = 8;
const int PSK_PASSPHRASE_MAX_LEN_IN_BYTES = 63;
diff --git a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/TlsVersion.aidl b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/TlsVersion.aidl
new file mode 100644
index 0000000..22a374f
--- /dev/null
+++ b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/TlsVersion.aidl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE. //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+// the interface (from the latest frozen version), the build system will
+// prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.wifi.supplicant;
+@Backing(type="int") @VintfStability
+enum TlsVersion {
+ TLS_V1_0 = 0,
+ TLS_V1_1 = 1,
+ TLS_V1_2 = 2,
+ TLS_V1_3 = 3,
+}
diff --git a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl
index 9a0a924..32e1510 100644
--- a/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl
+++ b/wifi/supplicant/aidl/aidl_api/android.hardware.wifi.supplicant/current/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl
@@ -39,4 +39,6 @@
SAE_PK = 4,
WFD_R2 = 8,
TRUST_ON_FIRST_USE = 16,
+ SET_TLS_MINIMUM_VERSION = 32,
+ TLS_V1_3 = 64,
}
diff --git a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl
index 0730a8c..c7961fa 100644
--- a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl
+++ b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaIfaceCallback.aidl
@@ -27,6 +27,7 @@
import android.hardware.wifi.supplicant.DppFailureCode;
import android.hardware.wifi.supplicant.DppProgressCode;
import android.hardware.wifi.supplicant.Hs20AnqpData;
+import android.hardware.wifi.supplicant.KeyMgmtMask;
import android.hardware.wifi.supplicant.OsuMethod;
import android.hardware.wifi.supplicant.QosPolicyData;
import android.hardware.wifi.supplicant.StaIfaceCallbackState;
@@ -252,6 +253,8 @@
* event is triggered by a particular network, the |SupplicantNetworkId|,
* |ssid|, |bssid| parameters must indicate the parameters of the network/AP
* which caused this state transition.
+ * <p>
+ * This callback is deprecated from AIDL v2, newer HAL should call onStateChangedWithAkm().
*
* @param newState New State of the interface. This must be one of the |State|
* values above.
@@ -303,4 +306,27 @@
* @param qosPolicyData QoS policies info requested by the AP.
*/
void onQosPolicyRequest(in int qosPolicyRequestId, in QosPolicyData[] qosPolicyData);
+
+ /**
+ * Used to indicate a state change event on this particular iface. If this
+ * event is triggered by a particular network, the |id|,
+ * |ssid|, |bssid| parameters must indicate the parameters of the network/AP
+ * which caused this state transition.
+ *
+ * @param newState New State of the interface. This must be one of the
+ * |StaIfaceCallbackState| values above.
+ * @param bssid BSSID of the corresponding AP which caused this state
+ * change event. This must be zero'ed if this event is not
+ * specific to a particular network.
+ * @param id ID of the corresponding network which caused this
+ * state change event. This must be invalid (-1) if this
+ * event is not specific to a particular network.
+ * @param ssid SSID of the corresponding network which caused this state
+ * change event. This must be empty if this event is not specific
+ * to a particular network.
+ * @param filsHlpSent Whether FILS HLP IEs were included in this association.
+ * @param keyMgmtMask current used key mgmt mask.
+ */
+ void onStateChangedWithAkm(in StaIfaceCallbackState newState, in byte[] bssid, in int id,
+ in byte[] ssid, in boolean filsHlpSent, in KeyMgmtMask keyMgmtMask);
}
diff --git a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl
index 267f1e8..44512a9 100644
--- a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl
+++ b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/ISupplicantStaNetwork.aidl
@@ -31,6 +31,7 @@
import android.hardware.wifi.supplicant.PairwiseCipherMask;
import android.hardware.wifi.supplicant.ProtoMask;
import android.hardware.wifi.supplicant.SaeH2eMode;
+import android.hardware.wifi.supplicant.TlsVersion;
/**
* Interface exposed by the supplicant for each station mode network
@@ -1118,4 +1119,16 @@
* |SupplicantStatusCode.FAILURE_NETWORK_INVALID|
*/
void setRoamingConsortiumSelection(in byte[] selectedRcoi);
+
+ /**
+ * Set the minimum TLS version for EAP phase1 param.
+ *
+ * @param tlsVersion the TLS version
+ *
+ * @throws ServiceSpecificException with one of the following values:
+ * |SupplicantStatusCode.FAILURE_ARGS_INVALID|,
+ * |SupplicantStatusCode.FAILURE_UNKNOWN|,
+ * |SupplicantStatusCode.FAILURE_NETWORK_INVALID|
+ */
+ void setMinimumTlsVersionEapPhase1Param(TlsVersion tlsVersion);
}
diff --git a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/TlsVersion.aidl b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/TlsVersion.aidl
new file mode 100644
index 0000000..316e881
--- /dev/null
+++ b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/TlsVersion.aidl
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+package android.hardware.wifi.supplicant;
+
+/**
+ * TlsVersion: TLS version.
+ */
+@VintfStability
+@Backing(type="int")
+enum TlsVersion {
+ TLS_V1_0,
+ TLS_V1_1,
+ TLS_V1_2,
+ TLS_V1_3,
+}
diff --git a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl
index 08006cf..a9434c4 100644
--- a/wifi/supplicant/aidl/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl
+++ b/wifi/supplicant/aidl/android/hardware/wifi/supplicant/WpaDriverCapabilitiesMask.aidl
@@ -42,4 +42,12 @@
* Trust On First Use
*/
TRUST_ON_FIRST_USE = 1 << 4,
+ /**
+ * TLS minimum version
+ */
+ SET_TLS_MINIMUM_VERSION = 1 << 5,
+ /**
+ * TLS V1.3
+ */
+ TLS_V1_3 = 1 << 6,
}
diff --git a/wifi/supplicant/aidl/vts/functional/Android.bp b/wifi/supplicant/aidl/vts/functional/Android.bp
index b959c75..937fdc7 100644
--- a/wifi/supplicant/aidl/vts/functional/Android.bp
+++ b/wifi/supplicant/aidl/vts/functional/Android.bp
@@ -36,20 +36,11 @@
"libvndksupport",
],
static_libs: [
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi.supplicant@1.0",
- "android.hardware.wifi.supplicant@1.1",
+ "android.hardware.wifi-V1-ndk",
"android.hardware.wifi.supplicant-V2-ndk",
"libwifi-system",
"libwifi-system-iface",
- "VtsHalWifiV1_0TargetTestUtil",
- "VtsHalWifiV1_5TargetTestUtil",
- "VtsHalWifiSupplicantV1_0TargetTestUtil",
+ "VtsHalWifiTargetTestUtil",
],
test_suites: [
"general-tests",
@@ -70,20 +61,11 @@
"libvndksupport",
],
static_libs: [
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi.supplicant@1.0",
- "android.hardware.wifi.supplicant@1.1",
+ "android.hardware.wifi-V1-ndk",
"android.hardware.wifi.supplicant-V2-ndk",
"libwifi-system",
"libwifi-system-iface",
- "VtsHalWifiV1_0TargetTestUtil",
- "VtsHalWifiV1_5TargetTestUtil",
- "VtsHalWifiSupplicantV1_0TargetTestUtil",
+ "VtsHalWifiTargetTestUtil",
],
test_suites: [
"general-tests",
@@ -104,20 +86,11 @@
"libvndksupport",
],
static_libs: [
- "android.hardware.wifi@1.0",
- "android.hardware.wifi@1.1",
- "android.hardware.wifi@1.2",
- "android.hardware.wifi@1.3",
- "android.hardware.wifi@1.4",
- "android.hardware.wifi@1.5",
- "android.hardware.wifi.supplicant@1.0",
- "android.hardware.wifi.supplicant@1.1",
+ "android.hardware.wifi-V1-ndk",
"android.hardware.wifi.supplicant-V2-ndk",
"libwifi-system",
"libwifi-system-iface",
- "VtsHalWifiV1_0TargetTestUtil",
- "VtsHalWifiV1_5TargetTestUtil",
- "VtsHalWifiSupplicantV1_0TargetTestUtil",
+ "VtsHalWifiTargetTestUtil",
],
test_suites: [
"general-tests",
diff --git a/wifi/supplicant/aidl/vts/functional/supplicant_sta_iface_aidl_test.cpp b/wifi/supplicant/aidl/vts/functional/supplicant_sta_iface_aidl_test.cpp
index 272a427..d57f539 100644
--- a/wifi/supplicant/aidl/vts/functional/supplicant_sta_iface_aidl_test.cpp
+++ b/wifi/supplicant/aidl/vts/functional/supplicant_sta_iface_aidl_test.cpp
@@ -206,6 +206,13 @@
QosPolicyData /* qosPolicyData */>&) override {
return ndk::ScopedAStatus::ok();
}
+ ::ndk::ScopedAStatus onStateChangedWithAkm(
+ ::aidl::android::hardware::wifi::supplicant::StaIfaceCallbackState /* newState */,
+ const std::vector<uint8_t>& /* bssid */, int32_t /* id */,
+ const std::vector<uint8_t>& /* ssid */, bool /* filsHlpSent */,
+ ::aidl::android::hardware::wifi::supplicant::KeyMgmtMask /* keyMgmtMask*/) override {
+ return ndk::ScopedAStatus::ok();
+ }
};
class SupplicantStaIfaceAidlTest : public testing::TestWithParam<std::string> {
diff --git a/wifi/supplicant/aidl/vts/functional/supplicant_sta_network_aidl_test.cpp b/wifi/supplicant/aidl/vts/functional/supplicant_sta_network_aidl_test.cpp
index b3f70da..e5d976c 100644
--- a/wifi/supplicant/aidl/vts/functional/supplicant_sta_network_aidl_test.cpp
+++ b/wifi/supplicant/aidl/vts/functional/supplicant_sta_network_aidl_test.cpp
@@ -19,6 +19,7 @@
#include <aidl/Vintf.h>
#include <aidl/android/hardware/wifi/supplicant/BnSupplicant.h>
#include <aidl/android/hardware/wifi/supplicant/BnSupplicantStaNetworkCallback.h>
+#include <aidl/android/hardware/wifi/supplicant/TlsVersion.h>
#include <android/binder_manager.h>
#include <android/binder_status.h>
#include <binder/IServiceManager.h>
@@ -51,6 +52,7 @@
using aidl::android::hardware::wifi::supplicant::PairwiseCipherMask;
using aidl::android::hardware::wifi::supplicant::ProtoMask;
using aidl::android::hardware::wifi::supplicant::SaeH2eMode;
+using aidl::android::hardware::wifi::supplicant::TlsVersion;
using aidl::android::hardware::wifi::supplicant::TransitionDisableIndication;
using aidl::android::hardware::wifi::supplicant::WpaDriverCapabilitiesMask;
using android::ProcessState;
@@ -791,6 +793,13 @@
EXPECT_TRUE(sta_network_->setRoamingConsortiumSelection(testSelection).isOk());
}
+/*
+ * SetMinimumTlsVersionEapPhase1Param
+ */
+TEST_P(SupplicantStaNetworkAidlTest, SetMinimumTlsVersionEapPhase1Param) {
+ EXPECT_TRUE(sta_network_->setMinimumTlsVersionEapPhase1Param(TlsVersion::TLS_V1_3).isOk());
+}
+
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SupplicantStaNetworkAidlTest);
INSTANTIATE_TEST_SUITE_P(Supplicant, SupplicantStaNetworkAidlTest,
testing::ValuesIn(android::getAidlHalInstanceNames(
diff --git a/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h b/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h
index 31042a2..740dc9f 100644
--- a/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h
+++ b/wifi/supplicant/aidl/vts/functional/supplicant_test_utils.h
@@ -14,16 +14,18 @@
* limitations under the License.
*/
-#ifndef SUPPLICANT_TEST_UTILS_H
-#define SUPPLICANT_TEST_UTILS_H
+#pragma once
#include <VtsCoreUtil.h>
+#include <aidl/android/hardware/wifi/IWifi.h>
#include <android-base/logging.h>
-#include <android/hardware/wifi/1.0/IWifi.h>
-#include <hidl/ServiceManagement.h>
-#include <supplicant_hidl_test_utils.h>
#include <wifi_system/supplicant_manager.h>
+#include "wifi_aidl_test_utils.h"
+
+using aidl::android::hardware::wifi::IfaceConcurrencyType;
+using aidl::android::hardware::wifi::IWifi;
+using aidl::android::hardware::wifi::IWifiChip;
using aidl::android::hardware::wifi::supplicant::IfaceInfo;
using aidl::android::hardware::wifi::supplicant::ISupplicant;
using aidl::android::hardware::wifi::supplicant::ISupplicantP2pIface;
@@ -31,6 +33,90 @@
using aidl::android::hardware::wifi::supplicant::KeyMgmtMask;
using android::wifi_system::SupplicantManager;
+const std::string kWifiInstanceName = std::string() + IWifi::descriptor + "/default";
+
+// Initialize the driver and firmware to STA mode using the vendor HAL.
+void initializeDriverAndFirmware(const std::string& wifi_instance_name) {
+ // Skip if wifi instance is not set.
+ if (wifi_instance_name == "") {
+ return;
+ }
+ if (getWifi(wifi_instance_name.c_str()) != nullptr) {
+ std::shared_ptr<IWifiChip> wifi_chip = getWifiChip(wifi_instance_name.c_str());
+ int mode_id;
+ EXPECT_TRUE(configureChipToSupportConcurrencyType(wifi_chip, IfaceConcurrencyType::STA,
+ &mode_id));
+ } else {
+ LOG(WARNING) << __func__ << ": Vendor HAL not supported";
+ }
+}
+
+// Deinitialize the driver and firmware using the vendor HAL.
+void deInitializeDriverAndFirmware(const std::string& wifi_instance_name) {
+ // Skip if wifi instance is not set.
+ if (wifi_instance_name == "") {
+ return;
+ }
+ if (getWifi(wifi_instance_name.c_str()) != nullptr) {
+ stopWifiService(wifi_instance_name.c_str());
+ } else {
+ LOG(WARNING) << __func__ << ": Vendor HAL not supported";
+ }
+}
+
+bool waitForSupplicantState(bool is_running) {
+ SupplicantManager supplicant_manager;
+ int count = 50; /* wait at most 5 seconds for completion */
+ while (count-- > 0) {
+ if (supplicant_manager.IsSupplicantRunning() == is_running) {
+ return true;
+ }
+ usleep(100000);
+ }
+ LOG(ERROR) << "Supplicant not " << is_running ? "running" : "stopped";
+ return false;
+}
+
+bool waitForSupplicantStart() {
+ return waitForSupplicantState(true);
+}
+
+bool waitForSupplicantStop() {
+ return waitForSupplicantState(false);
+}
+
+bool waitForWifiHalStop(const std::string& wifi_instance_name) {
+ std::shared_ptr<IWifi> wifi = getWifi(wifi_instance_name.c_str());
+ int count = 50; /* wait at most 5 seconds for completion */
+ while (count-- > 0) {
+ if (wifi != nullptr) {
+ bool started = false;
+ auto status = wifi->isStarted(&started);
+ if (status.isOk() && !started) {
+ return true;
+ }
+ }
+ usleep(100000);
+ wifi = getWifi(wifi_instance_name.c_str());
+ }
+ LOG(ERROR) << "Wifi HAL was not stopped";
+ return false;
+}
+
+bool waitForFrameworkReady() {
+ int waitCount = 15;
+ do {
+ // Check whether package service is ready or not.
+ if (!testing::checkSubstringInCommandOutput("/system/bin/service check package",
+ ": not found")) {
+ return true;
+ }
+ LOG(INFO) << "Framework is not ready";
+ sleep(1);
+ } while (waitCount-- > 0);
+ return false;
+}
+
std::string getStaIfaceName() {
std::array<char, PROPERTY_VALUE_MAX> buffer;
property_get("wifi.interface", buffer.data(), "wlan0");
@@ -43,14 +129,6 @@
return std::string(buffer.data());
}
-std::string getWifiInstanceName() {
- const std::vector<std::string> instances =
- android::hardware::getAllHalInstanceNames(
- ::android::hardware::wifi::V1_0::IWifi::descriptor);
- EXPECT_NE(0, instances.size());
- return instances.size() != 0 ? instances[0] : "";
-}
-
bool keyMgmtSupported(std::shared_ptr<ISupplicantStaIface> iface,
KeyMgmtMask expected) {
KeyMgmtMask caps;
@@ -68,17 +146,33 @@
}
void startSupplicant() {
- initializeDriverAndFirmware(getWifiInstanceName());
+ initializeDriverAndFirmware(kWifiInstanceName);
SupplicantManager supplicant_manager;
ASSERT_TRUE(supplicant_manager.StartSupplicant());
ASSERT_TRUE(supplicant_manager.IsSupplicantRunning());
}
-// Wrapper around the implementation in supplicant_hidl_test_util.
-void stopSupplicantService() { stopSupplicant(getWifiInstanceName()); }
+void stopSupplicantService() {
+ SupplicantManager supplicant_manager;
+ ASSERT_TRUE(supplicant_manager.StopSupplicant());
+ deInitializeDriverAndFirmware(kWifiInstanceName);
+ ASSERT_FALSE(supplicant_manager.IsSupplicantRunning());
+}
+
+bool startWifiFramework() {
+ std::system("svc wifi enable");
+ std::system("cmd wifi set-scan-always-available enabled");
+ return waitForSupplicantStart(); // wait for wifi to start.
+}
+
+bool stopWifiFramework(const std::string& wifi_instance_name) {
+ std::system("svc wifi disable");
+ std::system("cmd wifi set-scan-always-available disabled");
+ return waitForSupplicantStop() && waitForWifiHalStop(wifi_instance_name);
+}
void initializeService() {
- ASSERT_TRUE(stopWifiFramework(getWifiInstanceName()));
+ ASSERT_TRUE(stopWifiFramework(kWifiInstanceName));
std::system("/system/bin/start");
ASSERT_TRUE(waitForFrameworkReady());
stopSupplicantService();
@@ -106,5 +200,3 @@
}
return supplicant;
}
-
-#endif // SUPPLICANT_TEST_UTILS_H
\ No newline at end of file