1 /*
2 * Copyright (C) 2019 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 #include <cutils/sockets.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <utils/StrongPointer.h>
22
23 #include <chrono>
24 #include <cinttypes>
25 #include <condition_variable>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <fstream>
29 #include <mutex>
30 #include <string>
31 #include <thread>
32 #include <unordered_map>
33 #include <vector>
34
35 #include "chre/util/nanoapp/app_id.h"
36 #include "chre/util/system/napp_header_utils.h"
37 #include "chre/version.h"
38 #include "chre_host/file_stream.h"
39 #include "chre_host/host_protocol_host.h"
40 #include "chre_host/log.h"
41 #include "chre_host/napp_header.h"
42 #include "chre_host/socket_client.h"
43 #include "generated/chre_power_test_generated.h"
44
45 /**
46 * @file
47 * A test utility that connects to the CHRE daemon and provides commands to take
48 * control the power test nanoapp located at system/chre/apps/power_test
49 *
50 * Usage:
51 * chre_power_test_client load <optional: tcm> <optional: path>
52 * chre_power_test_client unload <optional: tcm>
53 * chre_power_test_client unloadall
54 * chre_power_test_client timer <optional: tcm> <enable> <interval_ns>
55 * chre_power_test_client wifi <optional: tcm> <enable> <interval_ns>
56 * <optional: wifi_scan_type>
57 * <optional: wifi_radio_chain>
58 * <optional: wifi_channel_set>
59 * chre_power_test_client gnss <optional: tcm> <enable> <interval_ms>
60 * <optional: next_fix_ms>
61 * chre_power_test_client cell <optional: tcm> <enable> <interval_ns>
62 * chre_power_test_client audio <optional: tcm> <enable> <duration_ns>
63 * chre_power_test_client sensor <optional: tcm> <enable> <sensor_type>
64 * <interval_ns> <optional: latency_ns>
65 * chre_power_test_client breakit <optional: tcm> <enable>
66 * chre_power_test_client gnss_meas <optional: tcm> <enable> <interval_ms>
67 * chre_power_test_client wifi_nan_sub <optional: tcm> <sub_type>
68 * <service_name>
69 * chre_power_test_client end_wifi_nan_sub <optional: tcm> <subscription_id>
70 *
71 * Command:
72 * load: load power test nanoapp to CHRE
73 * unload: unload power test nanoapp from CHRE
74 * unloadall: unload all nanoapps in CHRE
75 * timer: start/stop timer wake up
76 * wifi: start/stop periodic wifi scan
77 * gnss: start/stop periodic GPS scan
78 * cell: start/stop periodic cellular scan
79 * audio: start/stop periodic audio capture
80 * sensor: start/stop periodic sensor sampling
81 * breakit: start/stop all action for stress tests
82 * gnss_meas: start/stop periodic GNSS measurement
83 *
84 * <optional: tcm>: tcm for micro image, default for big image
85 * <enable>: enable/disable
86 *
87 * <sensor_type>:
88 * accelerometer
89 * instant_motion
90 * stationary
91 * gyroscope
92 * uncalibrated_gyroscope
93 * geomagnetic
94 * uncalibrated_geomagnetic
95 * pressure
96 * light
97 * proximity
98 * step
99 * step_counter
100 * uncalibrated_accelerometer
101 * accelerometer_temperature
102 * gyroscope_temperature
103 * geomagnetic_temperature
104 *
105 * For instant_motion and stationary sensor, it is not necessary to provide the
106 * interval and latency
107 *
108 * <wifi_scan_type>:
109 * active
110 * active_passive_dfs
111 * passive
112 * no_preference (default when omitted)
113 *
114 * <wifi_radio_chain>:
115 * default (default when omitted)
116 * low_latency
117 * low_power
118 * high_accuracy
119 *
120 * <wifi_channel_set>:
121 * non_dfs (default when omitted)
122 * all
123 */
124
125 using android::sp;
126 using android::chre::FragmentedLoadTransaction;
127 using android::chre::getStringFromByteVector;
128 using android::chre::HostProtocolHost;
129 using android::chre::IChreMessageHandlers;
130 using android::chre::NanoAppBinaryHeader;
131 using android::chre::readFileContents;
132 using android::chre::SocketClient;
133 using chre::power_test::MessageType;
134 using chre::power_test::SensorType;
135 using chre::power_test::WifiChannelSet;
136 using chre::power_test::WifiRadioChain;
137 using chre::power_test::WifiScanType;
138 using flatbuffers::FlatBufferBuilder;
139 using std::string;
140
141 // Aliased for consistency with the way these symbols are referenced in
142 // CHRE-side code
143 namespace fbs = ::chre::fbs;
144 namespace ptest = ::chre::power_test;
145
146 namespace {
147
148 //! The host endpoint we use when sending; Clients may use a value above
149 //! 0x8000 to enable unicast messaging (currently requires internal coordination
150 //! to avoid conflict).
151 constexpr uint16_t kHostEndpoint = 0x8003;
152
153 constexpr uint64_t kPowerTestAppId = 0x012345678900000f;
154 constexpr uint64_t kPowerTestTcmAppId = 0x0123456789000010;
155 constexpr uint64_t kUint64Max = std::numeric_limits<uint64_t>::max();
156
157 constexpr auto kTimeout = std::chrono::seconds(10);
158
159 const string kPowerTestName = "power_test.so";
160 const string kPowerTestTcmName = "power_test_tcm.so";
161 std::condition_variable kReadyCond;
162 std::mutex kReadyMutex;
163 std::unique_lock<std::mutex> kReadyCondLock(kReadyMutex);
164
165 enum class Command : uint32_t {
166 kUnloadAll = 0,
167 kLoad,
168 kUnload,
169 kTimer,
170 kWifi,
171 kGnss,
172 kCell,
173 kAudio,
174 kSensor,
175 kBreakIt,
176 kGnssMeas,
177 kNanSub,
178 kNanCancel,
179 };
180
181 std::unordered_map<string, Command> commandMap{
182 {"unloadall", Command::kUnloadAll},
183 {"load", Command::kLoad},
184 {"unload", Command::kUnload},
185 {"timer", Command::kTimer},
186 {"wifi", Command::kWifi},
187 {"gnss", Command::kGnss},
188 {"cell", Command::kCell},
189 {"audio", Command::kAudio},
190 {"sensor", Command::kSensor},
191 {"breakit", Command::kBreakIt},
192 {"gnss_meas", Command::kGnssMeas},
193 {"wifi_nan_sub", Command::kNanSub},
194 {"end_wifi_nan_sub", Command::kNanCancel}};
195
196 std::unordered_map<string, MessageType> messageTypeMap{
197 {"timer", MessageType::TIMER_TEST},
198 {"wifi", MessageType::WIFI_SCAN_TEST},
199 {"gnss", MessageType::GNSS_LOCATION_TEST},
200 {"cell", MessageType::CELL_QUERY_TEST},
201 {"audio", MessageType::AUDIO_REQUEST_TEST},
202 {"sensor", MessageType::SENSOR_REQUEST_TEST},
203 {"breakit", MessageType::BREAK_IT_TEST},
204 {"gnss_meas", MessageType::GNSS_MEASUREMENT_TEST},
205 {"wifi_nan_sub", MessageType::WIFI_NAN_SUB},
206 {"end_wifi_nan_sub", MessageType::WIFI_NAN_SUB_CANCEL}};
207
208 std::unordered_map<string, SensorType> sensorTypeMap{
209 {"accelerometer", SensorType::ACCELEROMETER},
210 {"instant_motion", SensorType::INSTANT_MOTION_DETECT},
211 {"stationary", SensorType::STATIONARY_DETECT},
212 {"gyroscope", SensorType::GYROSCOPE},
213 {"uncalibrated_gyroscope", SensorType::UNCALIBRATED_GYROSCOPE},
214 {"geomagnetic", SensorType::GEOMAGNETIC_FIELD},
215 {"uncalibrated_geomagnetic", SensorType::UNCALIBRATED_GEOMAGNETIC_FIELD},
216 {"pressure", SensorType::PRESSURE},
217 {"light", SensorType::LIGHT},
218 {"proximity", SensorType::PROXIMITY},
219 {"step", SensorType::STEP_DETECT},
220 {"step_counter", SensorType::STEP_COUNTER},
221 {"uncalibrated_accelerometer", SensorType::UNCALIBRATED_ACCELEROMETER},
222 {"accelerometer_temperature", SensorType::ACCELEROMETER_TEMPERATURE},
223 {"gyroscope_temperature", SensorType::GYROSCOPE_TEMPERATURE},
224 {"geomagnetic_temperature", SensorType::GEOMAGNETIC_FIELD_TEMPERATURE}};
225
226 std::unordered_map<string, WifiScanType> wifiScanTypeMap{
227 {"active", WifiScanType::ACTIVE},
228 {"active_passive_dfs", WifiScanType::ACTIVE_PLUS_PASSIVE_DFS},
229 {"passive", WifiScanType::PASSIVE},
230 {"no_preference", WifiScanType::NO_PREFERENCE}};
231
232 std::unordered_map<string, WifiRadioChain> wifiRadioChainMap{
233 {"default", WifiRadioChain::DEFAULT},
234 {"low_latency", WifiRadioChain::LOW_LATENCY},
235 {"low_power", WifiRadioChain::LOW_POWER},
236 {"high_accuracy", WifiRadioChain::HIGH_ACCURACY}};
237
238 std::unordered_map<string, WifiChannelSet> wifiChannelSetMap{
239 {"non_dfs", WifiChannelSet::NON_DFS}, {"all", WifiChannelSet::ALL}};
240
wifiScanTypeMatch(const string & name,WifiScanType * scanType)241 bool wifiScanTypeMatch(const string &name, WifiScanType *scanType) {
242 if (wifiScanTypeMap.find(name) != wifiScanTypeMap.end()) {
243 *scanType = wifiScanTypeMap[name];
244 return true;
245 }
246 return false;
247 }
248
wifiRadioChainMatch(const string & name,WifiRadioChain * radioChain)249 bool wifiRadioChainMatch(const string &name, WifiRadioChain *radioChain) {
250 if (wifiRadioChainMap.find(name) != wifiRadioChainMap.end()) {
251 *radioChain = wifiRadioChainMap[name];
252 return true;
253 }
254 return false;
255 }
256
wifiChannelSetMatch(const string & name,WifiChannelSet * channelSet)257 bool wifiChannelSetMatch(const string &name, WifiChannelSet *channelSet) {
258 if (wifiChannelSetMap.find(name) != wifiChannelSetMap.end()) {
259 *channelSet = wifiChannelSetMap[name];
260 return true;
261 }
262 return false;
263 }
264
265 class SocketCallbacks : public SocketClient::ICallbacks,
266 public IChreMessageHandlers {
267 public:
SocketCallbacks(std::condition_variable & readyCond)268 SocketCallbacks(std::condition_variable &readyCond)
269 : mConditionVariable(readyCond) {}
270
onMessageReceived(const void * data,size_t length)271 void onMessageReceived(const void *data, size_t length) override {
272 if (!HostProtocolHost::decodeMessageFromChre(data, length, *this)) {
273 LOGE("Failed to decode message");
274 }
275 }
276
onConnected()277 void onConnected() override {
278 LOGI("Socket (re)connected");
279 }
280
onConnectionAborted()281 void onConnectionAborted() override {
282 LOGI("Socket (re)connection aborted");
283 }
284
onDisconnected()285 void onDisconnected() override {
286 LOGI("Socket disconnected");
287 }
288
handleNanoappMessage(const fbs::NanoappMessageT & message)289 void handleNanoappMessage(const fbs::NanoappMessageT &message) override {
290 LOGI("Got message from nanoapp 0x%" PRIx64 " to endpoint 0x%" PRIx16
291 " with type 0x%" PRIx32 " and length %zu",
292 message.app_id, message.host_endpoint, message.message_type,
293 message.message.size());
294 if (message.message_type ==
295 static_cast<uint32_t>(MessageType::NANOAPP_RESPONSE)) {
296 handlePowerTestNanoappResponse(message.message);
297 }
298 }
299
handlePowerTestNanoappResponse(const std::vector<uint8_t> & message)300 void handlePowerTestNanoappResponse(const std::vector<uint8_t> &message) {
301 auto response =
302 flatbuffers::GetRoot<ptest::NanoappResponseMessage>(message.data());
303 flatbuffers::Verifier verifier(message.data(), message.size());
304 bool success = response->Verify(verifier);
305 mSuccess = success ? response->success() : false;
306 mConditionVariable.notify_all();
307 }
308
handleNanoappListResponse(const fbs::NanoappListResponseT & response)309 void handleNanoappListResponse(
310 const fbs::NanoappListResponseT &response) override {
311 LOGI("Got nanoapp list response with %zu apps:", response.nanoapps.size());
312 mAppIdVector.clear();
313 for (const auto &nanoapp : response.nanoapps) {
314 LOGI("App ID 0x%016" PRIx64 " version 0x%" PRIx32
315 " permissions 0x%" PRIx32 " enabled %d system %d",
316 nanoapp->app_id, nanoapp->version, nanoapp->permissions,
317 nanoapp->enabled, nanoapp->is_system);
318 mAppIdVector.push_back(nanoapp->app_id);
319 }
320 mConditionVariable.notify_all();
321 }
322
handleLoadNanoappResponse(const fbs::LoadNanoappResponseT & response)323 void handleLoadNanoappResponse(
324 const fbs::LoadNanoappResponseT &response) override {
325 LOGI("Got load nanoapp response, transaction ID 0x%" PRIx32 " result %d",
326 response.transaction_id, response.success);
327 mSuccess = response.success;
328 mConditionVariable.notify_all();
329 }
330
handleUnloadNanoappResponse(const fbs::UnloadNanoappResponseT & response)331 void handleUnloadNanoappResponse(
332 const fbs::UnloadNanoappResponseT &response) override {
333 LOGI("Got unload nanoapp response, transaction ID 0x%" PRIx32 " result %d",
334 response.transaction_id, response.success);
335 mSuccess = response.success;
336 mConditionVariable.notify_all();
337 }
338
actionSucceeded()339 bool actionSucceeded() {
340 return mSuccess;
341 }
342
getAppIdVector()343 std::vector<uint64_t> &getAppIdVector() {
344 return mAppIdVector;
345 }
346
347 private:
348 bool mSuccess = false;
349 std::condition_variable &mConditionVariable;
350 std::vector<uint64_t> mAppIdVector;
351 };
352
requestNanoappList(SocketClient & client)353 bool requestNanoappList(SocketClient &client) {
354 FlatBufferBuilder builder(64);
355 HostProtocolHost::encodeNanoappListRequest(builder);
356
357 LOGI("Sending app list request (%" PRIu32 " bytes)", builder.GetSize());
358 if (!client.sendMessage(builder.GetBufferPointer(), builder.GetSize())) {
359 LOGE("Failed to send message");
360 return false;
361 }
362 return true;
363 }
364
sendNanoappLoad(SocketClient & client,uint64_t appId,uint32_t appVersion,uint32_t apiVersion,uint32_t appFlags,const std::vector<uint8_t> & binary)365 bool sendNanoappLoad(SocketClient &client, uint64_t appId, uint32_t appVersion,
366 uint32_t apiVersion, uint32_t appFlags,
367 const std::vector<uint8_t> &binary) {
368 // Perform loading with 1 fragment for simplicity
369 FlatBufferBuilder builder(binary.size() + 128);
370 FragmentedLoadTransaction transaction = FragmentedLoadTransaction(
371 1 /* transactionId */, appId, appVersion, appFlags, apiVersion, binary,
372 binary.size() /* fragmentSize */);
373 HostProtocolHost::encodeFragmentedLoadNanoappRequest(
374 builder, transaction.getNextRequest());
375
376 LOGI("Sending load nanoapp request (%" PRIu32
377 " bytes total w/%zu bytes of "
378 "payload)",
379 builder.GetSize(), binary.size());
380 return client.sendMessage(builder.GetBufferPointer(), builder.GetSize());
381 }
382
sendLoadNanoappRequest(SocketClient & client,const std::string filenameNoExtension)383 bool sendLoadNanoappRequest(SocketClient &client,
384 const std::string filenameNoExtension) {
385 bool success = false;
386 std::vector<uint8_t> headerBuffer;
387 std::vector<uint8_t> binaryBuffer;
388 std::string headerName = filenameNoExtension + ".napp_header";
389 std::string binaryName = filenameNoExtension + ".so";
390 if (readFileContents(headerName.c_str(), headerBuffer) &&
391 readFileContents(binaryName.c_str(), binaryBuffer)) {
392 if (headerBuffer.size() != sizeof(NanoAppBinaryHeader)) {
393 LOGE("Header size mismatch");
394 } else {
395 // The header blob contains the struct above.
396 const auto *appHeader =
397 reinterpret_cast<const NanoAppBinaryHeader *>(headerBuffer.data());
398
399 // Build the target API version from major and minor.
400 uint32_t targetApiVersion = (appHeader->targetChreApiMajorVersion << 24) |
401 (appHeader->targetChreApiMinorVersion << 16);
402
403 success =
404 sendNanoappLoad(client, appHeader->appId, appHeader->appVersion,
405 targetApiVersion, appHeader->flags, binaryBuffer);
406 }
407 }
408 return success;
409 }
410
loadNanoapp(SocketClient & client,sp<SocketCallbacks> callbacks,const std::string filenameNoExt)411 bool loadNanoapp(SocketClient &client, sp<SocketCallbacks> callbacks,
412 const std::string filenameNoExt) {
413 if (!sendLoadNanoappRequest(client, filenameNoExt)) {
414 return false;
415 }
416 auto status = kReadyCond.wait_for(kReadyCondLock, kTimeout);
417 return (status == std::cv_status::no_timeout && callbacks->actionSucceeded());
418 }
419
sendUnloadNanoappRequest(SocketClient & client,uint64_t appId)420 bool sendUnloadNanoappRequest(SocketClient &client, uint64_t appId) {
421 FlatBufferBuilder builder(64);
422 constexpr uint32_t kTransactionId = 4321;
423 HostProtocolHost::encodeUnloadNanoappRequest(
424 builder, kTransactionId, appId, true /* allowSystemNanoappUnload */);
425
426 LOGI("Sending unload request for nanoapp 0x%016" PRIx64 " (size %" PRIu32 ")",
427 appId, builder.GetSize());
428 if (!client.sendMessage(builder.GetBufferPointer(), builder.GetSize())) {
429 LOGE("Failed to send message");
430 return false;
431 }
432 return true;
433 }
434
unloadNanoapp(SocketClient & client,sp<SocketCallbacks> callbacks,uint64_t appId)435 bool unloadNanoapp(SocketClient &client, sp<SocketCallbacks> callbacks,
436 uint64_t appId) {
437 if (!sendUnloadNanoappRequest(client, appId)) {
438 return false;
439 }
440 auto status = kReadyCond.wait_for(kReadyCondLock, kTimeout);
441 bool success =
442 (status == std::cv_status::no_timeout && callbacks->actionSucceeded());
443 LOGI("Unloaded the nanoapp with appId: %" PRIx64 " success: %d", appId,
444 success);
445 return success;
446 }
447
listNanoapps(SocketClient & client)448 bool listNanoapps(SocketClient &client) {
449 if (!requestNanoappList(client)) {
450 LOGE("Failed in listing nanoapps");
451 return false;
452 }
453 auto status = kReadyCond.wait_for(kReadyCondLock, kTimeout);
454 bool success = (status == std::cv_status::no_timeout);
455 LOGI("Listed nanoapps success: %d", success);
456 return success;
457 }
458
unloadAllNanoapps(SocketClient & client,sp<SocketCallbacks> callbacks)459 bool unloadAllNanoapps(SocketClient &client, sp<SocketCallbacks> callbacks) {
460 if (!listNanoapps(client)) {
461 return false;
462 }
463 for (auto appId : callbacks->getAppIdVector()) {
464 if (!unloadNanoapp(client, callbacks, appId)) {
465 LOGE("Failed in unloading nanoapps, unloading aborted");
466 return false;
467 }
468 }
469 LOGI("Unloaded all nanoapps succeeded");
470 return true;
471 }
472
isTcmArgSpecified(std::vector<string> & args)473 bool isTcmArgSpecified(std::vector<string> &args) {
474 return !args.empty() && args[0] == "tcm";
475 }
476
getId(std::vector<string> & args)477 inline uint64_t getId(std::vector<string> &args) {
478 return isTcmArgSpecified(args) ? kPowerTestTcmAppId : kPowerTestAppId;
479 }
480
searchPath(const string & name)481 const string searchPath(const string &name) {
482 const string kAdspPath = "vendor/dsp/adsp/" + name;
483 const string kSdspPath = "vendor/dsp/sdsp/" + name;
484 const string kEtcTestPath = "vendor/etc/chre/test/" + name;
485 const string kEtcPath = "vendor/etc/chre/" + name;
486
487 struct stat buf;
488 if (stat(kAdspPath.c_str(), &buf) == 0) {
489 return kAdspPath;
490 } else if (stat(kSdspPath.c_str(), &buf) == 0) {
491 return kSdspPath;
492 } else if (stat(kEtcTestPath.c_str(), &buf) == 0) {
493 return kEtcTestPath;
494 } else {
495 return kEtcPath;
496 }
497 }
498
499 /**
500 * When user provides the customized path in tcm mode, the args[1] is the path.
501 * In this case, the args[0] has to be "tcm". When user provide customized path
502 * for non-tcm mode, the args[0] is the path.
503 */
504
getPath(std::vector<string> & args)505 inline const string getPath(std::vector<string> &args) {
506 if (args.empty()) {
507 return searchPath(kPowerTestName);
508 }
509 if (args[0] == "tcm") {
510 if (args.size() > 1) {
511 return args[1];
512 }
513 return searchPath(kPowerTestTcmName);
514 }
515 return args[0];
516 }
517
getNanoseconds(std::vector<string> & args,size_t index)518 inline uint64_t getNanoseconds(std::vector<string> &args, size_t index) {
519 return args.size() > index ? strtoull(args[index].c_str(), NULL, 0) : 0;
520 }
521
getMilliseconds(std::vector<string> & args,size_t index)522 inline uint32_t getMilliseconds(std::vector<string> &args, size_t index) {
523 return args.size() > index ? strtoul(args[index].c_str(), NULL, 0) : 0;
524 }
525
isLoaded(SocketClient & client,sp<SocketCallbacks> callbacks,std::vector<string> & args)526 bool isLoaded(SocketClient &client, sp<SocketCallbacks> callbacks,
527 std::vector<string> &args) {
528 uint64_t id = getId(args);
529 if (!listNanoapps(client)) {
530 return false;
531 }
532 for (auto appId : callbacks->getAppIdVector()) {
533 if (appId == id) {
534 LOGI("The required nanoapp was loaded");
535 return true;
536 }
537 }
538 LOGE("The required nanoapp was not loaded");
539 return false;
540 }
541
validateSensorArguments(std::vector<string> & args)542 bool validateSensorArguments(std::vector<string> &args) {
543 if (args.size() < 3) {
544 LOGE("Sensor type is required");
545 return false;
546 }
547
548 if (sensorTypeMap.find(args[2]) == sensorTypeMap.end()) {
549 LOGE("Invalid sensor type");
550 return false;
551 }
552
553 SensorType sensorType = sensorTypeMap[args[2]];
554 if (sensorType == SensorType::STATIONARY_DETECT ||
555 sensorType == SensorType::INSTANT_MOTION_DETECT)
556 return true;
557
558 uint64_t intervalNanoseconds = getNanoseconds(args, 3);
559 uint64_t latencyNanoseconds = getNanoseconds(args, 4);
560 if (intervalNanoseconds == 0) {
561 LOGE("Non zero sensor sampling interval is required when enable");
562 return false;
563 }
564 if (latencyNanoseconds != 0 && latencyNanoseconds < intervalNanoseconds) {
565 LOGE("The latency is not zero and smaller than the interval");
566 return false;
567 }
568 return true;
569 }
570
validateWifiArguments(std::vector<string> & args)571 bool validateWifiArguments(std::vector<string> &args) {
572 if (args.size() < 3) {
573 LOGE("The interval is required");
574 return false;
575 }
576
577 bool valid = true;
578 WifiScanType scanType;
579 WifiRadioChain radioChain;
580 WifiChannelSet channelSet;
581 for (int i = 3; i < 6 && args.size() > i && valid; i++) {
582 valid = wifiScanTypeMatch(args[i], &scanType) ||
583 wifiRadioChainMatch(args[i], &radioChain) ||
584 wifiChannelSetMatch(args[i], &channelSet);
585 if (!valid) {
586 LOGE("Invalid WiFi scan parameters: %s", args[i].c_str());
587 return false;
588 }
589 }
590
591 uint64_t intervalNanoseconds = getNanoseconds(args, 2);
592 if (intervalNanoseconds == 0) {
593 LOGE("Non-zero WiFi request interval is required");
594 return false;
595 }
596
597 return true;
598 }
599
validateArguments(Command commandEnum,std::vector<string> & args)600 bool validateArguments(Command commandEnum, std::vector<string> &args) {
601 // Commands: unloadall, load, unload
602 if (static_cast<uint32_t>(commandEnum) < 3) return true;
603
604 // The other commands.
605 if (args.empty()) {
606 LOGE("Not enough parameters");
607 return false;
608 }
609
610 // For non tcm option, add one item to the head of args to align argument
611 // position with that with tcm option.
612 if (args[0] != "tcm") args.insert(args.begin(), "");
613 if (args.size() < 2) {
614 LOGE("Not enough parameters");
615 return false;
616 }
617
618 if (commandEnum == Command::kNanSub) {
619 if (args.size() != 3) {
620 LOGE("Incorrect number of parameters for NAN sub");
621 return false;
622 }
623 return true;
624 }
625
626 if (commandEnum == Command::kNanCancel) {
627 if (args.size() != 2) {
628 LOGE("Incorrect number of parameters for NAN cancel");
629 return false;
630 }
631 return true;
632 }
633
634 if (args[1] != "enable" && args[1] != "disable") {
635 LOGE("<enable> was neither enable nor disable");
636 return false;
637 }
638
639 if (commandEnum == Command::kBreakIt) return true;
640
641 if (args[1] == "disable") {
642 if (commandEnum != Command::kSensor) return true;
643 if (args.size() > 2 && sensorTypeMap.find(args[2]) != sensorTypeMap.end())
644 return true;
645 LOGE("No sensor type or invalid sensor type");
646 return false;
647 }
648
649 // Case of "enable":
650 if (commandEnum == Command::kSensor) {
651 return validateSensorArguments(args);
652 } else if (commandEnum == Command::kWifi) {
653 return validateWifiArguments(args);
654 } else {
655 if (args.size() < 3) {
656 LOGE("The interval or duration was not provided");
657 return false;
658 }
659
660 // For checking if the interval is 0. The getNanoseconds and
661 // and the getMilliseconds are exchangable in this case.
662 if (getNanoseconds(args, 2) == 0) {
663 LOGE("Non zero interval or duration is required when enable");
664 return false;
665 }
666 return true;
667 }
668 }
669
createTimerMessage(FlatBufferBuilder & fbb,std::vector<string> & args)670 void createTimerMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
671 bool enable = (args[1] == "enable");
672 uint64_t intervalNanoseconds = getNanoseconds(args, 2);
673 fbb.Finish(ptest::CreateTimerMessage(fbb, enable, intervalNanoseconds));
674 LOGI("Created TimerMessage, enable %d, wakeup interval ns %" PRIu64, enable,
675 intervalNanoseconds);
676 }
677
createWifiMessage(FlatBufferBuilder & fbb,std::vector<string> & args)678 void createWifiMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
679 bool enable = (args[1] == "enable");
680 uint64_t intervalNanoseconds = getNanoseconds(args, 2);
681 WifiScanType scanType = WifiScanType::NO_PREFERENCE;
682 WifiRadioChain radioChain = WifiRadioChain::DEFAULT;
683 WifiChannelSet channelSet = WifiChannelSet::NON_DFS;
684
685 // Check for the 3 optional parameters.
686 bool valid = true;
687 for (int i = 3; i < 6 && args.size() > i && valid; i++) {
688 valid = wifiScanTypeMatch(args[i], &scanType) ||
689 wifiRadioChainMatch(args[i], &radioChain) ||
690 wifiChannelSetMatch(args[i], &channelSet);
691 }
692
693 fbb.Finish(ptest::CreateWifiScanMessage(fbb, enable, intervalNanoseconds,
694 scanType, radioChain, channelSet));
695 LOGI("Created WifiScanMessage, enable %d, scan interval ns %" PRIu64
696 " scan type %" PRIu8 " radio chain %" PRIu8 " channel set %" PRIu8,
697 enable, intervalNanoseconds, static_cast<uint8_t>(scanType),
698 static_cast<uint8_t>(radioChain), static_cast<uint8_t>(channelSet));
699 }
700
createGnssMessage(FlatBufferBuilder & fbb,std::vector<string> & args)701 void createGnssMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
702 bool enable = (args[1] == "enable");
703 uint32_t intervalMilliseconds = getMilliseconds(args, 2);
704 uint32_t toNextFixMilliseconds = getMilliseconds(args, 3);
705 fbb.Finish(ptest::CreateGnssLocationMessage(fbb, enable, intervalMilliseconds,
706 toNextFixMilliseconds));
707 LOGI("Created GnssLocationMessage, enable %d, scan interval ms %" PRIu32
708 " min time to next fix ms %" PRIu32,
709 enable, intervalMilliseconds, toNextFixMilliseconds);
710 }
711
createCellMessage(FlatBufferBuilder & fbb,std::vector<string> & args)712 void createCellMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
713 bool enable = (args[1] == "enable");
714 uint64_t intervalNanoseconds = getNanoseconds(args, 2);
715 fbb.Finish(ptest::CreateCellQueryMessage(fbb, enable, intervalNanoseconds));
716 LOGI("Created CellQueryMessage, enable %d, query interval ns %" PRIu64,
717 enable, intervalNanoseconds);
718 }
719
createAudioMessage(FlatBufferBuilder & fbb,std::vector<string> & args)720 void createAudioMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
721 bool enable = (args[1] == "enable");
722 uint64_t durationNanoseconds = getNanoseconds(args, 2);
723 fbb.Finish(
724 ptest::CreateAudioRequestMessage(fbb, enable, durationNanoseconds));
725 LOGI("Created AudioRequestMessage, enable %d, buffer duration ns %" PRIu64,
726 enable, durationNanoseconds);
727 }
728
createSensorMessage(FlatBufferBuilder & fbb,std::vector<string> & args)729 void createSensorMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
730 bool enable = (args[1] == "enable");
731 SensorType sensorType = sensorTypeMap[args[2]];
732 uint64_t intervalNanoseconds = getNanoseconds(args, 3);
733 uint64_t latencyNanoseconds = getNanoseconds(args, 4);
734 if (sensorType == SensorType::STATIONARY_DETECT ||
735 sensorType == SensorType::INSTANT_MOTION_DETECT) {
736 intervalNanoseconds = kUint64Max;
737 latencyNanoseconds = 0;
738 }
739 fbb.Finish(ptest::CreateSensorRequestMessage(
740 fbb, enable, sensorType, intervalNanoseconds, latencyNanoseconds));
741 LOGI(
742 "Created SensorRequestMessage, enable %d, %s sensor, sampling "
743 "interval ns %" PRIu64 ", latency ns %" PRIu64,
744 enable, ptest::EnumNameSensorType(sensorType), intervalNanoseconds,
745 latencyNanoseconds);
746 }
747
createBreakItMessage(FlatBufferBuilder & fbb,std::vector<string> & args)748 void createBreakItMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
749 bool enable = (args[1] == "enable");
750 fbb.Finish(ptest::CreateBreakItMessage(fbb, enable));
751 LOGI("Created BreakItMessage, enable %d", enable);
752 }
753
createGnssMeasMessage(FlatBufferBuilder & fbb,std::vector<string> & args)754 void createGnssMeasMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
755 bool enable = (args[1] == "enable");
756 uint32_t intervalMilliseconds = getMilliseconds(args, 2);
757 fbb.Finish(
758 ptest::CreateGnssMeasurementMessage(fbb, enable, intervalMilliseconds));
759 LOGI("Created GnssMeasurementMessage, enable %d, interval ms %" PRIu32,
760 enable, intervalMilliseconds);
761 }
762
createNanSubMessage(FlatBufferBuilder & fbb,std::vector<string> & args)763 void createNanSubMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
764 uint8_t subType = atoi(args[1].c_str());
765 std::string &serviceName = args[2];
766 std::vector<uint8_t> serviceNameBytes(serviceName.begin(), serviceName.end());
767 fbb.Finish(
768 ptest::CreateWifiNanSubMessageDirect(fbb, subType, &serviceNameBytes));
769 LOGI("Created NAN subscription message, subType %d serviceName %s", subType,
770 serviceName.c_str());
771 }
772
createNanCancelMessage(FlatBufferBuilder & fbb,std::vector<string> & args)773 void createNanCancelMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
774 uint32_t subId = strtoul(args[1].c_str(), nullptr /* endptr */, 0 /* base */);
775 fbb.Finish(ptest::CreateWifiNanSubCancelMessage(fbb, subId));
776 LOGI("Created NAN subscription cancel message, subId %" PRIu32, subId);
777 }
778
sendMessageToNanoapp(SocketClient & client,sp<SocketCallbacks> callbacks,FlatBufferBuilder & fbb,uint64_t appId,MessageType messageType)779 bool sendMessageToNanoapp(SocketClient &client, sp<SocketCallbacks> callbacks,
780 FlatBufferBuilder &fbb, uint64_t appId,
781 MessageType messageType) {
782 FlatBufferBuilder builder(128);
783 HostProtocolHost::encodeNanoappMessage(
784 builder, appId, static_cast<uint32_t>(messageType), kHostEndpoint,
785 fbb.GetBufferPointer(), fbb.GetSize());
786 LOGI("sending %s message to nanoapp (%" PRIu32 " bytes w/%" PRIu32
787 " bytes of payload)",
788 ptest::EnumNameMessageType(messageType), builder.GetSize(),
789 fbb.GetSize());
790 if (!client.sendMessage(builder.GetBufferPointer(), builder.GetSize())) {
791 LOGE("Failed to send %s message", ptest::EnumNameMessageType(messageType));
792 return false;
793 }
794 auto status = kReadyCond.wait_for(kReadyCondLock, kTimeout);
795 bool success =
796 (status == std::cv_status::no_timeout && callbacks->actionSucceeded());
797 LOGI("Sent %s message to nanoapp success: %d",
798 ptest::EnumNameMessageType(messageType), success);
799 if (status == std::cv_status::timeout) {
800 LOGE("Sent %s message to nanoapp timeout",
801 ptest::EnumNameMessageType(messageType));
802 }
803 return success;
804 }
805
usage()806 static void usage() {
807 LOGI(
808 "\n"
809 "Usage:\n"
810 " chre_power_test_client load <optional: tcm> <optional: path>\n"
811 " chre_power_test_client unload <optional: tcm>\n"
812 " chre_power_test_client unloadall\n"
813 " chre_power_test_client timer <optional: tcm> <enable> <interval_ns>\n"
814 " chre_power_test_client wifi <optional: tcm> <enable> <interval_ns>"
815 " <optional: wifi_scan_type> <optional: wifi_radio_chain>"
816 " <optional: wifi_channel_set>\n"
817 " chre_power_test_client gnss <optional: tcm> <enable> <interval_ms>"
818 " <next_fix_ms>\n"
819 " chre_power_test_client cell <optional: tcm> <enable> <interval_ns>\n"
820 " chre_power_test_client audio <optional: tcm> <enable> <duration_ns>\n"
821 " chre_power_test_client sensor <optional: tcm> <enable> <sensor_type>"
822 " <interval_ns> <optional: latency_ns>\n"
823 " chre_power_test_client breakit <optional: tcm> <enable>\n"
824 " chre_power_test_client gnss_meas <optional: tcm> <enable> <interval_ms>"
825 "\n"
826 " chre_power_test_client wifi_nan_sub <optional: tcm> <sub_type>"
827 " <service_name>\n"
828 " chre_power_test_client end_wifi_nan_sub <optional: tcm>"
829 " <subscription_id>\n"
830 "Command:\n"
831 "load: load power test nanoapp to CHRE\n"
832 "unload: unload power test nanoapp from CHRE\n"
833 "unloadall: unload all nanoapps in CHRE\n"
834 "timer: start/stop timer wake up\n"
835 "wifi: start/stop periodic wifi scan\n"
836 "gnss: start/stop periodic GPS scan\n"
837 "cell: start/stop periodic cellular scan\n"
838 "audio: start/stop periodic audio capture\n"
839 "sensor: start/stop periodic sensor sampling\n"
840 "breakit: start/stop all action for stress tests\n"
841 "gnss_meas: start/stop periodic GNSS measurement\n"
842 "wifi_nan_sub: start a WiFi NAN subscription\n"
843 "end_wifi_nan_sub: end a WiFi NAN subscription\n"
844 "\n"
845 "<optional: tcm>: tcm for micro image, default for big image\n"
846 "<enable>: enable/disable\n"
847 "\n"
848 "<sensor_type>:\n"
849 " accelerometer\n"
850 " instant_motion\n"
851 " stationary\n"
852 " gyroscope\n"
853 " uncalibrated_gyroscope\n"
854 " geomagnetic\n"
855 " uncalibrated_geomagnetic\n"
856 " pressure\n"
857 " light\n"
858 " proximity\n"
859 " step\n"
860 " uncalibrated_accelerometer\n"
861 " accelerometer_temperature\n"
862 " gyroscope_temperature\n"
863 " geomanetic_temperature\n"
864 "\n"
865 " For instant_montion and stationary sersor, it is not necessary to"
866 " provide the interval and latency.\n"
867 "\n"
868 "<wifi_scan_type>:\n"
869 " active\n"
870 " active_passive_dfs\n"
871 " passive\n"
872 " no_preference (default when omitted)\n"
873 "\n"
874 "<wifi_radio_chain>:\n"
875 " default (default when omitted)\n"
876 " low_latency\n"
877 " low_power\n"
878 " high_accuracy\n"
879 "\n"
880 "<wifi_channel_set>:\n"
881 " non_dfs (default when omitted)\n"
882 " all\n");
883 }
884
createRequestMessage(Command commandEnum,FlatBufferBuilder & fbb,std::vector<string> & args)885 void createRequestMessage(Command commandEnum, FlatBufferBuilder &fbb,
886 std::vector<string> &args) {
887 switch (commandEnum) {
888 case Command::kTimer:
889 createTimerMessage(fbb, args);
890 break;
891 case Command::kWifi:
892 createWifiMessage(fbb, args);
893 break;
894 case Command::kGnss:
895 createGnssMessage(fbb, args);
896 break;
897 case Command::kCell:
898 createCellMessage(fbb, args);
899 break;
900 case Command::kAudio:
901 createAudioMessage(fbb, args);
902 break;
903 case Command::kSensor:
904 createSensorMessage(fbb, args);
905 break;
906 case Command::kBreakIt:
907 createBreakItMessage(fbb, args);
908 break;
909 case Command::kGnssMeas:
910 createGnssMeasMessage(fbb, args);
911 break;
912 case Command::kNanSub:
913 createNanSubMessage(fbb, args);
914 break;
915 case Command::kNanCancel:
916 createNanCancelMessage(fbb, args);
917 break;
918 default: {
919 usage();
920 }
921 }
922 }
923
924 } // anonymous namespace
925
main(int argc,char * argv[])926 int main(int argc, char *argv[]) {
927 int argi = 0;
928 const std::string name{argv[argi++]};
929 const std::string cmd{argi < argc ? argv[argi++] : ""};
930
931 string commandLine(name);
932
933 if (commandMap.find(cmd) == commandMap.end()) {
934 usage();
935 return -1;
936 }
937
938 commandLine.append(" " + cmd);
939 Command commandEnum = commandMap[cmd];
940
941 std::vector<std::string> args;
942 while (argi < argc) {
943 args.push_back(std::string(argv[argi++]));
944 commandLine.append(" " + args.back());
945 }
946
947 LOGI("Command line: %s", commandLine.c_str());
948
949 if (!validateArguments(commandEnum, args)) {
950 LOGE("Invalid arguments");
951 usage();
952 return -1;
953 }
954
955 SocketClient client;
956 sp<SocketCallbacks> callbacks = new SocketCallbacks(kReadyCond);
957
958 if (!client.connect("chre", callbacks)) {
959 LOGE("Couldn't connect to socket");
960 return -1;
961 }
962
963 bool success = false;
964 switch (commandEnum) {
965 case Command::kUnloadAll: {
966 success = unloadAllNanoapps(client, callbacks);
967 break;
968 }
969 case Command::kUnload: {
970 success = unloadNanoapp(client, callbacks, getId(args));
971 break;
972 }
973 case Command::kLoad: {
974 LOGI("Loading nanoapp from %s", getPath(args).c_str());
975 std::string filepath = getPath(args);
976 // Strip extension if present so the path can be used for both the
977 // nanoapp header and .so
978 size_t index = filepath.find_last_of(".");
979 if (index != std::string::npos) {
980 filepath = filepath.substr(0, index);
981 }
982 success = loadNanoapp(client, callbacks, filepath);
983 break;
984 }
985 default: {
986 if (!isLoaded(client, callbacks, args)) {
987 LOGE("The power test nanoapp has to be loaded before sending request");
988 return -1;
989 }
990 FlatBufferBuilder fbb(64);
991 createRequestMessage(commandEnum, fbb, args);
992 success = sendMessageToNanoapp(client, callbacks, fbb, getId(args),
993 messageTypeMap[cmd]);
994 }
995 }
996
997 client.disconnect();
998 return success ? 0 : -1;
999 }
1000