Loading...
Searching...
No Matches
MqttSessionExample.swift
Go to the documentation of this file.
1import Foundation
2
3/**
4 * MqttSession usage example for Swift
5 * Demonstrates working with MQTT session for publishing position data
6 */
7class MqttSessionExample: NSObject, NCMqttSessionListener {
8 private var sdk: NCNavigineSdk?
9 private var locationManager: NCLocationManager?
10 private var navigationManager: NCNavigationManager?
11 private var mqttSession: NCMqttSession?
12
13 override init() {
14 super.init()
15 initializeSdk()
16 }
17
18 /**
19 * Initialize SDK and get managers
20 */
21 private func initializeSdk() {
22 do {
23 // [swift_NavigineSdk_getInstance]
24 // Get SDK instance
25 sdk = NCNavigineSdk.getInstance()
26 // [swift_NavigineSdk_getInstance]
27
28 // [swift_NavigineSdk_setUserHash]
29 // Set user hash
30 sdk?.setUserHash("USER-HASH-HERE")
31 // [swift_NavigineSdk_setUserHash]
32
33 // [swift_NavigineSdk_setServer]
34 // Set server URL (optional)
35 sdk?.setServer("https://custom.navigine.com")
36 // [swift_NavigineSdk_setServer]
37
38 // [swift_NavigineSdk_getLocationManager]
39 // Get LocationManager for working with locations
40 locationManager = sdk?.getLocationManager()
41 // [swift_NavigineSdk_getLocationManager]
42
43 // [swift_NavigineSdk_getNavigationManager]
44 // Get NavigationManager for working with navigation
45 navigationManager = sdk?.getNavigationManager(locationManager)
46 // [swift_NavigineSdk_getNavigationManager]
47
48 // [swift_NavigineSdk_getMqttSession]
49 // Create MQTT session for publishing position data
50 mqttSession = sdk?.getMqttSession(navigationManager)
51 // [swift_NavigineSdk_getMqttSession]
52
53 if mqttSession != nil {
54 print("MqttSession successfully initialized")
55 }
56 } catch {
57 print("Error initializing SDK: \‍(error)")
58 }
59 }
60
61 /**
62 * Demonstrate MqttSession methods
63 */
64 func demonstrateMqttSessionMethods() {
65 guard let session = mqttSession else {
66 print("MqttSession not initialized")
67 return
68 }
69
70 // [swift_MqttSession_addListener]
71 // Add MQTT session listener
72 session.addListener(self)
73 // [swift_MqttSession_addListener]
74
75 // [swift_MqttSession_setSubTopic]
76 // Set MQTT sub-topic for publishing position data
77 // Final topic will be "navigine/mobile/positions/" + subTopic + "/" + deviceId
78 session.setSubTopic("location1")
79 // [swift_MqttSession_setSubTopic]
80
81 // [swift_MqttSession_connect]
82 // Connect to MQTT broker
83 // Server: MQTT broker hostname or IP address
84 // Port: MQTT broker port (typically 1883 for non-SSL, 8883 for SSL)
85 // Username: MQTT broker username for authentication
86 // Password: MQTT broker password for authentication
87 session.connect("mqtt.example.com", port: 1883, username: "username", password: "password")
88 // [swift_MqttSession_connect]
89
90 // Wait for connection
91 Thread.sleep(forTimeInterval: 2.0)
92
93 // [swift_MqttSession_publish]
94 // Publish a custom message to a specific MQTT topic
95 // The message will be sent asynchronously and the result will be notified through listener callbacks
96 let customTopic = "custom/device/status"
97 let customMessage = "{\"status\": \"online\", \"timestamp\": \‍(Int(Date().timeIntervalSince1970 * 1000))}"
98 session.publish(topic: customTopic, message: customMessage)
99 // [swift_MqttSession_publish]
100 }
101
102 /**
103 * Demonstrate MQTT session with different configurations
104 */
105 func demonstrateMqttSessionConfigurations() {
106 guard let session = mqttSession else {
107 print("MqttSession not initialized")
108 return
109 }
110
111 print("=== MQTT Session Configurations ===")
112
113 // Example 1: Connect with default port
114 // [swift_MqttSession_setSubTopic]
115 // Set sub-topic. Final topic will be "navigine/mobile/positions/location1/{deviceId}"
116 session.setSubTopic("location1")
117 // [swift_MqttSession_setSubTopic]
118 // [swift_MqttSession_connect]
119 // Connect to MQTT broker with default port 1883
120 session.connect("mqtt.example.com", port: 1883, username: "user", password: "pass")
121 // [swift_MqttSession_connect]
122
123 // Wait a bit
124 Thread.sleep(forTimeInterval: 1.0)
125
126 // Disconnect before reconnecting with different config
127 // [swift_MqttSession_disconnect]
128 // Disconnect from MQTT broker
129 session.disconnect()
130 // [swift_MqttSession_disconnect]
131
132 // Example 2: Connect with SSL port
133 // [swift_MqttSession_setSubTopic]
134 // Set sub-topic. Final topic will be "navigine/mobile/positions/building-a/{deviceId}"
135 session.setSubTopic("building-a")
136 // [swift_MqttSession_setSubTopic]
137 // [swift_MqttSession_connect]
138 // Connect to MQTT broker with SSL port 8883
139 session.connect("mqtt-secure.example.com", port: 8883, username: "user", password: "pass")
140 // [swift_MqttSession_connect]
141
142 // Wait a bit
143 Thread.sleep(forTimeInterval: 1.0)
144
145 // Example 3: Connect with different sub-topic
146 // [swift_MqttSession_setSubTopic]
147 // Set different sub-topic. Final topic will be "navigine/mobile/positions/floor_2/{deviceId}"
148 session.setSubTopic("floor_2")
149 // [swift_MqttSession_setSubTopic]
150 // [swift_MqttSession_connect]
151 // Connect to MQTT broker
152 session.connect("mqtt.example.com", port: 1883, username: "user", password: "pass")
153 // [swift_MqttSession_connect]
154 }
155
156 /**
157 * Demonstrate listener management
158 */
159 func demonstrateListenerManagement() {
160 guard let session = mqttSession else {
161 print("MqttSession not initialized")
162 return
163 }
164
165 print("=== Listener Management ===")
166
167 // Create listener objects
168 let listener1 = MqttSessionListenerImpl(name: "Listener 1")
169 let listener2 = MqttSessionListenerImpl(name: "Listener 2")
170
171 // [swift_MqttSession_addListener]
172 // Add first listener
173 session.addListener(listener1)
174 // [swift_MqttSession_addListener]
175
176 // [swift_MqttSession_addListener]
177 // Add second listener
178 session.addListener(listener2)
179 // [swift_MqttSession_addListener]
180
181 // Connect to trigger callbacks
182 // [swift_MqttSession_setSubTopic]
183 session.setSubTopic("location1")
184 // [swift_MqttSession_setSubTopic]
185 // [swift_MqttSession_connect]
186 session.connect("mqtt.example.com", port: 1883, username: "user", password: "pass")
187 // [swift_MqttSession_connect]
188
189 // Wait for connection
190 Thread.sleep(forTimeInterval: 2.0)
191
192 // [swift_MqttSession_publish]
193 // Publish custom messages to different topics
194 session.publish(topic: "custom/events", message: "{\"event\": \"user_action\"}")
195 session.publish(topic: "custom/logs", message: "Application started")
196 // [swift_MqttSession_publish]
197
198 // Wait for messages to be published
199 Thread.sleep(forTimeInterval: 1.0)
200
201 // [swift_MqttSession_removeListener]
202 // Remove first listener
203 session.removeListener(listener1)
204 // [swift_MqttSession_removeListener]
205
206 // [swift_MqttSession_removeListener]
207 // Remove second listener
208 session.removeListener(listener2)
209 // [swift_MqttSession_removeListener]
210 }
211
212 /**
213 * Clean up resources
214 */
215 func cleanup() {
216 if let session = mqttSession {
217 // [swift_MqttSession_removeListener]
218 // Remove MQTT session listener
219 session.removeListener(self)
220 // [swift_MqttSession_removeListener]
221
222 // [swift_MqttSession_disconnect]
223 // Disconnect from MQTT broker
224 session.disconnect()
225 // [swift_MqttSession_disconnect]
226 }
227 }
228
229 /**
230 * Main demonstration method
231 */
232 func runExample() {
233 print("=== MqttSession Example ===")
234
235 demonstrateMqttSessionMethods()
236 demonstrateMqttSessionConfigurations()
237 demonstrateListenerManagement()
238
239 // Wait a bit for connection events
240 Thread.sleep(forTimeInterval: 3.0)
241
242 cleanup()
243 print("=== Example completed ===")
244 }
245}
246
247// MARK: - NCMqttSessionListener
248
249extension MqttSessionExample {
250 // [swift_MqttSessionListener_onConnected]
251 func onConnected() {
252 print("MQTT session connected successfully")
253 }
254 // [swift_MqttSessionListener_onConnected]
255
256 // [swift_MqttSessionListener_onError]
257 func onError(_ error: Error?) {
258 if let error = error {
259 print("MQTT session error: \‍(error.localizedDescription)")
260 }
261 }
262 // [swift_MqttSessionListener_onError]
263
264 // [swift_MqttSessionListener_onMessagePublished]
265 func onMessagePublished() {
266 print("Message published successfully")
267 }
268 // [swift_MqttSessionListener_onMessagePublished]
269}
270
271/**
272 * Helper class for multiple listeners
273 */
274class MqttSessionListenerImpl: NSObject, NCMqttSessionListener {
275 let name: String
276
277 init(name: String) {
278 self.name = name
279 }
280
281 func onConnected() {
282 print("\‍(name): Connected")
283 }
284
285 func onError(_ error: Error?) {
286 if let error = error {
287 print("\‍(name): Error - \‍(error.localizedDescription)")
288 }
289 }
290
291 func onMessagePublished() {
292 print("\‍(name): Message published")
293 }
294}
295
296/**
297 * Function to run the example
298 */
299func main() {
300 let example = MqttSessionExample()
301 example.runExample()
302}
303
304// Run the example
305main()