summaryrefslogtreecommitdiff
path: root/src/components/application_manager/include/application_manager/application_manager_impl.h
blob: 7a26501afc73a4e057f6ca692c907e9d7d95f60b (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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_IMPL_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_IMPL_H_

#include <stdint.h>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <algorithm>
#include <memory>

#include "application_manager/hmi_command_factory.h"
#include "application_manager/application_manager.h"
#include "application_manager/hmi_capabilities.h"
#include "application_manager/message.h"
#include "application_manager/message_helper.h"
#include "application_manager/request_controller.h"
#include "application_manager/resumption/resume_ctrl.h"
#include "application_manager/vehicle_info_data.h"
#include "application_manager/state_controller_impl.h"
#include "application_manager/app_launch/app_launch_data.h"
#include "application_manager/application_manager_settings.h"
#include "application_manager/event_engine/event_dispatcher_impl.h"
#include "application_manager/hmi_interfaces_impl.h"

#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/protocol_handler.h"
#include "hmi_message_handler/hmi_message_observer.h"
#include "hmi_message_handler/hmi_message_sender.h"
#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/policies/policy_handler_observer.h"
#include "connection_handler/connection_handler.h"
#include "connection_handler/connection_handler_observer.h"
#include "connection_handler/device.h"
#include "formatters/CSmartFactory.h"
#include "policies/policy_handler.h"

#include "interfaces/HMI_API.h"
#include "interfaces/HMI_API_schema.h"
#include "interfaces/MOBILE_API_schema.h"

#include "interfaces/v4_protocol_v1_2_no_extra.h"
#include "interfaces/v4_protocol_v1_2_no_extra_schema.h"

#ifdef ENABLE_SECURITY
#include "security_manager/security_manager_listener.h"
#include "security_manager/ssl_context.h"
#endif  // ENABLE_SECURITY

#ifdef TELEMETRY_MONITOR
#include "telemetry_observer.h"
#endif  // TELEMETRY_MONITOR

#include "utils/macro.h"
#include "utils/shared_ptr.h"
#include "utils/message_queue.h"
#include "utils/prioritized_queue.h"
#include "utils/threads/thread.h"
#include "utils/threads/message_loop_thread.h"
#include "utils/lock.h"
#include "utils/data_accessor.h"
#include "utils/timer.h"
#include "smart_objects/smart_object.h"

struct BsonObject;

namespace threads {
class Thread;
}
class CommandNotificationImpl;

namespace application_manager {
namespace mobile_api = mobile_apis;
using namespace utils;
using namespace timer;
namespace custom_str = custom_string;

class ApplicationManagerImpl;

enum VRTTSSessionChanging { kVRSessionChanging = 0, kTTSSessionChanging };

struct CommandParametersPermissions;
typedef std::map<std::string, hmi_apis::Common_TransportType::eType>
    DeviceTypes;

namespace impl {
using namespace threads;

/*
 * These dummy classes are here to locally impose strong typing on different
 * kinds of messages
 * Currently there is no type difference between incoming and outgoing messages
 * And due to ApplicationManagerImpl works as message router it has to
 * distinguish
 * messages passed from it's different connection points
 * TODO(ik): replace these with globally defined message types
 * when we have them.
 */
struct MessageFromMobile : public utils::SharedPtr<Message> {
  MessageFromMobile() {}
  explicit MessageFromMobile(const utils::SharedPtr<Message>& message)
      : utils::SharedPtr<Message>(message) {}
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
};

struct MessageToMobile : public utils::SharedPtr<Message> {
  MessageToMobile() : is_final(false) {}
  explicit MessageToMobile(const utils::SharedPtr<Message>& message,
                           bool final_message)
      : utils::SharedPtr<Message>(message), is_final(final_message) {}
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
  // Signals if connection to mobile must be closed after sending this message
  bool is_final;
};

struct MessageFromHmi : public utils::SharedPtr<Message> {
  MessageFromHmi() {}
  explicit MessageFromHmi(const utils::SharedPtr<Message>& message)
      : utils::SharedPtr<Message>(message) {}
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
};

struct MessageToHmi : public utils::SharedPtr<Message> {
  MessageToHmi() {}
  explicit MessageToHmi(const utils::SharedPtr<Message>& message)
      : utils::SharedPtr<Message>(message) {}
  // PrioritizedQueue requres this method to decide which priority to assign
  size_t PriorityOrder() const {
    return (*this)->Priority().OrderingValue();
  }
};

// Short type names for prioritized message queues
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromMobile> >
    FromMobileQueue;
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToMobile> >
    ToMobileQueue;
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromHmi> >
    FromHmiQueue;
typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToHmi> >
    ToHmiQueue;

// AudioPassThru
typedef struct {
  std::vector<uint8_t> binary_data;
  int32_t session_key;
} AudioData;
typedef std::queue<AudioData> RawAudioDataQueue;
typedef threads::MessageLoopThread<RawAudioDataQueue> AudioPassThruQueue;
}
CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
typedef utils::SharedPtr<timer::Timer> TimerSPtr;

class ApplicationManagerImpl
    : public ApplicationManager,
      public hmi_message_handler::HMIMessageObserver,
      public protocol_handler::ProtocolObserver,
      public connection_handler::ConnectionHandlerObserver,
      public policy::PolicyHandlerObserver,
#ifdef ENABLE_SECURITY
      public security_manager::SecurityManagerListener,
#endif  // ENABLE_SECURITY
      public impl::FromMobileQueue::Handler,
      public impl::ToMobileQueue::Handler,
      public impl::FromHmiQueue::Handler,
      public impl::ToHmiQueue::Handler,
      public impl::AudioPassThruQueue::Handler
#ifdef TELEMETRY_MONITOR
      ,
      public telemetry_monitor::TelemetryObservable<AMTelemetryObserver>
#endif  // TELEMETRY_MONITOR
      {

  friend class ResumeCtrl;
  friend class CommandImpl;

 public:
  ApplicationManagerImpl(const ApplicationManagerSettings& am_settings,
                         const policy::PolicySettings& policy_settings);
  ~ApplicationManagerImpl();

  /**
   * Inits application manager
   */
  bool Init(resumption::LastState& last_state,
            media_manager::MediaManager* media_manager) OVERRIDE;

  /**
   * @brief Stop work.
   *
   * @return TRUE on success otherwise FALSE.
   **/
  bool Stop() OVERRIDE;

  DataAccessor<ApplicationSet> applications() const OVERRIDE;
  ApplicationSharedPtr application(uint32_t app_id) const OVERRIDE;

  ApplicationSharedPtr active_application() const OVERRIDE;

  ApplicationSharedPtr application_by_hmi_app(
      uint32_t hmi_app_id) const OVERRIDE;
  ApplicationSharedPtr application_by_policy_id(
      const std::string& policy_app_id) const OVERRIDE;

  std::vector<ApplicationSharedPtr> applications_by_button(
      uint32_t button) OVERRIDE;
  std::vector<ApplicationSharedPtr> applications_with_navi() OVERRIDE;
  std::vector<ApplicationSharedPtr> applications_with_mobile_projection()
      OVERRIDE;

  ApplicationSharedPtr get_limited_media_application() const OVERRIDE;
  ApplicationSharedPtr get_limited_navi_application() const OVERRIDE;
  ApplicationSharedPtr get_limited_voice_application() const OVERRIDE;
  ApplicationSharedPtr get_limited_mobile_projection_application()
      const OVERRIDE;

  uint32_t application_id(const int32_t correlation_id) OVERRIDE;
  void set_application_id(const int32_t correlation_id,
                          const uint32_t app_id) OVERRIDE;

  void OnHMILevelChanged(uint32_t app_id,
                         mobile_apis::HMILevel::eType from,
                         mobile_apis::HMILevel::eType to) OVERRIDE;

  void SendHMIStatusNotification(
      const utils::SharedPtr<Application> app) OVERRIDE;

#ifdef SDL_REMOTE_CONTROL
  ApplicationSharedPtr application(
      const std::string& device_id,
      const std::string& policy_app_id) const OVERRIDE;

  /**
   * @brief ChangeAppsHMILevel the function that will change application's
   * hmi level.
   *
   * @param app_id id of the application whose hmi level should be changed.
   *
   * @param level new hmi level for certain application.
   */
  void ChangeAppsHMILevel(uint32_t app_id, mobile_apis::HMILevel::eType level);

  void Erase(ApplicationSharedPtr app_to_remove) {
    DCHECK(app_to_remove);
    app_to_remove->RemoveExtensions();
    applications_.erase(app_to_remove);
  }

  virtual functional_modules::PluginManager& GetPluginManager() OVERRIDE {
    return plugin_manager_;
  }

  std::vector<std::string> devices(
      const std::string& policy_app_id) const OVERRIDE;

  virtual void SendPostMessageToMobile(const MessagePtr& message) OVERRIDE;

  virtual void SendPostMessageToHMI(const MessagePtr& message) OVERRIDE;
#endif  // SDL_REMOTE_CONTROL

  /**
   * @brief Checks if application with the same HMI type
   *        (media, voice communication or navi) exists
   *        in HMI_FULL or HMI_LIMITED level.
   *
   * @param app Pointer to application to compare with
   *
   * @return true if exist otherwise false
   */
  bool IsAppTypeExistsInFullOrLimited(ApplicationConstSharedPtr app) const;

  /**
   * @brief Checks if Application is subscribed for way points
   * @param Application AppID
   * @return true if Application is subscribed for way points
   * otherwise false
   */
  bool IsAppSubscribedForWayPoints(const uint32_t app_id) const OVERRIDE;

  /**
   * @brief Subscribe Application for way points
   * @param Application AppID
   */
  void SubscribeAppForWayPoints(const uint32_t app_id) OVERRIDE;

  /**
   * @brief Unsubscribe Application for way points
   * @param Application AppID
   */
  void UnsubscribeAppFromWayPoints(const uint32_t app_id) OVERRIDE;

  /**
   * @brief Is Any Application is subscribed for way points
   * @return true if some app is subscribed otherwise false
   */
  bool IsAnyAppSubscribedForWayPoints() const OVERRIDE;

  /**
   * @brief Get subscribed for way points
   * @return reference to set of subscribed apps for way points
   */
  const std::set<int32_t> GetAppsSubscribedForWayPoints() const OVERRIDE;

  /**
   * @brief Notifies all components interested in Vehicle Data update
   * i.e. new value of odometer etc and returns list of applications
   * subscribed for event.
   * @param vehicle_info Enum value of type of vehicle data
   * @param new value (for integer values currently) of vehicle data
   */
  std::vector<ApplicationSharedPtr> IviInfoUpdated(VehicleDataType vehicle_info,
                                                   int value) OVERRIDE;

  void OnApplicationRegistered(ApplicationSharedPtr app) OVERRIDE;

  HMICapabilities& hmi_capabilities() OVERRIDE;
  const HMICapabilities& hmi_capabilities() const OVERRIDE;

  /**
   * @brief ProcessQueryApp executes logic related to QUERY_APP system request.
   *
   * @param sm_object smart object wich is actually parsed json obtained within
   * system request.
   * @param connection_key connection key for app, which sent system request
   */
  void ProcessQueryApp(const smart_objects::SmartObject& sm_object,
                       const uint32_t connection_key) OVERRIDE;

  bool is_attenuated_supported() const OVERRIDE;

#ifdef TELEMETRY_MONITOR
  /**
   * @brief Setup observer for time metric.
   *
   * @param observer - pointer to observer
   */
  void SetTelemetryObserver(AMTelemetryObserver* observer) OVERRIDE;
#endif  // TELEMETRY_MONITOR

  ApplicationSharedPtr RegisterApplication(const utils::SharedPtr<
      smart_objects::SmartObject>& request_for_registration) OVERRIDE;
  /*
   * @brief Closes application by id
   *
   * @param app_id Application id
   * @param reason reason of unregistering application
   * @param is_resuming describes - is this unregister
   *        is normal or need to be resumed\
   * @param is_unexpected_disconnect
   * Indicates if connection was unexpectedly lost(TM layer, HB)
   */
  void UnregisterApplication(const uint32_t& app_id,
                             mobile_apis::Result::eType reason,
                             bool is_resuming = false,
                             bool is_unexpected_disconnect = false) OVERRIDE;

  /**
  * @brief Handle sequence for unauthorized application
  * @param app_id Application id
  */
  void OnAppUnauthorized(const uint32_t& app_id) OVERRIDE;

  /*
   * @brief Sets unregister reason for closing all registered applications
   * duringHU switching off
   *
   * @param reason Describes the reason for HU switching off
   */
  void SetUnregisterAllApplicationsReason(
      mobile_api::AppInterfaceUnregisteredReason::eType reason) OVERRIDE;

  /*
   * @brief Called on Master_reset or Factory_defaults
   * when User chooses to reset HU.
   * Resets Policy Table if applicable.
   */
  void HeadUnitReset(
      mobile_api::AppInterfaceUnregisteredReason::eType reason) OVERRIDE;

  /*
   * @brief Closes all registered applications
   */
  void UnregisterAllApplications();

  bool RemoveAppDataFromHMI(ApplicationSharedPtr app);
  bool LoadAppDataToHMI(ApplicationSharedPtr app);
  bool ActivateApplication(ApplicationSharedPtr app) OVERRIDE;

  /**
   * @brief Put application in FULL HMI Level if possible,
   *        otherwise put applicatuion other HMI level.
   *        do not send any notifications to mobile
   * @param app, application, that need to be puted in FULL
   * @return seted HMI Level
   */
  mobile_api::HMILevel::eType IsHmiLevelFullAllowed(ApplicationSharedPtr app);

  void ConnectToDevice(const std::string& device_mac) OVERRIDE;
  void OnHMIStartedCooperation() OVERRIDE;

  /*
   * @brief Returns unique correlation ID for HMI request
   *
   * @return Unique correlation ID
   */
  uint32_t GetNextHMICorrelationID() OVERRIDE;

  /* @brief Starts audio passthru process
   *
   * @return true on success, false if passthru is already in process
   */
  bool BeginAudioPassThrough() OVERRIDE;

  /*
   * @brief Finishes already started audio passthru process
   *
   * @return true on success, false if passthru is not active
   */
  bool EndAudioPassThrough() OVERRIDE;

  /*
   * @brief Retrieves driver distraction state
   *
   * @return Current state of the distraction state
   */
  inline bool driver_distraction() const;

  /*
   * @brief Sets state for driver distraction
   *
   * @param state New state to be set
   */
  void set_driver_distraction(const bool is_distracting) OVERRIDE;

  /*
   * @brief Retrieves if VR session has started
   *
   * @return Current VR session state (started, stopped)
   */
  inline bool vr_session_started() const;

  /*
   * @brief Sets VR session state
   *
   * @param state Current HMI VR session state
   */
  void set_vr_session_started(const bool state);

  /*
   * @brief Retrieves SDL access to all mobile apps
   *
   * @return Currently active state of the access
   */
  inline bool all_apps_allowed() const;

  /*
   * @brief Sets SDL access to all mobile apps
   *
   * @param allowed SDL access to all mobile apps
   */
  void SetAllAppsAllowed(const bool allowed) OVERRIDE;

  /**
   * @brief CreateRegularState create regular HMI state for application
   * @param app_id
   * @param hmi_level of returned state
   * @param audio_state of returned state
   * @param system_context of returned state
   * @return new regular HMI state
   */
  HmiStatePtr CreateRegularState(
      uint32_t app_id,
      mobile_apis::HMILevel::eType hmi_level,
      mobile_apis::AudioStreamingState::eType audio_state,
      mobile_apis::SystemContext::eType system_context) const OVERRIDE;

  /**
   * @brief SetState set regular audio state
   * @param app_id applicatio id
   * @param audio_state aaudio streaming state
   */
  void SetState(uint32_t app_id,
                mobile_apis::AudioStreamingState::eType audio_state) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, audio_state);
  }

  /**
   * @brief SetState setup regular hmi state, that will appear if no
   * specific events are active
   * @param app appication to setup regular State
   * @param state state of new regular state
   */
  template <bool SendActivateApp>
  void SetState(uint32_t app_id, HmiStatePtr new_state) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, new_state, SendActivateApp);
  }

  /**
   * @brief Checks, if given RPC is allowed at current HMI level for specific
   * application in policy table
   * @param app Application
   * @param hmi_level Current HMI level of application
   * @param function_id FunctionID of RPC
   * @param params_permissions Permissions for RPC parameters (e.g.
   * SubscribeVehicleData) defined in policy table
   * @return SUCCESS, if allowed, otherwise result code of check
   */
  mobile_apis::Result::eType CheckPolicyPermissions(
      const ApplicationSharedPtr app,
      const std::string& function_id,
      const RPCParams& rpc_params,
      CommandParametersPermissions* params_permissions = NULL) OVERRIDE;

  /**
   * @brief IsApplicationForbidden allows to distinguish if application is
   * not allowed to register, becuase of spaming.
   *
   * @param connection_key the conection key ofthe required application
   *
   * @param mobile_app_id application's mobile(policy) identifier.
   *
   * @return true in case application is allowed to register, false otherwise.
   */
  bool IsApplicationForbidden(uint32_t connection_key,
                              const std::string& mobile_app_id);

  struct ApplicationsAppIdSorter {
    bool operator()(const ApplicationSharedPtr lhs,
                    const ApplicationSharedPtr rhs) {
      return lhs->app_id() < rhs->app_id();
    }
  };

  struct ApplicationsMobileAppIdSorter {
    bool operator()(const ApplicationSharedPtr lhs,
                    const ApplicationSharedPtr rhs) {
      if (lhs->policy_app_id() == rhs->policy_app_id()) {
        return lhs->device() < rhs->device();
      }
      return lhs->policy_app_id() < rhs->policy_app_id();
    }
  };

  // typedef for Applications list
  typedef std::set<ApplicationSharedPtr, ApplicationsAppIdSorter> ApplictionSet;

  typedef std::set<ApplicationSharedPtr, ApplicationsPolicyAppIdSorter>
      AppsWaitRegistrationSet;

  // typedef for Applications list iterator
  typedef ApplictionSet::iterator ApplictionSetIt;

  // typedef for Applications list const iterator
  typedef ApplictionSet::const_iterator ApplictionSetConstIt;

  DataAccessor<AppsWaitRegistrationSet> apps_waiting_for_registration() const;
  ApplicationConstSharedPtr waiting_app(const uint32_t hmi_id) const;

  /**
   * @brief SetState Change regular audio state
   * @param app appication to setup regular State
   * @param audio_state of new regular state
   */
  template <bool SendActivateApp>
  void SetState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, hmi_level, SendActivateApp);
  }

  /**
   * @brief SetState Change regular hmi level and audio state
   * @param app appication to setup regular State
   * @param hmi_level of new regular state
   * @param audio_state of new regular state
   * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI
   */
  template <bool SendActivateApp>
  void SetState(uint32_t app_id,
                mobile_apis::HMILevel::eType hmi_level,
                mobile_apis::AudioStreamingState::eType audio_state) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, hmi_level, audio_state, SendActivateApp);
  }

  /**
   * @brief SetState Change regular hmi level and audio state
   * @param app appication to setup regular State
   * @param hmi_level of new regular state
   * @param audio_state of new regular state
   * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI
   */
  template <bool SendActivateApp>
  void SetState(uint32_t app_id,
                mobile_apis::HMILevel::eType hmi_level,
                mobile_apis::AudioStreamingState::eType audio_state,
                mobile_apis::SystemContext::eType system_context) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(
        app, hmi_level, audio_state, system_context, SendActivateApp);
  }

  /**
   * @brief SetState Change regular  system context
   * @param app appication to setup regular State
   * @param system_context of new regular state
   */
  void SetState(uint32_t app_id,
                mobile_apis::SystemContext::eType system_context) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, system_context);
  }

  /**
   * @brief SetState Change regular hmi level
   * @param app appication to setup regular State
   * @param hmi_level hmi level of new regular state
   */
  void SetHmiState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, hmi_level);
  }

  /**
   * @brief SetState Change regular hmi state
   * @param app appication to setup regular State
   * @param state new regular hmi state
   */
  void SetState(uint32_t app_id, HmiStatePtr state) {
    ApplicationSharedPtr app = application(app_id);
    if (!app) {
      LOG4CXX_ERROR(logger_,
                    "Application with appID=" << app_id << " does not exist");
      return;
    }
    state_ctrl_.SetRegularState(app, state);
  }

  /**
   * @brief Checks, if particular state is active
   * @param state_id State
   * @return True, if state is active, otherwise - false
   */
  bool IsStateActive(HmiState::StateID state_id) const;

  /**
   * @brief Notification from PolicyHandler about PTU.
   * Compares AppHMIType between saved in app and received from PTU. If they are
   * different method sends:
   * UI_ChangeRegistration with list new AppHMIType;
   * ActivateApp with HMI level BACKGROUND;
   * OnHMIStatus notification;
   * for app with HMI level FULL or LIMITED.
   * method sends:
   * UI_ChangeRegistration with list new AppHMIType
   * for app with HMI level BACKGROUND.
   */
  void OnUpdateHMIAppType(
      std::map<std::string, std::vector<std::string> > app_hmi_types) OVERRIDE;

  /**
   * @brief OnPTUFinished is called on policy table update coming
   * @param ptu_result True if PTU is succeeded, otherwise - false
   */
  void OnPTUFinished(const bool ptu_result) FINAL;

  /*
   * @brief Starts audio pass thru thread
   *
   * @param session_key     Session key of connection for Mobile side
   * @param correlation_id  Correlation id for response for Mobile side
   * @param max_duration    Max duration of audio recording in milliseconds
   * @param sampling_rate   Value for rate(8, 16, 22, 44 kHz)
   * @param bits_per_sample The quality the audio is recorded.
   * @param audio_type      Type of audio data
   */
  void StartAudioPassThruThread(int32_t session_key,
                                int32_t correlation_id,
                                int32_t max_duration,
                                int32_t sampling_rate,
                                int32_t bits_per_sample,
                                int32_t audio_type) OVERRIDE;

  /*
   * @brief Terminates audio pass thru thread
   * @param application_key Id of application for which
   * audio pass thru should be stopped
   */
  void StopAudioPassThru(int32_t application_key) OVERRIDE;

  /*
   * @brief Creates AudioPassThru data chunk and inserts it
   * to audio_pass_thru_messages_
   *
   * @param session_key Id of application for which
   * audio pass thru should be sent
   *
   * @param binary_data AudioPassThru data chunk
   */
  void SendAudioPassThroughNotification(
      uint32_t session_key, std::vector<uint8_t>& binary_data) OVERRIDE;

  std::string GetDeviceName(connection_handler::DeviceHandle handle);

  /*
   * @brief Converts connection string transport type representation
   * to HMI Common_TransportType
   *
   * @param transport_type String representing connection type
   *
   * @return Corresponding HMI TransporType value
   */
  hmi_apis::Common_TransportType::eType GetDeviceTransportType(
      const std::string& transport_type);

  void set_hmi_message_handler(hmi_message_handler::HMIMessageHandler* handler);
  void set_connection_handler(connection_handler::ConnectionHandler* handler);
  void set_protocol_handler(protocol_handler::ProtocolHandler* handler);

  void StartDevicesDiscovery();

  // Put message to the queue to be sent to mobile.
  // if |final_message| parameter is set connection to mobile will be closed
  // after processing this message
  void SendMessageToMobile(const commands::MessageSharedPtr message,
                           bool final_message = false) OVERRIDE;

  void SendMessageToHMI(const commands::MessageSharedPtr message) OVERRIDE;

  void RemoveHMIFakeParameters(
      application_manager::MessagePtr& message) OVERRIDE;

  bool ManageMobileCommand(const commands::MessageSharedPtr message,
                           commands::Command::CommandOrigin origin) OVERRIDE;
  bool ManageHMICommand(const commands::MessageSharedPtr message) OVERRIDE;

  /**
   * @brief TerminateRequest forces termination of request
   * @param connection_key - application id of request
   * @param corr_id correlation id of request
   * @param function_id function id of request
   */
  void TerminateRequest(const uint32_t connection_key,
                        const uint32_t corr_id,
                        const int32_t function_id) OVERRIDE;
  // Overriden ProtocolObserver method
  void OnMessageReceived(
      const ::protocol_handler::RawMessagePtr message) OVERRIDE;
  void OnMobileMessageSent(
      const ::protocol_handler::RawMessagePtr message) OVERRIDE;

  // Overriden HMIMessageObserver method
  void OnMessageReceived(
      hmi_message_handler::MessageSharedPointer message) OVERRIDE;
  void OnErrorSending(
      hmi_message_handler::MessageSharedPointer message) OVERRIDE;

  // Overriden ConnectionHandlerObserver method
  void OnDeviceListUpdated(
      const connection_handler::DeviceMap& device_list) OVERRIDE;
  void OnFindNewApplicationsRequest() OVERRIDE;
  void RemoveDevice(
      const connection_handler::DeviceHandle& device_handle) OVERRIDE;
  // DEPRECATED
  bool OnServiceStartedCallback(
      const connection_handler::DeviceHandle& device_handle,
      const int32_t& session_key,
      const protocol_handler::ServiceType& type) OVERRIDE;
  void OnServiceStartedCallback(
      const connection_handler::DeviceHandle& device_handle,
      const int32_t& session_key,
      const protocol_handler::ServiceType& type,
      const BsonObject* params) OVERRIDE;
  void OnServiceEndedCallback(
      const int32_t& session_key,
      const protocol_handler::ServiceType& type,
      const connection_handler::CloseSessionReason& close_reason) OVERRIDE;

#ifdef ENABLE_SECURITY
  // Overriden SecurityManagerListener method
  bool OnHandshakeDone(
      uint32_t connection_key,
      security_manager::SSLContext::HandshakeResult result) OVERRIDE;

  void OnCertificateUpdateRequired() OVERRIDE;

  security_manager::SSLContext::HandshakeContext GetHandshakeContext(
      uint32_t key) const OVERRIDE;
#endif  // ENABLE_SECURITY

  /**
   * @ Add notification to collection
   *
   * @param ptr Reference to shared pointer that point on hmi notification
   */
  void addNotification(const CommandSharedPtr ptr);

  /**
   * @ Add notification to collection
   *
   * @param ptr Reference to shared pointer that point on hmi notification
   */
  void removeNotification(const commands::Command* notification);

  /**
   * @ Updates request timeout
   *
   * @param connection_key Connection key of application
   * @param mobile_correlation_id Correlation ID of the mobile request
   * @param new_timeout_value New timeout in milliseconds to be set
   */
  void updateRequestTimeout(uint32_t connection_key,
                            uint32_t mobile_correlation_id,
                            uint32_t new_timeout_value) OVERRIDE;

  /**
   * @brief AddPolicyObserver allows to subscribe needed component to events
   * from policy.
   *
   * @param listener the component to subscribe.
   */
  void AddPolicyObserver(PolicyHandlerObserver* listener);

  /**
   * @brief RemovePolicyObserver allows to remove observer from collection.
   *
   * @param listener observer to remove.
   */
  void RemovePolicyObserver(PolicyHandlerObserver* listener);

  /**
   * @brief Checks HMI level and returns true if streaming is allowed
   * @param app_id Application id
   * @param service_type Service type to check
   * @return True if streaming is allowed, false in other case
   */
  bool HMILevelAllowsStreaming(
      uint32_t app_id,
      protocol_handler::ServiceType service_type) const OVERRIDE;

  /**
   * @brief Checks if application can stream (streaming service is started and
   * streaming is enabled in application)
   * @param app_id Application id
   * @param service_type Service type to check
   * @return True if streaming is allowed, false in other case
   */
  bool CanAppStream(uint32_t app_id,
                    protocol_handler::ServiceType service_type) const OVERRIDE;

  /**
   * @brief Ends opened navi services (audio/video) for application
   * @param app_id Application id
   */
  void EndNaviServices(uint32_t app_id) OVERRIDE;

  /**
   * @brief ForbidStreaming forbid the stream over the certain application.
   * @param app_id the application's id which should stop streaming.
   */
  void ForbidStreaming(uint32_t app_id) OVERRIDE;

  /**
   * @brief Called when application completes streaming configuration
   * @param app_id Streaming application id
   * @param service_type Streaming service type
   * @param result true if configuration is successful, false otherwise
   * @param rejected_params list of rejected parameters' name. Valid
   *                        only when result is false.
   */
  void OnStreamingConfigured(
      uint32_t app_id,
      protocol_handler::ServiceType service_type,
      bool result,
      std::vector<std::string>& rejected_params) OVERRIDE;

  /**
   * @brief Callback calls when application starts/stops data streaming
   * @param app_id Streaming application id
   * @param service_type Streaming service type
   * @param state Shows if streaming started or stopped
   */
  void OnAppStreaming(uint32_t app_id,
                      protocol_handler::ServiceType service_type,
                      bool state) OVERRIDE;

  mobile_api::HMILevel::eType GetDefaultHmiLevel(
      ApplicationConstSharedPtr application) const;

  /**
  * Getter for resume_controller
  * @return Resume Controller
  */
  resumption::ResumeCtrl& resume_controller() OVERRIDE {
    return *resume_ctrl_.get();
  }

  HmiInterfaces& hmi_interfaces() OVERRIDE {
    return hmi_interfaces_;
  }

  /**
   * Generate grammar ID
   *
   * @return New grammar ID
   */
  uint32_t GenerateGrammarID() OVERRIDE;

  /**
   * Generate new HMI application ID
   *
   * @return New HMI application ID
   */
  uint32_t GenerateNewHMIAppID() OVERRIDE;

  /**
   * @brief Parse smartObject and replace mobile app Id by HMI app ID
   *
   * @param message Smartobject to be parsed
   */
  void ReplaceMobileByHMIAppId(smart_objects::SmartObject& message);

  /**
   * @brief Parse smartObject and replace HMI app ID by mobile app Id
   *
   * @param message Smartobject to be parsed
   */
  void ReplaceHMIByMobileAppId(smart_objects::SmartObject& message);

  /*
   * @brief Save binary data to specified directory
   *
   * @param binary data
   * @param path for saving data
   * @param file_name File name
   * @param offset for saving data to existing file with offset.
   *        If offset is 0 - create new file ( overrite existing )
   *
   *
   * @return SUCCESS if file was saved, other code otherwise
   */
  mobile_apis::Result::eType SaveBinary(const std::vector<uint8_t>& binary_data,
                                        const std::string& file_path,
                                        const std::string& file_name,
                                        const int64_t offset) OVERRIDE;

  /**
   * @brief Get available app space
   * @param name of the app folder(make + mobile app id)
   * @return free app space.
   */
  uint32_t GetAvailableSpaceForApp(const std::string& folder_name);

  /*
   * @brief returns true if HMI is cooperating
   */
  bool IsHMICooperating() const OVERRIDE;

  /**
   * @brief Method used to send default app tts globalProperties
   * in case they were not provided from mobile side after defined time
   */
  void OnTimerSendTTSGlobalProperties();

  /**
   * @brief method adds application
   * to tts_global_properties_app_list_
   * @param app_id contains application which will
   * send TTS global properties after timeout
   */
  void AddAppToTTSGlobalPropertiesList(const uint32_t app_id) OVERRIDE;

  /**
   * @brief method removes application
   * from tts_global_properties_app_list_
   * @param app_id contains application which will
   * send TTS global properties after timeout
   */
  void RemoveAppFromTTSGlobalPropertiesList(const uint32_t app_id) OVERRIDE;

  /**
   * @brief method adds application in FULL and LIMITED state
   * to on_phone_call_app_list_.
   * Also OnHMIStateNotification with BACKGROUND state sent for these apps
   */
  void CreatePhoneCallAppList();

  /**
   * @brief method removes application from on_phone_call_app_list_.
   *
   * Also OnHMIStateNotification with previous HMI state sent for these apps
   */
  void ResetPhoneCallAppList();

  // TODO(AOleynik): Temporary added, to fix build. Should be reworked.
  connection_handler::ConnectionHandler& connection_handler() const OVERRIDE;
  protocol_handler::ProtocolHandler& protocol_handler() const OVERRIDE;

  virtual policy::PolicyHandlerInterface& GetPolicyHandler() OVERRIDE {
    return *policy_handler_;
  }

  virtual const policy::PolicyHandlerInterface& GetPolicyHandler()
      const OVERRIDE {
    return *policy_handler_;
  }

  /*
   * @brief Function Should be called when Low Voltage is occured
   */
  void OnLowVoltage();

  /*
   * @brief Function Should be called when WakeUp occures after Low Voltage
   */
  void OnWakeUp();

  /**
   * @brief IsApplicationForbidden allows to distinguish if application is
   * not allowed to register, because of spamming.
   *
   * @param connection_key the connection key ofthe required application
   *
   * @param policy_app_id application's mobile(policy) identifier.
   *
   * @return true in case application is allowed to register, false otherwise.
   */
  bool IsApplicationForbidden(uint32_t connection_key,
                              const std::string& policy_app_id) const OVERRIDE;

  policy::DeviceConsent GetUserConsentForDevice(
      const std::string& device_id) const OVERRIDE;

  // typedef for Applications list
  typedef std::set<std::string> ForbiddenApps;

  struct AppIdPredicate {
    uint32_t app_id_;
    AppIdPredicate(uint32_t app_id) : app_id_(app_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? app_id_ == app->app_id() : false;
    }
  };

  struct HmiAppIdPredicate {
    uint32_t hmi_app_id_;
    HmiAppIdPredicate(uint32_t hmi_app_id) : hmi_app_id_(hmi_app_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? hmi_app_id_ == app->hmi_app_id() : false;
    }
  };

  struct PolicyAppIdPredicate {
    std::string policy_app_id_;
    PolicyAppIdPredicate(const std::string& policy_app_id)
        : policy_app_id_(policy_app_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? policy_app_id_ == app->policy_app_id() : false;
    }
  };

  struct SubscribedToButtonPredicate {
    mobile_apis::ButtonName::eType button_;
    SubscribedToButtonPredicate(mobile_apis::ButtonName::eType button)
        : button_(button) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? app->IsSubscribedToButton(button_) : false;
    }
  };

  struct AppV4DevicePredicate {
    connection_handler::DeviceHandle handle_;
    AppV4DevicePredicate(const connection_handler::DeviceHandle handle)
        : handle_(handle) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app
                 ? handle_ == app->device() &&
                       Message::is_sufficient_version(
                           protocol_handler::MajorProtocolVersion::
                               PROTOCOL_VERSION_4,
                           app->protocol_version())
                 : false;
    }
  };

  struct DevicePredicate {
    connection_handler::DeviceHandle handle_;
    DevicePredicate(const connection_handler::DeviceHandle handle)
        : handle_(handle) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return handle_ == app->device() ? true : false;
    }
  };

  struct SubscribedToIVIPredicate {
    int32_t vehicle_info_;
    SubscribedToIVIPredicate(int32_t vehicle_info)
        : vehicle_info_(vehicle_info) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? app->IsSubscribedToIVI(vehicle_info_) : false;
    }
  };

  struct GrammarIdPredicate {
    uint32_t grammar_id_;
    GrammarIdPredicate(uint32_t grammar_id) : grammar_id_(grammar_id) {}
    bool operator()(const ApplicationSharedPtr app) const {
      return app ? grammar_id_ == app->get_grammar_id() : false;
    }
  };

  /**
   * @brief Sends UpdateAppList notification to HMI
   */
  void SendUpdateAppList() OVERRIDE;

  /**
   * @brief Marks applications received through QueryApps as should be
   * greyed out on HMI
   * @param is_greyed_out, true, if should be greyed out, otherwise - false
   * @param handle, device handle
   */
  void MarkAppsGreyOut(const connection_handler::DeviceHandle handle,
                       bool is_greyed_out) OVERRIDE;

  ApplicationConstSharedPtr WaitingApplicationByID(
      const uint32_t hmi_id) const OVERRIDE;

  DataAccessor<AppsWaitRegistrationSet> AppsWaitingForRegistration()
      const OVERRIDE;

  /**
   * @brief Checks, if apps list had been queried already from certain device
   * @param handle, Device handle
   * @return true, if list had been queried already, otherwise - false
   */
  bool IsAppsQueriedFrom(
      const connection_handler::DeviceHandle handle) const OVERRIDE;

  bool IsStopping() const OVERRIDE {
    return is_stopping_;
  }

  /**
   * @brief Clears all applications' persistent data
   */
  void ClearAppsPersistentData();

  StateController& state_controller() OVERRIDE;
  const ApplicationManagerSettings& get_settings() const OVERRIDE;
  virtual event_engine::EventDispatcher& event_dispatcher() OVERRIDE;

  app_launch::AppLaunchCtrl& app_launch_ctrl() OVERRIDE;

 private:
  /**
   * @brief PullLanguagesInfo allows to pull information about languages.
   *
   * @param app_data entry to parse
   *
   * @param ttsName tts name that should be filled.
   * @param vrSynonym vr synonymus that should be filled.
   */
  void PullLanguagesInfo(const smart_objects::SmartObject& app_data,
                         smart_objects::SmartObject& ttsName,
                         smart_objects::SmartObject& vrSynonym);

  /**
   * @brief Method transforms string to AppHMIType
   * @param str contains string AppHMIType
   * @return enum AppHMIType
   */
  mobile_apis::AppHMIType::eType StringToAppHMIType(std::string str);

  /**
   * @brief Method compares arrays of app HMI type
   * @param from_policy contains app HMI type from policy
   * @param from_application contains app HMI type from application
   * @return return TRUE if arrays of appHMIType equal, otherwise return FALSE
   */
  bool CompareAppHMIType(const smart_objects::SmartObject& from_policy,
                         const smart_objects::SmartObject& from_application);

  hmi_apis::HMI_API& hmi_so_factory();
  mobile_apis::MOBILE_API& mobile_so_factory();

  bool ConvertMessageToSO(const Message& message,
                          smart_objects::SmartObject& output);
  bool ConvertSOtoMessage(const smart_objects::SmartObject& message,
                          Message& output);

  MessageValidationResult ValidateMessageBySchema(
      const Message& message) OVERRIDE;

  utils::SharedPtr<Message> ConvertRawMsgToMessage(
      const ::protocol_handler::RawMessagePtr message);

  void ProcessMessageFromMobile(const utils::SharedPtr<Message> message);
  void ProcessMessageFromHMI(const utils::SharedPtr<Message> message);

  // threads::MessageLoopThread<*>::Handler implementations
  /*
   * @brief Handles for threads pumping different types
   * of messages. Beware, each is called on different thread!
   */
  // CALLED ON messages_from_mobile_ thread!
  void Handle(const impl::MessageFromMobile message) OVERRIDE;

  // CALLED ON messages_to_mobile_ thread!
  void Handle(const impl::MessageToMobile message) OVERRIDE;

  // CALLED ON messages_from_hmi_ thread!
  void Handle(const impl::MessageFromHmi message) OVERRIDE;

  // CALLED ON messages_to_hmi_ thread!
  void Handle(const impl::MessageToHmi message) OVERRIDE;

  // CALLED ON audio_pass_thru_messages_ thread!
  void Handle(const impl::AudioData message) OVERRIDE;

  template <typename ApplicationList>
  void PrepareApplicationListSO(ApplicationList app_list,
                                smart_objects::SmartObject& applications,
                                ApplicationManager& app_mngr) {
    CREATE_LOGGERPTR_LOCAL(logger_, "ApplicationManager");

    smart_objects::SmartArray* app_array = applications.asArray();
    uint32_t app_count = NULL == app_array ? 0 : app_array->size();
    typename ApplicationList::const_iterator it;
    for (it = app_list.begin(); it != app_list.end(); ++it) {
      if (!it->valid()) {
        LOG4CXX_ERROR(logger_, "Application not found ");
        continue;
      }

      smart_objects::SmartObject hmi_application(smart_objects::SmartType_Map);
      const protocol_handler::SessionObserver& session_observer =
          connection_handler().get_session_observer();
      if (MessageHelper::CreateHMIApplicationStruct(*it,
                                                    session_observer,
                                                    GetPolicyHandler(),
                                                    &hmi_application,
                                                    app_mngr)) {
        applications[app_count++] = hmi_application;
      } else {
        LOG4CXX_DEBUG(logger_, "Can't CreateHMIApplicationStruct ");
      }
    }

    if (0 == app_count) {
      LOG4CXX_WARN(logger_, "Empty applications list");
    }
  }

  void OnApplicationListUpdateTimer();

  /**
   * @brief CreateApplications creates aplpication adds it to application list
   * and prepare data for sending AppIcon request.
   *
   * @param obj_array applications array.
   *
   * @param connection_key connection key of app, which provided app list to
   * be created
   */
  void CreateApplications(smart_objects::SmartArray& obj_array,
                          const uint32_t connection_key);

  /*
   * @brief Function is called on IGN_OFF, Master_reset or Factory_defaults
   * to notify HMI that SDL is shutting down.
   */
  void SendOnSDLClose();

  /*
   * @brief returns true if low voltage state is active
   */
  bool IsLowVoltage();

 private:
  /*
   * NaviServiceStatusMap shows which navi service (audio/video) is opened
   * for specified application. Two bool values in std::pair mean:
   * 1st value - is video service opened or not
   * 2nd value - is audio service opened or not
   */
  typedef std::map<uint32_t, std::pair<bool, bool> > NaviServiceStatusMap;

  /**
   * @brief GetHashedAppID allows to obtain unique application id as a string.
   * It concatenates device mac and application id to obtain unique id.
   *
   * @param connection_key connection key for which need to obtain device mac;
   *
   * @param policy_app_id mobile(policy) application id on particular device.
   * This parameter will be concatenated with device id.
   *
   * @return unique aplication identifier.
   */
  std::string GetHashedAppID(uint32_t connection_key,
                             const std::string& policy_app_id) const;

  /**
   * @brief Removes suspended and stopped timers from timer pool
   */
  void ClearTimerPool();

  /**
   * @brief CloseNaviApp allows to unregister application in case the
   * EndServiceEndedAck
   * didn't come for at least one of services(audio or video)
   */
  void CloseNaviApp();

  /**
   * @brief Suspends streaming ability of application in case application's HMI
   * level
   * has been changed to not allowed for streaming
   */
  void EndNaviStreaming();

  /**
   * @brief Starts specified navi service for application
   * @param app_id Application to proceed
   * @param service_type Type of service to start
   * @return True on success, false on fail
   */
  // DEPRECATED
  bool StartNaviService(uint32_t app_id,
                        protocol_handler::ServiceType service_type);

  /**
   * @brief Starts specified navi service for application
   * @param app_id Application to proceed
   * @param service_type Type of service to start
   * @param params configuration parameters specified by mobile
   * @return True if service is immediately started or configuration
   * parameters are sent to HMI, false on other cases
   */
  bool StartNaviService(uint32_t app_id,
                        protocol_handler::ServiceType service_type,
                        const BsonObject* params);

  /**
   * @brief Stops specified navi service for application
   * @param app_id Application to proceed
   * @param service_type Type of service to stop
   */
  void StopNaviService(uint32_t app_id,
                       protocol_handler::ServiceType service_type);

  /**
   * @brief Allows streaming for application if it was disallowed by
   * DisallowStreaming()
   * @param app_id Application to proceed
   */
  void AllowStreaming(uint32_t app_id);

  /**
   * @brief Disallows streaming for application, but doesn't close
   * opened services. Streaming ability could be restored by AllowStreaming();
   * @param app_id Application to proceed
   */
  void DisallowStreaming(uint32_t app_id);

  /**
   * @brief Function returns supported SDL Protocol Version
   * @return protocol version depends on parameters from smartDeviceLink.ini.
   */
  protocol_handler::MajorProtocolVersion SupportedSDLVersion() const;

  /**
   * @brief Types of directories used by Application Manager
   */
  enum DirectoryType { TYPE_STORAGE, TYPE_SYSTEM, TYPE_ICONS };

  typedef std::map<DirectoryType, std::string> DirectoryTypeMap;
  DirectoryTypeMap dir_type_to_string_map_;

  /**
   * @brief Converts directory type to string
   * @param type Directory type
   * @return Stringified type
   */
  const std::string DirectoryTypeToString(DirectoryType type) const;

  /**
   * @brief Creates directory path, if necessary
   * @param path Directory path
   * @param type Directory type
   * @return true, if succedeed, otherwise - false
   */
  bool InitDirectory(const std::string& path, DirectoryType type) const;

  /**
   * @brief Checks, whether r/w permissions are present for particular path
   * @param path Directory path
   * @param type Directory type
   * @return true, if allowed, otherwise - false
   */
  bool IsReadWriteAllowed(const std::string& path, DirectoryType type) const;

  /**
   * @brief Removes apps, waiting for registration related to
   * certain device handle
   * @param handle, Device handle
   */
  void RemoveAppsWaitingForRegistration(
      const connection_handler::DeviceHandle handle);

  void ClearTTSGlobalPropertiesList();

  /**
   * @brief Converts BSON object containing video parameters to
   * smart object's map object
   * @param output the smart object to add video parameters
   * @param input BSON object to read parameters from
   */
  static void ConvertVideoParamsToSO(smart_objects::SmartObject& output,
                                     const BsonObject* input);

  /**
   * @brief Converts rejected parameters' names acquired from HMI to
   * SDL protocol's parameter names
   * @param list of rejected parameters' names
   * @return converted parameters' names
   */
  static std::vector<std::string> ConvertRejectedParamList(
      const std::vector<std::string>& input);

 private:
  const ApplicationManagerSettings& settings_;
  /**
   * @brief List of applications
   */
  ApplicationSet applications_;
  AppsWaitRegistrationSet apps_to_register_;
  ForbiddenApps forbidden_applications;

  // Lock for applications list
  mutable sync_primitives::Lock applications_list_lock_;
  mutable sync_primitives::Lock apps_to_register_list_lock_;
  mutable sync_primitives::Lock subscribed_way_points_apps_lock_;

  /**
   * @brief Map of correlation id  and associated application id.
   */
  std::map<const int32_t, const uint32_t> appID_list_;

  /**
   * @brief Set AppIDs of subscribed apps for way points
   */
  std::set<int32_t> subscribed_way_points_apps_list_;

  /**
   * @brief Map contains applications which
   * will send TTS global properties to HMI after timeout
   */
  std::map<uint32_t, TimevalStruct> tts_global_properties_app_list_;

  bool audio_pass_thru_active_;
  sync_primitives::Lock audio_pass_thru_lock_;
  sync_primitives::Lock tts_global_properties_app_list_lock_;
  bool is_distracting_driver_;
  bool is_vr_session_strated_;
  bool hmi_cooperating_;
  bool is_all_apps_allowed_;

  event_engine::EventDispatcherImpl event_dispatcher_;
  media_manager::MediaManager* media_manager_;

  hmi_message_handler::HMIMessageHandler* hmi_handler_;
  connection_handler::ConnectionHandler* connection_handler_;
  std::auto_ptr<policy::PolicyHandlerInterface> policy_handler_;
  protocol_handler::ProtocolHandler* protocol_handler_;
  request_controller::RequestController request_ctrl_;

#ifdef SDL_REMOTE_CONTROL
  functional_modules::PluginManager plugin_manager_;

  /**
   * @brief Map contains apps with HMI state before incoming call
   * After incoming call ends previous HMI state must restore
   *
   */
  struct AppState {
    AppState(const mobile_apis::HMILevel::eType& level,
             const mobile_apis::AudioStreamingState::eType& streaming_state,
             const mobile_apis::SystemContext::eType& context)
        : hmi_level(level)
        , audio_streaming_state(streaming_state)
        , system_context(context) {}

    mobile_apis::HMILevel::eType hmi_level;
    mobile_apis::AudioStreamingState::eType audio_streaming_state;
    mobile_apis::SystemContext::eType system_context;
  };
#endif  // SDL_REMOTE_CONTROL

  hmi_apis::HMI_API* hmi_so_factory_;
  mobile_apis::MOBILE_API* mobile_so_factory_;

  static uint32_t corelation_id_;
  static const uint32_t max_corelation_id_;

  // Construct message threads when everything is already created

  // Thread that pumps messages coming from mobile side.
  impl::FromMobileQueue messages_from_mobile_;
  // Thread that pumps messages being passed to mobile side.
  impl::ToMobileQueue messages_to_mobile_;
  // Thread that pumps messages coming from HMI.
  impl::FromHmiQueue messages_from_hmi_;
  // Thread that pumps messages being passed to HMI.
  impl::ToHmiQueue messages_to_hmi_;
  // Thread that pumps messages audio pass thru to mobile.
  impl::AudioPassThruQueue audio_pass_thru_messages_;

  std::auto_ptr<HMICapabilities> hmi_capabilities_;
  // The reason of HU shutdown
  mobile_api::AppInterfaceUnregisteredReason::eType unregister_reason_;

  /**
   * @brief Resume controler is responcible for save and load information
   * about persistent application data on disk, and save session ID for resuming
   * application in case INGITION_OFF or MASTER_RESSET
   */
  std::auto_ptr<resumption::ResumeCtrl> resume_ctrl_;

  HmiInterfacesImpl hmi_interfaces_;

  NaviServiceStatusMap navi_service_status_;
  sync_primitives::Lock navi_service_status_lock_;
  std::deque<uint32_t> navi_app_to_stop_;
  std::deque<uint32_t> navi_app_to_end_stream_;
  uint32_t navi_close_app_timeout_;
  uint32_t navi_end_stream_timeout_;

  std::vector<TimerSPtr> timer_pool_;
  sync_primitives::Lock timer_pool_lock_;
  sync_primitives::Lock stopping_application_mng_lock_;
  StateControllerImpl state_ctrl_;
  std::auto_ptr<app_launch::AppLaunchData> app_launch_dto_;
  std::auto_ptr<app_launch::AppLaunchCtrl> app_launch_ctrl_;

#ifdef TELEMETRY_MONITOR
  AMTelemetryObserver* metric_observer_;
#endif  // TELEMETRY_MONITOR

  Timer application_list_update_timer_;

  Timer tts_global_properties_timer_;

  bool is_low_voltage_;

  uint32_t apps_size_;

  volatile bool is_stopping_;

#ifdef BUILD_TESTS
 public:
  /**
   * @brief register a mock application without going through the formal
   * registration process. Only for unit testing.
   * @param mock_app the mock app to be registered
   */
  void AddMockApplication(ApplicationSharedPtr mock_app);

 private:
#endif

  DISALLOW_COPY_AND_ASSIGN(ApplicationManagerImpl);
};

bool ApplicationManagerImpl::vr_session_started() const {
  return is_vr_session_strated_;
}

bool ApplicationManagerImpl::driver_distraction() const {
  return is_distracting_driver_;
}

inline bool ApplicationManagerImpl::all_apps_allowed() const {
  return is_all_apps_allowed_;
}

}  // namespace application_manager

#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_IMPL_H_