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 kEtcPath = "vendor/etc/chre/" + name;
485 
486   struct stat buf;
487   if (stat(kAdspPath.c_str(), &buf) == 0) {
488     return kAdspPath;
489   } else if (stat(kSdspPath.c_str(), &buf) == 0) {
490     return kSdspPath;
491   } else {
492     return kEtcPath;
493   }
494 }
495 
496 /**
497  * When user provides the customized path in tcm mode, the args[1] is the path.
498  * In this case, the args[0] has to be "tcm". When user provide customized path
499  * for non-tcm mode, the args[0] is the path.
500  */
501 
getPath(std::vector<string> & args)502 inline const string getPath(std::vector<string> &args) {
503   if (args.empty()) {
504     return searchPath(kPowerTestName);
505   }
506   if (args[0] == "tcm") {
507     if (args.size() > 1) {
508       return args[1];
509     }
510     return searchPath(kPowerTestTcmName);
511   }
512   return args[0];
513 }
514 
getNanoseconds(std::vector<string> & args,size_t index)515 inline uint64_t getNanoseconds(std::vector<string> &args, size_t index) {
516   return args.size() > index ? strtoull(args[index].c_str(), NULL, 0) : 0;
517 }
518 
getMilliseconds(std::vector<string> & args,size_t index)519 inline uint32_t getMilliseconds(std::vector<string> &args, size_t index) {
520   return args.size() > index ? strtoul(args[index].c_str(), NULL, 0) : 0;
521 }
522 
isLoaded(SocketClient & client,sp<SocketCallbacks> callbacks,std::vector<string> & args)523 bool isLoaded(SocketClient &client, sp<SocketCallbacks> callbacks,
524               std::vector<string> &args) {
525   uint64_t id = getId(args);
526   if (!listNanoapps(client)) {
527     return false;
528   }
529   for (auto appId : callbacks->getAppIdVector()) {
530     if (appId == id) {
531       LOGI("The required nanoapp was loaded");
532       return true;
533     }
534   }
535   LOGE("The required nanoapp was not loaded");
536   return false;
537 }
538 
validateSensorArguments(std::vector<string> & args)539 bool validateSensorArguments(std::vector<string> &args) {
540   if (args.size() < 3) {
541     LOGE("Sensor type is required");
542     return false;
543   }
544 
545   if (sensorTypeMap.find(args[2]) == sensorTypeMap.end()) {
546     LOGE("Invalid sensor type");
547     return false;
548   }
549 
550   SensorType sensorType = sensorTypeMap[args[2]];
551   if (sensorType == SensorType::STATIONARY_DETECT ||
552       sensorType == SensorType::INSTANT_MOTION_DETECT)
553     return true;
554 
555   uint64_t intervalNanoseconds = getNanoseconds(args, 3);
556   uint64_t latencyNanoseconds = getNanoseconds(args, 4);
557   if (intervalNanoseconds == 0) {
558     LOGE("Non zero sensor sampling interval is required when enable");
559     return false;
560   }
561   if (latencyNanoseconds != 0 && latencyNanoseconds < intervalNanoseconds) {
562     LOGE("The latency is not zero and smaller than the interval");
563     return false;
564   }
565   return true;
566 }
567 
validateWifiArguments(std::vector<string> & args)568 bool validateWifiArguments(std::vector<string> &args) {
569   if (args.size() < 3) {
570     LOGE("The interval is required");
571     return false;
572   }
573 
574   bool valid = true;
575   WifiScanType scanType;
576   WifiRadioChain radioChain;
577   WifiChannelSet channelSet;
578   for (int i = 3; i < 6 && args.size() > i && valid; i++) {
579     valid = wifiScanTypeMatch(args[i], &scanType) ||
580             wifiRadioChainMatch(args[i], &radioChain) ||
581             wifiChannelSetMatch(args[i], &channelSet);
582     if (!valid) {
583       LOGE("Invalid WiFi scan parameters: %s", args[i].c_str());
584       return false;
585     }
586   }
587 
588   uint64_t intervalNanoseconds = getNanoseconds(args, 2);
589   if (intervalNanoseconds == 0) {
590     LOGE("Non-zero WiFi request interval is required");
591     return false;
592   }
593 
594   return true;
595 }
596 
validateArguments(Command commandEnum,std::vector<string> & args)597 bool validateArguments(Command commandEnum, std::vector<string> &args) {
598   // Commands: unloadall, load, unload
599   if (static_cast<uint32_t>(commandEnum) < 3) return true;
600 
601   // The other commands.
602   if (args.empty()) {
603     LOGE("Not enough parameters");
604     return false;
605   }
606 
607   // For non tcm option, add one item to the head of args to align argument
608   // position with that with tcm option.
609   if (args[0] != "tcm") args.insert(args.begin(), "");
610   if (args.size() < 2) {
611     LOGE("Not enough parameters");
612     return false;
613   }
614 
615   if (commandEnum == Command::kNanSub) {
616     if (args.size() != 3) {
617       LOGE("Incorrect number of parameters for NAN sub");
618       return false;
619     }
620     return true;
621   }
622 
623   if (commandEnum == Command::kNanCancel) {
624     if (args.size() != 2) {
625       LOGE("Incorrect number of parameters for NAN cancel");
626       return false;
627     }
628     return true;
629   }
630 
631   if (args[1] != "enable" && args[1] != "disable") {
632     LOGE("<enable> was neither enable nor disable");
633     return false;
634   }
635 
636   if (commandEnum == Command::kBreakIt) return true;
637 
638   if (args[1] == "disable") {
639     if (commandEnum != Command::kSensor) return true;
640     if (args.size() > 2 && sensorTypeMap.find(args[2]) != sensorTypeMap.end())
641       return true;
642     LOGE("No sensor type or invalid sensor type");
643     return false;
644   }
645 
646   // Case of "enable":
647   if (commandEnum == Command::kSensor) {
648     return validateSensorArguments(args);
649   } else if (commandEnum == Command::kWifi) {
650     return validateWifiArguments(args);
651   } else {
652     if (args.size() < 3) {
653       LOGE("The interval or duration was not provided");
654       return false;
655     }
656 
657     // For checking if the interval is 0. The getNanoseconds and
658     // and the getMilliseconds are exchangable in this case.
659     if (getNanoseconds(args, 2) == 0) {
660       LOGE("Non zero interval or duration is required when enable");
661       return false;
662     }
663     return true;
664   }
665 }
666 
createTimerMessage(FlatBufferBuilder & fbb,std::vector<string> & args)667 void createTimerMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
668   bool enable = (args[1] == "enable");
669   uint64_t intervalNanoseconds = getNanoseconds(args, 2);
670   fbb.Finish(ptest::CreateTimerMessage(fbb, enable, intervalNanoseconds));
671   LOGI("Created TimerMessage, enable %d, wakeup interval ns %" PRIu64, enable,
672        intervalNanoseconds);
673 }
674 
createWifiMessage(FlatBufferBuilder & fbb,std::vector<string> & args)675 void createWifiMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
676   bool enable = (args[1] == "enable");
677   uint64_t intervalNanoseconds = getNanoseconds(args, 2);
678   WifiScanType scanType = WifiScanType::NO_PREFERENCE;
679   WifiRadioChain radioChain = WifiRadioChain::DEFAULT;
680   WifiChannelSet channelSet = WifiChannelSet::NON_DFS;
681 
682   // Check for the 3 optional parameters.
683   bool valid = true;
684   for (int i = 3; i < 6 && args.size() > i && valid; i++) {
685     valid = wifiScanTypeMatch(args[i], &scanType) ||
686             wifiRadioChainMatch(args[i], &radioChain) ||
687             wifiChannelSetMatch(args[i], &channelSet);
688   }
689 
690   fbb.Finish(ptest::CreateWifiScanMessage(fbb, enable, intervalNanoseconds,
691                                           scanType, radioChain, channelSet));
692   LOGI("Created WifiScanMessage, enable %d, scan interval ns %" PRIu64
693        " scan type %" PRIu8 " radio chain %" PRIu8 " channel set %" PRIu8,
694        enable, intervalNanoseconds, static_cast<uint8_t>(scanType),
695        static_cast<uint8_t>(radioChain), static_cast<uint8_t>(channelSet));
696 }
697 
createGnssMessage(FlatBufferBuilder & fbb,std::vector<string> & args)698 void createGnssMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
699   bool enable = (args[1] == "enable");
700   uint32_t intervalMilliseconds = getMilliseconds(args, 2);
701   uint32_t toNextFixMilliseconds = getMilliseconds(args, 3);
702   fbb.Finish(ptest::CreateGnssLocationMessage(fbb, enable, intervalMilliseconds,
703                                               toNextFixMilliseconds));
704   LOGI("Created GnssLocationMessage, enable %d, scan interval ms %" PRIu32
705        " min time to next fix ms %" PRIu32,
706        enable, intervalMilliseconds, toNextFixMilliseconds);
707 }
708 
createCellMessage(FlatBufferBuilder & fbb,std::vector<string> & args)709 void createCellMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
710   bool enable = (args[1] == "enable");
711   uint64_t intervalNanoseconds = getNanoseconds(args, 2);
712   fbb.Finish(ptest::CreateCellQueryMessage(fbb, enable, intervalNanoseconds));
713   LOGI("Created CellQueryMessage, enable %d, query interval ns %" PRIu64,
714        enable, intervalNanoseconds);
715 }
716 
createAudioMessage(FlatBufferBuilder & fbb,std::vector<string> & args)717 void createAudioMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
718   bool enable = (args[1] == "enable");
719   uint64_t durationNanoseconds = getNanoseconds(args, 2);
720   fbb.Finish(
721       ptest::CreateAudioRequestMessage(fbb, enable, durationNanoseconds));
722   LOGI("Created AudioRequestMessage, enable %d, buffer duration ns %" PRIu64,
723        enable, durationNanoseconds);
724 }
725 
createSensorMessage(FlatBufferBuilder & fbb,std::vector<string> & args)726 void createSensorMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
727   bool enable = (args[1] == "enable");
728   SensorType sensorType = sensorTypeMap[args[2]];
729   uint64_t intervalNanoseconds = getNanoseconds(args, 3);
730   uint64_t latencyNanoseconds = getNanoseconds(args, 4);
731   if (sensorType == SensorType::STATIONARY_DETECT ||
732       sensorType == SensorType::INSTANT_MOTION_DETECT) {
733     intervalNanoseconds = kUint64Max;
734     latencyNanoseconds = 0;
735   }
736   fbb.Finish(ptest::CreateSensorRequestMessage(
737       fbb, enable, sensorType, intervalNanoseconds, latencyNanoseconds));
738   LOGI(
739       "Created SensorRequestMessage, enable %d, %s sensor, sampling "
740       "interval ns %" PRIu64 ", latency ns %" PRIu64,
741       enable, ptest::EnumNameSensorType(sensorType), intervalNanoseconds,
742       latencyNanoseconds);
743 }
744 
createBreakItMessage(FlatBufferBuilder & fbb,std::vector<string> & args)745 void createBreakItMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
746   bool enable = (args[1] == "enable");
747   fbb.Finish(ptest::CreateBreakItMessage(fbb, enable));
748   LOGI("Created BreakItMessage, enable %d", enable);
749 }
750 
createGnssMeasMessage(FlatBufferBuilder & fbb,std::vector<string> & args)751 void createGnssMeasMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
752   bool enable = (args[1] == "enable");
753   uint32_t intervalMilliseconds = getMilliseconds(args, 2);
754   fbb.Finish(
755       ptest::CreateGnssMeasurementMessage(fbb, enable, intervalMilliseconds));
756   LOGI("Created GnssMeasurementMessage, enable %d, interval ms %" PRIu32,
757        enable, intervalMilliseconds);
758 }
759 
createNanSubMessage(FlatBufferBuilder & fbb,std::vector<string> & args)760 void createNanSubMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
761   uint8_t subType = atoi(args[1].c_str());
762   std::string &serviceName = args[2];
763   std::vector<uint8_t> serviceNameBytes(serviceName.begin(), serviceName.end());
764   fbb.Finish(
765       ptest::CreateWifiNanSubMessageDirect(fbb, subType, &serviceNameBytes));
766   LOGI("Created NAN subscription message, subType %d serviceName %s", subType,
767        serviceName.c_str());
768 }
769 
createNanCancelMessage(FlatBufferBuilder & fbb,std::vector<string> & args)770 void createNanCancelMessage(FlatBufferBuilder &fbb, std::vector<string> &args) {
771   uint32_t subId = strtoul(args[1].c_str(), nullptr /* endptr */, 0 /* base */);
772   fbb.Finish(ptest::CreateWifiNanSubCancelMessage(fbb, subId));
773   LOGI("Created NAN subscription cancel message, subId %" PRIu32, subId);
774 }
775 
sendMessageToNanoapp(SocketClient & client,sp<SocketCallbacks> callbacks,FlatBufferBuilder & fbb,uint64_t appId,MessageType messageType)776 bool sendMessageToNanoapp(SocketClient &client, sp<SocketCallbacks> callbacks,
777                           FlatBufferBuilder &fbb, uint64_t appId,
778                           MessageType messageType) {
779   FlatBufferBuilder builder(128);
780   HostProtocolHost::encodeNanoappMessage(
781       builder, appId, static_cast<uint32_t>(messageType), kHostEndpoint,
782       fbb.GetBufferPointer(), fbb.GetSize());
783   LOGI("sending %s message to nanoapp (%" PRIu32 " bytes w/%" PRIu32
784        " bytes of payload)",
785        ptest::EnumNameMessageType(messageType), builder.GetSize(),
786        fbb.GetSize());
787   if (!client.sendMessage(builder.GetBufferPointer(), builder.GetSize())) {
788     LOGE("Failed to send %s message", ptest::EnumNameMessageType(messageType));
789     return false;
790   }
791   auto status = kReadyCond.wait_for(kReadyCondLock, kTimeout);
792   bool success =
793       (status == std::cv_status::no_timeout && callbacks->actionSucceeded());
794   LOGI("Sent %s message to nanoapp success: %d",
795        ptest::EnumNameMessageType(messageType), success);
796   if (status == std::cv_status::timeout) {
797     LOGE("Sent %s message to nanoapp timeout",
798          ptest::EnumNameMessageType(messageType));
799   }
800   return success;
801 }
802 
usage()803 static void usage() {
804   LOGI(
805       "\n"
806       "Usage:\n"
807       " chre_power_test_client load <optional: tcm> <optional: path>\n"
808       " chre_power_test_client unload <optional: tcm>\n"
809       " chre_power_test_client unloadall\n"
810       " chre_power_test_client timer <optional: tcm> <enable> <interval_ns>\n"
811       " chre_power_test_client wifi <optional: tcm> <enable> <interval_ns>"
812       " <optional: wifi_scan_type> <optional: wifi_radio_chain>"
813       " <optional: wifi_channel_set>\n"
814       " chre_power_test_client gnss <optional: tcm> <enable> <interval_ms>"
815       " <next_fix_ms>\n"
816       " chre_power_test_client cell <optional: tcm> <enable> <interval_ns>\n"
817       " chre_power_test_client audio <optional: tcm> <enable> <duration_ns>\n"
818       " chre_power_test_client sensor <optional: tcm> <enable> <sensor_type>"
819       " <interval_ns> <optional: latency_ns>\n"
820       " chre_power_test_client breakit <optional: tcm> <enable>\n"
821       " chre_power_test_client gnss_meas <optional: tcm> <enable> <interval_ms>"
822       "\n"
823       " chre_power_test_client wifi_nan_sub <optional: tcm> <sub_type>"
824       " <service_name>\n"
825       " chre_power_test_client end_wifi_nan_sub <optional: tcm>"
826       " <subscription_id>\n"
827       "Command:\n"
828       "load: load power test nanoapp to CHRE\n"
829       "unload: unload power test nanoapp from CHRE\n"
830       "unloadall: unload all nanoapps in CHRE\n"
831       "timer: start/stop timer wake up\n"
832       "wifi: start/stop periodic wifi scan\n"
833       "gnss: start/stop periodic GPS scan\n"
834       "cell: start/stop periodic cellular scan\n"
835       "audio: start/stop periodic audio capture\n"
836       "sensor: start/stop periodic sensor sampling\n"
837       "breakit: start/stop all action for stress tests\n"
838       "gnss_meas: start/stop periodic GNSS measurement\n"
839       "wifi_nan_sub: start a WiFi NAN subscription\n"
840       "end_wifi_nan_sub: end a WiFi NAN subscription\n"
841       "\n"
842       "<optional: tcm>: tcm for micro image, default for big image\n"
843       "<enable>: enable/disable\n"
844       "\n"
845       "<sensor_type>:\n"
846       " accelerometer\n"
847       " instant_motion\n"
848       " stationary\n"
849       " gyroscope\n"
850       " uncalibrated_gyroscope\n"
851       " geomagnetic\n"
852       " uncalibrated_geomagnetic\n"
853       " pressure\n"
854       " light\n"
855       " proximity\n"
856       " step\n"
857       " uncalibrated_accelerometer\n"
858       " accelerometer_temperature\n"
859       " gyroscope_temperature\n"
860       " geomanetic_temperature\n"
861       "\n"
862       " For instant_montion and stationary sersor, it is not necessary to"
863       " provide the interval and latency.\n"
864       "\n"
865       "<wifi_scan_type>:\n"
866       " active\n"
867       " active_passive_dfs\n"
868       " passive\n"
869       " no_preference (default when omitted)\n"
870       "\n"
871       "<wifi_radio_chain>:\n"
872       " default (default when omitted)\n"
873       " low_latency\n"
874       " low_power\n"
875       " high_accuracy\n"
876       "\n"
877       "<wifi_channel_set>:\n"
878       " non_dfs (default when omitted)\n"
879       " all\n");
880 }
881 
createRequestMessage(Command commandEnum,FlatBufferBuilder & fbb,std::vector<string> & args)882 void createRequestMessage(Command commandEnum, FlatBufferBuilder &fbb,
883                           std::vector<string> &args) {
884   switch (commandEnum) {
885     case Command::kTimer:
886       createTimerMessage(fbb, args);
887       break;
888     case Command::kWifi:
889       createWifiMessage(fbb, args);
890       break;
891     case Command::kGnss:
892       createGnssMessage(fbb, args);
893       break;
894     case Command::kCell:
895       createCellMessage(fbb, args);
896       break;
897     case Command::kAudio:
898       createAudioMessage(fbb, args);
899       break;
900     case Command::kSensor:
901       createSensorMessage(fbb, args);
902       break;
903     case Command::kBreakIt:
904       createBreakItMessage(fbb, args);
905       break;
906     case Command::kGnssMeas:
907       createGnssMeasMessage(fbb, args);
908       break;
909     case Command::kNanSub:
910       createNanSubMessage(fbb, args);
911       break;
912     case Command::kNanCancel:
913       createNanCancelMessage(fbb, args);
914       break;
915     default: {
916       usage();
917     }
918   }
919 }
920 
921 }  // anonymous namespace
922 
main(int argc,char * argv[])923 int main(int argc, char *argv[]) {
924   int argi = 0;
925   const std::string name{argv[argi++]};
926   const std::string cmd{argi < argc ? argv[argi++] : ""};
927 
928   string commandLine(name);
929 
930   if (commandMap.find(cmd) == commandMap.end()) {
931     usage();
932     return -1;
933   }
934 
935   commandLine.append(" " + cmd);
936   Command commandEnum = commandMap[cmd];
937 
938   std::vector<std::string> args;
939   while (argi < argc) {
940     args.push_back(std::string(argv[argi++]));
941     commandLine.append(" " + args.back());
942   }
943 
944   LOGI("Command line: %s", commandLine.c_str());
945 
946   if (!validateArguments(commandEnum, args)) {
947     LOGE("Invalid arguments");
948     usage();
949     return -1;
950   }
951 
952   SocketClient client;
953   sp<SocketCallbacks> callbacks = new SocketCallbacks(kReadyCond);
954 
955   if (!client.connect("chre", callbacks)) {
956     LOGE("Couldn't connect to socket");
957     return -1;
958   }
959 
960   bool success = false;
961   switch (commandEnum) {
962     case Command::kUnloadAll: {
963       success = unloadAllNanoapps(client, callbacks);
964       break;
965     }
966     case Command::kUnload: {
967       success = unloadNanoapp(client, callbacks, getId(args));
968       break;
969     }
970     case Command::kLoad: {
971       LOGI("Loading nanoapp from %s", getPath(args).c_str());
972       std::string filepath = getPath(args);
973       // Strip extension if present so the path can be used for both the
974       // nanoapp header and .so
975       size_t index = filepath.find_last_of(".");
976       if (index != std::string::npos) {
977         filepath = filepath.substr(0, index);
978       }
979       success = loadNanoapp(client, callbacks, filepath);
980       break;
981     }
982     default: {
983       if (!isLoaded(client, callbacks, args)) {
984         LOGE("The power test nanoapp has to be loaded before sending request");
985         return -1;
986       }
987       FlatBufferBuilder fbb(64);
988       createRequestMessage(commandEnum, fbb, args);
989       success = sendMessageToNanoapp(client, callbacks, fbb, getId(args),
990                                      messageTypeMap[cmd]);
991     }
992   }
993 
994   client.disconnect();
995   return success ? 0 : -1;
996 }
997