summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLProxy.m
blob: 8a1e6b3448665e84f1e99e14bd42f22a576b9b98 (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
// SDLProxy.m

#import "SDLProxy.h"

#import <ExternalAccessory/ExternalAccessory.h>
#import <UIKit/UIKit.h>
#import <objc/runtime.h>

#import "SDLAudioStreamingState.h"
#import "SDLLogMacros.h"
#import "SDLEncodedSyncPData.h"
#import "SDLFileType.h"
#import "SDLFunctionID.h"
#import "SDLGlobals.h"
#import "SDLHMILevel.h"
#import "SDLIAPTransport.h"
#import "SDLLanguage.h"
#import "SDLLayoutMode.h"
#import "SDLLockScreenStatusManager.h"
#import "SDLOnButtonEvent.h"
#import "SDLOnButtonPress.h"
#import "SDLOnHMIStatus.h"
#import "SDLOnSystemRequest.h"
#import "SDLPolicyDataParser.h"
#import "SDLProtocol.h"
#import "SDLProtocolMessage.h"
#import "SDLPutFile.h"
#import "SDLRPCPayload.h"
#import "SDLRPCResponse.h"
#import "SDLRegisterAppInterfaceResponse.h"
#import "SDLRequestType.h"
#import "SDLSecondaryTransportManager.h"
#import "SDLStreamingMediaManager.h"
#import "SDLSubscribeButton.h"
#import "SDLSystemContext.h"
#import "SDLSystemRequest.h"
#import "SDLTCPTransport.h"
#import "SDLTimer.h"
#import "SDLTransportType.h"
#import "SDLUnsubscribeButton.h"
#import "SDLVehicleType.h"
#import "SDLVersion.h"

#import "SDLRPCParameterNames.h"
#import "SDLRPCFunctionNames.h"

NS_ASSUME_NONNULL_BEGIN

typedef NSString SDLVehicleMake;

typedef void (^URLSessionTaskCompletionHandler)(NSData *data, NSURLResponse *response, NSError *error);
typedef void (^URLSessionDownloadTaskCompletionHandler)(NSURL *location, NSURLResponse *response, NSError *error);

NSString *const SDLProxyVersion = @"6.2.3";
const float StartSessionTime = 10.0;
const float NotifyProxyClosedDelay = (float)0.1;
const int PoliciesCorrelationId = 65535;
static float DefaultConnectionTimeout = 45.0;

@interface SDLProxy () {
    SDLLockScreenStatusManager *_lsm;
}

@property (copy, nonatomic) NSString *appId;
@property (strong, nonatomic) NSMutableSet<NSObject<SDLProxyListener> *> *mutableProxyListeners;
@property (nullable, nonatomic, strong) SDLDisplayCapabilities *displayCapabilities;
@property (nonatomic, strong) NSMutableDictionary<SDLVehicleMake *, Class> *securityManagers;
@property (nonatomic, strong) NSURLSession* urlSession;
@property (strong, nonatomic) dispatch_queue_t rpcProcessingQueue;

@end


@implementation SDLProxy

#pragma mark - Object lifecycle
- (instancetype)initWithTransport:(id<SDLTransportType>)transport delegate:(id<SDLProxyListener>)delegate secondaryTransportManager:(nullable SDLSecondaryTransportManager *)secondaryTransportManager {
    if (self = [super init]) {
        SDLLogD(@"Framework Version: %@", self.proxyVersion);
        _lsm = [[SDLLockScreenStatusManager alloc] init];
        _rpcProcessingQueue = dispatch_queue_create("com.sdl.rpcProcessingQueue", DISPATCH_QUEUE_SERIAL);
        _mutableProxyListeners = [NSMutableSet setWithObject:delegate];
        _securityManagers = [NSMutableDictionary dictionary];

        _protocol = [[SDLProtocol alloc] init];
        _transport = transport;
        _transport.delegate = _protocol;

        [_protocol.protocolDelegateTable addObject:self];
        _protocol.transport = transport;

        // make sure that secondary transport manager is started prior to starting protocol
        if (secondaryTransportManager != nil) {
            [secondaryTransportManager startWithPrimaryProtocol:_protocol];
        }

        [self.transport connect];

        SDLLogV(@"Proxy transport initialization");
        [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
        
        NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.timeoutIntervalForRequest = DefaultConnectionTimeout;
        configuration.timeoutIntervalForResource = DefaultConnectionTimeout;
        configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
        
        _urlSession = [NSURLSession sessionWithConfiguration:configuration];

    }

    return self;
}

+ (SDLProxy *)iapProxyWithListener:(id<SDLProxyListener>)delegate secondaryTransportManager:(nullable SDLSecondaryTransportManager *)secondaryTransportManager {
    SDLIAPTransport *transport = [[SDLIAPTransport alloc] init];
    SDLProxy *ret = [[SDLProxy alloc] initWithTransport:transport delegate:delegate secondaryTransportManager:secondaryTransportManager];

    return ret;
}

+ (SDLProxy *)tcpProxyWithListener:(id<SDLProxyListener>)delegate tcpIPAddress:(NSString *)ipaddress tcpPort:(NSString *)port secondaryTransportManager:(nullable SDLSecondaryTransportManager *)secondaryTransportManager {
    SDLTCPTransport *transport = [[SDLTCPTransport alloc] initWithHostName:ipaddress portNumber:port];

    SDLProxy *ret = [[SDLProxy alloc] initWithTransport:transport delegate:delegate secondaryTransportManager:secondaryTransportManager];

    return ret;
}

- (void)dealloc {
    if (self.protocol.securityManager != nil) {
        [self.protocol.securityManager stop];
    }

    if (self.transport != nil) {
        [self.transport disconnect];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[EAAccessoryManager sharedAccessoryManager] unregisterForLocalNotifications];
    
    [_urlSession invalidateAndCancel];
    SDLLogV(@"Proxy dealloc");
}

- (void)notifyProxyClosed {
    if (_isConnected) {
        _isConnected = NO;
        [self invokeMethodOnDelegates:@selector(onProxyClosed) withObject:nil];
    }
}


#pragma mark - Application Lifecycle

- (void)sendMobileHMIState {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self sdl_sendMobileHMIState];
    });
}

- (void)sdl_sendMobileHMIState {
    UIApplicationState appState = [UIApplication sharedApplication].applicationState;
    SDLOnHMIStatus *HMIStatusRPC = [[SDLOnHMIStatus alloc] init];

    HMIStatusRPC.audioStreamingState = SDLAudioStreamingStateNotAudible;
    HMIStatusRPC.systemContext = SDLSystemContextMain;

    switch (appState) {
        case UIApplicationStateActive: {
            HMIStatusRPC.hmiLevel = SDLHMILevelFull;
        } break;
        case UIApplicationStateBackground: // Fallthrough
        case UIApplicationStateInactive: {
            HMIStatusRPC.hmiLevel = SDLHMILevelBackground;
        } break;
        default: break;
    }

    SDLLogD(@"Mobile UIApplication state changed, sending to remote system: %@", HMIStatusRPC.hmiLevel);
    [self sendRPC:HMIStatusRPC];
}

#pragma mark - Accessors

- (NSSet<NSObject<SDLProxyListener> *> *)proxyListeners {
    return [self.mutableProxyListeners copy];
}


#pragma mark - Setters / Getters

- (NSString *)proxyVersion {
    return SDLProxyVersion;
}

#pragma mark - SecurityManager

- (void)addSecurityManagers:(NSArray<Class> *)securityManagerClasses forAppId:(NSString *)appId {
    NSParameterAssert(securityManagerClasses != nil);
    NSParameterAssert(appId != nil);
    self.appId = appId;

    for (Class securityManagerClass in securityManagerClasses) {
        if (![securityManagerClass conformsToProtocol:@protocol(SDLSecurityType)]) {
            NSString *reason = [NSString stringWithFormat:@"Invalid security manager: Class %@ does not conform to SDLSecurityType protocol", NSStringFromClass(securityManagerClass)];
            @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:reason userInfo:nil];
        }

        NSSet<NSString *> *vehicleMakes = [securityManagerClass availableMakes];

        if (vehicleMakes == nil || vehicleMakes.count == 0) {
            NSString *reason = [NSString stringWithFormat:@"Invalid security manager: Failed to retrieve makes for class %@", NSStringFromClass(securityManagerClass)];
            @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:reason userInfo:nil];
        }

        for (NSString *vehicleMake in vehicleMakes) {
            self.securityManagers[vehicleMake] = securityManagerClass;
        }
    }
}

- (nullable id<SDLSecurityType>)securityManagerForMake:(NSString *)make {
    if ((make != nil) && (self.securityManagers[make] != nil)) {
        Class securityManagerClass = self.securityManagers[make];
        self.protocol.appId = self.appId;
        return [[securityManagerClass alloc] init];
    }

    return nil;
}


#pragma mark - SDLProtocolListener Implementation

- (void)onProtocolOpened {
    _isConnected = YES;
    SDLLogV(@"Proxy RPC protocol opened");
    // The RPC payload will be created by the protocol object...it's weird and confusing, I know.
    [self.protocol startServiceWithType:SDLServiceTypeRPC payload:nil];

    if (self.startSessionTimer == nil) {
        self.startSessionTimer = [[SDLTimer alloc] initWithDuration:StartSessionTime repeat:NO];
        __weak typeof(self) weakSelf = self;
        self.startSessionTimer.elapsedBlock = ^{
            SDLLogW(@"Start session timed out");
            [weakSelf performSelector:@selector(notifyProxyClosed) withObject:nil afterDelay:NotifyProxyClosedDelay];
        };
    }
    [self.startSessionTimer start];
}

- (void)onProtocolClosed {
    [self notifyProxyClosed];
}

- (void)onError:(NSString *)info exception:(NSException *)e {
    [self invokeMethodOnDelegates:@selector(onError:) withObject:e];
}

- (void)onTransportError:(NSError *)error {
    [self invokeMethodOnDelegates:@selector(onTransportError:) withObject:error];
}

- (void)handleProtocolStartServiceACKMessage:(SDLProtocolMessage *)startServiceACK {
    // Turn off the timer, the start session response came back
    [self.startSessionTimer cancel];
    SDLLogV(@"StartSession (response)\nSessionId: %d for serviceType %d", startServiceACK.header.sessionID, startServiceACK.header.serviceType);

    if (startServiceACK.header.serviceType == SDLServiceTypeRPC) {
        [self invokeMethodOnDelegates:@selector(onProxyOpened) withObject:nil];
    }
}

- (void)onProtocolMessageReceived:(SDLProtocolMessage *)msgData {
    @try {
        [self handleProtocolMessage:msgData];
    } @catch (NSException *e) {
        SDLLogW(@"Proxy: Failed to handle protocol message %@", e);
    }
}


#pragma mark - Message sending
- (void)sendRPC:(SDLRPCMessage *)message {
    if ([message.getFunctionName isEqualToString:@"SubscribeButton"]) {
        BOOL handledRPC = [self sdl_adaptButtonSubscribeMessage:(SDLSubscribeButton *)message];
        if (handledRPC) { return; }
    } else if ([message.getFunctionName isEqualToString:@"UnsubscribeButton"]) {
        BOOL handledRPC = [self sdl_adaptButtonUnsubscribeMessage:(SDLUnsubscribeButton *)message];
        if (handledRPC) { return; }
    }

    @try {
        [self.protocol sendRPC:message];
    } @catch (NSException *exception) {
        SDLLogE(@"Proxy: Failed to send RPC message: %@", message.name);
    }
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (BOOL)sdl_adaptButtonSubscribeMessage:(SDLSubscribeButton *)message {
    if ([SDLGlobals sharedGlobals].rpcVersion.major >= 5) {
        if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
            SDLSubscribeButton *playPauseMessage = [message copy];
            playPauseMessage.buttonName = SDLButtonNamePlayPause;

            @try {
                [self.protocol sendRPC:message];
                [self.protocol sendRPC:playPauseMessage];
            } @catch (NSException *exception) {
                SDLLogE(@"Proxy: Failed to send RPC message: %@", message.name);
            }

            return YES;
        } else if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
            return NO;
        }
    } else { // Major version < 5
        if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
            return NO;
        } else if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
            SDLSubscribeButton *okMessage = [message copy];
            okMessage.buttonName = SDLButtonNameOk;

            @try {
                [self.protocol sendRPC:okMessage];
            } @catch (NSException *exception) {
                SDLLogE(@"Proxy: Failed to send RPC message: %@", message.name);
            }

            return YES;
        }
    }

    return NO;
}

- (BOOL)sdl_adaptButtonUnsubscribeMessage:(SDLUnsubscribeButton *)message {
    if ([SDLGlobals sharedGlobals].rpcVersion.major >= 5) {
        if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
            SDLUnsubscribeButton *playPauseMessage = [message copy];
            playPauseMessage.buttonName = SDLButtonNamePlayPause;

            @try {
                [self.protocol sendRPC:message];
                [self.protocol sendRPC:playPauseMessage];
            } @catch (NSException *exception) {
                SDLLogE(@"Proxy: Failed to send RPC message: %@", message.name);
            }

            return YES;
        } else if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
            return NO;
        }
    } else { // Major version < 5
        if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
            return NO;
        } else if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
            SDLUnsubscribeButton *okMessage = [message copy];
            okMessage.buttonName = SDLButtonNameOk;

            @try {
                [self.protocol sendRPC:okMessage];
            } @catch (NSException *exception) {
                SDLLogE(@"Proxy: Failed to send RPC message: %@", message.name);
            }

            return YES;
        }
    }

    return NO;
}
#pragma clang diagnostic pop

#pragma mark - Message Receiving

- (void)handleProtocolMessage:(SDLProtocolMessage *)incomingMessage {
    // Convert protocol message to dictionary
    NSDictionary<NSString *, id> *rpcMessageAsDictionary = [incomingMessage rpcDictionary];
    [self handleRPCDictionary:rpcMessageAsDictionary];
}

- (void)handleRPCDictionary:(NSDictionary<NSString *, id> *)dict {
    SDLRPCMessage *message = [[SDLRPCMessage alloc] initWithDictionary:[dict mutableCopy]];
    NSString *functionName = [message getFunctionName];
    NSString *messageType = [message messageType];

    // If it's a response, append response
    if ([messageType isEqualToString:SDLRPCParameterNameResponse]) {
        BOOL notGenericResponseMessage = ![functionName isEqualToString:@"GenericResponse"];
        if (notGenericResponseMessage) {
            functionName = [NSString stringWithFormat:@"%@Response", functionName];
        }
    }

    // From the function name, create the corresponding RPCObject and initialize it
    NSString *functionClassName = [NSString stringWithFormat:@"SDL%@", functionName];
    SDLRPCMessage *newMessage = [[NSClassFromString(functionClassName) alloc] initWithDictionary:[dict mutableCopy]];

    // Log the RPC message
    SDLLogV(@"Message received: %@", newMessage);

    // Intercept and handle several messages ourselves

    if ([functionName isEqualToString:@"RegisterAppInterfaceResponse"]) {
        [self handleRegisterAppInterfaceResponse:(SDLRPCResponse *)newMessage];
    }

    if ([functionName isEqualToString:@"OnEncodedSyncPData"]) {
        [self handleSyncPData:newMessage];
    }

    if ([functionName isEqualToString:@"OnSystemRequest"]) {
        [self handleSystemRequest:dict];
    }

    if ([functionName isEqualToString:@"SystemRequestResponse"]) {
        [self handleSystemRequestResponse:newMessage];
    }


    if ([functionName isEqualToString:@"OnButtonPress"]) {
        SDLOnButtonPress *message = (SDLOnButtonPress *)newMessage;
        if ([SDLGlobals sharedGlobals].rpcVersion.major >= 5) {
            BOOL handledRPC = [self sdl_handleOnButtonPressPostV5:message];
            if (handledRPC) { return; }
        } else { // RPC version of 4 or less (connected to an old head unit)
            BOOL handledRPC = [self sdl_handleOnButtonPressPreV5:message];
            if (handledRPC) { return; }
        }
    }

    if ([functionName isEqualToString:@"OnButtonEvent"]) {
        SDLOnButtonEvent *message = (SDLOnButtonEvent *)newMessage;
        if ([SDLGlobals sharedGlobals].rpcVersion.major >= 5) {
            BOOL handledRPC = [self sdl_handleOnButtonEventPostV5:message];
            if (handledRPC) { return; }
        } else {
            BOOL handledRPC = [self sdl_handleOnButtonEventPreV5:message];
            if (handledRPC) { return; }
        }
    }

    [self sdl_invokeDelegateMethodsWithFunction:functionName message:newMessage];
    
    //Intercepting SDLRPCFunctionNameOnAppInterfaceUnregistered must happen after it is broadcasted as a notification above. This will prevent reconnection attempts in the lifecycle manager when the AppInterfaceUnregisteredReason should prevent reconnections.
    if ([functionName isEqualToString:SDLRPCFunctionNameOnAppInterfaceUnregistered] || [functionName isEqualToString:SDLRPCFunctionNameUnregisterAppInterface]) {
        [self handleRPCUnregistered:dict];
    }

    // When an OnHMIStatus notification comes in, after passing it on (above), generate an "OnLockScreenNotification"
    if ([functionName isEqualToString:@"OnHMIStatus"]) {
        [self handleAfterHMIStatus:newMessage];
    }

    // When an OnDriverDistraction notification comes in, after passing it on (above), generate an "OnLockScreenNotification"
    if ([functionName isEqualToString:@"OnDriverDistraction"]) {
        [self handleAfterDriverDistraction:newMessage];
    }
}

- (void)sdl_invokeDelegateMethodsWithFunction:(NSString *)functionName message:(SDLRPCMessage *)message {
    // Formulate the name of the method to call and invoke the method on the delegate(s)
    NSString *handlerName = [NSString stringWithFormat:@"on%@:", functionName];
    SEL handlerSelector = NSSelectorFromString(handlerName);
    [self invokeMethodOnDelegates:handlerSelector withObject:message];
}


#pragma mark - RPC Handlers

- (void)handleRPCUnregistered:(NSDictionary<NSString *, id> *)messageDictionary {
    SDLLogW(@"Unregistration forced by module. %@", messageDictionary);
    [self notifyProxyClosed];
}

- (void)handleRegisterAppInterfaceResponse:(SDLRPCResponse *)response {
    SDLRegisterAppInterfaceResponse *registerResponse = (SDLRegisterAppInterfaceResponse *)response;

    self.protocol.securityManager = [self securityManagerForMake:registerResponse.vehicleType.make];
    if (self.protocol.securityManager && [self.protocol.securityManager respondsToSelector:@selector(setAppId:)]) {
        self.protocol.securityManager.appId = self.appId;
    }

    if ([SDLGlobals sharedGlobals].protocolVersion.major >= 4) {
        [self sendMobileHMIState];
        // Send SDL updates to application state
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendMobileHMIState) name:UIApplicationDidBecomeActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendMobileHMIState) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
}

- (void)handleSyncPData:(SDLRPCMessage *)message {
    // If URL != nil, perform HTTP Post and don't pass the notification to proxy listeners
    SDLLogV(@"OnEncodedSyncPData: %@", message);

    NSString *urlString = (NSString *)[message getParameters:@"URL"];
    NSDictionary<NSString *, id> *encodedSyncPData = (NSDictionary<NSString *, id> *)[message getParameters:@"data"];
    NSNumber *encodedSyncPTimeout = (NSNumber *)[message getParameters:@"Timeout"];

    if (urlString && encodedSyncPData && encodedSyncPTimeout) {
        [self sendEncodedSyncPData:encodedSyncPData toURL:urlString withTimeout:encodedSyncPTimeout];
    }
}

- (void)handleSystemRequest:(NSDictionary<NSString *, id> *)dict {
    SDLLogV(@"OnSystemRequest");

    SDLOnSystemRequest *systemRequest = [[SDLOnSystemRequest alloc] initWithDictionary:[dict mutableCopy]];
    SDLRequestType requestType = systemRequest.requestType;

    // Handle the various OnSystemRequest types
    if ([requestType isEqualToEnum:SDLRequestTypeProprietary]) {
        [self handleSystemRequestProprietary:systemRequest];
    } else if ([requestType isEqualToEnum:SDLRequestTypeLockScreenIconURL]) {
        [self sdl_handleSystemRequestLockScreenIconURL:systemRequest];
    } else if ([requestType isEqualToEnum:SDLRequestTypeIconURL]) {
        [self sdl_handleSystemRequestIconURL:systemRequest];
    } else if ([requestType isEqualToEnum:SDLRequestTypeHTTP]) {
        [self sdl_handleSystemRequestHTTP:systemRequest];
    } else if ([requestType isEqualToEnum:SDLRequestTypeLaunchApp]) {
        [self sdl_handleSystemRequestLaunchApp:systemRequest];
    }
}

- (void)handleSystemRequestResponse:(SDLRPCMessage *)message {
    SDLLogV(@"SystemRequestResponse to be discarded");
}

#pragma mark BackCompatability ButtonName Helpers

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (BOOL)sdl_handleOnButtonPressPreV5:(SDLOnButtonPress *)message {
    // Drop PlayPause, this shouldn't come in
    if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
        return YES;
    } else if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
        // Send Ok and Play/Pause notifications
        SDLOnButtonPress *playPausePress = [message copy];
        playPausePress.buttonName = SDLButtonNamePlayPause;

        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:playPausePress];
        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:message];
        return YES;
    }

    return NO;
}

- (BOOL)sdl_handleOnButtonPressPostV5:(SDLOnButtonPress *)message {
    if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
        // Send PlayPause & OK notifications
        SDLOnButtonPress *okPress = [message copy];
        okPress.buttonName = SDLButtonNameOk;

        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:okPress];
        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:message];
        return YES;
    } else if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
        // Send PlayPause and OK notifications
        SDLOnButtonPress *playPausePress = [message copy];
        playPausePress.buttonName = SDLButtonNamePlayPause;

        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:playPausePress];
        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:message];
        return YES;
    }

    return NO;
}

- (BOOL)sdl_handleOnButtonEventPreV5:(SDLOnButtonEvent *)message {
    // Drop PlayPause, this shouldn't come in
    if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
        return YES;
    } else if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
        // Send Ok and Play/Pause notifications
        SDLOnButtonEvent *playPauseEvent = [message copy];
        playPauseEvent.buttonName = SDLButtonNamePlayPause;

        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:playPauseEvent];
        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:message];
        return YES;
    }

    return NO;
}

- (BOOL)sdl_handleOnButtonEventPostV5:(SDLOnButtonEvent *)message {
    if ([message.buttonName isEqualToEnum:SDLButtonNamePlayPause]) {
        // Send PlayPause & OK notifications
        SDLOnButtonEvent *okEvent = [message copy];
        okEvent.buttonName = SDLButtonNameOk;

        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:okEvent];
        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:message];
        return YES;
    } else if ([message.buttonName isEqualToEnum:SDLButtonNameOk]) {
        // Send PlayPause and OK notifications
        SDLOnButtonEvent *playPauseEvent = [message copy];
        playPauseEvent.buttonName = SDLButtonNamePlayPause;

        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:playPauseEvent];
        [self sdl_invokeDelegateMethodsWithFunction:message.getFunctionName message:message];
        return YES;
    }

    return NO;
}
#pragma clang diagnostic pop


#pragma mark Handle Post-Invoke of Delegate Methods
- (void)handleAfterHMIStatus:(SDLRPCMessage *)message {
    SDLHMILevel hmiLevel = (SDLHMILevel)[message getParameters:SDLRPCParameterNameHMILevel];
    _lsm.hmiLevel = hmiLevel;

    SEL callbackSelector = NSSelectorFromString(@"onOnLockScreenNotification:");
    [self invokeMethodOnDelegates:callbackSelector withObject:_lsm.lockScreenStatusNotification];
}

- (void)handleAfterDriverDistraction:(SDLRPCMessage *)message {
    NSString *stateString = (NSString *)[message getParameters:SDLRPCParameterNameState];
    BOOL state = [stateString isEqualToString:@"DD_ON"] ? YES : NO;
    _lsm.driverDistracted = state;

    SEL callbackSelector = NSSelectorFromString(@"onOnLockScreenNotification:");
    [self invokeMethodOnDelegates:callbackSelector withObject:_lsm.lockScreenStatusNotification];
}


#pragma mark OnSystemRequest Handlers
- (void)sdl_handleSystemRequestLaunchApp:(SDLOnSystemRequest *)request {
    NSURL *URLScheme = [NSURL URLWithString:request.url];
    if (URLScheme == nil) {
        SDLLogW(@"System request LaunchApp failed: invalid URL sent from module: %@", request.url);
        return;
    }
    // If system version is less than 9.0 http://stackoverflow.com/a/5337804/1370927
    if (SDL_SYSTEM_VERSION_LESS_THAN(@"9.0")) {
        // Return early if we can't openURL because openURL will crash instead of fail silently in < 9.0
        if (![[UIApplication sharedApplication] canOpenURL:URLScheme]) {
            return;
        }
    }
    [[UIApplication sharedApplication] openURL:URLScheme];
}

- (void)handleSystemRequestProprietary:(SDLOnSystemRequest *)request {
    NSDictionary<NSString *, id> *JSONDictionary = [self validateAndParseSystemRequest:request];
    if (JSONDictionary == nil || request.url == nil) {
        return;
    }

    NSDictionary<NSString *, id> *requestData = JSONDictionary[@"HTTPRequest"];
    NSString *bodyString = requestData[@"body"];
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

    // Parse and display the policy data.
    SDLPolicyDataParser *pdp = [[SDLPolicyDataParser alloc] init];
    NSData *policyData = [pdp unwrap:bodyData];
    if (policyData != nil) {
        [pdp parsePolicyData:policyData];
        SDLLogV(@"Policy data received");
    }

    // Send the HTTP Request
    __weak typeof(self) weakSelf = self;
    [self uploadForBodyDataDictionary:JSONDictionary
                            URLString:request.url
                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                         __strong typeof(weakSelf) strongSelf = weakSelf;

                        if (error) {
                            SDLLogW(@"OnSystemRequest HTTP response error: %@", error);
                            return;
                        }

                        if (data == nil || data.length == 0) {
                            SDLLogW(@"OnSystemRequest HTTP response error: no data received");
                            return;
                        }

                        // Create the SystemRequest RPC to send to module.
                        SDLLogV(@"OnSystemRequest HTTP response");
                        SDLSystemRequest *request = [[SDLSystemRequest alloc] init];
                        request.correlationID = [NSNumber numberWithInt:PoliciesCorrelationId];
                        request.requestType = SDLRequestTypeProprietary;
                        request.bulkData = data;

                        // Parse and display the policy data.
                        SDLPolicyDataParser *pdp = [[SDLPolicyDataParser alloc] init];
                        NSData *policyData = [pdp unwrap:data];
                        if (policyData) {
                            [pdp parsePolicyData:policyData];
                            SDLLogV(@"Cloud policy data: %@", pdp);
                        }

                        // Send the RPC Request
                        [strongSelf sendRPC:request];
                    }];
}

- (void)sdl_handleSystemRequestLockScreenIconURL:(SDLOnSystemRequest *)request {
	__weak typeof(self) weakSelf = self;
    [self sdl_sendDataTaskWithURL:[NSURL URLWithString:request.url]
                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
					__strong typeof(weakSelf) strongSelf = weakSelf;
                    if (error != nil) {
                        SDLLogW(@"OnSystemRequest (lock screen icon) HTTP download task failed: %@", error.localizedDescription);
                        return;
                    }
                    
                    UIImage *icon = [UIImage imageWithData:data];
                    [strongSelf invokeMethodOnDelegates:@selector(onReceivedLockScreenIcon:) withObject:icon];
                }];
}

- (void)sdl_handleSystemRequestIconURL:(SDLOnSystemRequest *)request {
    __weak typeof(self) weakSelf = self;
    [self sdl_sendDataTaskWithURL:[NSURL URLWithString:request.url]
                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                    __strong typeof(weakSelf) strongSelf = weakSelf;
                    if (error != nil) {
                        SDLLogW(@"OnSystemRequest (icon url) HTTP download task failed: %@", error.localizedDescription);
                        return;
                    } else if (data.length == 0) {
                        SDLLogW(@"OnSystemRequest (icon url) HTTP download task failed to get the cloud app icon image data");
                        return;
                    }

                    SDLSystemRequest *iconURLSystemRequest = [[SDLSystemRequest alloc] initWithType:SDLRequestTypeIconURL fileName:request.url];
                    iconURLSystemRequest.bulkData = data;

                    [strongSelf sendRPC:iconURLSystemRequest];
                }];
}

- (void)sdl_handleSystemRequestHTTP:(SDLOnSystemRequest *)request {
    if (request.bulkData.length == 0) {
        // TODO: not sure how we want to handle http requests that don't have bulk data (maybe as GET?)
        return;
    }

    __weak typeof(self) weakSelf = self;
    [self sdl_uploadData:request.bulkData
              toURLString:request.url
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (error != nil) {
                SDLLogW(@"OnSystemRequest (HTTP) error: %@", error.localizedDescription);
                return;
            }

            if (data.length == 0) {
                SDLLogW(@"OnSystemRequest (HTTP) error: no data returned");
                return;
            }

            // Show the HTTP response
            SDLLogV(@"OnSystemRequest (HTTP) response: %@", response);

            // Create the SystemRequest RPC to send to module.
            SDLPutFile *putFile = [[SDLPutFile alloc] init];
            putFile.fileType = SDLFileTypeJSON;
            putFile.correlationID = @(PoliciesCorrelationId);
            putFile.syncFileName = @"response_data";
            putFile.bulkData = data;

            // Send RPC Request
            [strongSelf sendRPC:putFile];
        }];
}

/**
 *  Determine if the System Request is valid and return it's JSON dictionary, if available.
 *
 *  @param request The system request to parse
 *
 *  @return A parsed JSON dictionary, or nil if it couldn't be parsed
 */
- (nullable NSDictionary<NSString *, id> *)validateAndParseSystemRequest:(SDLOnSystemRequest *)request {
    NSString *urlString = request.url;
    SDLFileType fileType = request.fileType;

    // Validate input
    if (urlString == nil || [NSURL URLWithString:urlString] == nil) {
        SDLLogW(@"OnSystemRequest validation failure: URL is nil");
        return nil;
    }

    if (![fileType isEqualToEnum:SDLFileTypeJSON]) {
        SDLLogW(@"OnSystemRequest validation failure: file type is not JSON");
        return nil;
    }

    // Get data dictionary from the bulkData
    NSError *error = nil;
    NSDictionary<NSString *, id> *JSONDictionary = [NSJSONSerialization JSONObjectWithData:request.bulkData options:kNilOptions error:&error];
    if (error != nil) {
        SDLLogW(@"OnSystemRequest validation failure: data is not valid JSON");
        return nil;
    }

    return JSONDictionary;
}

/**
 *  Start an upload for some data to a web address specified
 *
 *  @param data              The data to be passed to the server
 *  @param urlString         The URL the data should be POSTed to
 *  @param completionHandler A completion handler of what to do when the server responds
 */
- (void)sdl_uploadData:(NSData *_Nonnull)data toURLString:(NSString *_Nonnull)urlString completionHandler:(URLSessionTaskCompletionHandler _Nullable)completionHandler {
    // NSURLRequest configuration
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    request.HTTPMethod = @"POST";

    SDLLogV(@"OnSystemRequest (HTTP) upload task created for URL: %@", urlString);

    // Create the upload task
    [self sdl_sendUploadRequest:request withData:data completionHandler:completionHandler];
}

/**
 *  Start an upload for a body data dictionary, this is used by the "proprietary" system request needed for backward compatibility
 *
 *  @param dictionary        The system request dictionary that contains the HTTP data to be sent
 *  @param urlString         A string containing the URL to send the upload to
 *  @param completionHandler A completion handler returning the response from the server to the upload task
 */
- (void)uploadForBodyDataDictionary:(NSDictionary<NSString *, id> *)dictionary URLString:(NSString *)urlString completionHandler:(URLSessionTaskCompletionHandler)completionHandler {
    NSParameterAssert(dictionary != nil);
    NSParameterAssert(urlString != nil);
    NSParameterAssert(completionHandler != NULL);

    // Extract data from the dictionary
    NSDictionary<NSString *, id> *requestData = dictionary[@"HTTPRequest"];
    NSDictionary *headers = requestData[@"headers"];
    NSString *contentType = headers[@"ContentType"];
    NSTimeInterval timeout = [headers[@"ConnectTimeout"] doubleValue];
    NSString *method = headers[@"RequestMethod"];
    NSString *bodyString = requestData[@"body"];
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

    // NSURLRequest configuration
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:contentType forHTTPHeaderField:@"content-type"];
    request.timeoutInterval = timeout;
    request.HTTPMethod = method;

    SDLLogV(@"OnSystemRequest (Proprietary) upload task created for URL: %@", urlString);

    // Create the upload task
    [self sdl_sendUploadRequest:request withData:bodyData completionHandler:completionHandler];
}

- (void)sdl_sendUploadRequest:(NSURLRequest*)request withData:(NSData*)data completionHandler:(URLSessionTaskCompletionHandler)completionHandler {
    NSMutableURLRequest* mutableRequest = [request mutableCopy];
    
    if ([mutableRequest.URL.scheme isEqualToString:@"http"]) {
        mutableRequest.URL = [NSURL URLWithString:[mutableRequest.URL.absoluteString stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:@"https"]];
    }
    
    [[self.urlSession uploadTaskWithRequest:request fromData:data completionHandler:completionHandler] resume];
}

- (void)sdl_sendDataTaskWithURL:(NSURL*)url completionHandler:(URLSessionTaskCompletionHandler)completionHandler {
    if ([url.scheme isEqualToString:@"http"]) {
        url = [NSURL URLWithString:[url.absoluteString stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:@"https"]];
    }
    
    [[self.urlSession dataTaskWithURL:url completionHandler:completionHandler] resume];
}

#pragma mark - Delegate management

- (void)addDelegate:(NSObject<SDLProxyListener> *)delegate {
    @synchronized(self.mutableProxyListeners) {
        [self.mutableProxyListeners addObject:delegate];
    }
}

- (void)removeDelegate:(NSObject<SDLProxyListener> *)delegate {
    @synchronized(self.mutableProxyListeners) {
        [self.mutableProxyListeners removeObject:delegate];
    }
}

- (void)invokeMethodOnDelegates:(SEL)aSelector withObject:(nullable id)object {
    // Occurs on the protocol receive serial queue
    dispatch_async(_rpcProcessingQueue, ^{
        for (id<SDLProxyListener> listener in self.proxyListeners) {
            if ([listener respondsToSelector:aSelector]) {
                // HAX: http://stackoverflow.com/questions/7017281/performselector-may-cause-a-leak-because-its-selector-is-unknown
                ((void (*)(id, SEL, id))[(NSObject *)listener methodForSelector:aSelector])(listener, aSelector, object);
            }
        }
    });
}


#pragma mark - System Request and SyncP handling

- (void)sendEncodedSyncPData:(NSDictionary<NSString *, id> *)encodedSyncPData toURL:(NSString *)urlString withTimeout:(NSNumber *)timeout {
    // Configure HTTP URL & Request
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.timeoutInterval = 60;

    // Prepare the data in the required format
    NSString *encodedSyncPDataString = [[NSString stringWithFormat:@"%@", encodedSyncPData] componentsSeparatedByString:@"\""][1];
    NSArray<NSString *> *array = [NSArray arrayWithObject:encodedSyncPDataString];
    NSDictionary<NSString *, id> *dictionary = @{ @"data": array };
    NSError *JSONSerializationError = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&JSONSerializationError];
    if (JSONSerializationError) {
        SDLLogW(@"Error attempting to create SyncPData for HTTP request: %@", JSONSerializationError);
        return;
    }

    // Send the HTTP Request
    __weak typeof(self) weakSelf = self;
    [[self.urlSession uploadTaskWithRequest:request
                                   fromData:data
                          completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                           [weakSelf syncPDataNetworkRequestCompleteWithData:data response:response error:error];
                                       }] resume];

    SDLLogV(@"OnEncodedSyncPData (HTTP Request)");
}

// Handle the OnEncodedSyncPData HTTP Response
- (void)syncPDataNetworkRequestCompleteWithData:(NSData *)data response:(NSURLResponse *)response error:(NSError *)error {
    // Sample of response: {"data":["SDLKGLSDKFJLKSjdslkfjslkJLKDSGLKSDJFLKSDJF"]}
    SDLLogV(@"OnEncodedSyncPData (HTTP Response): %@", response);

    // Validate response data.
    if (data == nil || data.length == 0) {
        SDLLogW(@"OnEncodedSyncPData (HTTP Response): no data returned");
        return;
    }

    // Convert data to RPCRequest
    NSError *JSONConversionError = nil;
    NSDictionary<NSString *, id> *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONConversionError];
    if (!JSONConversionError) {
        SDLEncodedSyncPData *request = [[SDLEncodedSyncPData alloc] init];
        request.correlationID = [NSNumber numberWithInt:PoliciesCorrelationId];
        request.data = [responseDictionary objectForKey:@"data"];

        [self sendRPC:request];
    }
}


#pragma mark - PutFile Streaming
- (void)putFileStream:(NSInputStream *)inputStream withRequest:(SDLPutFile *)putFileRPCRequest {
    inputStream.delegate = self;
    objc_setAssociatedObject(inputStream, @"SDLPutFile", putFileRPCRequest, OBJC_ASSOCIATION_RETAIN);
    objc_setAssociatedObject(inputStream, @"BaseOffset", [putFileRPCRequest offset], OBJC_ASSOCIATION_RETAIN);

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
}

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
    switch (eventCode) {
        case NSStreamEventHasBytesAvailable: {
            // Grab some bytes from the stream and send them in a SDLPutFile RPC Request
            NSUInteger currentStreamOffset = [[stream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedIntegerValue];

            NSMutableData *buffer = [NSMutableData dataWithLength:[[SDLGlobals sharedGlobals] mtuSizeForServiceType:SDLServiceTypeRPC]];
            NSInteger nBytesRead = [(NSInputStream *)stream read:(uint8_t *)buffer.mutableBytes maxLength:buffer.length];
            if (nBytesRead > 0) {
                NSData *data = [buffer subdataWithRange:NSMakeRange(0, (NSUInteger)nBytesRead)];
                NSUInteger baseOffset = [(NSNumber *)objc_getAssociatedObject(stream, @"BaseOffset") unsignedIntegerValue];
                NSUInteger newOffset = baseOffset + currentStreamOffset;

                SDLPutFile *putFileRPCRequest = (SDLPutFile *)objc_getAssociatedObject(stream, @"SDLPutFile");
                [putFileRPCRequest setOffset:[NSNumber numberWithUnsignedInteger:newOffset]];
                [putFileRPCRequest setLength:[NSNumber numberWithUnsignedInteger:(NSUInteger)nBytesRead]];
                [putFileRPCRequest setBulkData:data];

                [self sendRPC:putFileRPCRequest];
            }

            break;
        }
        case NSStreamEventEndEncountered: {
            // Cleanup the stream
            [stream close];
            [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

            break;
        }
        case NSStreamEventErrorOccurred: {
            SDLLogE(@"NSStream error attempting to upload putfile stream: %lu", (unsigned long)eventCode);
            break;
        }
        default: {
            break;
        }
    }
}

@end

NS_ASSUME_NONNULL_END