/
ArtikWebsockets.swift
828 lines (732 loc) · 29.9 KB
/
ArtikWebsockets.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
//
// ArtikWebsockets.swift
// ArtikCloudSwift
//
// Created by Paul-Valentin Mini on 1/17/18.
// Copyright © 2017-2018 Samsung Electronics Co., Ltd. All rights reserved.
//
import Foundation
import PromiseKit
import Starscream
@available(watchOS, unavailable)
public protocol ArtikWebsocketDelegate: class {
/// Called when the socket has successfuly established a connection.
///
/// - Parameter socket: The `ArtikWebsocket` which connected.
func websocketDidConnect(socket: ArtikWebsocket)
/// Called when the socket has been disconnected, indicating if it was due to an error and if it is attempting to reconnect.
///
/// - Parameters:
/// - socket: The `ArtikWebsocket` which disconnected.
/// - reconnecting: A `Bool` indicating if it is attempting to reconnect.
/// - error: The `Error` causing the disconnection, `nil` if not caused by an error.
func websocketDidDisconnect(socket: ArtikWebsocket, reconnecting: Bool, error: Error?)
/// Called when an error occured while performing an operation.
///
/// - Parameters:
/// - socket: The `ArtikWebsocket` where an error occured.
/// - error: The `Error` which occured.
func websocketEncounteredError(socket: ArtikWebsocket, error: Error)
}
@available(watchOS, unavailable)
open class ArtikWebsocket: WebSocketDelegate {
fileprivate let pingInterval: Int = 30
fileprivate var websocket: WebSocket!
fileprivate var attempts: Int = 0
fileprivate var reconnect = true
fileprivate var pingUUID: UUID? = nil
fileprivate var token: Token? {
didSet {
didSetToken()
}
}
public var name: String {
return ""
}
public var endpoint: String {
return ""
}
public var url: URL {
return URL(string: ArtikCloudSwiftSettings.websocketPath + endpoint)!
}
public var isConnected: Bool {
return websocket.isConnected
}
public weak var delegate: ArtikWebsocketDelegate?
public var maximumAttemps: Int = 5
fileprivate init() {
commonInit()
}
deinit {
disconnect()
}
// Public
/// Connect to the WebSocket server on a background thread, using the provided `Token` or by getting it from `ArtikCloudSwiftSettings`.
///
/// - Parameter token: (Optional) A specific `Token` to use for this socket.
public func connect(token: Token? = nil) {
trace()
guard !isConnected else {
return
}
if let _ = token {
self.token = token
websocket.connect()
} else {
APIHelpers.getAuthToken(preference: ArtikCloudSwiftSettings.preferredTokenForWebsockets).done { token in
self.token = token
self.websocket.connect()
}.catch { error -> Void in
self.delegate?.websocketEncounteredError(socket: self, error: error)
}
}
}
/// Connect to the WebSocket server on a background thread async after the provided deadline.
///
/// - Parameter deadline: A `Double` representing the deadline from now to execute `.connect()`.
/// - Parameter token: (Optional) A specific `Token` to use for this socket.
public func connect(deadline: Double, token: Token? = nil) {
DispatchQueue.main.asyncAfter(deadline: .now() + deadline) {
self.connect(token: token)
}
}
/// Disconnect from the server.
public func disconnect() {
trace()
reconnect = false
pingUUID = nil
guard isConnected else {
return
}
websocket.disconnect()
}
// WebSocketDelegate
public func websocketDidConnect(socket: WebSocketClient) {
trace()
attempts = 0
reconnect = true
pingUUID = nil
handlePing()
delegate?.websocketDidConnect(socket: self)
}
public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
trace()
if reconnect {
var reconnect = attempts <= maximumAttemps
if let error = error {
reconnect = reconnect && shouldSocketAttemptToReconnect(error as NSError)
}
if reconnect {
attempts += 1
connect(deadline: 0.5 * pow(2, Double(attempts > 1 ? attempts - 1 : 0)))
delegate?.websocketDidDisconnect(socket: self, reconnecting: true, error: error)
return
}
}
delegate?.websocketDidDisconnect(socket: self, reconnecting: false, error: error)
}
public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
trace()
do {
if let data = text.data(using: .utf8), let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
if let type = json["type"] as? String, type == "ping" {
handlePing()
return
} else if let error = json["error"] as? [String:Any], let code = error["code"] as? Int, let message = error["message"] as? String {
websocketDidReceiveError(socket: socket, error: ArtikError.websocket(reason: .receivedAckError(code: code, message: message)))
return
}
websocketDidReceiveJSON(socket: socket, json: json)
} else {
delegate?.websocketEncounteredError(socket: self, error: ArtikError.websocket(reason: .unableToSerializeReceivedData))
}
} catch {
delegate?.websocketEncounteredError(socket: self, error: error)
}
}
public func websocketDidReceiveData(socket: WebSocketClient, data: Data) {}
// Overridable Methods
fileprivate func websocketDidReceiveJSON(socket: WebSocketClient, json: [String:Any]) {
trace()
}
fileprivate func websocketDidReceiveError(socket: WebSocketClient, error: ArtikError) {
trace()
delegate?.websocketEncounteredError(socket: self, error: error)
}
// Private
fileprivate func commonInit() {
websocket = WebSocket(url: url)
websocket.delegate = self
websocket.enabledSSLCipherSuites = [TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256]
}
fileprivate func didSetToken() {
if let token = token {
websocket.request.setValue(token.getHeaderValue(), forHTTPHeaderField: APIHelpers.authorizationHeaderKey)
}
}
fileprivate func trace(function: NSString = #function) {
ArtikCloudSwiftSettings.trace?("ARTIK Cloud Websocket:\n \(name): \(function)")
}
fileprivate func handlePing() {
trace()
let current = UUID()
pingUUID = current
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(pingInterval + 10)) { [weak self, current] in
guard let _self = self else {
return
}
if _self.isConnected && _self.pingUUID == current {
_self.commonInit()
_self.websocketDidDisconnect(socket: _self.websocket, error: ArtikError.websocket(reason: .pingTimeout))
}
}
}
fileprivate func shouldSocketAttemptToReconnect(_ error: NSError) -> Bool {
if error.domain == WebSocket.ErrorDomain {
switch error.code {
case 401:
return false
case 403:
return false
case 429:
return false
default:
break
}
}
return true
}
}
@available(watchOS, unavailable)
public protocol EventsWebsocketDelegate: ArtikWebsocketDelegate {
/// Called when the socket receives an event.
///
/// - Parameters:
/// - socket: The `EventsWebsocket` which received the event.
/// - event: The `EventsWebsocket.EventType` received.
/// - uid: (Optional) The User ID involved in the event.
/// - aid: (Optional) The Application ID from which the event comes from.
/// - did: (Optional) The Device ID involved in the event.
/// - dtid: (Optional) The Device Type ID involved in the event.
/// - ts: The `ArtikTimestamp` at which the event occured.
func websocketDidReceiveEvent(socket: EventsWebsocket, event: EventsWebsocket.EventType, uid: String?, aid: String?, did: String?, dtid: String?, ts: ArtikTimestamp)
}
@available(watchOS, unavailable)
open class EventsWebsocket: ArtikWebsocket {
public enum EventType: String {
case new = "device.new"
case connected = "device.connected"
case updated = "device.updated"
case disconnected = "device.disconnected"
case deleted = "device.deleted"
case online = "device.status.online"
case offline = "device.status.offline"
case userProfileUpdated = "user.profile.updated"
}
override public var name: String {
return "Events"
}
override public var endpoint: String {
return "/events"
}
override public var url: URL {
var params = [String]()
if let uid = uid {
params.append("uid=\(uid)")
}
if let dids = dids, dids.count > 0 {
if dids.count == 1, let first = dids.first {
params.append("did=\(first)")
} else {
params.append("dids=\(dids.joined(separator: ","))")
}
}
if let events = events, events.count > 0 {
params.append("events=\(events.map { $0.rawValue }.joined(separator: ","))")
}
if params.count > 0 {
return URL(string: ArtikCloudSwiftSettings.websocketPath + endpoint + "?\(params.joined(separator: "&"))")!
}
return URL(string: ArtikCloudSwiftSettings.websocketPath + endpoint)!
}
fileprivate var ignoreEvents = [String:Set<EventType>]()
public fileprivate(set) var uid: String?
public fileprivate(set) var dids: [String]?
public fileprivate(set) var events: [EventType]?
/// Initialize an Events Websocket
///
/// - Parameters:
/// - uid: (Optional) User ID of the target stream. If not specified, the uid implied in the access token is assumed.
/// - dids: (Optional) Device IDs for which to receive events.
/// - events: (Optional) Event names or event names with wildcard (e.g., device.*, user.profile.updated).
public init(uid: String? = nil, dids: [String]? = nil, events: [EventType]? = nil) {
self.uid = uid
self.dids = dids
self.events = events
super.init()
}
// Public Methods
/// Ignore a certain event type for a specific device.
///
/// - Parameters:
/// - event: The `EventType` to be ignored.
/// - did: The Device's ID.
public func ignoreEvent(_ event: EventType, forDid did: String) {
if var ignoreList = ignoreEvents[did] {
ignoreList.insert(event)
ignoreEvents[did] = ignoreList
return
}
ignoreEvents[did] = [event]
}
/// Ignore certain event types for a specific device.
///
/// - Parameters:
/// - events: The `Set<EventType>` to be ignored.
/// - did: The Device's ID.
public func ignoreEvents(_ events: Set<EventType>, forDid did: String) {
if let ignoreList = ignoreEvents[did] {
ignoreEvents[did] = ignoreList.union(events)
return
}
ignoreEvents[did] = events
}
/// Stop ignoring a certain event type for a specific device.
///
/// - Parameters:
/// - event: The `EventType` to stop ignoring.
/// - did: The Device's ID.
public func stopIgnoringEvent(_ event: EventType, forDid did: String) {
guard var ignoreList = ignoreEvents[did] else {
return
}
ignoreList.remove(event)
ignoreEvents[did] = ignoreList.count > 0 ? ignoreList : nil
}
/// Stop ignoring any event types for a specific device.
///
/// - Parameter did: The Device's ID
public func stopIgnoringEvents(forDid did: String) {
_ = ignoreEvents.removeValue(forKey: did)
}
/// Stop ignoring any event types for any devices.
public func stopIgnoringEvents() {
ignoreEvents.removeAll()
}
/// Get the events ignored for a specific device.
///
/// - Parameter did: The Device's ID.
/// - Returns: Returns a `Set<EventType>` or nil if nothing is ignored.
public func getEventsIgnored(forDid did: String) -> Set<EventType>? {
return ignoreEvents[did]
}
// Overridable Methods
override fileprivate func websocketDidReceiveJSON(socket: WebSocketClient, json: [String : Any]) {
super.websocketDidReceiveJSON(socket: socket, json: json)
if let data = json["data"] as? [String:Any], let eventraw = json["event"] as? String, let event = EventType(rawValue: eventraw), let ts = json["ts"] as? ArtikTimestamp {
let did = data["did"] as? String
if let did = did, let ignoreList = ignoreEvents[did], ignoreList.contains(event) {
return
}
(delegate as? EventsWebsocketDelegate)?.websocketDidReceiveEvent(socket: self, event: event, uid: data["uid"] as? String, aid: data["aid"] as? String, did: did, dtid: data["dtid"] as? String, ts: ts)
} else {
delegate?.websocketEncounteredError(socket: self, error: ArtikError.json(reason: .unexpectedFormat))
}
}
}
@available(watchOS, unavailable)
public protocol LiveWebsocketDelegate: ArtikWebsocketDelegate {
/// Called when the socket receives a message.
///
/// - Parameters:
/// - socket: The `LiveWebsocket` which received the message.
/// - mid: The message's ID.
/// - data: The message's data.
/// - sdid: The Source Device ID of the message.
/// - sdtid: (Optional) The Source Device Type ID of the message.
/// - uid: (Optional) The User ID related to the message.
/// - ts: The `ArtikTimestamp` at which the message was received.
func websocketDidReceiveMessage(socket: LiveWebsocket, mid: String, data: [String:Any], sdid: String, sdtid: String?, uid: String?, ts: ArtikTimestamp)
}
@available(watchOS, unavailable)
open class LiveWebsocket: ArtikWebsocket {
override public var name: String {
return "Live"
}
override public var endpoint: String {
return "/live"
}
override public var url: URL {
var string = ArtikCloudSwiftSettings.websocketPath + endpoint
if let sdids = sdids {
string += "?sdids=\(sdids.joined(separator: ","))"
} else if let sdtids = sdtids {
string += "?sdtids=\(sdtids.joined(separator: ","))"
} else {
string += "?includeSharedDevices=\(includeSharedDevices)"
if let uid = uid {
string += "&uid=\(uid)"
}
}
return URL(string: string)!
}
fileprivate var ignoreDids = Set<String>()
public fileprivate(set) var uid: String?
public fileprivate(set) var includeSharedDevices: Bool = false
public fileprivate(set) var sdids: [String]?
public fileprivate(set) var sdtids: [String]?
/// Initialize a Live (Firehose) Websocket for a specific user
///
/// - Parameter uid: (Optional) User ID of the target stream, inferred from token if ommited.
/// - Parameter includeSharedDevices: (Optional) Include shared devices (default: `false`).
public init(uid: String? = nil, includeSharedDevices: Bool = false) {
self.uid = uid
self.includeSharedDevices = includeSharedDevices
super.init()
}
/// Initialize a Live (Firehose) Websocket for specific devices
///
/// - Parameter sdids: List of source device IDs.
public init(sdids: [String]) {
self.sdids = sdids
super.init()
}
/// Initialize a Live (Firehose) Websocket for specific device types
///
/// - Parameter sdtids: List of source device type IDs.
public init(sdtids: [String]) {
self.sdtids = sdtids
super.init()
}
// Public Methods
/// Start ignoring messages from a specific device.
///
/// - Parameter did: The Device's ID.
public func ignore(did: String) {
ignoreDids.insert(did)
}
/// Stop ignoring messages from a specific device.
///
/// - Parameter did: The Device's ID.
public func stopIgnoring(did: String) {
_ = ignoreDids.remove(did)
}
/// Stop ignoring messages of any device previously ignored.
public func stopIgnoring() {
ignoreDids.removeAll()
}
/// Used to know if a specific device's messages are currently being ignored.
///
/// - Parameter did: The Device' ID.
/// - Returns: Returns a `Bool` indicating if the device is currently being ignored.
public func isIgnoring(did: String) -> Bool {
return ignoreDids.contains(did)
}
// Overridable Methods
override fileprivate func websocketDidReceiveJSON(socket: WebSocketClient, json: [String : Any]) {
super.websocketDidReceiveJSON(socket: socket, json: json)
if let sdid = json["sdid"] as? String, let data = json["data"] as? [String:Any], let ts = json["ts"] as? ArtikTimestamp, let mid = json["mid"] as? String {
guard !ignoreDids.contains(sdid) else {
return
}
(delegate as? LiveWebsocketDelegate)?.websocketDidReceiveMessage(socket: self, mid: mid, data: data, sdid: sdid, sdtid: json["sdtid"] as? String, uid: json["uid"] as? String, ts: ts)
} else {
delegate?.websocketEncounteredError(socket: self, error: ArtikError.json(reason: .unexpectedFormat))
}
}
}
@available(watchOS, unavailable)
public protocol DeviceWebsocketDelegate: ArtikWebsocketDelegate {
/// Called when the socket receives an action for a device.
///
/// - Parameters:
/// - socket: The `DeviceWebsocket` which received the action.
/// - mid: The Action's ID.
/// - data: The Action's data.
/// - ddid: The Action's Destination Device ID.
func websocketDidReceiveAction(socket: DeviceWebsocket, mid: String, data: [String:Any], ddid: String)
}
@available(watchOS, unavailable)
open class DeviceWebsocket: ArtikWebsocket {
public enum MessageType: String {
case register = "register"
case unregister = "unregister"
case list = "list"
}
override public var name: String {
return "Device"
}
override public var endpoint: String {
return "/websocket"
}
override public var url: URL {
return URL(string: ArtikCloudSwiftSettings.websocketPath + endpoint + "?ack=\(ack)")!
}
fileprivate var listPromise: Resolver<[String]>?
fileprivate var registrationPromise: Resolver<Void>?
fileprivate var messagePromise: Resolver<String?>?
public fileprivate(set) var ack: Bool
var isResponsePending: Bool {
return registrationPromise != nil || listPromise != nil || messagePromise != nil
}
/// Initialize a Device Websocket.
///
/// - Parameter ack: (Optional) WebSocket returns ACK messages for each message sent by client. If not specified, defaults to `false`.
public init(ack: Bool = false) {
self.ack = ack
super.init()
}
override public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
super.websocketDidDisconnect(socket: socket, error: error)
listPromise?.reject(ArtikError.websocket(reason: .responseTimedout))
listPromise = nil
registrationPromise?.reject(ArtikError.websocket(reason: .responseTimedout))
registrationPromise = nil
messagePromise?.reject(ArtikError.websocket(reason: .responseTimedout))
messagePromise = nil
}
// Public
/// Connect to the WebSocket on a background thread.
///
/// - Parameter token: (Optional) A specific `Token` to use when registering devices.
public override func connect(token: Token?) {
super.connect(token: token)
}
/// Connect to the WebSocket on a background thread async after the provided deadline.
///
/// - Parameter deadline: A `Double` representing the deadline from now to execute `.connect()`.
/// - Parameter token: (Optional) A specific `Token` to use when registering devices.
public override func connect(deadline: Double, token: Token?) {
super.connect(deadline: deadline, token: token)
}
/// Register a device with the socket.
///
/// - Parameters:
/// - did: The Device's ID.
/// - token: (Optional) A specific `Token` to use. If ommited, the `Token` provided when connecting will be used, or one from `ArtikCloudSwiftSettings`.
/// - Returns: A `Promise<Void>`. If `ack` is `True`, waits for the response to fulfill.
public func register(did: String, token: Token? = nil) -> Promise<Void> {
let (promise, resolver) = Promise<Void>.pending()
trace()
if isResponsePending {
resolver.reject(ArtikError.websocket(reason: .writeAlreadyOngoing))
return promise
} else if ack {
registrationPromise = resolver
}
guard isConnected else {
resolver.reject(ArtikError.websocket(reason: .socketIsNotConnected))
return promise
}
guard let token = token ?? self.token else {
resolver.reject(ArtikError.websocket(reason: .tokenRequired))
return promise
}
var parameters: [String:Any] = [
"sdid": did,
APIHelpers.authorizationHeaderKey: token.getHeaderValue(),
"type": MessageType.register.rawValue
]
if let cid = ArtikCloudSwiftSettings.clientID {
parameters["cid"] = cid
}
do {
let completion: (() -> ())? = ack ? nil : {
resolver.fulfill(())
}
websocket.write(string: try toJson(parameters), completion: completion)
} catch {
resolver.reject(error)
}
return promise
}
/// Unregister a device from the socket.
///
/// - Parameter did: The Device's ID.
/// - Returns: A `Promise<Void>`. If `ack` is `True`, waits for the response to fulfill.
public func unregister(did: String) -> Promise<Void> {
let (promise, resolver) = Promise<Void>.pending()
trace()
if isResponsePending {
resolver.reject(ArtikError.websocket(reason: .writeAlreadyOngoing))
return promise
} else if ack {
registrationPromise = resolver
}
guard isConnected else {
resolver.reject(ArtikError.websocket(reason: .socketIsNotConnected))
return promise
}
var parameters: [String:Any] = [
"sdid": did,
"type": MessageType.unregister.rawValue
]
if let cid = ArtikCloudSwiftSettings.clientID {
parameters["cid"] = cid
}
do {
let completion: (() -> ())? = ack ? nil : {
resolver.fulfill(())
}
websocket.write(string: try toJson(parameters), completion: completion)
} catch {
resolver.reject(error)
}
return promise
}
/// Get a list of devices currently registered on the socket.
///
/// - Returns: A `Promise<[String]>` containing the devices' IDs.
public func list() -> Promise<[String]> {
let (promise, resolver) = Promise<[String]>.pending()
trace()
if isResponsePending {
resolver.reject(ArtikError.websocket(reason: .writeAlreadyOngoing))
return promise
} else if ack {
listPromise = resolver
}
guard isConnected else {
resolver.reject(ArtikError.websocket(reason: .socketIsNotConnected))
return promise
}
var parameters: [String:Any] = ["type": MessageType.list.rawValue]
if let cid = ArtikCloudSwiftSettings.clientID {
parameters["cid"] = cid
}
do {
websocket.write(string: try toJson(parameters))
} catch {
resolver.reject(error)
}
return promise
}
/// Send a message from a device through the socket.
///
/// - Parameters:
/// - sdid: The Source Device's ID.
/// - data: The Message's data.
/// - ts: The Message timestamp. Must be a valid time: past time, present or future up to the current server timestamp grace period. Current time if omitted.
/// - Returns: A `Promise<String?>` representing the resulting message's id. If `ack` is `false`, fulfills with `nil`.
public func sendMessage(sdid: String, data: [String:Any], ts: ArtikTimestamp? = nil) -> Promise<String?> {
return sendMessage(ddid: nil, sdid: sdid, data: data, ts: ts)
}
/// Send an action to a device through the socket.
///
/// - Parameters:
/// - ddid: The Destination Device's ID.
/// - sdid: (Optional) The Source Device's ID.
/// - data: The Action's data.
/// - ts: The Action timestamp. Must be a valid time: past time, present or future up to the current server timestamp grace period. Current time if omitted.
/// - Returns: A `Promise<String?>` representing the resulting message's id. If `ack` is `false`, fulfills with `nil`.
public func sendAction(ddid: String, sdid: String? = nil, data: [String:Any], ts: ArtikTimestamp? = nil) -> Promise<String?> {
return sendMessage(ddid: ddid, sdid: sdid, data: data, ts: ts)
}
// Overridable Methods
override func websocketDidReceiveJSON(socket: WebSocketClient, json: [String : Any]) {
super.websocketDidReceiveJSON(socket: socket, json: json)
if ack {
if let promise = registrationPromise {
if let data = json["data"] as? [String:Any], let code = data["code"] as? Int, code == 200, let message = data["message"] as? String, message == "OK" {
promise.fulfill(())
registrationPromise = nil
return
} else {
promise.reject(ArtikError.websocket(reason: .unexpectedResponse))
registrationPromise = nil
}
}
if let promise = messagePromise {
if let data = json["data"] as? [String:Any], let mid = data["mid"] as? String {
promise.fulfill(mid)
messagePromise = nil
return
} else {
promise.reject(ArtikError.websocket(reason: .unexpectedResponse))
messagePromise = nil
}
}
} else {
registrationPromise?.fulfill(())
registrationPromise = nil
messagePromise?.fulfill(nil)
messagePromise = nil
}
if let promise = listPromise {
if let data = json["data"] as? [String:Any], let code = data["code"] as? Int, code == 200, let message = data["message"] as? [String] {
promise.fulfill(message)
listPromise = nil
return
} else {
promise.reject(ArtikError.websocket(reason: .unexpectedResponse))
listPromise = nil
}
}
if let ddid = json["ddid"] as? String, let mid = json["mid"] as? String, let data = json["data"] as? [String:Any] {
(delegate as? DeviceWebsocketDelegate)?.websocketDidReceiveAction(socket: self, mid: mid, data: data, ddid: ddid)
}
}
override func websocketDidReceiveError(socket: WebSocketClient, error: ArtikError) {
if let promise = registrationPromise {
promise.reject(error)
registrationPromise = nil
} else if let promise = messagePromise {
promise.reject(error)
messagePromise = nil
} else if let promise = listPromise {
promise.reject(error)
listPromise = nil
} else {
super.websocketDidReceiveError(socket: socket, error: error)
}
}
// Private Methods
override fileprivate func didSetToken() {
// Do nothing
}
fileprivate func toJson(_ data: [String:Any]) throws -> String {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
if let result = String(data: jsonData, encoding: .utf8) {
return result
}
throw ArtikError.websocket(reason: .unableToEncodeMessage)
}
fileprivate func sendMessage(ddid: String?, sdid: String?, data: [String:Any], ts: ArtikTimestamp? = nil) -> Promise<String?> {
let (promise, resolver) = Promise<String?>.pending()
trace()
if isResponsePending {
resolver.reject(ArtikError.websocket(reason: .writeAlreadyOngoing))
return promise
} else if ack {
messagePromise = resolver
}
guard isConnected else {
resolver.reject(ArtikError.websocket(reason: .socketIsNotConnected))
return promise
}
var parameters: [String:Any] = [
"data": data
]
if let ddid = ddid {
parameters["ddid"] = ddid
}
if let sdid = sdid {
parameters["sdid"] = sdid
}
if let ts = ts {
parameters["ts"] = ts
}
if let cid = ArtikCloudSwiftSettings.clientID {
parameters["cid"] = cid
}
do {
let completion: (() -> ())? = ack ? nil : {
resolver.fulfill(nil)
}
websocket.write(string: try toJson(parameters), completion: completion)
} catch {
resolver.reject(error)
}
return promise
}
}