• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 #include "BroadcastRadio.h"
18 #include <broadcastradio-utils-aidl/Utils.h>
19 #include "resources.h"
20 
21 #include <aidl/android/hardware/broadcastradio/IdentifierType.h>
22 #include <aidl/android/hardware/broadcastradio/Result.h>
23 
24 #include <android-base/logging.h>
25 #include <android-base/strings.h>
26 
27 #include <private/android_filesystem_config.h>
28 
29 namespace aidl::android::hardware::broadcastradio {
30 
31 using ::aidl::android::hardware::broadcastradio::utils::resultToInt;
32 using ::aidl::android::hardware::broadcastradio::utils::tunesTo;
33 using ::android::base::EqualsIgnoreCase;
34 using ::ndk::ScopedAStatus;
35 using ::std::literals::chrono_literals::operator""ms;
36 using ::std::literals::chrono_literals::operator""s;
37 using ::std::lock_guard;
38 using ::std::mutex;
39 using ::std::string;
40 using ::std::vector;
41 
42 namespace {
43 
44 inline constexpr std::chrono::milliseconds kSeekDelayTimeMs = 200ms;
45 inline constexpr std::chrono::milliseconds kStepDelayTimeMs = 100ms;
46 inline constexpr std::chrono::milliseconds kTuneDelayTimeMs = 150ms;
47 inline constexpr std::chrono::seconds kListDelayTimeS = 1s;
48 
49 // clang-format off
50 const AmFmRegionConfig kDefaultAmFmConfig = {
51         {
52                 {87500, 108000, 100, 100},  // FM
53                 {153, 282, 3, 9},           // AM LW
54                 {531, 1620, 9, 9},          // AM MW
55                 {1600, 30000, 1, 5},        // AM SW
56         },
57         AmFmRegionConfig::DEEMPHASIS_D50,
58         AmFmRegionConfig::RDS};
59 // clang-format on
60 
initProperties(const VirtualRadio & virtualRadio)61 Properties initProperties(const VirtualRadio& virtualRadio) {
62     Properties prop = {};
63 
64     prop.maker = "Android";
65     prop.product = virtualRadio.getName();
66     prop.supportedIdentifierTypes = vector<IdentifierType>({
67             IdentifierType::AMFM_FREQUENCY_KHZ,
68             IdentifierType::RDS_PI,
69             IdentifierType::HD_STATION_ID_EXT,
70             IdentifierType::DAB_SID_EXT,
71     });
72     prop.vendorInfo = vector<VendorKeyValue>({
73             {"com.android.sample", "sample"},
74     });
75 
76     return prop;
77 }
78 
79 // Makes ProgramInfo that does not point to any particular program
makeSampleProgramInfo(const ProgramSelector & selector)80 ProgramInfo makeSampleProgramInfo(const ProgramSelector& selector) {
81     ProgramInfo info = {};
82     info.selector = selector;
83     info.logicallyTunedTo =
84             utils::makeIdentifier(IdentifierType::AMFM_FREQUENCY_KHZ,
85                                   utils::getId(selector, IdentifierType::AMFM_FREQUENCY_KHZ));
86     info.physicallyTunedTo = info.logicallyTunedTo;
87     return info;
88 }
89 
checkDumpCallerHasWritePermissions(int fd)90 static bool checkDumpCallerHasWritePermissions(int fd) {
91     uid_t uid = AIBinder_getCallingUid();
92     if (uid == AID_ROOT || uid == AID_SHELL || uid == AID_SYSTEM) {
93         return true;
94     }
95     dprintf(fd, "BroadcastRadio HAL dump must be root, shell or system\n");
96     return false;
97 }
98 
99 }  // namespace
100 
BroadcastRadio(const VirtualRadio & virtualRadio)101 BroadcastRadio::BroadcastRadio(const VirtualRadio& virtualRadio)
102     : mVirtualRadio(virtualRadio),
103       mAmFmConfig(kDefaultAmFmConfig),
104       mProperties(initProperties(virtualRadio)) {
105     const auto& ranges = kDefaultAmFmConfig.ranges;
106     if (ranges.size() > 0) {
107         ProgramSelector sel = utils::makeSelectorAmfm(ranges[0].lowerBound);
108         VirtualProgram virtualProgram = {};
109         if (mVirtualRadio.getProgram(sel, &virtualProgram)) {
110             mCurrentProgram = virtualProgram.selector;
111         } else {
112             mCurrentProgram = sel;
113         }
114     }
115 }
116 
~BroadcastRadio()117 BroadcastRadio::~BroadcastRadio() {
118     mThread.reset();
119 }
120 
getAmFmRegionConfig(bool full,AmFmRegionConfig * returnConfigs)121 ScopedAStatus BroadcastRadio::getAmFmRegionConfig(bool full, AmFmRegionConfig* returnConfigs) {
122     if (full) {
123         *returnConfigs = {};
124         returnConfigs->ranges = vector<AmFmBandRange>({
125                 {65000, 108000, 10, 0},  // FM
126                 {150, 30000, 1, 0},      // AM
127         });
128         returnConfigs->fmDeemphasis =
129                 AmFmRegionConfig::DEEMPHASIS_D50 | AmFmRegionConfig::DEEMPHASIS_D75;
130         returnConfigs->fmRds = AmFmRegionConfig::RDS | AmFmRegionConfig::RBDS;
131         return ScopedAStatus::ok();
132     }
133     lock_guard<mutex> lk(mMutex);
134     *returnConfigs = mAmFmConfig;
135     return ScopedAStatus::ok();
136 }
137 
getDabRegionConfig(vector<DabTableEntry> * returnConfigs)138 ScopedAStatus BroadcastRadio::getDabRegionConfig(vector<DabTableEntry>* returnConfigs) {
139     *returnConfigs = {
140             {"5A", 174928},  {"7D", 194064},  {"8A", 195936},  {"8B", 197648},  {"9A", 202928},
141             {"9B", 204640},  {"9C", 206352},  {"10B", 211648}, {"10C", 213360}, {"10D", 215072},
142             {"11A", 216928}, {"11B", 218640}, {"11C", 220352}, {"11D", 222064}, {"12A", 223936},
143             {"12B", 225648}, {"12C", 227360}, {"12D", 229072},
144     };
145     return ScopedAStatus::ok();
146 }
147 
getImage(int32_t id,vector<uint8_t> * returnImage)148 ScopedAStatus BroadcastRadio::getImage(int32_t id, vector<uint8_t>* returnImage) {
149     LOG(DEBUG) << __func__ << ": fetching image " << std::hex << id;
150 
151     if (id == resources::kDemoPngId) {
152         *returnImage = vector<uint8_t>(resources::kDemoPng, std::end(resources::kDemoPng));
153         return ScopedAStatus::ok();
154     }
155 
156     LOG(WARNING) << __func__ << ": image of id " << std::hex << id << " doesn't exist";
157     *returnImage = {};
158     return ScopedAStatus::ok();
159 }
160 
getProperties(Properties * returnProperties)161 ScopedAStatus BroadcastRadio::getProperties(Properties* returnProperties) {
162     lock_guard<mutex> lk(mMutex);
163     *returnProperties = mProperties;
164     return ScopedAStatus::ok();
165 }
166 
tuneInternalLocked(const ProgramSelector & sel)167 ProgramInfo BroadcastRadio::tuneInternalLocked(const ProgramSelector& sel) {
168     LOG(DEBUG) << __func__ << ": tune (internal) to " << sel.toString();
169 
170     VirtualProgram virtualProgram = {};
171     ProgramInfo programInfo;
172     if (mVirtualRadio.getProgram(sel, &virtualProgram)) {
173         mCurrentProgram = virtualProgram.selector;
174         programInfo = virtualProgram;
175     } else {
176         mCurrentProgram = sel;
177         programInfo = makeSampleProgramInfo(sel);
178     }
179     mIsTuneCompleted = true;
180 
181     return programInfo;
182 }
183 
setTunerCallback(const std::shared_ptr<ITunerCallback> & callback)184 ScopedAStatus BroadcastRadio::setTunerCallback(const std::shared_ptr<ITunerCallback>& callback) {
185     LOG(DEBUG) << __func__ << ": setTunerCallback";
186 
187     if (callback == nullptr) {
188         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
189                 resultToInt(Result::INVALID_ARGUMENTS), "cannot set tuner callback to null");
190     }
191 
192     lock_guard<mutex> lk(mMutex);
193     mCallback = callback;
194 
195     return ScopedAStatus::ok();
196 }
197 
unsetTunerCallback()198 ScopedAStatus BroadcastRadio::unsetTunerCallback() {
199     LOG(DEBUG) << __func__ << ": unsetTunerCallback";
200 
201     lock_guard<mutex> lk(mMutex);
202     mCallback = nullptr;
203 
204     return ScopedAStatus::ok();
205 }
206 
tune(const ProgramSelector & program)207 ScopedAStatus BroadcastRadio::tune(const ProgramSelector& program) {
208     LOG(DEBUG) << __func__ << ": tune to " << program.toString() << "...";
209 
210     lock_guard<mutex> lk(mMutex);
211     if (mCallback == nullptr) {
212         LOG(ERROR) << __func__ << ": callback is not registered.";
213         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
214                 resultToInt(Result::INVALID_STATE), "callback is not registered");
215     }
216 
217     if (!utils::isSupported(mProperties, program)) {
218         LOG(WARNING) << __func__ << ": selector not supported: " << program.toString();
219         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
220                 resultToInt(Result::NOT_SUPPORTED), "selector is not supported");
221     }
222 
223     if (!utils::isValid(program)) {
224         LOG(ERROR) << __func__ << ": selector is not valid: " << program.toString();
225         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
226                 resultToInt(Result::INVALID_ARGUMENTS), "selector is not valid");
227     }
228 
229     cancelLocked();
230 
231     mIsTuneCompleted = false;
232     std::shared_ptr<ITunerCallback> callback = mCallback;
233     auto task = [this, program, callback]() {
234         ProgramInfo programInfo = {};
235         {
236             lock_guard<mutex> lk(mMutex);
237             programInfo = tuneInternalLocked(program);
238         }
239         callback->onCurrentProgramInfoChanged(programInfo);
240     };
241     auto cancelTask = [program, callback]() { callback->onTuneFailed(Result::CANCELED, program); };
242     mThread->schedule(task, cancelTask, kTuneDelayTimeMs);
243 
244     return ScopedAStatus::ok();
245 }
246 
seek(bool directionUp,bool skipSubChannel)247 ScopedAStatus BroadcastRadio::seek(bool directionUp, bool skipSubChannel) {
248     LOG(DEBUG) << __func__ << ": seek " << (directionUp ? "up" : "down") << " with skipSubChannel? "
249                << (skipSubChannel ? "yes" : "no") << "...";
250 
251     lock_guard<mutex> lk(mMutex);
252     if (mCallback == nullptr) {
253         LOG(ERROR) << __func__ << ": callback is not registered.";
254         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
255                 resultToInt(Result::INVALID_STATE), "callback is not registered");
256     }
257 
258     cancelLocked();
259 
260     const auto& list = mVirtualRadio.getProgramList();
261     std::shared_ptr<ITunerCallback> callback = mCallback;
262     auto cancelTask = [callback]() { callback->onTuneFailed(Result::CANCELED, {}); };
263     if (list.empty()) {
264         mIsTuneCompleted = false;
265         auto task = [callback]() {
266             LOG(DEBUG) << "seek: program list is empty, seek couldn't stop";
267 
268             callback->onTuneFailed(Result::TIMEOUT, {});
269         };
270         mThread->schedule(task, cancelTask, kSeekDelayTimeMs);
271 
272         return ScopedAStatus::ok();
273     }
274 
275     // The list is not sorted here since it has already stored in VirtualRadio.
276     // If the list is not sorted in advance, it should be sorted here.
277     const auto& current = mCurrentProgram;
278     auto found = std::lower_bound(list.begin(), list.end(), VirtualProgram({current}));
279     if (directionUp) {
280         if (found < list.end() - 1) {
281             if (tunesTo(current, found->selector)) found++;
282         } else {
283             found = list.begin();
284         }
285     } else {
286         if (found > list.begin() && found != list.end()) {
287             found--;
288         } else {
289             found = list.end() - 1;
290         }
291     }
292     const ProgramSelector tuneTo = found->selector;
293 
294     mIsTuneCompleted = false;
295     auto task = [this, tuneTo, callback]() {
296         ProgramInfo programInfo = {};
297         {
298             lock_guard<mutex> lk(mMutex);
299             programInfo = tuneInternalLocked(tuneTo);
300         }
301         callback->onCurrentProgramInfoChanged(programInfo);
302     };
303     mThread->schedule(task, cancelTask, kSeekDelayTimeMs);
304 
305     return ScopedAStatus::ok();
306 }
307 
step(bool directionUp)308 ScopedAStatus BroadcastRadio::step(bool directionUp) {
309     LOG(DEBUG) << __func__ << ": step " << (directionUp ? "up" : "down") << "...";
310 
311     lock_guard<mutex> lk(mMutex);
312     if (mCallback == nullptr) {
313         LOG(ERROR) << __func__ << ": callback is not registered.";
314         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
315                 resultToInt(Result::INVALID_STATE), "callback is not registered");
316     }
317 
318     cancelLocked();
319 
320     if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ)) {
321         LOG(WARNING) << __func__ << ": can't step in anything else than AM/FM";
322         return ScopedAStatus::fromServiceSpecificErrorWithMessage(
323                 resultToInt(Result::NOT_SUPPORTED), "cannot step in anything else than AM/FM");
324     }
325 
326     int64_t stepTo = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ);
327     std::optional<AmFmBandRange> range = getAmFmRangeLocked();
328     if (!range) {
329         LOG(ERROR) << __func__ << ": can't find current band or tune operation is in process";
330         ScopedAStatus::fromServiceSpecificErrorWithMessage(
331                 resultToInt(Result::INTERNAL_ERROR),
332                 "can't find current band or tune operation is in process");
333     }
334 
335     if (directionUp) {
336         stepTo += range->spacing;
337     } else {
338         stepTo -= range->spacing;
339     }
340     if (stepTo > range->upperBound) {
341         stepTo = range->lowerBound;
342     }
343     if (stepTo < range->lowerBound) {
344         stepTo = range->upperBound;
345     }
346 
347     mIsTuneCompleted = false;
348     std::shared_ptr<ITunerCallback> callback = mCallback;
349     auto task = [this, stepTo, callback]() {
350         ProgramInfo programInfo;
351         {
352             lock_guard<mutex> lk(mMutex);
353             programInfo = tuneInternalLocked(utils::makeSelectorAmfm(stepTo));
354         }
355         callback->onCurrentProgramInfoChanged(programInfo);
356     };
357     auto cancelTask = [callback]() { callback->onTuneFailed(Result::CANCELED, {}); };
358     mThread->schedule(task, cancelTask, kStepDelayTimeMs);
359 
360     return ScopedAStatus::ok();
361 }
362 
cancelLocked()363 void BroadcastRadio::cancelLocked() {
364     LOG(DEBUG) << __func__ << ": cancelling current operations...";
365 
366     mThread->cancelAll();
367     if (mCurrentProgram.primaryId.type != IdentifierType::INVALID) {
368         mIsTuneCompleted = true;
369     }
370 }
371 
cancel()372 ScopedAStatus BroadcastRadio::cancel() {
373     LOG(DEBUG) << __func__ << ": cancel pending tune, seek and step...";
374 
375     lock_guard<mutex> lk(mMutex);
376     cancelLocked();
377 
378     return ScopedAStatus::ok();
379 }
380 
startProgramListUpdates(const ProgramFilter & filter)381 ScopedAStatus BroadcastRadio::startProgramListUpdates(const ProgramFilter& filter) {
382     LOG(DEBUG) << __func__ << ": requested program list updates, filter = " << filter.toString()
383                << "...";
384 
385     auto filterCb = [&filter](const VirtualProgram& program) {
386         return utils::satisfies(filter, program.selector);
387     };
388 
389     lock_guard<mutex> lk(mMutex);
390 
391     const auto& list = mVirtualRadio.getProgramList();
392     vector<VirtualProgram> filteredList;
393     std::copy_if(list.begin(), list.end(), std::back_inserter(filteredList), filterCb);
394 
395     auto task = [this, filteredList]() {
396         std::shared_ptr<ITunerCallback> callback;
397         {
398             lock_guard<mutex> lk(mMutex);
399             if (mCallback == nullptr) {
400                 LOG(WARNING) << "Callback is null when updating program List";
401                 return;
402             }
403             callback = mCallback;
404         }
405 
406         ProgramListChunk chunk = {};
407         chunk.purge = true;
408         chunk.complete = true;
409         chunk.modified = vector<ProgramInfo>(filteredList.begin(), filteredList.end());
410 
411         callback->onProgramListUpdated(chunk);
412     };
413     mThread->schedule(task, kListDelayTimeS);
414 
415     return ScopedAStatus::ok();
416 }
417 
stopProgramListUpdates()418 ScopedAStatus BroadcastRadio::stopProgramListUpdates() {
419     LOG(DEBUG) << __func__ << ": requested program list updates to stop...";
420     // TODO(b/243681584) Implement stop program list updates method
421     return ScopedAStatus::ok();
422 }
423 
isConfigFlagSet(ConfigFlag flag,bool * returnIsSet)424 ScopedAStatus BroadcastRadio::isConfigFlagSet(ConfigFlag flag, [[maybe_unused]] bool* returnIsSet) {
425     LOG(DEBUG) << __func__ << ": flag = " << toString(flag);
426 
427     LOG(INFO) << __func__ << ": getting ConfigFlag is not supported";
428     return ScopedAStatus::fromServiceSpecificErrorWithMessage(
429             resultToInt(Result::NOT_SUPPORTED), "getting ConfigFlag is not supported");
430 }
431 
setConfigFlag(ConfigFlag flag,bool value)432 ScopedAStatus BroadcastRadio::setConfigFlag(ConfigFlag flag, bool value) {
433     LOG(DEBUG) << __func__ << ": flag = " << toString(flag) << ", value = " << value;
434 
435     LOG(INFO) << __func__ << ": setting ConfigFlag is not supported";
436     return ScopedAStatus::fromServiceSpecificErrorWithMessage(
437             resultToInt(Result::NOT_SUPPORTED), "setting ConfigFlag is not supported");
438 }
439 
setParameters(const vector<VendorKeyValue> & parameters,vector<VendorKeyValue> * returnParameters)440 ScopedAStatus BroadcastRadio::setParameters(
441         [[maybe_unused]] const vector<VendorKeyValue>& parameters,
442         vector<VendorKeyValue>* returnParameters) {
443     // TODO(b/243682330) Support vendor parameter functionality
444     *returnParameters = {};
445     return ScopedAStatus::ok();
446 }
447 
getParameters(const vector<string> & keys,vector<VendorKeyValue> * returnParameters)448 ScopedAStatus BroadcastRadio::getParameters([[maybe_unused]] const vector<string>& keys,
449                                             vector<VendorKeyValue>* returnParameters) {
450     // TODO(b/243682330) Support vendor parameter functionality
451     *returnParameters = {};
452     return ScopedAStatus::ok();
453 }
454 
getAmFmRangeLocked() const455 std::optional<AmFmBandRange> BroadcastRadio::getAmFmRangeLocked() const {
456     if (!mIsTuneCompleted) {
457         LOG(WARNING) << __func__ << ": tune operation is in process";
458         return {};
459     }
460     if (!utils::hasId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ)) {
461         LOG(WARNING) << __func__ << ": current program does not has AMFM_FREQUENCY_KHZ identifier";
462         return {};
463     }
464 
465     int64_t freq = utils::getId(mCurrentProgram, IdentifierType::AMFM_FREQUENCY_KHZ);
466     for (const auto& range : mAmFmConfig.ranges) {
467         if (range.lowerBound <= freq && range.upperBound >= freq) {
468             return range;
469         }
470     }
471 
472     return {};
473 }
474 
registerAnnouncementListener(const std::shared_ptr<IAnnouncementListener> & listener,const vector<AnnouncementType> & enabled,std::shared_ptr<ICloseHandle> * returnCloseHandle)475 ScopedAStatus BroadcastRadio::registerAnnouncementListener(
476         [[maybe_unused]] const std::shared_ptr<IAnnouncementListener>& listener,
477         const vector<AnnouncementType>& enabled, std::shared_ptr<ICloseHandle>* returnCloseHandle) {
478     LOG(DEBUG) << __func__ << ": registering announcement listener for "
479                << utils::vectorToString(enabled);
480 
481     // TODO(b/243683842) Support announcement listener
482     *returnCloseHandle = nullptr;
483     LOG(INFO) << __func__ << ": registering announcementListener is not supported";
484     return ScopedAStatus::fromServiceSpecificErrorWithMessage(
485             resultToInt(Result::NOT_SUPPORTED),
486             "registering announcementListener is not supported");
487 }
488 
dump(int fd,const char ** args,uint32_t numArgs)489 binder_status_t BroadcastRadio::dump(int fd, const char** args, uint32_t numArgs) {
490     if (numArgs == 0) {
491         return dumpsys(fd);
492     }
493 
494     string option = string(args[0]);
495     if (EqualsIgnoreCase(option, "--help")) {
496         return cmdHelp(fd);
497     } else if (EqualsIgnoreCase(option, "--tune")) {
498         return cmdTune(fd, args, numArgs);
499     } else if (EqualsIgnoreCase(option, "--seek")) {
500         return cmdSeek(fd, args, numArgs);
501     } else if (EqualsIgnoreCase(option, "--step")) {
502         return cmdStep(fd, args, numArgs);
503     } else if (EqualsIgnoreCase(option, "--cancel")) {
504         return cmdCancel(fd, numArgs);
505     } else if (EqualsIgnoreCase(option, "--startProgramListUpdates")) {
506         return cmdStartProgramListUpdates(fd, args, numArgs);
507     } else if (EqualsIgnoreCase(option, "--stopProgramListUpdates")) {
508         return cmdStopProgramListUpdates(fd, numArgs);
509     }
510     dprintf(fd, "Invalid option: %s\n", option.c_str());
511     return STATUS_BAD_VALUE;
512 }
513 
dumpsys(int fd)514 binder_status_t BroadcastRadio::dumpsys(int fd) {
515     if (!checkDumpCallerHasWritePermissions(fd)) {
516         return STATUS_PERMISSION_DENIED;
517     }
518     lock_guard<mutex> lk(mMutex);
519     dprintf(fd, "AmFmRegionConfig: %s\n", mAmFmConfig.toString().c_str());
520     dprintf(fd, "Properties: %s \n", mProperties.toString().c_str());
521     if (mIsTuneCompleted) {
522         dprintf(fd, "Tune completed\n");
523     } else {
524         dprintf(fd, "Tune not completed\n");
525     }
526     if (mCallback == nullptr) {
527         dprintf(fd, "No ITunerCallback registered\n");
528     } else {
529         dprintf(fd, "ITunerCallback registered\n");
530     }
531     dprintf(fd, "CurrentProgram: %s \n", mCurrentProgram.toString().c_str());
532     return STATUS_OK;
533 }
534 
cmdHelp(int fd) const535 binder_status_t BroadcastRadio::cmdHelp(int fd) const {
536     dprintf(fd, "Usage: \n\n");
537     dprintf(fd, "[no args]: dumps focus listener / gain callback registered status\n");
538     dprintf(fd, "--help: shows this help\n");
539     dprintf(fd,
540             "--tune amfm <FREQUENCY>: tunes amfm radio to frequency (in Hz) specified: "
541             "frequency (int) \n"
542             "--tune dab <SID> <ENSEMBLE>: tunes dab radio to sid and ensemble specified: "
543             "sidExt (int), ensemble (int) \n");
544     dprintf(fd,
545             "--seek [up|down] <SKIP_SUB_CHANNEL>: seek with direction (up or down) and "
546             "option whether skipping sub channel: "
547             "skipSubChannel (string, should be either \"true\" or \"false\")\n");
548     dprintf(fd, "--step [up|down]: step in direction (up or down) specified\n");
549     dprintf(fd, "--cancel: cancel current pending tune, step, and seek\n");
550     dprintf(fd,
551             "--startProgramListUpdates <IDENTIFIER_TYPES> <IDENTIFIERS> <INCLUDE_CATEGORIES> "
552             "<EXCLUDE_MODIFICATIONS>: start update program list with the filter specified: "
553             "identifier types (string, in format <TYPE>,<TYPE>,...,<TYPE> or \"null\" (if empty), "
554             "where TYPE is int), "
555             "program identifiers (string, in format "
556             "<TYPE>:<VALUE>,<TYPE>:<VALUE>,...,<TYPE>:<VALUE> or \"null\" (if empty), "
557             "where TYPE is int and VALUE is long), "
558             "includeCategories (string, should be either \"true\" or \"false\"), "
559             "excludeModifications (string, should be either \"true\" or \"false\")\n");
560     dprintf(fd, "--stopProgramListUpdates: stop current pending program list updates\n");
561     dprintf(fd,
562             "Note on <TYPE> for --startProgramList command: it is int for identifier type. "
563             "Please see broadcastradio/aidl/android/hardware/broadcastradio/IdentifierType.aidl "
564             "for its definition.\n");
565     dprintf(fd,
566             "Note on <VALUE> for --startProgramList command: it is long type for identifier value. "
567             "Please see broadcastradio/aidl/android/hardware/broadcastradio/IdentifierType.aidl "
568             "for its value.\n");
569 
570     return STATUS_OK;
571 }
572 
cmdTune(int fd,const char ** args,uint32_t numArgs)573 binder_status_t BroadcastRadio::cmdTune(int fd, const char** args, uint32_t numArgs) {
574     if (!checkDumpCallerHasWritePermissions(fd)) {
575         return STATUS_PERMISSION_DENIED;
576     }
577     if (numArgs != 3 && numArgs != 4) {
578         dprintf(fd,
579                 "Invalid number of arguments: please provide --tune amfm <FREQUENCY> "
580                 "or --tune dab <SID> <ENSEMBLE>\n");
581         return STATUS_BAD_VALUE;
582     }
583     bool isDab = false;
584     if (EqualsIgnoreCase(string(args[1]), "dab")) {
585         isDab = true;
586     } else if (!EqualsIgnoreCase(string(args[1]), "amfm")) {
587         dprintf(fd, "Unknown radio type provided with tune: %s\n", args[1]);
588         return STATUS_BAD_VALUE;
589     }
590     ProgramSelector sel = {};
591     if (isDab) {
592         if (numArgs != 5 && numArgs != 3) {
593             dprintf(fd,
594                     "Invalid number of arguments: please provide "
595                     "--tune dab <SID> <ENSEMBLE> <FREQUENCY> or "
596                     "--tune dab <SID>\n");
597             return STATUS_BAD_VALUE;
598         }
599         int sid;
600         if (!utils::parseArgInt(string(args[2]), &sid)) {
601             dprintf(fd, "Non-integer sid provided with tune: %s\n", args[2]);
602             return STATUS_BAD_VALUE;
603         }
604         if (numArgs == 3) {
605             sel = utils::makeSelectorDab(sid);
606         } else {
607             int ensemble;
608             if (!utils::parseArgInt(string(args[3]), &ensemble)) {
609                 dprintf(fd, "Non-integer ensemble provided with tune: %s\n", args[3]);
610                 return STATUS_BAD_VALUE;
611             }
612             int freq;
613             if (!utils::parseArgInt(string(args[4]), &freq)) {
614                 dprintf(fd, "Non-integer frequency provided with tune: %s\n", args[4]);
615                 return STATUS_BAD_VALUE;
616             }
617             sel = utils::makeSelectorDab(sid, ensemble, freq);
618         }
619     } else {
620         if (numArgs != 3) {
621             dprintf(fd, "Invalid number of arguments: please provide --tune amfm <FREQUENCY>\n");
622             return STATUS_BAD_VALUE;
623         }
624         int freq;
625         if (!utils::parseArgInt(string(args[2]), &freq)) {
626             dprintf(fd, "Non-integer frequency provided with tune: %s\n", args[2]);
627             return STATUS_BAD_VALUE;
628         }
629         sel = utils::makeSelectorAmfm(freq);
630     }
631 
632     auto tuneResult = tune(sel);
633     if (!tuneResult.isOk()) {
634         dprintf(fd, "Unable to tune %s radio to %s\n", args[1], sel.toString().c_str());
635         return STATUS_BAD_VALUE;
636     }
637     dprintf(fd, "Tune %s radio to %s \n", args[1], sel.toString().c_str());
638     return STATUS_OK;
639 }
640 
cmdSeek(int fd,const char ** args,uint32_t numArgs)641 binder_status_t BroadcastRadio::cmdSeek(int fd, const char** args, uint32_t numArgs) {
642     if (!checkDumpCallerHasWritePermissions(fd)) {
643         return STATUS_PERMISSION_DENIED;
644     }
645     if (numArgs != 3) {
646         dprintf(fd,
647                 "Invalid number of arguments: please provide --seek <DIRECTION> "
648                 "<SKIP_SUB_CHANNEL>\n");
649         return STATUS_BAD_VALUE;
650     }
651     string seekDirectionIn = string(args[1]);
652     bool seekDirectionUp;
653     if (!utils::parseArgDirection(seekDirectionIn, &seekDirectionUp)) {
654         dprintf(fd, "Invalid direction (\"up\" or \"down\") provided with seek: %s\n",
655                 seekDirectionIn.c_str());
656         return STATUS_BAD_VALUE;
657     }
658     string skipSubChannelIn = string(args[2]);
659     bool skipSubChannel;
660     if (!utils::parseArgBool(skipSubChannelIn, &skipSubChannel)) {
661         dprintf(fd, "Invalid skipSubChannel (\"true\" or \"false\") provided with seek: %s\n",
662                 skipSubChannelIn.c_str());
663         return STATUS_BAD_VALUE;
664     }
665 
666     auto seekResult = seek(seekDirectionUp, skipSubChannel);
667     if (!seekResult.isOk()) {
668         dprintf(fd, "Unable to seek in %s direction\n", seekDirectionIn.c_str());
669         return STATUS_BAD_VALUE;
670     }
671     dprintf(fd, "Seek in %s direction\n", seekDirectionIn.c_str());
672     return STATUS_OK;
673 }
674 
cmdStep(int fd,const char ** args,uint32_t numArgs)675 binder_status_t BroadcastRadio::cmdStep(int fd, const char** args, uint32_t numArgs) {
676     if (!checkDumpCallerHasWritePermissions(fd)) {
677         return STATUS_PERMISSION_DENIED;
678     }
679     if (numArgs != 2) {
680         dprintf(fd, "Invalid number of arguments: please provide --step <DIRECTION>\n");
681         return STATUS_BAD_VALUE;
682     }
683     string stepDirectionIn = string(args[1]);
684     bool stepDirectionUp;
685     if (!utils::parseArgDirection(stepDirectionIn, &stepDirectionUp)) {
686         dprintf(fd, "Invalid direction (\"up\" or \"down\") provided with step: %s\n",
687                 stepDirectionIn.c_str());
688         return STATUS_BAD_VALUE;
689     }
690 
691     auto stepResult = step(stepDirectionUp);
692     if (!stepResult.isOk()) {
693         dprintf(fd, "Unable to step in %s direction\n", stepDirectionIn.c_str());
694         return STATUS_BAD_VALUE;
695     }
696     dprintf(fd, "Step in %s direction\n", stepDirectionIn.c_str());
697     return STATUS_OK;
698 }
699 
cmdCancel(int fd,uint32_t numArgs)700 binder_status_t BroadcastRadio::cmdCancel(int fd, uint32_t numArgs) {
701     if (!checkDumpCallerHasWritePermissions(fd)) {
702         return STATUS_PERMISSION_DENIED;
703     }
704     if (numArgs != 1) {
705         dprintf(fd,
706                 "Invalid number of arguments: please provide --cancel "
707                 "only and no more arguments\n");
708         return STATUS_BAD_VALUE;
709     }
710 
711     auto cancelResult = cancel();
712     if (!cancelResult.isOk()) {
713         dprintf(fd, "Unable to cancel pending tune, seek, and step\n");
714         return STATUS_BAD_VALUE;
715     }
716     dprintf(fd, "Canceled pending tune, seek, and step\n");
717     return STATUS_OK;
718 }
719 
cmdStartProgramListUpdates(int fd,const char ** args,uint32_t numArgs)720 binder_status_t BroadcastRadio::cmdStartProgramListUpdates(int fd, const char** args,
721                                                            uint32_t numArgs) {
722     if (!checkDumpCallerHasWritePermissions(fd)) {
723         return STATUS_PERMISSION_DENIED;
724     }
725     if (numArgs != 5) {
726         dprintf(fd,
727                 "Invalid number of arguments: please provide --startProgramListUpdates "
728                 "<IDENTIFIER_TYPES> <IDENTIFIERS> <INCLUDE_CATEGORIES> "
729                 "<EXCLUDE_MODIFICATIONS>\n");
730         return STATUS_BAD_VALUE;
731     }
732     string filterTypesStr = string(args[1]);
733     std::vector<IdentifierType> filterTypeList;
734     if (!EqualsIgnoreCase(filterTypesStr, "null") &&
735         !utils::parseArgIdentifierTypeArray(filterTypesStr, &filterTypeList)) {
736         dprintf(fd,
737                 "Invalid identifier types provided with startProgramListUpdates: %s, "
738                 "should be: <TYPE>,<TYPE>,...,<TYPE>\n",
739                 filterTypesStr.c_str());
740         return STATUS_BAD_VALUE;
741     }
742     string filtersStr = string(args[2]);
743     std::vector<ProgramIdentifier> filterList;
744     if (!EqualsIgnoreCase(filtersStr, "null") &&
745         !utils::parseProgramIdentifierList(filtersStr, &filterList)) {
746         dprintf(fd,
747                 "Invalid program identifiers provided with startProgramListUpdates: %s, "
748                 "should be: <TYPE>:<VALUE>,<TYPE>:<VALUE>,...,<TYPE>:<VALUE>\n",
749                 filtersStr.c_str());
750         return STATUS_BAD_VALUE;
751     }
752     string includeCategoriesStr = string(args[3]);
753     bool includeCategories;
754     if (!utils::parseArgBool(includeCategoriesStr, &includeCategories)) {
755         dprintf(fd,
756                 "Invalid includeCategories (\"true\" or \"false\") "
757                 "provided with startProgramListUpdates : %s\n",
758                 includeCategoriesStr.c_str());
759         return STATUS_BAD_VALUE;
760     }
761     string excludeModificationsStr = string(args[4]);
762     bool excludeModifications;
763     if (!utils::parseArgBool(excludeModificationsStr, &excludeModifications)) {
764         dprintf(fd,
765                 "Invalid excludeModifications(\"true\" or \"false\") "
766                 "provided with startProgramListUpdates : %s\n",
767                 excludeModificationsStr.c_str());
768         return STATUS_BAD_VALUE;
769     }
770     ProgramFilter filter = {filterTypeList, filterList, includeCategories, excludeModifications};
771 
772     auto updateResult = startProgramListUpdates(filter);
773     if (!updateResult.isOk()) {
774         dprintf(fd, "Unable to start program list update for filter %s \n",
775                 filter.toString().c_str());
776         return STATUS_BAD_VALUE;
777     }
778     dprintf(fd, "Start program list update for filter %s\n", filter.toString().c_str());
779     return STATUS_OK;
780 }
781 
cmdStopProgramListUpdates(int fd,uint32_t numArgs)782 binder_status_t BroadcastRadio::cmdStopProgramListUpdates(int fd, uint32_t numArgs) {
783     if (!checkDumpCallerHasWritePermissions(fd)) {
784         return STATUS_PERMISSION_DENIED;
785     }
786     if (numArgs != 1) {
787         dprintf(fd,
788                 "Invalid number of arguments: please provide --stopProgramListUpdates "
789                 "only and no more arguments\n");
790         return STATUS_BAD_VALUE;
791     }
792 
793     auto stopResult = stopProgramListUpdates();
794     if (!stopResult.isOk()) {
795         dprintf(fd, "Unable to stop pending program list update\n");
796         return STATUS_BAD_VALUE;
797     }
798     dprintf(fd, "Stop pending program list update\n");
799     return STATUS_OK;
800 }
801 
802 }  // namespace aidl::android::hardware::broadcastradio
803