blob: 5de206bee24076c5f71cd17900e04df1eb1a68cf [file] [log] [blame]
Yu Shan726d51a2022-02-22 17:37:21 -08001/*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "VtsHalAutomotiveVehicle"
18
19#include <IVhalClient.h>
20#include <VehicleHalTypes.h>
21#include <VehicleUtils.h>
22#include <aidl/Gtest.h>
23#include <aidl/Vintf.h>
24#include <aidl/android/hardware/automotive/vehicle/IVehicle.h>
25#include <android-base/stringprintf.h>
26#include <android-base/thread_annotations.h>
27#include <android/binder_process.h>
28#include <gtest/gtest.h>
29#include <hidl/GtestPrinter.h>
30#include <hidl/ServiceManagement.h>
31#include <inttypes.h>
32#include <utils/Log.h>
Yu Shan4569ef52022-03-18 14:34:25 -070033#include <utils/SystemClock.h>
Yu Shan726d51a2022-02-22 17:37:21 -080034
35#include <chrono>
36#include <mutex>
37#include <unordered_map>
38#include <unordered_set>
39#include <vector>
40
41using ::aidl::android::hardware::automotive::vehicle::IVehicle;
42using ::aidl::android::hardware::automotive::vehicle::StatusCode;
43using ::aidl::android::hardware::automotive::vehicle::SubscribeOptions;
44using ::aidl::android::hardware::automotive::vehicle::VehicleArea;
45using ::aidl::android::hardware::automotive::vehicle::VehicleProperty;
46using ::aidl::android::hardware::automotive::vehicle::VehiclePropertyAccess;
47using ::aidl::android::hardware::automotive::vehicle::VehiclePropertyType;
48using ::android::getAidlHalInstanceNames;
49using ::android::base::ScopedLockAssertion;
50using ::android::base::StringPrintf;
Chen Chengfaf9adc2022-06-22 23:09:09 +000051using ::android::frameworks::automotive::vhal::ErrorCode;
Yu Shan726d51a2022-02-22 17:37:21 -080052using ::android::frameworks::automotive::vhal::HalPropError;
53using ::android::frameworks::automotive::vhal::IHalPropConfig;
54using ::android::frameworks::automotive::vhal::IHalPropValue;
55using ::android::frameworks::automotive::vhal::ISubscriptionCallback;
56using ::android::frameworks::automotive::vhal::IVhalClient;
57using ::android::hardware::getAllHalInstanceNames;
58using ::android::hardware::Sanitize;
59using ::android::hardware::automotive::vehicle::toInt;
60
61constexpr int32_t kInvalidProp = 0x31600207;
62
63struct ServiceDescriptor {
64 std::string name;
65 bool isAidlService;
66};
67
68class VtsVehicleCallback final : public ISubscriptionCallback {
69 private:
70 std::mutex mLock;
71 std::unordered_map<int32_t, size_t> mEventsCount GUARDED_BY(mLock);
Yu Shan4569ef52022-03-18 14:34:25 -070072 std::unordered_map<int32_t, std::vector<int64_t>> mEventTimestamps GUARDED_BY(mLock);
Yu Shan726d51a2022-02-22 17:37:21 -080073 std::condition_variable mEventCond;
74
75 public:
76 void onPropertyEvent(const std::vector<std::unique_ptr<IHalPropValue>>& values) override {
77 {
78 std::lock_guard<std::mutex> lockGuard(mLock);
79 for (auto& value : values) {
Yu Shan4569ef52022-03-18 14:34:25 -070080 int32_t propId = value->getPropId();
81 mEventsCount[propId] += 1;
82 mEventTimestamps[propId].push_back(value->getTimestamp());
Yu Shan726d51a2022-02-22 17:37:21 -080083 }
84 }
85 mEventCond.notify_one();
86 }
87
88 void onPropertySetError([[maybe_unused]] const std::vector<HalPropError>& errors) override {
89 // Do nothing.
90 }
91
92 template <class Rep, class Period>
93 bool waitForExpectedEvents(int32_t propId, size_t expectedEvents,
94 const std::chrono::duration<Rep, Period>& timeout) {
95 std::unique_lock<std::mutex> uniqueLock(mLock);
96 return mEventCond.wait_for(uniqueLock, timeout, [this, propId, expectedEvents] {
97 ScopedLockAssertion lockAssertion(mLock);
98 return mEventsCount[propId] >= expectedEvents;
99 });
100 }
101
Yu Shan4569ef52022-03-18 14:34:25 -0700102 std::vector<int64_t> getEventTimestamps(int32_t propId) {
103 {
104 std::lock_guard<std::mutex> lockGuard(mLock);
105 return mEventTimestamps[propId];
106 }
107 }
108
Yu Shan726d51a2022-02-22 17:37:21 -0800109 void reset() {
110 std::lock_guard<std::mutex> lockGuard(mLock);
111 mEventsCount.clear();
112 }
113};
114
115class VtsHalAutomotiveVehicleTargetTest : public testing::TestWithParam<ServiceDescriptor> {
116 public:
117 virtual void SetUp() override {
118 auto descriptor = GetParam();
119 if (descriptor.isAidlService) {
120 mVhalClient = IVhalClient::tryCreateAidlClient(descriptor.name.c_str());
121 } else {
122 mVhalClient = IVhalClient::tryCreateHidlClient(descriptor.name.c_str());
123 }
124
125 ASSERT_NE(mVhalClient, nullptr) << "Failed to connect to VHAL";
126
127 mCallback = std::make_shared<VtsVehicleCallback>();
128 }
129
130 static bool isBooleanGlobalProp(int32_t property) {
131 return (property & toInt(VehiclePropertyType::MASK)) ==
132 toInt(VehiclePropertyType::BOOLEAN) &&
133 (property & toInt(VehicleArea::MASK)) == toInt(VehicleArea::GLOBAL);
134 }
135
136 protected:
137 std::shared_ptr<IVhalClient> mVhalClient;
138 std::shared_ptr<VtsVehicleCallback> mCallback;
139};
140
141TEST_P(VtsHalAutomotiveVehicleTargetTest, useAidlBackend) {
142 if (!mVhalClient->isAidlVhal()) {
143 GTEST_SKIP() << "AIDL backend is not available, HIDL backend is used instead";
144 }
145}
146
147TEST_P(VtsHalAutomotiveVehicleTargetTest, useHidlBackend) {
148 if (mVhalClient->isAidlVhal()) {
149 GTEST_SKIP() << "AIDL backend is available, HIDL backend is not used";
150 }
151}
152
153// Test getAllPropConfig() returns at least 4 property configs.
154TEST_P(VtsHalAutomotiveVehicleTargetTest, getAllPropConfigs) {
155 ALOGD("VtsHalAutomotiveVehicleTargetTest::getAllPropConfigs");
156
157 auto result = mVhalClient->getAllPropConfigs();
158
159 ASSERT_TRUE(result.ok()) << "Failed to get all property configs, error: "
160 << result.error().message();
161 ASSERT_GE(result.value().size(), 4u) << StringPrintf(
162 "Expect to get at least 4 property configs, got %zu", result.value().size());
163}
164
165// Test getPropConfigs() can query all properties listed in CDD.
166TEST_P(VtsHalAutomotiveVehicleTargetTest, getRequiredPropConfigs) {
167 ALOGD("VtsHalAutomotiveVehicleTargetTest::getRequiredPropConfigs");
168
169 // Check the properties listed in CDD
170 std::vector<int32_t> properties = {
171 toInt(VehicleProperty::GEAR_SELECTION), toInt(VehicleProperty::NIGHT_MODE),
172 toInt(VehicleProperty::PARKING_BRAKE_ON), toInt(VehicleProperty::PERF_VEHICLE_SPEED)};
173
174 auto result = mVhalClient->getPropConfigs(properties);
175
176 ASSERT_TRUE(result.ok()) << "Failed to get required property config, error: "
177 << result.error().message();
178 ASSERT_EQ(result.value().size(), 4u)
179 << StringPrintf("Expect to get exactly 4 configs, got %zu", result.value().size());
180}
181
182// Test getPropConfig() with an invalid propertyId returns an error code.
183TEST_P(VtsHalAutomotiveVehicleTargetTest, getPropConfigsWithInvalidProp) {
184 ALOGD("VtsHalAutomotiveVehicleTargetTest::getPropConfigsWithInvalidProp");
185
186 auto result = mVhalClient->getPropConfigs({kInvalidProp});
187
188 ASSERT_FALSE(result.ok()) << StringPrintf(
189 "Expect failure to get prop configs for invalid prop: %" PRId32, kInvalidProp);
190 ASSERT_NE(result.error().message(), "") << "Expect error message not to be empty";
191}
192
193// Test get() return current value for properties.
194TEST_P(VtsHalAutomotiveVehicleTargetTest, get) {
195 ALOGD("VtsHalAutomotiveVehicleTargetTest::get");
196
197 int32_t propId = toInt(VehicleProperty::PERF_VEHICLE_SPEED);
198 auto result = mVhalClient->getValueSync(*mVhalClient->createHalPropValue(propId));
199
200 ASSERT_TRUE(result.ok()) << StringPrintf("Failed to get value for property: %" PRId32
201 ", error: %s",
202 propId, result.error().message().c_str());
203 ASSERT_NE(result.value(), nullptr) << "Result value must not be null";
204}
205
206// Test get() with an invalid propertyId return an error codes.
207TEST_P(VtsHalAutomotiveVehicleTargetTest, getInvalidProp) {
208 ALOGD("VtsHalAutomotiveVehicleTargetTest::getInvalidProp");
209
210 auto result = mVhalClient->getValueSync(*mVhalClient->createHalPropValue(kInvalidProp));
211
212 ASSERT_FALSE(result.ok()) << StringPrintf(
213 "Expect failure to get property for invalid prop: %" PRId32, kInvalidProp);
214}
215
216// Test set() on read_write properties.
217TEST_P(VtsHalAutomotiveVehicleTargetTest, setProp) {
218 ALOGD("VtsHalAutomotiveVehicleTargetTest::setProp");
219
220 // skip hvac related properties
221 std::unordered_set<int32_t> hvacProps = {toInt(VehicleProperty::HVAC_DEFROSTER),
222 toInt(VehicleProperty::HVAC_AC_ON),
223 toInt(VehicleProperty::HVAC_MAX_AC_ON),
224 toInt(VehicleProperty::HVAC_MAX_DEFROST_ON),
225 toInt(VehicleProperty::HVAC_RECIRC_ON),
226 toInt(VehicleProperty::HVAC_DUAL_ON),
227 toInt(VehicleProperty::HVAC_AUTO_ON),
228 toInt(VehicleProperty::HVAC_POWER_ON),
229 toInt(VehicleProperty::HVAC_AUTO_RECIRC_ON),
230 toInt(VehicleProperty::HVAC_ELECTRIC_DEFROSTER_ON)};
231 auto result = mVhalClient->getAllPropConfigs();
232 ASSERT_TRUE(result.ok());
233
234 for (const auto& cfgPtr : result.value()) {
235 const IHalPropConfig& cfg = *cfgPtr;
236 int32_t propId = cfg.getPropId();
237 // test on boolean and writable property
238 if (cfg.getAccess() == toInt(VehiclePropertyAccess::READ_WRITE) &&
239 isBooleanGlobalProp(propId) && !hvacProps.count(propId)) {
240 auto propToGet = mVhalClient->createHalPropValue(propId);
241 auto getValueResult = mVhalClient->getValueSync(*propToGet);
242
243 ASSERT_TRUE(getValueResult.ok())
244 << StringPrintf("Failed to get value for property: %" PRId32 ", error: %s",
245 propId, getValueResult.error().message().c_str());
246 ASSERT_NE(getValueResult.value(), nullptr)
247 << StringPrintf("Result value must not be null for property: %" PRId32, propId);
248
249 const IHalPropValue& value = *getValueResult.value();
250 size_t intValueSize = value.getInt32Values().size();
251 ASSERT_EQ(intValueSize, 1u) << StringPrintf(
252 "Expect exactly 1 int value for boolean property: %" PRId32 ", got %zu", propId,
253 intValueSize);
254
255 int setValue = value.getInt32Values()[0] == 1 ? 0 : 1;
256 auto propToSet = mVhalClient->createHalPropValue(propId);
257 propToSet->setInt32Values({setValue});
258 auto setValueResult = mVhalClient->setValueSync(*propToSet);
259
260 ASSERT_TRUE(setValueResult.ok())
261 << StringPrintf("Failed to set value for property: %" PRId32 ", error: %s",
262 propId, setValueResult.error().message().c_str());
263
264 // check set success
265 getValueResult = mVhalClient->getValueSync(*propToGet);
266 ASSERT_TRUE(getValueResult.ok())
267 << StringPrintf("Failed to get value for property: %" PRId32 ", error: %s",
268 propId, getValueResult.error().message().c_str());
269 ASSERT_NE(getValueResult.value(), nullptr)
270 << StringPrintf("Result value must not be null for property: %" PRId32, propId);
271 ASSERT_EQ(getValueResult.value()->getInt32Values(), std::vector<int32_t>({setValue}))
272 << StringPrintf("Boolean value not updated after set for property: %" PRId32,
273 propId);
274 }
275 }
276}
277
278// Test set() on an read_only property.
279TEST_P(VtsHalAutomotiveVehicleTargetTest, setNotWritableProp) {
280 ALOGD("VtsHalAutomotiveVehicleTargetTest::setNotWritableProp");
281
282 int32_t propId = toInt(VehicleProperty::PERF_VEHICLE_SPEED);
283 auto getValueResult = mVhalClient->getValueSync(*mVhalClient->createHalPropValue(propId));
284 ASSERT_TRUE(getValueResult.ok())
285 << StringPrintf("Failed to get value for property: %" PRId32 ", error: %s", propId,
286 getValueResult.error().message().c_str());
287
288 auto setValueResult = mVhalClient->setValueSync(*getValueResult.value());
289
290 ASSERT_FALSE(setValueResult.ok()) << "Expect set a read-only value to fail";
Chen Chengfaf9adc2022-06-22 23:09:09 +0000291 ASSERT_EQ(setValueResult.error().code(), ErrorCode::ACCESS_DENIED_FROM_VHAL);
Yu Shan726d51a2022-02-22 17:37:21 -0800292}
293
294// Test subscribe() and unsubscribe().
295TEST_P(VtsHalAutomotiveVehicleTargetTest, subscribeAndUnsubscribe) {
296 ALOGD("VtsHalAutomotiveVehicleTargetTest::subscribeAndUnsubscribe");
297
298 int32_t propId = toInt(VehicleProperty::PERF_VEHICLE_SPEED);
299
Yu Shan4569ef52022-03-18 14:34:25 -0700300 auto propConfigsResult = mVhalClient->getPropConfigs({propId});
301
302 ASSERT_TRUE(propConfigsResult.ok()) << "Failed to get property config for PERF_VEHICLE_SPEED: "
303 << "error: " << propConfigsResult.error().message();
304 ASSERT_EQ(propConfigsResult.value().size(), 1u)
305 << "Expect to return 1 config for PERF_VEHICLE_SPEED";
306 auto& propConfig = propConfigsResult.value()[0];
307 float minSampleRate = propConfig->getMinSampleRate();
308 float maxSampleRate = propConfig->getMaxSampleRate();
309
310 if (minSampleRate < 1) {
311 GTEST_SKIP() << "Sample rate for vehicle speed < 1 times/sec, skip test since it would "
312 "take too long";
313 }
Yu Shan726d51a2022-02-22 17:37:21 -0800314
315 auto client = mVhalClient->getSubscriptionClient(mCallback);
316 ASSERT_NE(client, nullptr) << "Failed to get subscription client";
317
Yu Shan4569ef52022-03-18 14:34:25 -0700318 auto result = client->subscribe({{.propId = propId, .sampleRate = minSampleRate}});
Yu Shan726d51a2022-02-22 17:37:21 -0800319
320 ASSERT_TRUE(result.ok()) << StringPrintf("Failed to subscribe to property: %" PRId32
321 ", error: %s",
322 propId, result.error().message().c_str());
Yu Shan4569ef52022-03-18 14:34:25 -0700323
324 if (mVhalClient->isAidlVhal()) {
325 // Skip checking timestamp for HIDL because the behavior for sample rate and timestamp is
326 // only specified clearly for AIDL.
327
328 // Timeout is 2 seconds, which gives a 1 second buffer.
329 ASSERT_TRUE(mCallback->waitForExpectedEvents(propId, std::floor(minSampleRate),
330 std::chrono::seconds(2)))
331 << "Didn't get enough events for subscribing to minSampleRate";
332 }
333
334 result = client->subscribe({{.propId = propId, .sampleRate = maxSampleRate}});
335
336 ASSERT_TRUE(result.ok()) << StringPrintf("Failed to subscribe to property: %" PRId32
337 ", error: %s",
338 propId, result.error().message().c_str());
339
340 if (mVhalClient->isAidlVhal()) {
341 ASSERT_TRUE(mCallback->waitForExpectedEvents(propId, std::floor(maxSampleRate),
342 std::chrono::seconds(2)))
343 << "Didn't get enough events for subscribing to maxSampleRate";
344
345 std::unordered_set<int64_t> timestamps;
346 // Event event should have a different timestamp.
347 for (const int64_t& eventTimestamp : mCallback->getEventTimestamps(propId)) {
348 ASSERT_TRUE(timestamps.find(eventTimestamp) == timestamps.end())
349 << "two events for the same property must not have the same timestamp";
350 timestamps.insert(eventTimestamp);
351 }
352 }
Yu Shan726d51a2022-02-22 17:37:21 -0800353
354 result = client->unsubscribe({propId});
355 ASSERT_TRUE(result.ok()) << StringPrintf("Failed to unsubscribe to property: %" PRId32
356 ", error: %s",
357 propId, result.error().message().c_str());
358
359 mCallback->reset();
360 ASSERT_FALSE(mCallback->waitForExpectedEvents(propId, 10, std::chrono::seconds(1)))
361 << "Expect not to get events after unsubscription";
362}
363
364// Test subscribe() with an invalid property.
365TEST_P(VtsHalAutomotiveVehicleTargetTest, subscribeInvalidProp) {
366 ALOGD("VtsHalAutomotiveVehicleTargetTest::subscribeInvalidProp");
367
368 std::vector<SubscribeOptions> options = {
369 SubscribeOptions{.propId = kInvalidProp, .sampleRate = 10.0}};
370
371 auto client = mVhalClient->getSubscriptionClient(mCallback);
372 ASSERT_NE(client, nullptr) << "Failed to get subscription client";
373
374 auto result = client->subscribe(options);
375
376 ASSERT_FALSE(result.ok()) << StringPrintf("Expect subscribing to property: %" PRId32 " to fail",
377 kInvalidProp);
378}
379
Yu Shan4569ef52022-03-18 14:34:25 -0700380// Test the timestamp returned in GetValues results is the timestamp when the value is retrieved.
381TEST_P(VtsHalAutomotiveVehicleTargetTest, testGetValuesTimestampAIDL) {
382 if (!mVhalClient->isAidlVhal()) {
383 GTEST_SKIP() << "Skip checking timestamp for HIDL because the behavior is only specified "
384 "for AIDL";
385 }
386
387 int32_t propId = toInt(VehicleProperty::PARKING_BRAKE_ON);
388 auto prop = mVhalClient->createHalPropValue(propId);
389
390 auto result = mVhalClient->getValueSync(*prop);
391
392 ASSERT_TRUE(result.ok()) << StringPrintf("Failed to get value for property: %" PRId32
393 ", error: %s",
394 propId, result.error().message().c_str());
395 ASSERT_NE(result.value(), nullptr) << "Result value must not be null";
396 ASSERT_EQ(result.value()->getInt32Values().size(), 1u) << "Result must contain 1 int value";
397
398 bool parkBrakeOnValue1 = (result.value()->getInt32Values()[0] == 1);
399 int64_t timestampValue1 = result.value()->getTimestamp();
400
401 result = mVhalClient->getValueSync(*prop);
402
403 ASSERT_TRUE(result.ok()) << StringPrintf("Failed to get value for property: %" PRId32
404 ", error: %s",
405 propId, result.error().message().c_str());
406 ASSERT_NE(result.value(), nullptr) << "Result value must not be null";
407 ASSERT_EQ(result.value()->getInt32Values().size(), 1u) << "Result must contain 1 int value";
408
409 bool parkBarkeOnValue2 = (result.value()->getInt32Values()[0] == 1);
410 int64_t timestampValue2 = result.value()->getTimestamp();
411
412 if (parkBarkeOnValue2 == parkBrakeOnValue1) {
413 ASSERT_EQ(timestampValue2, timestampValue1)
414 << "getValue result must contain a timestamp updated when the value was updated, if"
415 "the value does not change, expect the same timestamp";
416 } else {
417 ASSERT_GT(timestampValue2, timestampValue1)
418 << "getValue result must contain a timestamp updated when the value was updated, if"
419 "the value changes, expect the newer value has a larger timestamp";
420 }
421}
422
Yu Shan726d51a2022-02-22 17:37:21 -0800423std::vector<ServiceDescriptor> getDescriptors() {
424 std::vector<ServiceDescriptor> descriptors;
425 for (std::string name : getAidlHalInstanceNames(IVehicle::descriptor)) {
426 descriptors.push_back({
427 .name = name,
428 .isAidlService = true,
429 });
430 }
431 for (std::string name : getAllHalInstanceNames(IVehicle::descriptor)) {
432 descriptors.push_back({
433 .name = name,
434 .isAidlService = false,
435 });
436 }
437 return descriptors;
438}
439
440GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(VtsHalAutomotiveVehicleTargetTest);
441
442INSTANTIATE_TEST_SUITE_P(PerInstance, VtsHalAutomotiveVehicleTargetTest,
443 testing::ValuesIn(getDescriptors()),
444 [](const testing::TestParamInfo<ServiceDescriptor>& info) {
445 std::string name = "";
446 if (info.param.isAidlService) {
447 name += "aidl_";
448 } else {
449 name += "hidl_";
450 }
451 name += info.param.name;
452 return Sanitize(name);
453 });
454
455int main(int argc, char** argv) {
456 ::testing::InitGoogleTest(&argc, argv);
457 ABinderProcess_setThreadPoolMaxThreadCount(1);
458 return RUN_ALL_TESTS();
459}