TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / qemu / at_parser.cpp
1 /*
2  * Copyright (C) 2016 Simon Fels <morphis@gravedo.de>
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 3, as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranties of
10  * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11  * PURPOSE.  See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  */
17
18 #include "anbox/qemu//at_parser.h"
19 #include "anbox/logger.h"
20 #include "anbox/utils.h"
21
22 namespace anbox {
23 namespace qemu {
24 AtParser::AtParser() {}
25
26 void AtParser::register_command(const std::string &command,
27                                 CommandHandler handler) {
28   handlers_.insert({command, handler});
29 }
30
31 void AtParser::process_data(std::vector<std::uint8_t> &data) {
32   size_t bytes_processed = 0;
33   for (size_t pos = 0; pos < data.size();) {
34     const auto byte = data.at(pos);
35     if (byte == '\n' || byte == '\r') {
36       std::string command;
37       command.insert(
38           0, reinterpret_cast<const char *>(data.data()) + bytes_processed,
39           pos - bytes_processed);
40       bytes_processed += (pos - bytes_processed) + 1;
41       processs_command(command);
42     }
43     pos++;
44   }
45
46   data.erase(data.begin(), data.begin() + bytes_processed);
47 }
48
49 void AtParser::processs_command(const std::string &command) {
50   if (!utils::string_starts_with(command, "AT")) {
51     WARNING("Invalid AT command: '%s'", command);
52     return;
53   }
54
55   // Strip AT prefix from command
56   auto real_command = command.substr(2, command.length() - 2);
57
58   DEBUG("command: %s", real_command);
59
60   CommandHandler handler = nullptr;
61   for (const auto &iter : handlers_) {
62     if (utils::string_starts_with(real_command, iter.first)) {
63       handler = iter.second;
64       break;
65     }
66   }
67
68   if (!handler) {
69     WARNING("No handler for command '%s' available", real_command);
70     return;
71   }
72
73   handler(real_command);
74 }
75 }  // namespace qemu
76 }  // namespace anbox