blob: 42e550e75ac177939d1e6777afb6c170a6793930 [file] [log] [blame]
Weilin Xub2a6ca62022-05-08 23:47:04 +00001/*
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>
Weilin Xu97203b02022-06-23 00:19:03 +000025#include <android-base/strings.h>
26
27#include <private/android_filesystem_config.h>
Weilin Xub2a6ca62022-05-08 23:47:04 +000028
29namespace aidl::android::hardware::broadcastradio {
30
31using ::aidl::android::hardware::broadcastradio::utils::resultToInt;
32using ::aidl::android::hardware::broadcastradio::utils::tunesTo;
Weilin Xu97203b02022-06-23 00:19:03 +000033using ::android::base::EqualsIgnoreCase;
Weilin Xub2a6ca62022-05-08 23:47:04 +000034using ::ndk::ScopedAStatus;
35using ::std::literals::chrono_literals::operator""ms;
36using ::std::literals::chrono_literals::operator""s;
37using ::std::lock_guard;
38using ::std::mutex;
39using ::std::string;
40using ::std::vector;
41
42namespace {
43
44inline constexpr std::chrono::milliseconds kSeekDelayTimeMs = 200ms;
45inline constexpr std::chrono::milliseconds kStepDelayTimeMs = 100ms;
46inline constexpr std::chrono::milliseconds kTuneDelayTimeMs = 150ms;
47inline constexpr std::chrono::seconds kListDelayTimeS = 1s;
48
49// clang-format off
50const 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
61Properties 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
80ProgramInfo 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
Weilin Xu97203b02022-06-23 00:19:03 +000090static 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
Weilin Xub2a6ca62022-05-08 23:47:04 +000099} // namespace
100
101BroadcastRadio::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
117BroadcastRadio::~BroadcastRadio() {
118 mThread.reset();
119}
120
121ScopedAStatus 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
138ScopedAStatus 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
148ScopedAStatus 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
161ScopedAStatus BroadcastRadio::getProperties(Properties* returnProperties) {
162 lock_guard<mutex> lk(mMutex);
163 *returnProperties = mProperties;
164 return ScopedAStatus::ok();
165}
166
167ProgramInfo 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
184ScopedAStatus 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
198ScopedAStatus BroadcastRadio::unsetTunerCallback() {
199 LOG(DEBUG) << __func__ << ": unsetTunerCallback";
200
201 lock_guard<mutex> lk(mMutex);
202 mCallback = nullptr;
203
204 return ScopedAStatus::ok();
205}
206
207ScopedAStatus 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 };
Weilin Xud7483322022-11-29 01:12:36 +0000241 auto cancelTask = [program, callback]() { callback->onTuneFailed(Result::CANCELED, program); };
242 mThread->schedule(task, cancelTask, kTuneDelayTimeMs);
Weilin Xub2a6ca62022-05-08 23:47:04 +0000243
244 return ScopedAStatus::ok();
245}
246
247ScopedAStatus 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;
Weilin Xud7483322022-11-29 01:12:36 +0000262 auto cancelTask = [callback]() { callback->onTuneFailed(Result::CANCELED, {}); };
Weilin Xub2a6ca62022-05-08 23:47:04 +0000263 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 };
Weilin Xud7483322022-11-29 01:12:36 +0000270 mThread->schedule(task, cancelTask, kSeekDelayTimeMs);
Weilin Xub2a6ca62022-05-08 23:47:04 +0000271
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 };
Weilin Xud7483322022-11-29 01:12:36 +0000303 mThread->schedule(task, cancelTask, kSeekDelayTimeMs);
Weilin Xub2a6ca62022-05-08 23:47:04 +0000304
305 return ScopedAStatus::ok();
306}
307
308ScopedAStatus 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 };
Weilin Xud7483322022-11-29 01:12:36 +0000357 auto cancelTask = [callback]() { callback->onTuneFailed(Result::CANCELED, {}); };
358 mThread->schedule(task, cancelTask, kStepDelayTimeMs);
Weilin Xub2a6ca62022-05-08 23:47:04 +0000359
360 return ScopedAStatus::ok();
361}
362
363void 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
372ScopedAStatus 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
381ScopedAStatus 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
418ScopedAStatus 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
424ScopedAStatus 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
432ScopedAStatus 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
440ScopedAStatus 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
448ScopedAStatus 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
455std::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
475ScopedAStatus 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
Weilin Xu97203b02022-06-23 00:19:03 +0000489binder_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
514binder_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
535binder_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
573binder_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 != 4) {
593 dprintf(fd,
594 "Invalid number of arguments: please provide --tune dab <SID> <ENSEMBLE>\n");
595 return STATUS_BAD_VALUE;
596 }
597 int sid;
598 if (!utils::parseArgInt(string(args[2]), &sid)) {
599 dprintf(fd, "Non-integer sid provided with tune: %s\n", string(args[2]).c_str());
600 return STATUS_BAD_VALUE;
601 }
602 int ensemble;
603 if (!utils::parseArgInt(string(args[3]), &ensemble)) {
604 dprintf(fd, "Non-integer ensemble provided with tune: %s\n", string(args[3]).c_str());
605 return STATUS_BAD_VALUE;
606 }
607 sel = utils::makeSelectorDab(sid, ensemble);
608 } else {
609 if (numArgs != 3) {
610 dprintf(fd, "Invalid number of arguments: please provide --tune amfm <FREQUENCY>\n");
611 return STATUS_BAD_VALUE;
612 }
613 int freq;
614 if (!utils::parseArgInt(string(args[2]), &freq)) {
615 dprintf(fd, "Non-integer frequency provided with tune: %s\n", string(args[2]).c_str());
616 return STATUS_BAD_VALUE;
617 }
618 sel = utils::makeSelectorAmfm(freq);
619 }
620
621 auto tuneResult = tune(sel);
622 if (!tuneResult.isOk()) {
623 dprintf(fd, "Unable to tune %s radio to %s\n", args[1], sel.toString().c_str());
624 return STATUS_BAD_VALUE;
625 }
626 dprintf(fd, "Tune %s radio to %s \n", args[1], sel.toString().c_str());
627 return STATUS_OK;
628}
629
630binder_status_t BroadcastRadio::cmdSeek(int fd, const char** args, uint32_t numArgs) {
631 if (!checkDumpCallerHasWritePermissions(fd)) {
632 return STATUS_PERMISSION_DENIED;
633 }
634 if (numArgs != 3) {
635 dprintf(fd,
636 "Invalid number of arguments: please provide --seek <DIRECTION> "
637 "<SKIP_SUB_CHANNEL>\n");
638 return STATUS_BAD_VALUE;
639 }
640 string seekDirectionIn = string(args[1]);
641 bool seekDirectionUp;
642 if (!utils::parseArgDirection(seekDirectionIn, &seekDirectionUp)) {
643 dprintf(fd, "Invalid direction (\"up\" or \"down\") provided with seek: %s\n",
644 seekDirectionIn.c_str());
645 return STATUS_BAD_VALUE;
646 }
647 string skipSubChannelIn = string(args[2]);
648 bool skipSubChannel;
649 if (!utils::parseArgBool(skipSubChannelIn, &skipSubChannel)) {
650 dprintf(fd, "Invalid skipSubChannel (\"true\" or \"false\") provided with seek: %s\n",
651 skipSubChannelIn.c_str());
652 return STATUS_BAD_VALUE;
653 }
654
655 auto seekResult = seek(seekDirectionUp, skipSubChannel);
656 if (!seekResult.isOk()) {
657 dprintf(fd, "Unable to seek in %s direction\n", seekDirectionIn.c_str());
658 return STATUS_BAD_VALUE;
659 }
660 dprintf(fd, "Seek in %s direction\n", seekDirectionIn.c_str());
661 return STATUS_OK;
662}
663
664binder_status_t BroadcastRadio::cmdStep(int fd, const char** args, uint32_t numArgs) {
665 if (!checkDumpCallerHasWritePermissions(fd)) {
666 return STATUS_PERMISSION_DENIED;
667 }
668 if (numArgs != 2) {
669 dprintf(fd, "Invalid number of arguments: please provide --step <DIRECTION>\n");
670 return STATUS_BAD_VALUE;
671 }
672 string stepDirectionIn = string(args[1]);
673 bool stepDirectionUp;
674 if (!utils::parseArgDirection(stepDirectionIn, &stepDirectionUp)) {
675 dprintf(fd, "Invalid direction (\"up\" or \"down\") provided with step: %s\n",
676 stepDirectionIn.c_str());
677 return STATUS_BAD_VALUE;
678 }
679
680 auto stepResult = step(stepDirectionUp);
681 if (!stepResult.isOk()) {
682 dprintf(fd, "Unable to step in %s direction\n", stepDirectionIn.c_str());
683 return STATUS_BAD_VALUE;
684 }
685 dprintf(fd, "Step in %s direction\n", stepDirectionIn.c_str());
686 return STATUS_OK;
687}
688
689binder_status_t BroadcastRadio::cmdCancel(int fd, uint32_t numArgs) {
690 if (!checkDumpCallerHasWritePermissions(fd)) {
691 return STATUS_PERMISSION_DENIED;
692 }
693 if (numArgs != 1) {
694 dprintf(fd,
695 "Invalid number of arguments: please provide --cancel "
696 "only and no more arguments\n");
697 return STATUS_BAD_VALUE;
698 }
699
700 auto cancelResult = cancel();
701 if (!cancelResult.isOk()) {
702 dprintf(fd, "Unable to cancel pending tune, seek, and step\n");
703 return STATUS_BAD_VALUE;
704 }
705 dprintf(fd, "Canceled pending tune, seek, and step\n");
706 return STATUS_OK;
707}
708
709binder_status_t BroadcastRadio::cmdStartProgramListUpdates(int fd, const char** args,
710 uint32_t numArgs) {
711 if (!checkDumpCallerHasWritePermissions(fd)) {
712 return STATUS_PERMISSION_DENIED;
713 }
714 if (numArgs != 5) {
715 dprintf(fd,
716 "Invalid number of arguments: please provide --startProgramListUpdates "
717 "<IDENTIFIER_TYPES> <IDENTIFIERS> <INCLUDE_CATEGORIES> "
718 "<EXCLUDE_MODIFICATIONS>\n");
719 return STATUS_BAD_VALUE;
720 }
721 string filterTypesStr = string(args[1]);
722 std::vector<IdentifierType> filterTypeList;
723 if (!EqualsIgnoreCase(filterTypesStr, "null") &&
724 !utils::parseArgIdentifierTypeArray(filterTypesStr, &filterTypeList)) {
725 dprintf(fd,
726 "Invalid identifier types provided with startProgramListUpdates: %s, "
727 "should be: <TYPE>,<TYPE>,...,<TYPE>\n",
728 filterTypesStr.c_str());
729 return STATUS_BAD_VALUE;
730 }
731 string filtersStr = string(args[2]);
732 std::vector<ProgramIdentifier> filterList;
733 if (!EqualsIgnoreCase(filtersStr, "null") &&
734 !utils::parseProgramIdentifierList(filtersStr, &filterList)) {
735 dprintf(fd,
736 "Invalid program identifiers provided with startProgramListUpdates: %s, "
737 "should be: <TYPE>:<VALUE>,<TYPE>:<VALUE>,...,<TYPE>:<VALUE>\n",
738 filtersStr.c_str());
739 return STATUS_BAD_VALUE;
740 }
741 string includeCategoriesStr = string(args[3]);
742 bool includeCategories;
743 if (!utils::parseArgBool(includeCategoriesStr, &includeCategories)) {
744 dprintf(fd,
745 "Invalid includeCategories (\"true\" or \"false\") "
746 "provided with startProgramListUpdates : %s\n",
747 includeCategoriesStr.c_str());
748 return STATUS_BAD_VALUE;
749 }
750 string excludeModificationsStr = string(args[4]);
751 bool excludeModifications;
752 if (!utils::parseArgBool(excludeModificationsStr, &excludeModifications)) {
753 dprintf(fd,
754 "Invalid excludeModifications(\"true\" or \"false\") "
755 "provided with startProgramListUpdates : %s\n",
756 excludeModificationsStr.c_str());
757 return STATUS_BAD_VALUE;
758 }
759 ProgramFilter filter = {filterTypeList, filterList, includeCategories, excludeModifications};
760
761 auto updateResult = startProgramListUpdates(filter);
762 if (!updateResult.isOk()) {
763 dprintf(fd, "Unable to start program list update for filter %s \n",
764 filter.toString().c_str());
765 return STATUS_BAD_VALUE;
766 }
767 dprintf(fd, "Start program list update for filter %s\n", filter.toString().c_str());
768 return STATUS_OK;
769}
770
771binder_status_t BroadcastRadio::cmdStopProgramListUpdates(int fd, uint32_t numArgs) {
772 if (!checkDumpCallerHasWritePermissions(fd)) {
773 return STATUS_PERMISSION_DENIED;
774 }
775 if (numArgs != 1) {
776 dprintf(fd,
777 "Invalid number of arguments: please provide --stopProgramListUpdates "
778 "only and no more arguments\n");
779 return STATUS_BAD_VALUE;
780 }
781
782 auto stopResult = stopProgramListUpdates();
783 if (!stopResult.isOk()) {
784 dprintf(fd, "Unable to stop pending program list update\n");
785 return STATUS_BAD_VALUE;
786 }
787 dprintf(fd, "Stop pending program list update\n");
788 return STATUS_OK;
789}
790
Weilin Xub2a6ca62022-05-08 23:47:04 +0000791} // namespace aidl::android::hardware::broadcastradio