summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLStreamDelegate.m
blob: 11bba6e5e3792bf714de2e71c2f5ea75810b60b8 (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
//
//  SDLtreamDelegate.m
//

#import "SDLStreamDelegate.h"
#import "SDLLogMacros.h"

NS_ASSUME_NONNULL_BEGIN

@interface SDLStreamDelegate () {
    dispatch_queue_t _input_stream_queue;
}

@end


@implementation SDLStreamDelegate

- (instancetype)init {
    self = [super init];
    if (self) {
        _streamOpenHandler = defaultStreamOpenHandler;
        _streamHasBytesHandler = defaultStreamHasBytesHandler;
        _streamHasSpaceHandler = defaultStreamHasSpaceHandler;
        _streamErrorHandler = defaultStreamErrorHandler;
        _streamEndHandler = defaultStreamErrorHandler;

        _input_stream_queue = dispatch_queue_create("com.sdl.streamdelegate.input", DISPATCH_QUEUE_SERIAL);
    }
    return self;
}

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
    switch (eventCode) {
        case NSStreamEventOpenCompleted: {
            if (_streamOpenHandler) {
                self.streamOpenHandler(stream);
            }
            break;
        }
        case NSStreamEventHasBytesAvailable: {
            if (_streamHasBytesHandler) {
                dispatch_async(_input_stream_queue, ^{
                    self.streamHasBytesHandler((NSInputStream *)stream);
                });
            }
            break;
        }
        case NSStreamEventHasSpaceAvailable: {
            if (_streamHasSpaceHandler) {
                self.streamHasSpaceHandler((NSOutputStream *)stream);
            }
            break;
        }
        case NSStreamEventErrorOccurred: {
            if (_streamErrorHandler) {
                self.streamErrorHandler(stream);
            }
            break;
        }
        case NSStreamEventEndEncountered: {
            if (_streamEndHandler) {
                self.streamEndHandler(stream);
            }
            break;
        }
        case NSStreamEventNone:
        default: {
            break;
        }
    }
}

SDLStreamOpenHandler defaultStreamOpenHandler = ^(NSStream *stream) {
    SDLLogV(@"Transport stream event open");
};

SDLStreamHasBytesHandler defaultStreamHasBytesHandler = ^(NSInputStream *istream) {
    SDLLogV(@"Transport stream event has bytes");
};

SDLStreamHasSpaceHandler defaultStreamHasSpaceHandler = ^(NSOutputStream *ostream) {
    SDLLogV(@"Transport stream event has space");
};

SDLStreamErrorHandler defaultStreamErrorHandler = ^(NSStream *stream) {
    SDLLogV(@"Transport stream event error");
};

SDLStreamEndHandler defaultStreamEndHandler = ^(NSStream *stream) {
    SDLLogV(@"Transport stream event end");
};

@end

NS_ASSUME_NONNULL_END