-
Notifications
You must be signed in to change notification settings - Fork 122
/
MeshNetworkManager.swift
930 lines (858 loc) · 44.1 KB
/
MeshNetworkManager.swift
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
/*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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.
*/
import Foundation
/// The main object responsible for managing the mesh network.
public class MeshNetworkManager {
/// Mesh Network data.
private var meshData: MeshData
/// The Network Layer handler.
private var networkManager: NetworkManager?
/// Storage to keep the app data.
private let storage: Storage
/// A queue to handle incoming and outgoing messages.
internal let queue: DispatchQueue
/// A queue to call delegate methods on.
internal let delegateQueue: DispatchQueue
/// The Proxy Filter state.
public internal(set) var proxyFilter: ProxyFilter
/// The logger delegate will be called whenever a new log entry is created.
public weak var logger: LoggerDelegate?
/// The delegate will receive callbacks whenever a complete
/// Mesh Message has been received and reassembled.
public weak var delegate: MeshNetworkDelegate?
/// The sender object should send PDUs created by the manager
/// using any Bearer.
public weak var transmitter: Transmitter?
// MARK: - Network Manager properties
/// The Default TTL will be used for sending messages, if the value has
/// not been set in the Provisioner's Node. By default it is set to 5,
/// which is a reasonable value. The TTL shall be in range 2...127.
public var defaultTtl: UInt8 = 5
/// The timeout after which an incomplete segmented message will be
/// abandoned. The timer is restarted each time a segment of this
/// message is received.
///
/// The incomplete timeout should be set to at least 10 seconds.
public var incompleteMessageTimeout: TimeInterval = 10.0
/// The amount of time after which the lower transport layer sends a
/// Segment Acknowledgment message after receiving a segment of a
/// multi-segment message where the destination is a Unicast Address
/// of the Provisioner's Element.
///
/// The acknowledgment timer shall be set to a minimum of
/// 150 + 50 * TTL milliseconds. The TTL dependent part is added
/// automatically, and this value shall specify only the constant part.
public var acknowledgmentTimerInterval: TimeInterval = 0.150
/// The time within which a Segment Acknowledgment message is
/// expected to be received after a segment of a segmented message has
/// been sent. When the timer is fired, the non-acknowledged segments
/// are repeated, at most ``retransmissionLimit`` times.
///
/// The transmission timer shall be set to a minimum of
/// 200 + 50 * TTL milliseconds. The TTL dependent part is added
/// automatically, and this value shall specify only the constant part.
///
/// If the bearer is using GATT, it is recommended to set the transmission
/// interval longer than the connection interval, so that the acknowledgment
/// had a chance to be received.
public var transmissionTimerInterval: TimeInterval = 0.200
/// Number of times a non-acknowledged segment of a segmented message
/// will be retransmitted before the message will be cancelled.
///
/// The limit may be decreased with increasing of ``transmissionTimerInterval``
/// as the target Node has more time to reply with the Segment
/// Acknowledgment message.
public var retransmissionLimit: Int = 5
/// If the Element does not receive a response within a period of time known
/// as the acknowledged message timeout, then the Element may consider the
/// message has not been delivered, without sending any additional messages.
///
/// The ``MeshNetworkDelegate/meshNetworkManager(_:failedToSendMessage:from:to:error:)-ogo4``
/// callback will be called on timeout.
///
/// The acknowledged message timeout should be set to a minimum of 30 seconds.
public var acknowledgmentMessageTimeout: TimeInterval = 30.0
/// The base time after which the acknowledged message will be repeated.
///
/// The repeat timer will be set to the base time + 50 * TTL milliseconds +
/// 50 * segment count. The TTL and segment count dependent parts are added
/// automatically, and this value shall specify only the constant part.
public var acknowledgmentMessageInterval: TimeInterval = 2.0
/// According to Bluetooth Mesh Profile 1.0.1, section 3.10.5, if the IV Index
/// of the mesh network increased by more than 42 since the last connection
/// (which can take at least 48 weeks), the Node should be re-provisioned.
/// However, as this library can be used to provision other Nodes, it should not
/// be blocked from sending messages to the network only because the phone wasn't
/// connected to the network for that time. This flag can disable this check,
/// effectively allowing such connection.
///
/// The same can be achieved by clearing the app data (uninstalling and reinstalling
/// the app) and importing the mesh network. With no "previous" IV Index, the
/// library will accept any IV Index received in the Secure Network beacon upon
/// connection to the GATT Proxy Node.
public var allowIvIndexRecoveryOver42: Bool = false
/// IV Update Test Mode enables efficient testing of the IV Update procedure.
/// The IV Update test mode removes the 96-hour limit; all other behavior of the device
/// are unchanged.
///
/// - seeAlso: Bluetooth Mesh Profile 1.0.1, section 3.10.5.1.
public var ivUpdateTestMode: Bool = false
// MARK: - Computed properties
/// The ``MeshNetwork`` object, or `nil`, if the network has not been loaded yet.
public var meshNetwork: MeshNetwork? {
return meshData.meshNetwork
}
/// Whether the Mesh Network has been created, or not.
public var isNetworkCreated: Bool {
return meshData.meshNetwork != nil
}
// MARK: - Constructors
/// Initializes the Mesh Network Manager.
///
/// If storage is not provided, a local file will be used instead.
///
/// - important: After the manager has been initialized, the ``localElements``
/// property must be set . Otherwise, none of status messages will
/// be parsed correctly and they will be returned to the delegate
/// as ``UnknownMessage``s.
///
/// - parameters:
/// - storage: The storage to use to save the network configuration.
/// - queue: The `DispatchQueue` to process requests on. By default, the a global
/// background concurrent queue will be used.
/// Note, that if multiple messages are sent shortly one after another,
/// processing them in a concurrent queue may cause some of them to be
/// discarded despite the fact that they were received in the ascending
/// order of SeqAuth, as one with a greater SeqAuth value may be processed
/// before the previous one, causing the replay protection validation fail
/// for the latter. This library stores 2 last SeqAuth values, so if a
/// message with a unique SeqAuth is processed after its successor, it
/// will be processed correctly.
/// - delegateQueue: The `DispatchQueue` to call delegate methods on.
/// By default the global main queue will be used.
/// - seeAlso: ``LocalStorage``
/// - seeAlso: ``LowerTransportLayer.checkAgainstReplayAttack(_:NetworkPdu)``
public init(using storage: Storage = LocalStorage(),
queue: DispatchQueue = DispatchQueue.global(qos: .background),
delegateQueue: DispatchQueue = DispatchQueue.main) {
self.storage = storage
self.meshData = MeshData()
self.queue = queue
self.delegateQueue = delegateQueue
self.proxyFilter = ProxyFilter(delegateQueue)
// Only now self can be used.
self.proxyFilter.use(with: self)
}
/// Initializes the Mesh Network Manager. It will use the ``LocalStorage`` with the given
/// file name.
///
/// - important: After the manager has been initialized, the ``localElements``
/// property must be set . Otherwise, none of status messages will
/// be parsed correctly and they will be returned to the delegate
/// as ``UnknownMessage``s.
///
/// - parameters:
/// - fileName: File name to keep the configuration.
/// - queue: The `DispatchQueue` to process requests on. By default, the a global
/// background concurrent queue will be used.
/// Note, that if multiple messages are sent shortly one after another,
/// processing them in a concurrent queue may cause some of them to be
/// discarded despite the fact that they were received in the ascending
/// order of SeqAuth, as one with a greater SeqAuth value may be processed
/// before the previous one, causing the replay protection validation fail
/// for the latter. This library stores 2 last SeqAuth values, so if a
/// message with a unique SeqAuth is processed after its successor, it
/// will be processed correctly.
/// - delegateQueue: The `DispatchQueue` to call delegate methods on.
/// By default the global main queue will be used.
///
/// - seeAlso: ``LocalStorage``
public convenience init(using fileName: String,
queue: DispatchQueue = DispatchQueue.global(qos: .background),
delegateQueue: DispatchQueue = DispatchQueue.main) {
self.init(using: LocalStorage(fileName: fileName),
queue: queue,
delegateQueue: delegateQueue)
}
}
// MARK: - Mesh Network API
public extension MeshNetworkManager {
/// Generates a new Mesh Network configuration with default values.
///
/// This method will override the existing configuration, if such exists.
/// The mesh network will contain one ``Provisioner`` with the given name
/// and randomly generated Primary Network Key.
///
/// - parameters:
/// - name: The user given network name.
/// - provisionerName: The user given local provisioner name.
func createNewMeshNetwork(withName name: String, by provisionerName: String) -> MeshNetwork {
return createNewMeshNetwork(withName: name, by: Provisioner(name: provisionerName))
}
/// Generates a new Mesh Network configuration with default values.
///
/// This method will override the existing configuration, if such exists.
/// The mesh network will contain the given ``Provisioner``
/// and randomly generated Primary Network Key.
///
/// - parameters:
/// - name: The user given network name.
/// - provisioner: The default Provisioner.
func createNewMeshNetwork(withName name: String, by provisioner: Provisioner) -> MeshNetwork {
let network = MeshNetwork(name: name)
// Add a new default provisioner.
try! network.add(provisioner: provisioner)
meshData.meshNetwork = network
networkManager = NetworkManager(self)
return network
}
/// An array of Elements of the local Node.
///
/// Use this property if you want to extend the capabilities of the local
/// Node with additional Elements and Models. For example, you may add an
/// additional Element with Generic On/Off Client Model if you support this
/// feature in your app. Make sure there is enough addresses for all the
/// Elements created. If a collision is found, the colliding Elements will
/// be ignored.
///
/// The mandatory Models (Configuration Server and Client and Health Server
/// and Client) will be added automatically to the Primary Element,
/// and should not be added explicitly.
///
/// The mesh network must be created or loaded before setting this field,
/// otherwise it has no effect.
///
/// - important: This property has to be set even if no custom Models are
/// defined as the set operation initializes the mandatory Models.
/// It can be set to an empty array.
var localElements: [Element] {
get {
return meshNetwork?.localElements ?? []
}
set {
meshNetwork?.localElements = newValue
networkManager?.accessLayer.reinitializePublishers()
}
}
}
// MARK: - Provisioning
public extension MeshNetworkManager {
/// This method returns the ``ProvisioningManager`` that can be used
/// to provision the given device.
///
/// - parameter unprovisionedDevice: The device to be added to mesh network.
/// - parameter bearer: The Provisioning Bearer to be used for sending
/// provisioning PDUs.
/// - returns: The Provisioning manager that should be used to continue
/// provisioning process after identification.
/// - throws: This method throws when the mesh network has not been created.
func provision(unprovisionedDevice: UnprovisionedDevice,
over bearer: ProvisioningBearer) throws -> ProvisioningManager {
guard let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
return ProvisioningManager(for: unprovisionedDevice, over: bearer, in: meshNetwork)
}
}
// MARK: - Send / Receive Mesh Messages
public extension MeshNetworkManager {
/// This method should be called whenever a PDU has been received from the mesh
/// network using any bearer.
///
/// When a complete Mesh Message is received and reassembled, the delegate's
/// ``MeshNetworkDelegate/meshNetworkManager(_:didReceiveMessage:sentFrom:to:)``
/// will be called.
///
/// For easier integration with ``GattBearer``, instead of calling this method,
/// set the manager as Bearer's ``Bearer/dataDelegate``.
///
/// - parameters:
/// - data: The PDU received.
/// - type: The PDU type.
func bearerDidDeliverData(_ data: Data, ofType type: PduType) {
guard let networkManager = networkManager else {
return
}
queue.async {
networkManager.handle(incomingPdu: data, ofType: type)
}
}
/// This method tries to publish the given message using the
/// publication information set in the Model.
///
/// If the retransmission is set to a value greater than 0, and the message
/// is unacknowledged, this method will retransmit it number of times
/// with the count and interval specified in the retransmission object.
///
/// If the publication is not configured for the given Model, this method
/// does nothing.
///
/// - parameters:
/// - message: The message to be sent.
/// - model: The model from which to send the message.
@discardableResult
func publish(_ message: MeshMessage, from model: Model) -> MessageHandle? {
guard let networkManager = networkManager,
let publish = model.publish,
let localElement = model.parentElement,
let _ = meshNetwork?.applicationKeys[publish.index] else {
return nil
}
queue.async {
networkManager.publish(message, from: model)
}
return MessageHandle(for: message, sentFrom: localElement.unicastAddress,
to: publish.publicationAddress.address, using: self)
}
/// Encrypts the message with the Application Key and a Network Key
/// bound to it, and sends to the given destination address.
///
/// This method does not send nor return PDUs to be sent. Instead,
/// for each created segment it calls transmitter's ``Transmitter/send(_:ofType:)``
/// method, which should send the PDU over the air. This is in order to support
/// retransmitting in case a packet was lost and needs to be sent again
/// after block acknowledgment was received.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - destination: The destination address.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - applicationKey: The Application Key to sign the message.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func send(_ message: MeshMessage,
from localElement: Element? = nil, to destination: MeshAddress,
withTtl initialTtl: UInt8? = nil,
using applicationKey: ApplicationKey) throws -> MessageHandle {
guard let networkManager = networkManager, let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let localNode = meshNetwork.localProvisioner?.node,
let source = localElement ?? localNode.elements.first else {
print("Error: Local Provisioner has no Unicast Address assigned")
throw AccessError.invalidSource
}
guard source.parentNode == localNode else {
print("Error: The Element does not belong to the local Node")
throw AccessError.invalidElement
}
guard initialTtl == nil || initialTtl! <= 127 else {
print("Error: TTL value \(initialTtl!) is invalid")
throw AccessError.invalidTtl
}
queue.async {
networkManager.send(message, from: source, to: destination,
withTtl: initialTtl, using: applicationKey)
}
return MessageHandle(for: message, sentFrom: source.unicastAddress,
to: destination.address, using: self)
}
/// Encrypts the message with the Application Key and a Network Key
/// bound to it, and sends to the given Group.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - group: The target Group.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - applicationKey: The Application Key to sign the message.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func send(_ message: MeshMessage,
from localElement: Element? = nil, to group: Group,
withTtl initialTtl: UInt8? = nil,
using applicationKey: ApplicationKey) throws -> MessageHandle {
return try send(message, from: localElement, to: group.address,
withTtl: initialTtl, using: applicationKey)
}
/// Encrypts the message with the first Application Key bound to the given
/// Model and a Network Key bound to it, and sends it to the Node
/// to which the Model belongs to.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - model: The destination Model.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - applicationKey: The Application Key to sign the message.
/// - throws: This method throws when the mesh network has not been created,
/// the target Model does not belong to any Element, or has
/// no Application Key bound to it, or when
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func send(_ message: MeshMessage,
from localElement: Element? = nil, to model: Model,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let element = model.parentElement else {
print("Error: Element does not belong to a Node")
throw AccessError.invalidDestination
}
guard let firstKeyIndex = model.bind.first,
let meshNetwork = meshNetwork,
let applicationKey = meshNetwork.applicationKeys[firstKeyIndex] else {
print("Error: Model is not bound to any Application Key")
throw AccessError.modelNotBoundToAppKey
}
return try send(message, from: localElement, to: MeshAddress(element.unicastAddress),
withTtl: initialTtl, using: applicationKey)
}
/// Encrypts the message with the common Application Key bound to both given
/// Models and a Network Key bound to it, and sends it to the Node
/// to which the target Model belongs to.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - localElement: The source Element. If `nil`, the primary
/// Element will be used. The Element must belong
/// to the local Provisioner's Node.
/// - model: The destination Model.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local or target Model do not belong to any Element, or have
/// no common Application Key bound to them, or when
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the given local Element
/// does not belong to the local Node.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func send(_ message: MeshMessage,
from localModel: Model, to model: Model,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let element = model.parentElement else {
print("Error: Element does not belong to a Node")
throw AccessError.invalidDestination
}
guard let localElement = localModel.parentElement else {
print("Error: Source Model does not belong to an Element")
throw AccessError.invalidSource
}
guard let commonKeyIndex = model.bind.first(where: { localModel.bind.contains($0) }),
let applicationKey = meshNetwork.applicationKeys[commonKeyIndex] else {
print("Error: Models are not bound to any common Application Key")
throw AccessError.modelNotBoundToAppKey
}
return try send(message, from: localElement, to: MeshAddress(element.unicastAddress),
withTtl: initialTtl, using: applicationKey)
}
/// Sends Configuration Message to the Node with given destination Address.
/// The `destination` must be a Unicast Address, otherwise the method
/// throws an error.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - destination: The destination Unicast Address.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the destination address
/// is not a Unicast Address or it belongs to an unknown Node.
/// Error ``AccessError/cannotDelete`` is sent when trying to
/// delete the last Network Key on the device.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func send(_ message: ConfigMessage, to destination: Address,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
guard let networkManager = networkManager, let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let localProvisioner = meshNetwork.localProvisioner,
let source = localProvisioner.primaryUnicastAddress else {
print("Error: Local Provisioner has no Unicast Address assigned")
throw AccessError.invalidSource
}
guard destination.isUnicast else {
print("Error: Address: 0x\(destination.hex) is not a Unicast Address")
throw AccessError.invalidDestination
}
guard let node = meshNetwork.node(withAddress: destination) else {
print("Error: Unknown destination Node")
throw AccessError.invalidDestination
}
guard let _ = node.networkKeys.first else {
print("Fatal Error: The target Node does not have Network Key")
throw AccessError.invalidDestination
}
guard let _ = node.deviceKey else {
print("Error: Node's Device Key is unknown")
throw AccessError.noDeviceKey
}
if message is ConfigNetKeyDelete {
guard node.networkKeys.count > 1 else {
print("Error: Cannot remove last Network Key")
throw AccessError.cannotDelete
}
}
guard initialTtl == nil || initialTtl! <= 127 else {
print("Error: TTL value \(initialTtl!) is invalid")
throw AccessError.invalidTtl
}
queue.async {
networkManager.send(message, to: node.primaryUnicastAddress, withTtl: initialTtl)
}
return MessageHandle(for: message, sentFrom: source,
to: node.primaryUnicastAddress, using: self)
}
/// Sends Configuration Message to the given Node.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - node: The destination Node.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the destination address
/// is not a Unicast Address or it belongs to an unknown Node.
/// Error ``AccessError/cannotDelete`` is sent when trying to
/// delete the last Network Key on the device.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func send(_ message: ConfigMessage, to node: Node,
withTtl initialTtl: UInt8? = nil) throws -> MessageHandle {
return try send(message, to: node.primaryUnicastAddress, withTtl: initialTtl)
}
/// Sends Configuration Message to the local Node.
///
/// An appropriate callback of the ``MeshNetworkDelegate`` will be called when
/// the message has been sent successfully or a problem occured.
///
/// - parameters:
/// - message: The message to be sent.
/// - node: The destination Node.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created,
/// the local Node does not have configuration capabilities
/// (no Unicast Address assigned), or the destination address
/// is not a Unicast Address or it belongs to an unknown Node.
/// Error ``AccessError/cannotDelete`` is sent when trying to
/// delete the last Network Key on the device.
/// - returns: Message handle that can be used to cancel sending.
@discardableResult
func sendToLocalNode(_ message: ConfigMessage) throws -> MessageHandle {
guard let meshNetwork = meshNetwork else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
guard let localProvisioner = meshNetwork.localProvisioner,
let destination = localProvisioner.primaryUnicastAddress else {
print("Error: Local Provisioner has no Unicast Address assigned")
throw AccessError.invalidSource
}
return try send(message, to: destination, withTtl: 1)
}
/// Sends the Proxy Configuration Message to the connected Proxy Node.
///
/// This method will only work if the bearer uses is GATT Proxy.
/// The message will be encrypted and sent to the ``Transmitter``, which
/// should deliver the PDU to the connected Node.
///
/// - parameters:
/// - message: The Proxy Configuration message to be sent.
/// - initialTtl: The initial TTL (Time To Live) value of the message.
/// If `nil`, the default Node TTL will be used.
/// - throws: This method throws when the mesh network has not been created.
func send(_ message: ProxyConfigurationMessage) throws {
guard let networkManager = networkManager else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
queue.async {
networkManager.send(message)
}
}
/// Cancels sending the message with the given identifier.
///
/// - parameter messageId: The message identifier.
func cancel(_ messageId: MessageHandle) throws {
guard let networkManager = networkManager else {
print("Error: Mesh Network not created")
throw MeshNetworkError.noNetwork
}
queue.async {
networkManager.cancel(messageId)
}
}
}
// MARK: - Helper methods for Bearer support
extension MeshNetworkManager: BearerDataDelegate {
public func bearer(_ bearer: Bearer, didDeliverData data: Data, ofType type: PduType) {
bearerDidDeliverData(data, ofType: type)
}
}
// MARK: - Managing sequence numbers.
public extension MeshNetworkManager {
/// This method sets the next outgoing sequence number of the given Element on local Node.
/// This 24-bit number will be set in the next message sent by this Element. The sequence
/// number is increased by 1 every time the Element sends a message.
///
/// Mind, that the sequence number is the least significant 24-bits of a SeqAuth, where
/// the 32 most significant bits are called IV Index. The sequence number resets to 0
/// when the device re-enters IV Index Normal Operation after 96-144 hours of being
/// in IV Index Update In Progress phase. The current IV Index is obtained from the
/// Secure Network beacon upon connection to Proxy Node. Setting too low sequence
/// number will effectively block the Element from sending messages to the network,
/// until it will increase enough not to be discarded by other nodes.
///
/// - important: This method should not be used, unless you need to reuse the same
/// Provisioner's Unicast Address on another device, or a device where the
/// app was uninstalled and reinstalled. Even then the use of it is not recommended.
/// The sequence number is an internal parameter of the Element and is
/// managed automatically by the library. Instead, each device (phone) should
/// use a separate Provisioner with unique set of Unicast Addresses, which
/// should not change on export/import.
///
/// - parameters:
/// - sequence: The new sequence number.
/// - element: The Element of a Node associated with the local Provisioner.
func setSequenceNumber(_ sequence: UInt32, forLocalElement element: Element) {
guard let meshNetwork = meshNetwork,
element.parentNode?.isLocalProvisioner == true,
let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString) else {
return
}
defaults.set(sequence & 0x00FFFFFF, forKey: "S\(element.unicastAddress.hex)")
}
/// Returns the next sequence number that would be used by the given Element on local Node.
///
/// - important: The sequence number is an internal parameter of an Element.
/// Apps should not use this method unless necessary. It is recommended
/// to create a new Provisioner with a unique Unicast Address instead.
///
/// - parameter element: The local Element to get sequence number of.
/// - returns: The next sequence number, or `nil` if the Element does not belong
/// to the local Element or the mesh network does not exist.
func getSequenceNumber(ofLocalElement element: Element) -> UInt32? {
guard let meshNetwork = meshNetwork,
element.parentNode?.isLocalProvisioner == true,
let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString) else {
return nil
}
return UInt32(defaults.integer(forKey: "S\(element.unicastAddress.hex)"))
}
}
// MARK: - Save / Load
public extension MeshNetworkManager {
/// Loads the Mesh Network configuration from the ``Storage`` set in the initiator
/// of the manager.
///
/// If the storage was not specified, the default local file will be used.
///
/// If the storage is empty, this method tries to migrate the database from the
/// nRF Mesh 1.0.x to the new format. This is useful when the library or the app
/// has been updated. For fresh installs, when the storage is empty and the legacy
/// version was not found this method returns `false`.
///
/// - returns: `True` if the network settings were loaded,
/// `false` otherwise.
/// - throws: If loading configuration failed.
func load() throws -> Bool {
if let data = storage.load() {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
meshData = try decoder.decode(MeshData.self, from: data)
guard let meshNetwork = meshData.meshNetwork else {
return false
}
// Restore the last IV Index. The last IV Index is stored since version 2.2.2.
if let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString),
let map = defaults.object(forKey: IvIndex.indexKey) as? [String : Any],
let ivIndex = IvIndex.fromMap(map) {
meshNetwork.ivIndex = ivIndex
}
networkManager = NetworkManager(self)
proxyFilter.newNetworkCreated()
return true
} else if let legacyState = MeshStateManager.load() {
// The app has been updated from version 1.0.x to 2.0.
// Time to migrate the data to the new format.
let network = MeshNetwork(name: legacyState.name)
try! network.add(provisioner: legacyState.provisioner,
withAddress: legacyState.provisionerUnicastAddress)
let provisionerNode = network.localProvisioner!.node!
provisionerNode.defaultTTL = legacyState.provisionerDefaultTtl
network.ivIndex = legacyState.ivIndex
network.networkKeys.removeAll()
let networkKey = legacyState.networkKey
network.add(networkKey: networkKey)
legacyState.applicationKeys(boundTo: networkKey).forEach {
network.add(applicationKey: $0)
}
legacyState.groups.forEach {
try? network.add(group: $0)
}
legacyState.nodes(provisionedUsingNetworkKey: networkKey).forEach {
try? network.add(node: $0)
}
// Restore the sequence number from the legacy version.
let defaultsKey = "nRFMeshSequenceNumber"
let oldDefaults = UserDefaults.standard
let oldSequence = UInt32(oldDefaults.integer(forKey: defaultsKey))
let newDefaults = UserDefaults(suiteName: network.uuid.uuidString)!
// The version 1.0.x had only one local Element, so there is no need to
// update sequence numbers for other possible local Elements.
newDefaults.set(oldSequence + 1, forKey: "S\(legacyState.provisionerUnicastAddress.hex)")
// Clean up.
oldDefaults.removeObject(forKey: defaultsKey)
MeshStateManager.cleanup()
meshData.meshNetwork = network
networkManager = NetworkManager(self)
proxyFilter.newNetworkCreated()
return save()
}
return false
}
/// Saves the Mesh Network configuration in the ``Storage`` given in the initiator
/// of the manager.
///
/// If storage was not specified, the local file will be used.
///
/// - returns: `True` if the network settings was saved, `false` otherwise.
func save() -> Bool {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let data = try! encoder.encode(meshData)
return storage.save(data)
}
}
// MARK: - Export / Import
public extension MeshNetworkManager {
/// Returns the exported Mesh Network configuration as JSON Data.
/// The returned Data can be transferred to another application and
/// imported. The JSON is compatible with Bluetooth Mesh Configuration Database 1.0.1 scheme.
///
/// - returns: The mesh network configuration as JSON Data.
func export() -> Data {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
if #available(iOS 11.0, *) {
encoder.outputFormatting = .sortedKeys
}
return try! encoder.encode(meshData.meshNetwork)
}
/// Returns the exported Mesh Network configuration as JSON Data.
/// The returned Data can be transferred to another application and
/// imported. The JSON is compatible with Bluetooth Mesh scheme.
///
/// The export configuration lets exporting only a part of the
/// network configuration. For example, when sharing the network with
/// a guest, a home owner may create a Guest Network Key and Guest
/// Application Key bound to it, configure Nodes in the guest room to
/// use these keys, define guest Groups and Scenes and then export only
/// the related part of the whole configuration. Moreover, the exported
/// JSON may exclude all Device Keys, so that the guest cannot reconfigure
/// the Nodes (although nothing forbids them from adding new Nodes using
/// guest keys). When the guest leaves the room, the guest Network Key may
/// be updated, so the guest cannot control devices afterwards.
///
/// - parameter configuration: The export configuration that lets to
/// narrow down what elements of the configuration
/// should be exported.
/// - returns: The mesh network configuration as JSON Data.
func export(_ configuration: ExportConfiguration) -> Data {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
if #available(iOS 11.0, *) {
encoder.outputFormatting = .sortedKeys
}
let meshNetwork = meshData.meshNetwork?.copy(using: configuration)
return try! encoder.encode(meshNetwork)
}
/// Imports the Mesh Network configuration from the given Data.
/// The data must contain valid JSON with Bluetooth Mesh Configuration Database 1.0.1 scheme.
///
/// - parameter data: JSON as Data.
/// - returns: The imported mesh network.
/// - throws: This method throws an error if import or adding
/// the local Provisioner failed.
func `import`(from data: Data) throws -> MeshNetwork {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let meshNetwork = try decoder.decode(MeshNetwork.self, from: data)
meshData.meshNetwork = meshNetwork
// Restore the last IV Index. The last IV Index is stored since version 2.2.2.
if let defaults = UserDefaults(suiteName: meshNetwork.uuid.uuidString),
let map = defaults.object(forKey: IvIndex.indexKey) as? [String : Any],
let ivIndex = IvIndex.fromMap(map) {
meshNetwork.ivIndex = ivIndex
}
networkManager = NetworkManager(self)
proxyFilter.newNetworkCreated()
return meshNetwork
}
}