aboutsummaryrefslogtreecommitdiff
path: root/host/commands/modem_simulator/call_service.cpp
blob: 674c15361c49b440ab7d1d86c939ad8798218605 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//
// Copyright (C) 2020 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "host/commands/modem_simulator/call_service.h"

#include <android-base/logging.h>

#include <chrono>
#include <iostream>
#include <thread>

#include "host/commands/modem_simulator/nvram_config.h"

namespace cuttlefish {

CallService::CallService(int32_t service_id, ChannelMonitor* channel_monitor,
                         ThreadLooper* thread_looper)
    : ModemService(service_id, this->InitializeCommandHandlers(),
                   channel_monitor, thread_looper) {
  InitializeServiceState();
}

void CallService::InitializeServiceState() {
  auto nvram_config = NvramConfig::Get();
  auto instance = nvram_config->ForInstance(service_id_);
  in_emergency_mode_ = instance.emergency_mode();

  last_active_call_index_ = 1;
  mute_on_ = false;
}

void CallService::SetupDependency(SimService* sim, NetworkService* net) {
  sim_service_ = sim;
  network_service_ = net;
}

std::vector<CommandHandler> CallService::InitializeCommandHandlers() {
  std::vector<CommandHandler> command_handlers = {
      CommandHandler("D",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleDial(client, cmd);
                     }),
      CommandHandler(
          "A",
          [this](const Client& client) { this->HandleAcceptCall(client); }),
      CommandHandler(
          "H",
          [this](const Client& client) { this->HandleRejectCall(client); }),
      CommandHandler(
          "+CLCC",
          [this](const Client& client) { this->HandleCurrentCalls(client); }),
      CommandHandler("+CHLD=",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleHangup(client, cmd);
                     }),
      CommandHandler("+CMUT",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleMute(client, cmd);
                     }),
      CommandHandler("+VTS=",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleSendDtmf(client, cmd);
                     }),
      CommandHandler("+CUSD=",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleCancelUssd(client, cmd);
                     }),
      CommandHandler("+WSOS=0",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleEmergencyMode(client, cmd);
                     }),
      CommandHandler("+REMOTECALL",
                     [this](const Client& client, std::string& cmd) {
                       this->HandleRemoteCall(client, cmd);
                     }),
  };
  return (command_handlers);
}

// This also resumes held calls
void CallService::SimulatePendingCallsAnswered() {
  for (auto& iter : active_calls_) {
    if (iter.second.isCallDialing()) {
      iter.second.SetCallActive();
    }
  }
}

void CallService::TimerWaitingRemoteCallResponse(CallToken call_token) {
  LOG(DEBUG) << "Dialing id: " << call_token.first
             << ", number: " << call_token.second << "timeout, cancel";
  auto iter = active_calls_.find(call_token.first);
  if (iter != active_calls_.end() && iter->second.number == call_token.second) {
    if (iter->second.remote_client != std::nullopt) {
      CloseRemoteConnection(*(iter->second.remote_client));
    }
    active_calls_.erase(iter);  // match
    CallStateUpdate();
  }  // else not match, ignore
}

/* ATD */
void CallService::HandleDial(const Client& client, const std::string& command) {
  // Check the network registration state
  auto registration_state = NetworkService::NET_REGISTRATION_UNKNOWN;
  if (network_service_) {
    registration_state = network_service_->GetVoiceRegistrationState();
  }

  bool emergency_only = false;
  if (registration_state == NetworkService::NET_REGISTRATION_HOME ||
      registration_state == NetworkService::NET_REGISTRATION_ROAMING) {
    emergency_only = false;
  } else if (registration_state == NetworkService::NET_REGISTRATION_EMERGENCY) {
    emergency_only = true;
  } else {
    client.SendCommandResponse(kCmeErrorNoNetworkService);
    return;
  }

  CommandParser cmd(command);
  cmd.SkipPrefixAT();

  std::string number;
  bool emergency_number = false;
  /**
   * Normal dial:     ATDnumber[clir];
   * Emergency dial:  ATDnumber@[category],#[clir];
   */
  auto pos = cmd->find_last_of('@');
  if (pos != std::string_view::npos) {
    emergency_number = true;
    number = cmd->substr(1, pos -1); // Skip 'D' and ignore category, clir
  } else {  // Remove 'i' or 'I' or ';'
    pos = cmd->find_last_of('i');
    if (pos == std::string_view::npos) {
      pos = cmd->find_last_of('I');
      if (pos == std::string_view::npos) {
        pos = cmd->find_last_of(';');
      }
    }
    if (pos == std::string_view::npos) {
      number = cmd->substr(1);
    } else {
      number = cmd->substr(1, pos -1);
    }
  }

  // Check the number is valid digits or not
  if (strspn(number.c_str(), "1234567890") != number.size()) {
    client.SendCommandResponse(kCmeErrorInCorrectParameters);
    return;
  }

  if (emergency_only && !emergency_number) {
    client.SendCommandResponse(kCmeErrorNetworkNotAllowedEmergencyCallsOnly);
    return;
  }

  // If the number is not emergency number, FDN enabled and the number is not in
  // the fdn list, return kCmeErrorFixedDialNumberOnlyAllowed.
  if (!emergency_number && sim_service_->IsFDNEnabled() &&
      !sim_service_->IsFixedDialNumber(number)) {
    client.SendCommandResponse(kCmeErrorFixedDialNumberOnlyAllowed);
    return;
  }

  int port = 0;
  if (number.length() == 11) {
    port = std::stoi(number.substr(7));
  } else if (number.length() == 4) {
    port = std::stoi(number);
  }

  if (port >= kRemotePortRange.first &&
      port <= kRemotePortRange.second) {  // May be a remote call
    std::stringstream ss;
    ss << port;
    auto remote_port = ss.str();
    auto remote_client = ConnectToRemoteCvd(remote_port);
    if (!remote_client->IsOpen()) {
      client.SendCommandResponse(kCmeErrorNoNetworkService);
      return;
    }
    auto local_host_port = GetHostId();
    if (local_host_port == remote_port) {
      client.SendCommandResponse(kCmeErrorOperationNotAllowed);
      return;
    }

    if (channel_monitor_) {
      channel_monitor_->SetRemoteClient(remote_client, false);
    }

    ss.clear();
    ss.str("");
    ss << "AT+REMOTECALL=4,0,0,\"" << local_host_port << "\",129";

    SendCommandToRemote(remote_client, "REM0");
    SendCommandToRemote(remote_client, ss.str());

    CallStatus call_status(remote_port);
    call_status.is_remote_call = true;
    call_status.is_mobile_terminated = false;
    call_status.call_state = CallStatus::CALL_STATE_DIALING;
    call_status.remote_client = remote_client;
    int index = last_active_call_index_++;

    auto call_token = std::make_pair(index, call_status.number);
    call_status.timeout_serial = thread_looper_->Post(
        makeSafeCallback<CallService>(this,
                                      [call_token](CallService* me) {
                                        me->TimerWaitingRemoteCallResponse(
                                            call_token);
                                      }),
        std::chrono::minutes(1));

    active_calls_[index] = call_status;
  } else {
    CallStatus call_status(number);
    call_status.is_mobile_terminated = false;
    call_status.call_state = CallStatus::CALL_STATE_DIALING;
    auto index = last_active_call_index_++;
    active_calls_[index] = call_status;

    if (emergency_number) {
      in_emergency_mode_ = true;
      SendUnsolicitedCommand("+WSOS: 1");
    }
    thread_looper_->Post(
        makeSafeCallback(this, &CallService::SimulatePendingCallsAnswered),
        std::chrono::seconds(1));
  }

  client.SendCommandResponse("OK");
  std::this_thread::sleep_for(std::chrono::seconds(2));
}

void CallService::SendCallStatusToRemote(CallStatus& call,
                                         CallStatus::CallState state) {
  if (call.is_remote_call && call.remote_client != std::nullopt) {
    std::stringstream ss;
    ss << "AT+REMOTECALL=" << state << "," << call.is_voice_mode << ","
       << call.is_multi_party << ",\"" << GetHostId() << "\","
       << call.is_international;

    SendCommandToRemote(*(call.remote_client), ss.str());
    if (state == CallStatus::CALL_STATE_HANGUP) {
      CloseRemoteConnection(*(call.remote_client));
    }
  }
}

/* ATA */
void CallService::HandleAcceptCall(const Client& client) {
  for (auto& iter : active_calls_) {
    if (iter.second.isCallIncoming()) {
      iter.second.SetCallActive();
      SendCallStatusToRemote(iter.second, CallStatus::CALL_STATE_ACTIVE);
    } else if (iter.second.isCallActive()) {
      iter.second.SetCallBackground();
      SendCallStatusToRemote(iter.second, CallStatus::CALL_STATE_HELD);
    }
  }

  client.SendCommandResponse("OK");
}

/* ATH */
void CallService::HandleRejectCall(const Client& client) {
  for (auto iter = active_calls_.begin(); iter != active_calls_.end();) {
    /* ATH: hangup, since user is busy */
    if (iter->second.isCallIncoming()) {
      SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_HANGUP);
      iter = active_calls_.erase(iter);
    } else {
      ++iter;
    }
  }

  client.SendCommandResponse("OK");
}

/**
 * AT+CLCC
 *   Returns list of current calls of MT. If command succeeds but no
 *   calls are available, no information response is sent to TE.
 *
 *   command             Possible response(s)
 *   AT+CLCC               [+CLCC: <ccid1>,<dir>,<stat>,<mode>,<mpty>
 *                         [,<number>,<type>[,<alpha>[,<priority>
 *                         [,<CLI validity>]]]][<CR><LF>
 *                         +CLCC: <ccid2>,<dir>,<stat>,<mode>,<mpty>
 *                         [,<number>,<type>[,<alpha>[,<priority>[,<CLI validity>]]]]
 *                         +CME ERROR: <err>
 *
 * <ccidx>: integer type. This number can be used in +CHLD command
 * operations. Value range is from 1 to N. N, the maximum number of
 * simultaneous call control processes is implementation specific.
 * <dir>: integer type
 *       0 mobile originated (MO) call
         1 mobile terminated (MT) call
 * <stat>: integer type (state of the call)
 *       0 active
 *       1 held
 *       2 dialing (MO call)
 *       3 alerting (MO call)
 *       4 incoming (MT call)
 *       5 waiting (MT call)
 * <mode>: integer type (bearer/teleservice)
 *       0 voice
 *       1 data
 *       2 fax
 *       3 voice followed by data, voice mode
 *       4 alternating voice/data, voice mode
 *       5 alternating voice/fax, voice mode
 *       6 voice followed by data, data mode
 *       7 alternating voice/data, data mode
 *       8 alternating voice/fax, fax mode
 *       9 unknown
 * <mpty>: integer type
 *       0 call is not one of multiparty (conference) call parties
 *       1 call is one of multiparty (conference) call parties
 * <number>: string type phone number in format specified by <type>.
 * <type>: type of address octet in integer format
 *
 *see RIL_REQUEST_GET_CURRENT_CALLS in RIL
 */
void CallService::HandleCurrentCalls(const Client& client) {
  std::vector<std::string> responses;
  std::stringstream ss;

  // AT+CLCC
  // [+CLCC: <ccid1>,<dir>,<stat>,<mode>,<mpty>[,<number>,<type>[,<alpha>[,<priority>[,<CLI validity>]]]]
  // [+CLCC: <ccid2>,<dir>,<stat>,<mode>,<mpty>[,<number>,<type>[,<alpha>[,<priority>[,<CLI validity>]]]]
  // [...]]]
  for (auto iter = active_calls_.begin(); iter != active_calls_.end(); ++iter) {
    int index = iter->first;
    int dir = iter->second.is_mobile_terminated;
    CallStatus::CallState call_state = iter->second.call_state;
    int mode = iter->second.is_voice_mode;
    int mpty = iter->second.is_multi_party;
    int type = iter->second.is_international ? 145 : 129;
    std::string number = iter->second.number;

    ss.clear();
    ss << "+CLCC: " << index << "," << dir << "," << call_state << ","
        << mode << "," << mpty << "," << number<<  "," << type;
    responses.push_back(ss.str());
    ss.str("");
  }

  responses.push_back("OK");
  client.SendCommandResponse(responses);
}

/**
 * AT+CHLD
 *   This command allows the control of the following call related services:
 *   1) a call can be temporarily disconnected from the MT but the connection
 *      is retained by the network;
 *   2) multiparty conversation (conference calls);
 *   3) the served subscriber who has two calls (one held and the other
 *     either active or alerting) can connect the other parties and release
 *     the served subscriber's own connection.
 *
 *   Calls can be put on hold, recovered, released, added to conversation,
 *   and transferred similarly.
 *
 *   command             Possible response(s)
 *   +CHLD=<n>           +CME ERROR: <err>
 *
 *   +CHLD=?             +CHLD: (list of supported <n>s)
 *   e.g. +CHLD: (0,1,1x,2,2x,3,4)
 *
 *
 * see RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND
 *     RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND
 *     RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE
 *     RIL_REQUEST_CONFERENCE
 *     RIL_REQUEST_SEPARATE_CONNECTION
 *     RIL_REQUEST_HANGUP
 *     RIL_REQUEST_UDUB in RIL
 */
void CallService::HandleHangup(const Client& client,
                               const std::string& command) {
  std::vector<std::string> responses;
  CommandParser cmd(command);
  cmd.SkipPrefix();

  std::string action(*cmd);
  int n = std::stoi(action.substr(0, 1));
  int index = -1;
  if (cmd->length() > 1) {
    index = std::stoi(action.substr(1));
  }

  switch (n) {
    case 0:  // Release all held calls or set User Determined User Busy(UDUB) for a waiting call
      for (auto iter = active_calls_.begin(); iter != active_calls_.end();) {
        if (iter->second.isCallIncoming() ||
            iter->second.isCallBackground() ||
            iter->second.isCallWaiting()) {
          SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_HANGUP);
          iter = active_calls_.erase(iter);
        } else {
          ++iter;
        }
      }
      break;
    case 1:
      if (index == -1) {  // Release all active calls and accepts the other(hold or waiting) call
        for (auto iter = active_calls_.begin(); iter != active_calls_.end();) {
          if (iter->second.isCallActive()) {
            SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_HANGUP);
            iter = active_calls_.erase(iter);
            continue;
          } else if (iter->second.isCallBackground() ||
              iter->second.isCallWaiting()) {
            iter->second.SetCallActive();
            SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_ACTIVE);
          }
          ++iter;
        }
      } else {  // Release a specific active call
        auto iter = active_calls_.find(index);
        if (iter != active_calls_.end()) {
          SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_HANGUP);
          active_calls_.erase(iter);
        }
      }
      break;
    case 2:
      if (index == -1) {  // Place all active calls and the waiting calls, activates all held calls
        for (auto& iter : active_calls_) {
          if (iter.second.isCallActive() || iter.second.isCallWaiting()) {
            iter.second.SetCallBackground();
            SendCallStatusToRemote(iter.second, CallStatus::CALL_STATE_HELD);
          } else if (iter.second.isCallBackground()) {
            iter.second.SetCallActive();
            SendCallStatusToRemote(iter.second, CallStatus::CALL_STATE_ACTIVE);
          }
        }
      } else {  // Disconnect a call from the conversation
        auto iter = active_calls_.find(index);
        if (iter != active_calls_.end()) {
          SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_HANGUP);
          active_calls_.erase(iter);
        }
      }
      break;
    case 3:  // Adds an held call to the conversation
      for (auto iter = active_calls_.begin(); iter != active_calls_.end(); ++iter) {
        if (iter->second.isCallBackground()) {
          iter->second.SetCallActive();
          SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_ACTIVE);
        }
      }
      break;
    case 4:  // Connect the two calls
      for (auto iter = active_calls_.begin(); iter != active_calls_.end(); ++iter) {
        if (iter->second.isCallBackground()) {
          iter->second.SetCallActive();
          SendCallStatusToRemote(iter->second, CallStatus::CALL_STATE_ACTIVE);
        }
      }
      break;
    default:
      client.SendCommandResponse(kCmeErrorOperationNotAllowed);
      return;
  }
  client.SendCommandResponse("OK");
}

/**
 * AT+CMUT
 *   This command is used to enable and disable the uplink voice muting
 * during a voice call.
 *   Read command returns the current value of <n>.
 *
 * Command          Possible response(s)
 * +CMUT=[<n>]        +CME ERROR: <err>
 * +CMUT?             +CMUT: <n>
 *                    +CME ERROR: <err>
 *
 * <n>: integer type
 *   0 mute off
 *   1 mute on
 *
 * see RIL_REQUEST_SET_MUTE or RIL_REQUEST_GET_MUTE in RIL
 */
void CallService::HandleMute(const Client& client, const std::string& command) {
  std::vector<std::string> responses;
  std::stringstream ss;

  CommandParser cmd(command);
  cmd.SkipPrefix();  // If AT+CMUT?, it remains AT+CMUT?

  if (cmd == "AT+CMUT?") {
    ss << "+CMUT: " << mute_on_;
    responses.push_back(ss.str());
  } else {  // AT+CMUT = <n>
    int n = cmd.GetNextInt();
    switch (n) {
      case 0:  // Mute off
        mute_on_ = false;
        break;
      case 1:  // Mute on
        mute_on_ = true;
        break;
      default:
        client.SendCommandResponse(kCmeErrorInCorrectParameters);
        return;
    }
  }
  responses.push_back("OK");
  client.SendCommandResponse(responses);
}

/**
 * AT+VTS
 *   This command transmits DTMF, after a successful call connection.
 * Setting Command is used to send one or more ASCII characters which make
 * MSC (Mobile Switching Center) send DTMF tone to remote User.
 *
 * Command                         Possible response(s)
 * AT+VTS=<dtmf>[,<duration>]        +CME ERROR: <err>
 *
 * <dtmf>
 *   A single ASCII character in the set { 0 -9, #, *, A – D}.
 * <duration>
 *   Refer to duration value range of +VTD command
 *
 * see RIL_REQUEST_DTMF in RIL
 */
void CallService::HandleSendDtmf(const Client& client,
                                 const std::string& /*command*/) {
  client.SendCommandResponse("OK");
}

void CallService::HandleCancelUssd(const Client& client,
                                   const std::string& /*command*/) {
  client.SendCommandResponse("OK");
}

/**
 * AT+WSOS
 *
 * Command          Possible response(s)
 * +WSOS=[<n>]        +CME ERROR: <err>
 * +WSOS?             +WSOS: <n>
 *                    +CME ERROR: <err>
 *
 * <n>: integer type
 *   0 enter emergency mode
 *   1 exit emergency mode
 *
 * see RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE
 *     RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE
 *     RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE in RIL
 */
void CallService::HandleEmergencyMode(const Client& client,
                                      const std::string& command) {
  std::vector<std::string> responses;
  CommandParser cmd(command);
  cmd.SkipPrefix();

  if (cmd == "AT+WSOS?") {
    std::stringstream ss;
    ss << "+WSOS: " << in_emergency_mode_;
    responses.push_back(ss.str());
  } else {
    int n = cmd.GetNextInt();
    switch (n) {
      case 0:  // Exit
        in_emergency_mode_ = false;
        break;
      case 1:  // Enter
        in_emergency_mode_ = true;
        break;
      default:
        client.SendCommandResponse(kCmeErrorInCorrectParameters);
        return;
    }
    auto nvram_config = NvramConfig::Get();
    auto instance = nvram_config->ForInstance(service_id_);
    instance.set_emergency_mode(in_emergency_mode_);
    NvramConfig::SaveToFile();
  }
  client.SendCommandResponse("OK");
}

void CallService::CallStateUpdate() {
  SendUnsolicitedCommand("RING");
}

/**
 * AT+REMOTECALL=<dir>,<stat>,<mode>,<mpty>,<number>,<num_type>
 *   This command allows to dial a remote voice call with another cuttlefish
 * emulator. If request is successful, the remote emulator can simulate hold on,
 * hang up, reject and so on.
 *
 * e.g. AT+REMOTECALL=4,0,0,6521,129
 *
 * <stat>: integer type (state of the call)
 *       0 active
 *       1 held
 *       2 dialing (MO call)
 *       3 alerting (MO call)
 *       4 incoming (MT call)
 *       5 waiting (MT call)
 * <mode>: integer type
 *       0 voice
 *       1 data
 *       2 fax
 *       3 voice followed by data, voice mode
 *       4 alternating voice/data, voice mode
 *       5 alternating voice/fax, voice mode
 *       6 voice followed by data, data mode
 *       7 alternating voice/data, data mode
 *       8 alternating voice/fax, fax mode
 *       9 unknown
 * <mpty>: integer type
 *       0 call is not one of multiparty (conference) call parties
 *       1 call is one of multiparty (conference) call parties
 * <number>: string here maybe remote port
 * <num_type>: type of address octet in integer format
 *
 * Note: reason should be added to indicate why hang up. Since not realizing
 *       RIL_LAST_CALL_FAIL_CAUSE, delay to be implemented.
 */
void CallService::HandleRemoteCall(const Client& client,
                                   const std::string& command) {
  CommandParser cmd(command);
  cmd.SkipPrefix();

  int state = cmd.GetNextInt();
  int mode = cmd.GetNextInt();
  int mpty = cmd.GetNextInt();
  auto number = cmd.GetNextStr();
  int num_type = cmd.GetNextInt();

  // According to the number to determine whether it is a existing call
  auto iter = active_calls_.begin();
  for (; iter != active_calls_.end(); ++iter) {
    if (iter->second.number == number) {
      break;
    }
  }

  switch (state) {
    case CallStatus::CALL_STATE_ACTIVE: {
      if (iter != active_calls_.end()) {
        iter->second.SetCallActive();
        if (iter->second.timeout_serial != std::nullopt) {
          thread_looper_->CancelSerial(*(iter->second.timeout_serial));
        }
      }
      break;
    }
    case CallStatus::CALL_STATE_HELD:
      if (iter != active_calls_.end()) {
        iter->second.SetCallBackground();
        if (iter->second.timeout_serial != std::nullopt) {
          thread_looper_->CancelSerial(*(iter->second.timeout_serial));
        }
      }
      break;
    case CallStatus::CALL_STATE_HANGUP:
      if (iter != active_calls_.end()) {
        auto client = iter->second.remote_client;
        if (client != std::nullopt) {
          CloseRemoteConnection(*client);
        }
        if (iter->second.timeout_serial != std::nullopt) {
          thread_looper_->CancelSerial(*(iter->second.timeout_serial));
        }
        active_calls_.erase(iter);
      }
      break;
    case CallStatus::CALL_STATE_INCOMING: {
      if (network_service_) {
        if (network_service_->isRadioOff()) {
          LOG(DEBUG) << " radio is off, reject incoming call from: " << number;
          client.client_fd->Close();
          return;
        }
      }
      CallStatus call_status(number);
      call_status.is_remote_call = true;
      call_status.is_voice_mode = mode;
      call_status.is_multi_party = mpty;
      call_status.is_mobile_terminated = true;
      call_status.is_international = (num_type == 145);
      call_status.remote_client = client.client_fd;
      call_status.call_state = CallStatus::CALL_STATE_INCOMING;

      auto index = last_active_call_index_++;
      active_calls_[index] = call_status;
      break;
    }
    default:  // Unsupported call state
      return;
  }
  thread_looper_->Post(makeSafeCallback(this, &CallService::CallStateUpdate));
}

}  // namespace cuttlefish