summaryrefslogtreecommitdiff
path: root/chromium/third_party/nearby/src/internal/platform/implementation/ios/Mediums/Ble/Sockets/Source/Shared/GNSSocket.m
blob: 2a1c342f53c190c866bf877ca235fcc9f154afca (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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import "internal/platform/implementation/ios/Mediums/Ble/Sockets/Source/Shared/GNSSocket+Private.h"

#import "internal/platform/implementation/ios/Mediums/Ble/Sockets/Source/Shared/GNSWeavePacket.h"
#import "GoogleToolboxForMac/GTMLogger.h"

typedef void (^GNSIncomingChunkReceivedBlock)(NSData *incomingData);

@interface GNSSocket () {
  NSMutableData *_incomingBuffer;
  id _peer;
}

// Handler to generate a chunk for sending data. When the bluetooth stack is ready to send
// more data the handler is called recursively to send the next chunk.
@property(nonatomic, copy) GNSSendChunkBlock sendChunkCallback;

// Handler to receive chunk from the central.
@property(nonatomic, copy) GNSIncomingChunkReceivedBlock incomingChunkReceivedCallback;

@property(nonatomic, readwrite, assign, getter=isConnected) BOOL connected;

@property(nonatomic, readwrite) NSUUID *socketIdentifier;

- (instancetype)initWithOwner:(id<GNSSocketOwner>)owner
                         peer:(id)peer
                        queue:(dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER;

@end

@implementation GNSSocket

- (void)dealloc {
  [_owner socketWillBeDeallocated:self];
}

- (BOOL)isSendOperationInProgress {
  return self.sendChunkCallback != nil;
}

- (void)sendData:(NSData *)data
    progressHandler:(GNSProgressHandler)progressHandler
         completion:(GNSErrorHandler)completion {
  void (^callCompletion)(NSError *) = ^(NSError *error) {
    if (completion) dispatch_async(_queue, ^{ completion(error); });
  };

  if (self.sendChunkCallback) {
    GTMLoggerInfo(@"Send operation already in progress");
    callCompletion(GNSErrorWithCode(GNSErrorOperationInProgress));
    return;
  }
  data = [data copy];
  NSUInteger totalDataSize = data.length;
  GTMLoggerInfo(@"Sending data with size %lu", (unsigned long)totalDataSize);

  // Capture self for the duration of the send operation, to ensure it is completely sent.
  // If the connection is lost, the block will be deleted and the retain cycle broken.
  __typeof__(self) selfRef = self;  // this avoids the retain cycle compiler warning
  self.sendChunkCallback = ^(NSUInteger offset) {
    __typeof__(self) self = selfRef;
    if (!self.isConnected) {
      self.sendChunkCallback = nil;
      callCompletion(GNSErrorWithCode(GNSErrorNoConnection));
      return;
    }
    if (progressHandler) {
      float progressPercentage = 1.0;
      if (totalDataSize > 0) {
        progressPercentage = (float)offset / totalDataSize;
      }
      progressHandler(progressPercentage);
    }
    NSUInteger newOffset = offset;
    GNSWeaveDataPacket *dataPacket =
        [GNSWeaveDataPacket dataPacketWithPacketCounter:self.sendPacketCounter
                                             packetSize:self.packetSize
                                                   data:data
                                                 offset:&newOffset];
    [self incrementSendPacketCounter];

    GTMLoggerInfo(@"Sending chunk with size %ld", (long)(newOffset - offset));
    [self.owner sendData:[dataPacket serialize] socket:self completion:^(NSError *_Nullable error) {
      if (error) {
        GTMLoggerInfo(@"Error sending chunk");
        self.sendChunkCallback = nil;
        callCompletion(error);
      } else {
        if (newOffset < totalDataSize) {
          // Dispatch async to avoid stack overflow on large payloads.
          dispatch_async(self.queue, ^{ self.sendChunkCallback(newOffset); });
        } else {
          GTMLoggerInfo(@"Finished sending payload");
          self.sendChunkCallback = nil;
          callCompletion(nil);
        }
      }
    }];
  };
  self.sendChunkCallback(0);
}

- (void)disconnect {
  if (!_connected) {
    GTMLoggerInfo(@"Socket already disconnected, socket: %@, delegate %@, owner %@", self,
                  _delegate, _owner);
    return;
  }
  GTMLoggerInfo(@"Disconnect");
  [_owner disconnectSocket:self];
}

- (NSString *)description {
  return [NSString stringWithFormat:@"<%@: %p, %@, central: %@>", [self class], self,
                                    _connected ? @"connected" : @"not connected",
                                    self.peerIdentifier.UUIDString];
}

- (NSUUID *)peerIdentifier {
  return (NSUUID *)[_peer identifier];
}

- (NSUUID *)serviceIdentifier {
  return [_owner socketServiceIdentifier:self];
}

#pragma mark - Private

- (instancetype)init {
  [self doesNotRecognizeSelector:_cmd];
  return nil;
}

- (instancetype)initWithOwner:(id<GNSSocketOwner>)owner
                  centralPeer:(CBCentral *)centralPeer
                        queue:(dispatch_queue_t)queue {
  return [self initWithOwner:owner peer:centralPeer queue:queue];
}

- (instancetype)initWithOwner:(id<GNSSocketOwner>)owner
               peripheralPeer:(CBPeripheral *)peripheralPeer
                        queue:(dispatch_queue_t)queue {
  return [self initWithOwner:owner peer:peripheralPeer queue:queue];
}

- (instancetype)initWithOwner:(id<GNSSocketOwner>)owner
                         peer:(id)peer
                        queue:(dispatch_queue_t)queue {
  self = [super init];
  if (self) {
    NSAssert(owner, @"Socket should have an owner.");
    NSAssert(peer, @"Socket should have a peer.");
    _owner = owner;
    _peer = peer;
    _queue = queue;
    _socketIdentifier = [NSUUID UUID];
    _packetSize = kGNSMinSupportedPacketSize;
  }
  return self;
}

- (void)incrementReceivePacketCounter {
  _receivePacketCounter = (_receivePacketCounter + 1) % kGNSMaxPacketCounterValue;
  GTMLoggerDebug(@"New receive packet counter %d", _receivePacketCounter);
}

- (void)incrementSendPacketCounter {
  _sendPacketCounter = (_sendPacketCounter + 1) % kGNSMaxPacketCounterValue;
  GTMLoggerDebug(@"New send packet counter %d", _sendPacketCounter);
}

- (void)didConnect {
  _connected = YES;
  [_delegate socketDidConnect:self];
}

- (void)didDisconnectWithError:(NSError *)error {
  _connected = NO;
  _incomingChunkReceivedCallback = nil;
  _incomingBuffer = nil;
  [_delegate socket:self didDisconnectWithError:error];
}

- (void)didReceiveIncomingWeaveDataPacket:(GNSWeaveDataPacket *)dataPacket {
  if (!_connected) {
    GTMLoggerError(@"Cannot receive incoming data packet while not being connected");
    return;
  }
  if (dataPacket.isFirstPacket) {
    NSAssert(!_incomingBuffer, @"There should not be a receive operation in progress.");
    _incomingBuffer = [NSMutableData data];
  }
  GTMLoggerInfo(@"Received chunk with size %lu", (unsigned long)dataPacket.data.length);
  [_incomingBuffer appendData:dataPacket.data];
  if (dataPacket.isLastPacket) {
    NSData *incomingData = _incomingBuffer;
    _incomingBuffer = nil;
    GTMLoggerInfo(@"Finished receiving payload with size %lu", (unsigned long)incomingData.length);
    [self.delegate socket:self didReceiveData:incomingData];
  }
}

- (BOOL)waitingForIncomingData {
  return _incomingBuffer != nil;
}

- (CBPeripheral *)peerAsPeripheral {
  NSAssert([_peer isKindOfClass:[CBPeripheral class]], @"Wrong peer type %@", _peer);
  if ([_peer isKindOfClass:[CBPeripheral class]]) {
    return _peer;
  } else {
    return nil;
  }
}

- (CBCentral *)peerAsCentral {
  NSAssert([_peer isKindOfClass:[CBCentral class]], @"Wrong peer type %@", _peer);
  if ([_peer isKindOfClass:[CBCentral class]]) {
    return _peer;
  } else {
    return nil;
  }
}

@end