@openmdm/push-mqtt 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present OpenMDM Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,146 @@
1
+ import { DatabaseAdapter, PushAdapter } from '@openmdm/core';
2
+
3
+ /**
4
+ * OpenMDM MQTT Push Adapter
5
+ *
6
+ * MQTT-based push adapter for sending commands to Android devices.
7
+ * Ideal for private networks, air-gapped environments, and self-hosted deployments
8
+ * where FCM cannot be used.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { createMDM } from '@openmdm/core';
13
+ * import { mqttPushAdapter } from '@openmdm/push-mqtt';
14
+ *
15
+ * const mdm = createMDM({
16
+ * database: drizzleAdapter(db),
17
+ * push: mqttPushAdapter({
18
+ * brokerUrl: 'mqtt://localhost:1883',
19
+ * // or: brokerUrl: 'mqtts://broker.example.com:8883',
20
+ * username: 'mdm-server',
21
+ * password: 'secret',
22
+ * }),
23
+ * });
24
+ * ```
25
+ */
26
+
27
+ interface MQTTAdapterOptions {
28
+ /**
29
+ * MQTT broker URL
30
+ * Examples: 'mqtt://localhost:1883', 'mqtts://broker.example.com:8883'
31
+ */
32
+ brokerUrl: string;
33
+ /**
34
+ * Username for MQTT authentication
35
+ */
36
+ username?: string;
37
+ /**
38
+ * Password for MQTT authentication
39
+ */
40
+ password?: string;
41
+ /**
42
+ * Client ID prefix (default: 'openmdm-server')
43
+ * A random suffix will be added for uniqueness
44
+ */
45
+ clientIdPrefix?: string;
46
+ /**
47
+ * Topic prefix for device messages (default: 'openmdm/devices')
48
+ * Messages will be published to: {topicPrefix}/{deviceId}/commands
49
+ */
50
+ topicPrefix?: string;
51
+ /**
52
+ * Database adapter for storing/retrieving connection state
53
+ */
54
+ database?: DatabaseAdapter;
55
+ /**
56
+ * Quality of Service level (default: 1)
57
+ * 0 = At most once, 1 = At least once, 2 = Exactly once
58
+ */
59
+ qos?: 0 | 1 | 2;
60
+ /**
61
+ * Whether to retain messages (default: false)
62
+ * Retained messages are delivered to new subscribers
63
+ */
64
+ retain?: boolean;
65
+ /**
66
+ * Message expiry interval in seconds (default: 3600 = 1 hour)
67
+ * MQTT 5.0 feature
68
+ */
69
+ messageExpiryInterval?: number;
70
+ /**
71
+ * TLS/SSL options for secure connections
72
+ */
73
+ tls?: {
74
+ ca?: string | Buffer | string[] | Buffer[];
75
+ cert?: string | Buffer;
76
+ key?: string | Buffer;
77
+ rejectUnauthorized?: boolean;
78
+ };
79
+ /**
80
+ * Reconnection options
81
+ */
82
+ reconnect?: {
83
+ enabled?: boolean;
84
+ maxRetries?: number;
85
+ initialDelay?: number;
86
+ maxDelay?: number;
87
+ };
88
+ /**
89
+ * Clean session flag (default: true)
90
+ * If false, the broker stores subscriptions and queued messages
91
+ */
92
+ cleanSession?: boolean;
93
+ /**
94
+ * Keep-alive interval in seconds (default: 60)
95
+ */
96
+ keepAlive?: number;
97
+ }
98
+ /**
99
+ * Create an MQTT push adapter for OpenMDM
100
+ */
101
+ declare function mqttPushAdapter(options: MQTTAdapterOptions): PushAdapter;
102
+ /**
103
+ * Create MQTT adapter from environment variables
104
+ *
105
+ * Expects:
106
+ * - MQTT_BROKER_URL: MQTT broker URL
107
+ * - MQTT_USERNAME: (optional) Username
108
+ * - MQTT_PASSWORD: (optional) Password
109
+ */
110
+ declare function mqttPushAdapterFromEnv(options?: Partial<MQTTAdapterOptions>): PushAdapter;
111
+ /**
112
+ * Additional utility types for MQTT-specific features
113
+ */
114
+ interface MQTTDeviceStatus {
115
+ deviceId: string;
116
+ online: boolean;
117
+ lastSeen: Date;
118
+ subscriptions?: string[];
119
+ }
120
+ /**
121
+ * Extended MQTT adapter with device presence tracking
122
+ */
123
+ interface MQTTExtendedAdapter extends PushAdapter {
124
+ /**
125
+ * Get device online status
126
+ */
127
+ getDeviceStatus(deviceId: string): MQTTDeviceStatus | undefined;
128
+ /**
129
+ * Get all online devices
130
+ */
131
+ getOnlineDevices(): MQTTDeviceStatus[];
132
+ /**
133
+ * Check if device is currently online
134
+ */
135
+ isDeviceOnline(deviceId: string): boolean;
136
+ /**
137
+ * Disconnect from MQTT broker
138
+ */
139
+ disconnect(): Promise<void>;
140
+ }
141
+ /**
142
+ * Create an extended MQTT adapter with device presence tracking
143
+ */
144
+ declare function mqttExtendedAdapter(options: MQTTAdapterOptions): MQTTExtendedAdapter;
145
+
146
+ export { type MQTTAdapterOptions, type MQTTDeviceStatus, type MQTTExtendedAdapter, mqttExtendedAdapter, mqttPushAdapter, mqttPushAdapterFromEnv };
package/dist/index.js ADDED
@@ -0,0 +1,320 @@
1
+ // src/index.ts
2
+ import * as mqtt from "mqtt";
3
+ function mqttPushAdapter(options) {
4
+ const topicPrefix = options.topicPrefix ?? "openmdm/devices";
5
+ const qos = options.qos ?? 1;
6
+ const retain = options.retain ?? false;
7
+ const messageExpiryInterval = options.messageExpiryInterval ?? 3600;
8
+ const database = options.database;
9
+ const clientId = `${options.clientIdPrefix ?? "openmdm-server"}-${Math.random().toString(36).substring(2, 10)}`;
10
+ const devicePresence = /* @__PURE__ */ new Map();
11
+ const pendingAcks = /* @__PURE__ */ new Map();
12
+ const client = mqtt.connect(options.brokerUrl, {
13
+ clientId,
14
+ username: options.username,
15
+ password: options.password,
16
+ clean: options.cleanSession ?? true,
17
+ keepalive: options.keepAlive ?? 60,
18
+ reconnectPeriod: options.reconnect?.enabled !== false ? options.reconnect?.initialDelay ?? 1e3 : 0,
19
+ ...options.tls && {
20
+ ca: options.tls.ca,
21
+ cert: options.tls.cert,
22
+ key: options.tls.key,
23
+ rejectUnauthorized: options.tls.rejectUnauthorized ?? true
24
+ }
25
+ });
26
+ let connected = false;
27
+ let connectionError = null;
28
+ client.on("connect", () => {
29
+ connected = true;
30
+ connectionError = null;
31
+ console.log("[OpenMDM MQTT] Connected to broker");
32
+ client.subscribe(`${topicPrefix}/+/presence`, { qos: 1 }, (err) => {
33
+ if (err) {
34
+ console.error("[OpenMDM MQTT] Failed to subscribe to presence:", err);
35
+ }
36
+ });
37
+ client.subscribe(`${topicPrefix}/+/ack`, { qos: 1 }, (err) => {
38
+ if (err) {
39
+ console.error("[OpenMDM MQTT] Failed to subscribe to acks:", err);
40
+ }
41
+ });
42
+ });
43
+ client.on("disconnect", () => {
44
+ connected = false;
45
+ console.log("[OpenMDM MQTT] Disconnected from broker");
46
+ });
47
+ client.on("error", (err) => {
48
+ connectionError = err;
49
+ console.error("[OpenMDM MQTT] Connection error:", err);
50
+ });
51
+ client.on("reconnect", () => {
52
+ console.log("[OpenMDM MQTT] Reconnecting...");
53
+ });
54
+ client.on("message", (topic, payload) => {
55
+ try {
56
+ const parts = topic.split("/");
57
+ const deviceId = parts[parts.length - 2];
58
+ const messageType = parts[parts.length - 1];
59
+ if (messageType === "presence") {
60
+ const data = JSON.parse(payload.toString());
61
+ devicePresence.set(deviceId, {
62
+ deviceId,
63
+ online: data.online ?? true,
64
+ lastSeen: /* @__PURE__ */ new Date()
65
+ });
66
+ console.log(
67
+ `[OpenMDM MQTT] Device ${deviceId} is ${data.online ? "online" : "offline"}`
68
+ );
69
+ } else if (messageType === "ack") {
70
+ const data = JSON.parse(payload.toString());
71
+ const messageId = data.messageId;
72
+ if (messageId && pendingAcks.has(messageId)) {
73
+ const pending = pendingAcks.get(messageId);
74
+ clearTimeout(pending.timeout);
75
+ pendingAcks.delete(messageId);
76
+ pending.resolve({
77
+ success: true,
78
+ messageId
79
+ });
80
+ }
81
+ }
82
+ } catch (error) {
83
+ console.error("[OpenMDM MQTT] Error processing message:", error);
84
+ }
85
+ });
86
+ async function waitForConnection(timeoutMs = 5e3) {
87
+ if (connected) return;
88
+ return new Promise((resolve, reject) => {
89
+ const timeout = setTimeout(() => {
90
+ reject(new Error("MQTT connection timeout"));
91
+ }, timeoutMs);
92
+ const checkConnection = () => {
93
+ if (connected) {
94
+ clearTimeout(timeout);
95
+ resolve();
96
+ } else if (connectionError) {
97
+ clearTimeout(timeout);
98
+ reject(connectionError);
99
+ } else {
100
+ setTimeout(checkConnection, 100);
101
+ }
102
+ };
103
+ checkConnection();
104
+ });
105
+ }
106
+ function generateMessageId() {
107
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
108
+ }
109
+ function buildPayload(message, messageId) {
110
+ return JSON.stringify({
111
+ messageId,
112
+ type: message.type,
113
+ payload: message.payload,
114
+ priority: message.priority ?? "normal",
115
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
116
+ });
117
+ }
118
+ async function publishToDevice(deviceId, message, waitForAck = true) {
119
+ await waitForConnection();
120
+ const messageId = generateMessageId();
121
+ const topic = `${topicPrefix}/${deviceId}/commands`;
122
+ const payload = buildPayload(message, messageId);
123
+ return new Promise((resolve) => {
124
+ if (waitForAck) {
125
+ const timeout = setTimeout(() => {
126
+ pendingAcks.delete(messageId);
127
+ resolve({
128
+ success: true,
129
+ messageId
130
+ });
131
+ }, 3e4);
132
+ pendingAcks.set(messageId, { resolve, timeout });
133
+ }
134
+ client.publish(
135
+ topic,
136
+ payload,
137
+ {
138
+ qos,
139
+ retain,
140
+ properties: {
141
+ messageExpiryInterval
142
+ }
143
+ },
144
+ (err) => {
145
+ if (err) {
146
+ if (waitForAck && pendingAcks.has(messageId)) {
147
+ const pending = pendingAcks.get(messageId);
148
+ clearTimeout(pending.timeout);
149
+ pendingAcks.delete(messageId);
150
+ }
151
+ resolve({
152
+ success: false,
153
+ error: err.message
154
+ });
155
+ } else if (!waitForAck) {
156
+ resolve({
157
+ success: true,
158
+ messageId
159
+ });
160
+ }
161
+ }
162
+ );
163
+ });
164
+ }
165
+ return {
166
+ async send(deviceId, message) {
167
+ try {
168
+ const result = await publishToDevice(deviceId, message);
169
+ if (result.success) {
170
+ console.log(
171
+ `[OpenMDM MQTT] Sent to ${deviceId}: ${message.type} (${result.messageId})`
172
+ );
173
+ } else {
174
+ console.error(
175
+ `[OpenMDM MQTT] Failed to send to ${deviceId}:`,
176
+ result.error
177
+ );
178
+ }
179
+ return result;
180
+ } catch (error) {
181
+ console.error(`[OpenMDM MQTT] Error sending to ${deviceId}:`, error);
182
+ return {
183
+ success: false,
184
+ error: error.message || "MQTT send failed"
185
+ };
186
+ }
187
+ },
188
+ async sendBatch(deviceIds, message) {
189
+ const results = [];
190
+ let successCount = 0;
191
+ let failureCount = 0;
192
+ const promises = deviceIds.map(async (deviceId) => {
193
+ const result = await publishToDevice(deviceId, message, false);
194
+ return { deviceId, result };
195
+ });
196
+ const settledResults = await Promise.all(promises);
197
+ for (const { deviceId, result } of settledResults) {
198
+ results.push({ deviceId, result });
199
+ if (result.success) {
200
+ successCount++;
201
+ } else {
202
+ failureCount++;
203
+ }
204
+ }
205
+ console.log(
206
+ `[OpenMDM MQTT] Batch sent: ${successCount} success, ${failureCount} failed`
207
+ );
208
+ return { successCount, failureCount, results };
209
+ },
210
+ async registerToken(deviceId, token) {
211
+ if (database) {
212
+ await database.upsertPushToken({
213
+ deviceId,
214
+ provider: "mqtt",
215
+ token: token || deviceId
216
+ // Use deviceId as token if not provided
217
+ });
218
+ }
219
+ console.log(`[OpenMDM MQTT] Registered device ${deviceId}`);
220
+ },
221
+ async unregisterToken(deviceId) {
222
+ devicePresence.delete(deviceId);
223
+ if (database) {
224
+ await database.deletePushToken(deviceId, "mqtt");
225
+ }
226
+ console.log(`[OpenMDM MQTT] Unregistered device ${deviceId}`);
227
+ },
228
+ async subscribe(deviceId, topic) {
229
+ const fullTopic = `${topicPrefix}/topics/${topic}`;
230
+ await waitForConnection();
231
+ const payload = JSON.stringify({
232
+ action: "subscribe",
233
+ topic,
234
+ deviceId,
235
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
236
+ });
237
+ return new Promise((resolve, reject) => {
238
+ client.publish(
239
+ `${topicPrefix}/${deviceId}/subscribe`,
240
+ payload,
241
+ { qos: 1 },
242
+ (err) => {
243
+ if (err) {
244
+ reject(err);
245
+ } else {
246
+ console.log(
247
+ `[OpenMDM MQTT] Requested ${deviceId} to subscribe to ${topic}`
248
+ );
249
+ resolve();
250
+ }
251
+ }
252
+ );
253
+ });
254
+ },
255
+ async unsubscribe(deviceId, topic) {
256
+ await waitForConnection();
257
+ const payload = JSON.stringify({
258
+ action: "unsubscribe",
259
+ topic,
260
+ deviceId,
261
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
262
+ });
263
+ return new Promise((resolve, reject) => {
264
+ client.publish(
265
+ `${topicPrefix}/${deviceId}/unsubscribe`,
266
+ payload,
267
+ { qos: 1 },
268
+ (err) => {
269
+ if (err) {
270
+ reject(err);
271
+ } else {
272
+ console.log(
273
+ `[OpenMDM MQTT] Requested ${deviceId} to unsubscribe from ${topic}`
274
+ );
275
+ resolve();
276
+ }
277
+ }
278
+ );
279
+ });
280
+ }
281
+ };
282
+ }
283
+ function mqttPushAdapterFromEnv(options) {
284
+ const brokerUrl = process.env.MQTT_BROKER_URL;
285
+ if (!brokerUrl) {
286
+ throw new Error("MQTT_BROKER_URL environment variable is required");
287
+ }
288
+ return mqttPushAdapter({
289
+ ...options,
290
+ brokerUrl,
291
+ username: process.env.MQTT_USERNAME ?? options?.username,
292
+ password: process.env.MQTT_PASSWORD ?? options?.password
293
+ });
294
+ }
295
+ function mqttExtendedAdapter(options) {
296
+ const baseAdapter = mqttPushAdapter(options);
297
+ const devicePresence = /* @__PURE__ */ new Map();
298
+ return {
299
+ ...baseAdapter,
300
+ getDeviceStatus(deviceId) {
301
+ return devicePresence.get(deviceId);
302
+ },
303
+ getOnlineDevices() {
304
+ return Array.from(devicePresence.values()).filter((d) => d.online);
305
+ },
306
+ isDeviceOnline(deviceId) {
307
+ const status = devicePresence.get(deviceId);
308
+ return status?.online ?? false;
309
+ },
310
+ async disconnect() {
311
+ console.log("[OpenMDM MQTT] Disconnecting...");
312
+ }
313
+ };
314
+ }
315
+ export {
316
+ mqttExtendedAdapter,
317
+ mqttPushAdapter,
318
+ mqttPushAdapterFromEnv
319
+ };
320
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * OpenMDM MQTT Push Adapter\n *\n * MQTT-based push adapter for sending commands to Android devices.\n * Ideal for private networks, air-gapped environments, and self-hosted deployments\n * where FCM cannot be used.\n *\n * @example\n * ```typescript\n * import { createMDM } from '@openmdm/core';\n * import { mqttPushAdapter } from '@openmdm/push-mqtt';\n *\n * const mdm = createMDM({\n * database: drizzleAdapter(db),\n * push: mqttPushAdapter({\n * brokerUrl: 'mqtt://localhost:1883',\n * // or: brokerUrl: 'mqtts://broker.example.com:8883',\n * username: 'mdm-server',\n * password: 'secret',\n * }),\n * });\n * ```\n */\n\nimport * as mqtt from 'mqtt';\nimport type {\n PushAdapter,\n PushMessage,\n PushResult,\n PushBatchResult,\n DatabaseAdapter,\n} from '@openmdm/core';\n\nexport interface MQTTAdapterOptions {\n /**\n * MQTT broker URL\n * Examples: 'mqtt://localhost:1883', 'mqtts://broker.example.com:8883'\n */\n brokerUrl: string;\n\n /**\n * Username for MQTT authentication\n */\n username?: string;\n\n /**\n * Password for MQTT authentication\n */\n password?: string;\n\n /**\n * Client ID prefix (default: 'openmdm-server')\n * A random suffix will be added for uniqueness\n */\n clientIdPrefix?: string;\n\n /**\n * Topic prefix for device messages (default: 'openmdm/devices')\n * Messages will be published to: {topicPrefix}/{deviceId}/commands\n */\n topicPrefix?: string;\n\n /**\n * Database adapter for storing/retrieving connection state\n */\n database?: DatabaseAdapter;\n\n /**\n * Quality of Service level (default: 1)\n * 0 = At most once, 1 = At least once, 2 = Exactly once\n */\n qos?: 0 | 1 | 2;\n\n /**\n * Whether to retain messages (default: false)\n * Retained messages are delivered to new subscribers\n */\n retain?: boolean;\n\n /**\n * Message expiry interval in seconds (default: 3600 = 1 hour)\n * MQTT 5.0 feature\n */\n messageExpiryInterval?: number;\n\n /**\n * TLS/SSL options for secure connections\n */\n tls?: {\n ca?: string | Buffer | string[] | Buffer[];\n cert?: string | Buffer;\n key?: string | Buffer;\n rejectUnauthorized?: boolean;\n };\n\n /**\n * Reconnection options\n */\n reconnect?: {\n enabled?: boolean;\n maxRetries?: number;\n initialDelay?: number;\n maxDelay?: number;\n };\n\n /**\n * Clean session flag (default: true)\n * If false, the broker stores subscriptions and queued messages\n */\n cleanSession?: boolean;\n\n /**\n * Keep-alive interval in seconds (default: 60)\n */\n keepAlive?: number;\n}\n\ninterface DevicePresence {\n deviceId: string;\n online: boolean;\n lastSeen: Date;\n}\n\n/**\n * Create an MQTT push adapter for OpenMDM\n */\nexport function mqttPushAdapter(options: MQTTAdapterOptions): PushAdapter {\n const topicPrefix = options.topicPrefix ?? 'openmdm/devices';\n const qos = options.qos ?? 1;\n const retain = options.retain ?? false;\n const messageExpiryInterval = options.messageExpiryInterval ?? 3600;\n const database = options.database;\n\n // Generate unique client ID\n const clientId = `${options.clientIdPrefix ?? 'openmdm-server'}-${Math.random().toString(36).substring(2, 10)}`;\n\n // Device presence tracking\n const devicePresence = new Map<string, DevicePresence>();\n\n // Pending acknowledgments: messageId -> resolve function\n const pendingAcks = new Map<\n string,\n { resolve: (result: PushResult) => void; timeout: NodeJS.Timeout }\n >();\n\n // Create MQTT client\n const client = mqtt.connect(options.brokerUrl, {\n clientId,\n username: options.username,\n password: options.password,\n clean: options.cleanSession ?? true,\n keepalive: options.keepAlive ?? 60,\n reconnectPeriod: options.reconnect?.enabled !== false ? (options.reconnect?.initialDelay ?? 1000) : 0,\n ...(options.tls && {\n ca: options.tls.ca,\n cert: options.tls.cert,\n key: options.tls.key,\n rejectUnauthorized: options.tls.rejectUnauthorized ?? true,\n }),\n });\n\n // Connection state\n let connected = false;\n let connectionError: Error | null = null;\n\n client.on('connect', () => {\n connected = true;\n connectionError = null;\n console.log('[OpenMDM MQTT] Connected to broker');\n\n // Subscribe to presence topic for all devices\n client.subscribe(`${topicPrefix}/+/presence`, { qos: 1 }, (err) => {\n if (err) {\n console.error('[OpenMDM MQTT] Failed to subscribe to presence:', err);\n }\n });\n\n // Subscribe to acknowledgment topic for all devices\n client.subscribe(`${topicPrefix}/+/ack`, { qos: 1 }, (err) => {\n if (err) {\n console.error('[OpenMDM MQTT] Failed to subscribe to acks:', err);\n }\n });\n });\n\n client.on('disconnect', () => {\n connected = false;\n console.log('[OpenMDM MQTT] Disconnected from broker');\n });\n\n client.on('error', (err) => {\n connectionError = err;\n console.error('[OpenMDM MQTT] Connection error:', err);\n });\n\n client.on('reconnect', () => {\n console.log('[OpenMDM MQTT] Reconnecting...');\n });\n\n // Handle incoming messages\n client.on('message', (topic, payload) => {\n try {\n const parts = topic.split('/');\n const deviceId = parts[parts.length - 2];\n const messageType = parts[parts.length - 1];\n\n if (messageType === 'presence') {\n // Device presence update\n const data = JSON.parse(payload.toString());\n devicePresence.set(deviceId, {\n deviceId,\n online: data.online ?? true,\n lastSeen: new Date(),\n });\n\n console.log(\n `[OpenMDM MQTT] Device ${deviceId} is ${data.online ? 'online' : 'offline'}`\n );\n } else if (messageType === 'ack') {\n // Message acknowledgment\n const data = JSON.parse(payload.toString());\n const messageId = data.messageId;\n\n if (messageId && pendingAcks.has(messageId)) {\n const pending = pendingAcks.get(messageId)!;\n clearTimeout(pending.timeout);\n pendingAcks.delete(messageId);\n\n pending.resolve({\n success: true,\n messageId,\n });\n }\n }\n } catch (error) {\n console.error('[OpenMDM MQTT] Error processing message:', error);\n }\n });\n\n /**\n * Wait for connection to be established\n */\n async function waitForConnection(timeoutMs: number = 5000): Promise<void> {\n if (connected) return;\n\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error('MQTT connection timeout'));\n }, timeoutMs);\n\n const checkConnection = () => {\n if (connected) {\n clearTimeout(timeout);\n resolve();\n } else if (connectionError) {\n clearTimeout(timeout);\n reject(connectionError);\n } else {\n setTimeout(checkConnection, 100);\n }\n };\n\n checkConnection();\n });\n }\n\n /**\n * Generate unique message ID\n */\n function generateMessageId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n }\n\n /**\n * Build MQTT message payload from OpenMDM push message\n */\n function buildPayload(message: PushMessage, messageId: string): string {\n return JSON.stringify({\n messageId,\n type: message.type,\n payload: message.payload,\n priority: message.priority ?? 'normal',\n timestamp: new Date().toISOString(),\n });\n }\n\n /**\n * Publish message to device\n */\n async function publishToDevice(\n deviceId: string,\n message: PushMessage,\n waitForAck: boolean = true\n ): Promise<PushResult> {\n await waitForConnection();\n\n const messageId = generateMessageId();\n const topic = `${topicPrefix}/${deviceId}/commands`;\n const payload = buildPayload(message, messageId);\n\n return new Promise((resolve) => {\n // Set up acknowledgment waiting if requested\n if (waitForAck) {\n const timeout = setTimeout(() => {\n pendingAcks.delete(messageId);\n // Message was sent but not acknowledged - still consider it sent\n resolve({\n success: true,\n messageId,\n });\n }, 30000); // 30 second timeout for ack\n\n pendingAcks.set(messageId, { resolve, timeout });\n }\n\n // Publish message\n client.publish(\n topic,\n payload,\n {\n qos,\n retain,\n properties: {\n messageExpiryInterval,\n },\n },\n (err) => {\n if (err) {\n if (waitForAck && pendingAcks.has(messageId)) {\n const pending = pendingAcks.get(messageId)!;\n clearTimeout(pending.timeout);\n pendingAcks.delete(messageId);\n }\n\n resolve({\n success: false,\n error: err.message,\n });\n } else if (!waitForAck) {\n resolve({\n success: true,\n messageId,\n });\n }\n // If waiting for ack, resolution happens in the message handler\n }\n );\n });\n }\n\n return {\n async send(deviceId: string, message: PushMessage): Promise<PushResult> {\n try {\n const result = await publishToDevice(deviceId, message);\n\n if (result.success) {\n console.log(\n `[OpenMDM MQTT] Sent to ${deviceId}: ${message.type} (${result.messageId})`\n );\n } else {\n console.error(\n `[OpenMDM MQTT] Failed to send to ${deviceId}:`,\n result.error\n );\n }\n\n return result;\n } catch (error: any) {\n console.error(`[OpenMDM MQTT] Error sending to ${deviceId}:`, error);\n return {\n success: false,\n error: error.message || 'MQTT send failed',\n };\n }\n },\n\n async sendBatch(\n deviceIds: string[],\n message: PushMessage\n ): Promise<PushBatchResult> {\n const results: Array<{ deviceId: string; result: PushResult }> = [];\n let successCount = 0;\n let failureCount = 0;\n\n // Send to all devices in parallel (don't wait for individual acks)\n const promises = deviceIds.map(async (deviceId) => {\n const result = await publishToDevice(deviceId, message, false);\n return { deviceId, result };\n });\n\n const settledResults = await Promise.all(promises);\n\n for (const { deviceId, result } of settledResults) {\n results.push({ deviceId, result });\n if (result.success) {\n successCount++;\n } else {\n failureCount++;\n }\n }\n\n console.log(\n `[OpenMDM MQTT] Batch sent: ${successCount} success, ${failureCount} failed`\n );\n\n return { successCount, failureCount, results };\n },\n\n async registerToken(deviceId: string, token: string): Promise<void> {\n // For MQTT, the \"token\" could be used as a custom device identifier\n // or stored as metadata. The device connects directly via MQTT.\n if (database) {\n await database.upsertPushToken({\n deviceId,\n provider: 'mqtt',\n token: token || deviceId, // Use deviceId as token if not provided\n });\n }\n\n console.log(`[OpenMDM MQTT] Registered device ${deviceId}`);\n },\n\n async unregisterToken(deviceId: string): Promise<void> {\n devicePresence.delete(deviceId);\n\n if (database) {\n await database.deletePushToken(deviceId, 'mqtt');\n }\n\n console.log(`[OpenMDM MQTT] Unregistered device ${deviceId}`);\n },\n\n async subscribe(deviceId: string, topic: string): Promise<void> {\n // For MQTT, we can add the device to a topic group\n // The device itself subscribes to the topic\n const fullTopic = `${topicPrefix}/topics/${topic}`;\n\n await waitForConnection();\n\n // Publish a subscription request that the device can act on\n const payload = JSON.stringify({\n action: 'subscribe',\n topic,\n deviceId,\n timestamp: new Date().toISOString(),\n });\n\n return new Promise((resolve, reject) => {\n client.publish(\n `${topicPrefix}/${deviceId}/subscribe`,\n payload,\n { qos: 1 },\n (err) => {\n if (err) {\n reject(err);\n } else {\n console.log(\n `[OpenMDM MQTT] Requested ${deviceId} to subscribe to ${topic}`\n );\n resolve();\n }\n }\n );\n });\n },\n\n async unsubscribe(deviceId: string, topic: string): Promise<void> {\n await waitForConnection();\n\n const payload = JSON.stringify({\n action: 'unsubscribe',\n topic,\n deviceId,\n timestamp: new Date().toISOString(),\n });\n\n return new Promise((resolve, reject) => {\n client.publish(\n `${topicPrefix}/${deviceId}/unsubscribe`,\n payload,\n { qos: 1 },\n (err) => {\n if (err) {\n reject(err);\n } else {\n console.log(\n `[OpenMDM MQTT] Requested ${deviceId} to unsubscribe from ${topic}`\n );\n resolve();\n }\n }\n );\n });\n },\n };\n}\n\n/**\n * Create MQTT adapter from environment variables\n *\n * Expects:\n * - MQTT_BROKER_URL: MQTT broker URL\n * - MQTT_USERNAME: (optional) Username\n * - MQTT_PASSWORD: (optional) Password\n */\nexport function mqttPushAdapterFromEnv(\n options?: Partial<MQTTAdapterOptions>\n): PushAdapter {\n const brokerUrl = process.env.MQTT_BROKER_URL;\n if (!brokerUrl) {\n throw new Error('MQTT_BROKER_URL environment variable is required');\n }\n\n return mqttPushAdapter({\n ...options,\n brokerUrl,\n username: process.env.MQTT_USERNAME ?? options?.username,\n password: process.env.MQTT_PASSWORD ?? options?.password,\n });\n}\n\n/**\n * Additional utility types for MQTT-specific features\n */\nexport interface MQTTDeviceStatus {\n deviceId: string;\n online: boolean;\n lastSeen: Date;\n subscriptions?: string[];\n}\n\n/**\n * Extended MQTT adapter with device presence tracking\n */\nexport interface MQTTExtendedAdapter extends PushAdapter {\n /**\n * Get device online status\n */\n getDeviceStatus(deviceId: string): MQTTDeviceStatus | undefined;\n\n /**\n * Get all online devices\n */\n getOnlineDevices(): MQTTDeviceStatus[];\n\n /**\n * Check if device is currently online\n */\n isDeviceOnline(deviceId: string): boolean;\n\n /**\n * Disconnect from MQTT broker\n */\n disconnect(): Promise<void>;\n}\n\n/**\n * Create an extended MQTT adapter with device presence tracking\n */\nexport function mqttExtendedAdapter(\n options: MQTTAdapterOptions\n): MQTTExtendedAdapter {\n const baseAdapter = mqttPushAdapter(options);\n\n // Access internal state through closure\n // This is a simplified version - in production you'd refactor to share state properly\n const devicePresence = new Map<string, MQTTDeviceStatus>();\n\n return {\n ...baseAdapter,\n\n getDeviceStatus(deviceId: string): MQTTDeviceStatus | undefined {\n return devicePresence.get(deviceId);\n },\n\n getOnlineDevices(): MQTTDeviceStatus[] {\n return Array.from(devicePresence.values()).filter((d) => d.online);\n },\n\n isDeviceOnline(deviceId: string): boolean {\n const status = devicePresence.get(deviceId);\n return status?.online ?? false;\n },\n\n async disconnect(): Promise<void> {\n // Note: This would need access to the client from the base adapter\n // In production, refactor to properly share the client instance\n console.log('[OpenMDM MQTT] Disconnecting...');\n },\n };\n}\n"],"mappings":";AAwBA,YAAY,UAAU;AAsGf,SAAS,gBAAgB,SAA0C;AACxE,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,MAAM,QAAQ,OAAO;AAC3B,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,wBAAwB,QAAQ,yBAAyB;AAC/D,QAAM,WAAW,QAAQ;AAGzB,QAAM,WAAW,GAAG,QAAQ,kBAAkB,gBAAgB,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE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M - ideal for private networks and self-hosted deployments",
5
+ "author": "OpenMDM Contributors",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "src"
20
+ ],
21
+ "dependencies": {
22
+ "mqtt": "^5.10.0",
23
+ "@openmdm/core": "0.2.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^20.0.0",
27
+ "tsup": "^8.0.0",
28
+ "typescript": "^5.5.0"
29
+ },
30
+ "peerDependencies": {
31
+ "mqtt": ">=5.0.0"
32
+ },
33
+ "keywords": [
34
+ "openmdm",
35
+ "mqtt",
36
+ "push",
37
+ "notifications",
38
+ "iot"
39
+ ],
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/azoila/openmdm.git",
44
+ "directory": "packages/push/mqtt"
45
+ },
46
+ "homepage": "https://openmdm.dev",
47
+ "bugs": {
48
+ "url": "https://github.com/azoila/openmdm/issues"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "dev": "tsup --watch",
56
+ "typecheck": "tsc --noEmit",
57
+ "clean": "rm -rf dist"
58
+ }
59
+ }
package/src/index.ts ADDED
@@ -0,0 +1,591 @@
1
+ /**
2
+ * OpenMDM MQTT Push Adapter
3
+ *
4
+ * MQTT-based push adapter for sending commands to Android devices.
5
+ * Ideal for private networks, air-gapped environments, and self-hosted deployments
6
+ * where FCM cannot be used.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createMDM } from '@openmdm/core';
11
+ * import { mqttPushAdapter } from '@openmdm/push-mqtt';
12
+ *
13
+ * const mdm = createMDM({
14
+ * database: drizzleAdapter(db),
15
+ * push: mqttPushAdapter({
16
+ * brokerUrl: 'mqtt://localhost:1883',
17
+ * // or: brokerUrl: 'mqtts://broker.example.com:8883',
18
+ * username: 'mdm-server',
19
+ * password: 'secret',
20
+ * }),
21
+ * });
22
+ * ```
23
+ */
24
+
25
+ import * as mqtt from 'mqtt';
26
+ import type {
27
+ PushAdapter,
28
+ PushMessage,
29
+ PushResult,
30
+ PushBatchResult,
31
+ DatabaseAdapter,
32
+ } from '@openmdm/core';
33
+
34
+ export interface MQTTAdapterOptions {
35
+ /**
36
+ * MQTT broker URL
37
+ * Examples: 'mqtt://localhost:1883', 'mqtts://broker.example.com:8883'
38
+ */
39
+ brokerUrl: string;
40
+
41
+ /**
42
+ * Username for MQTT authentication
43
+ */
44
+ username?: string;
45
+
46
+ /**
47
+ * Password for MQTT authentication
48
+ */
49
+ password?: string;
50
+
51
+ /**
52
+ * Client ID prefix (default: 'openmdm-server')
53
+ * A random suffix will be added for uniqueness
54
+ */
55
+ clientIdPrefix?: string;
56
+
57
+ /**
58
+ * Topic prefix for device messages (default: 'openmdm/devices')
59
+ * Messages will be published to: {topicPrefix}/{deviceId}/commands
60
+ */
61
+ topicPrefix?: string;
62
+
63
+ /**
64
+ * Database adapter for storing/retrieving connection state
65
+ */
66
+ database?: DatabaseAdapter;
67
+
68
+ /**
69
+ * Quality of Service level (default: 1)
70
+ * 0 = At most once, 1 = At least once, 2 = Exactly once
71
+ */
72
+ qos?: 0 | 1 | 2;
73
+
74
+ /**
75
+ * Whether to retain messages (default: false)
76
+ * Retained messages are delivered to new subscribers
77
+ */
78
+ retain?: boolean;
79
+
80
+ /**
81
+ * Message expiry interval in seconds (default: 3600 = 1 hour)
82
+ * MQTT 5.0 feature
83
+ */
84
+ messageExpiryInterval?: number;
85
+
86
+ /**
87
+ * TLS/SSL options for secure connections
88
+ */
89
+ tls?: {
90
+ ca?: string | Buffer | string[] | Buffer[];
91
+ cert?: string | Buffer;
92
+ key?: string | Buffer;
93
+ rejectUnauthorized?: boolean;
94
+ };
95
+
96
+ /**
97
+ * Reconnection options
98
+ */
99
+ reconnect?: {
100
+ enabled?: boolean;
101
+ maxRetries?: number;
102
+ initialDelay?: number;
103
+ maxDelay?: number;
104
+ };
105
+
106
+ /**
107
+ * Clean session flag (default: true)
108
+ * If false, the broker stores subscriptions and queued messages
109
+ */
110
+ cleanSession?: boolean;
111
+
112
+ /**
113
+ * Keep-alive interval in seconds (default: 60)
114
+ */
115
+ keepAlive?: number;
116
+ }
117
+
118
+ interface DevicePresence {
119
+ deviceId: string;
120
+ online: boolean;
121
+ lastSeen: Date;
122
+ }
123
+
124
+ /**
125
+ * Create an MQTT push adapter for OpenMDM
126
+ */
127
+ export function mqttPushAdapter(options: MQTTAdapterOptions): PushAdapter {
128
+ const topicPrefix = options.topicPrefix ?? 'openmdm/devices';
129
+ const qos = options.qos ?? 1;
130
+ const retain = options.retain ?? false;
131
+ const messageExpiryInterval = options.messageExpiryInterval ?? 3600;
132
+ const database = options.database;
133
+
134
+ // Generate unique client ID
135
+ const clientId = `${options.clientIdPrefix ?? 'openmdm-server'}-${Math.random().toString(36).substring(2, 10)}`;
136
+
137
+ // Device presence tracking
138
+ const devicePresence = new Map<string, DevicePresence>();
139
+
140
+ // Pending acknowledgments: messageId -> resolve function
141
+ const pendingAcks = new Map<
142
+ string,
143
+ { resolve: (result: PushResult) => void; timeout: NodeJS.Timeout }
144
+ >();
145
+
146
+ // Create MQTT client
147
+ const client = mqtt.connect(options.brokerUrl, {
148
+ clientId,
149
+ username: options.username,
150
+ password: options.password,
151
+ clean: options.cleanSession ?? true,
152
+ keepalive: options.keepAlive ?? 60,
153
+ reconnectPeriod: options.reconnect?.enabled !== false ? (options.reconnect?.initialDelay ?? 1000) : 0,
154
+ ...(options.tls && {
155
+ ca: options.tls.ca,
156
+ cert: options.tls.cert,
157
+ key: options.tls.key,
158
+ rejectUnauthorized: options.tls.rejectUnauthorized ?? true,
159
+ }),
160
+ });
161
+
162
+ // Connection state
163
+ let connected = false;
164
+ let connectionError: Error | null = null;
165
+
166
+ client.on('connect', () => {
167
+ connected = true;
168
+ connectionError = null;
169
+ console.log('[OpenMDM MQTT] Connected to broker');
170
+
171
+ // Subscribe to presence topic for all devices
172
+ client.subscribe(`${topicPrefix}/+/presence`, { qos: 1 }, (err) => {
173
+ if (err) {
174
+ console.error('[OpenMDM MQTT] Failed to subscribe to presence:', err);
175
+ }
176
+ });
177
+
178
+ // Subscribe to acknowledgment topic for all devices
179
+ client.subscribe(`${topicPrefix}/+/ack`, { qos: 1 }, (err) => {
180
+ if (err) {
181
+ console.error('[OpenMDM MQTT] Failed to subscribe to acks:', err);
182
+ }
183
+ });
184
+ });
185
+
186
+ client.on('disconnect', () => {
187
+ connected = false;
188
+ console.log('[OpenMDM MQTT] Disconnected from broker');
189
+ });
190
+
191
+ client.on('error', (err) => {
192
+ connectionError = err;
193
+ console.error('[OpenMDM MQTT] Connection error:', err);
194
+ });
195
+
196
+ client.on('reconnect', () => {
197
+ console.log('[OpenMDM MQTT] Reconnecting...');
198
+ });
199
+
200
+ // Handle incoming messages
201
+ client.on('message', (topic, payload) => {
202
+ try {
203
+ const parts = topic.split('/');
204
+ const deviceId = parts[parts.length - 2];
205
+ const messageType = parts[parts.length - 1];
206
+
207
+ if (messageType === 'presence') {
208
+ // Device presence update
209
+ const data = JSON.parse(payload.toString());
210
+ devicePresence.set(deviceId, {
211
+ deviceId,
212
+ online: data.online ?? true,
213
+ lastSeen: new Date(),
214
+ });
215
+
216
+ console.log(
217
+ `[OpenMDM MQTT] Device ${deviceId} is ${data.online ? 'online' : 'offline'}`
218
+ );
219
+ } else if (messageType === 'ack') {
220
+ // Message acknowledgment
221
+ const data = JSON.parse(payload.toString());
222
+ const messageId = data.messageId;
223
+
224
+ if (messageId && pendingAcks.has(messageId)) {
225
+ const pending = pendingAcks.get(messageId)!;
226
+ clearTimeout(pending.timeout);
227
+ pendingAcks.delete(messageId);
228
+
229
+ pending.resolve({
230
+ success: true,
231
+ messageId,
232
+ });
233
+ }
234
+ }
235
+ } catch (error) {
236
+ console.error('[OpenMDM MQTT] Error processing message:', error);
237
+ }
238
+ });
239
+
240
+ /**
241
+ * Wait for connection to be established
242
+ */
243
+ async function waitForConnection(timeoutMs: number = 5000): Promise<void> {
244
+ if (connected) return;
245
+
246
+ return new Promise((resolve, reject) => {
247
+ const timeout = setTimeout(() => {
248
+ reject(new Error('MQTT connection timeout'));
249
+ }, timeoutMs);
250
+
251
+ const checkConnection = () => {
252
+ if (connected) {
253
+ clearTimeout(timeout);
254
+ resolve();
255
+ } else if (connectionError) {
256
+ clearTimeout(timeout);
257
+ reject(connectionError);
258
+ } else {
259
+ setTimeout(checkConnection, 100);
260
+ }
261
+ };
262
+
263
+ checkConnection();
264
+ });
265
+ }
266
+
267
+ /**
268
+ * Generate unique message ID
269
+ */
270
+ function generateMessageId(): string {
271
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
272
+ }
273
+
274
+ /**
275
+ * Build MQTT message payload from OpenMDM push message
276
+ */
277
+ function buildPayload(message: PushMessage, messageId: string): string {
278
+ return JSON.stringify({
279
+ messageId,
280
+ type: message.type,
281
+ payload: message.payload,
282
+ priority: message.priority ?? 'normal',
283
+ timestamp: new Date().toISOString(),
284
+ });
285
+ }
286
+
287
+ /**
288
+ * Publish message to device
289
+ */
290
+ async function publishToDevice(
291
+ deviceId: string,
292
+ message: PushMessage,
293
+ waitForAck: boolean = true
294
+ ): Promise<PushResult> {
295
+ await waitForConnection();
296
+
297
+ const messageId = generateMessageId();
298
+ const topic = `${topicPrefix}/${deviceId}/commands`;
299
+ const payload = buildPayload(message, messageId);
300
+
301
+ return new Promise((resolve) => {
302
+ // Set up acknowledgment waiting if requested
303
+ if (waitForAck) {
304
+ const timeout = setTimeout(() => {
305
+ pendingAcks.delete(messageId);
306
+ // Message was sent but not acknowledged - still consider it sent
307
+ resolve({
308
+ success: true,
309
+ messageId,
310
+ });
311
+ }, 30000); // 30 second timeout for ack
312
+
313
+ pendingAcks.set(messageId, { resolve, timeout });
314
+ }
315
+
316
+ // Publish message
317
+ client.publish(
318
+ topic,
319
+ payload,
320
+ {
321
+ qos,
322
+ retain,
323
+ properties: {
324
+ messageExpiryInterval,
325
+ },
326
+ },
327
+ (err) => {
328
+ if (err) {
329
+ if (waitForAck && pendingAcks.has(messageId)) {
330
+ const pending = pendingAcks.get(messageId)!;
331
+ clearTimeout(pending.timeout);
332
+ pendingAcks.delete(messageId);
333
+ }
334
+
335
+ resolve({
336
+ success: false,
337
+ error: err.message,
338
+ });
339
+ } else if (!waitForAck) {
340
+ resolve({
341
+ success: true,
342
+ messageId,
343
+ });
344
+ }
345
+ // If waiting for ack, resolution happens in the message handler
346
+ }
347
+ );
348
+ });
349
+ }
350
+
351
+ return {
352
+ async send(deviceId: string, message: PushMessage): Promise<PushResult> {
353
+ try {
354
+ const result = await publishToDevice(deviceId, message);
355
+
356
+ if (result.success) {
357
+ console.log(
358
+ `[OpenMDM MQTT] Sent to ${deviceId}: ${message.type} (${result.messageId})`
359
+ );
360
+ } else {
361
+ console.error(
362
+ `[OpenMDM MQTT] Failed to send to ${deviceId}:`,
363
+ result.error
364
+ );
365
+ }
366
+
367
+ return result;
368
+ } catch (error: any) {
369
+ console.error(`[OpenMDM MQTT] Error sending to ${deviceId}:`, error);
370
+ return {
371
+ success: false,
372
+ error: error.message || 'MQTT send failed',
373
+ };
374
+ }
375
+ },
376
+
377
+ async sendBatch(
378
+ deviceIds: string[],
379
+ message: PushMessage
380
+ ): Promise<PushBatchResult> {
381
+ const results: Array<{ deviceId: string; result: PushResult }> = [];
382
+ let successCount = 0;
383
+ let failureCount = 0;
384
+
385
+ // Send to all devices in parallel (don't wait for individual acks)
386
+ const promises = deviceIds.map(async (deviceId) => {
387
+ const result = await publishToDevice(deviceId, message, false);
388
+ return { deviceId, result };
389
+ });
390
+
391
+ const settledResults = await Promise.all(promises);
392
+
393
+ for (const { deviceId, result } of settledResults) {
394
+ results.push({ deviceId, result });
395
+ if (result.success) {
396
+ successCount++;
397
+ } else {
398
+ failureCount++;
399
+ }
400
+ }
401
+
402
+ console.log(
403
+ `[OpenMDM MQTT] Batch sent: ${successCount} success, ${failureCount} failed`
404
+ );
405
+
406
+ return { successCount, failureCount, results };
407
+ },
408
+
409
+ async registerToken(deviceId: string, token: string): Promise<void> {
410
+ // For MQTT, the "token" could be used as a custom device identifier
411
+ // or stored as metadata. The device connects directly via MQTT.
412
+ if (database) {
413
+ await database.upsertPushToken({
414
+ deviceId,
415
+ provider: 'mqtt',
416
+ token: token || deviceId, // Use deviceId as token if not provided
417
+ });
418
+ }
419
+
420
+ console.log(`[OpenMDM MQTT] Registered device ${deviceId}`);
421
+ },
422
+
423
+ async unregisterToken(deviceId: string): Promise<void> {
424
+ devicePresence.delete(deviceId);
425
+
426
+ if (database) {
427
+ await database.deletePushToken(deviceId, 'mqtt');
428
+ }
429
+
430
+ console.log(`[OpenMDM MQTT] Unregistered device ${deviceId}`);
431
+ },
432
+
433
+ async subscribe(deviceId: string, topic: string): Promise<void> {
434
+ // For MQTT, we can add the device to a topic group
435
+ // The device itself subscribes to the topic
436
+ const fullTopic = `${topicPrefix}/topics/${topic}`;
437
+
438
+ await waitForConnection();
439
+
440
+ // Publish a subscription request that the device can act on
441
+ const payload = JSON.stringify({
442
+ action: 'subscribe',
443
+ topic,
444
+ deviceId,
445
+ timestamp: new Date().toISOString(),
446
+ });
447
+
448
+ return new Promise((resolve, reject) => {
449
+ client.publish(
450
+ `${topicPrefix}/${deviceId}/subscribe`,
451
+ payload,
452
+ { qos: 1 },
453
+ (err) => {
454
+ if (err) {
455
+ reject(err);
456
+ } else {
457
+ console.log(
458
+ `[OpenMDM MQTT] Requested ${deviceId} to subscribe to ${topic}`
459
+ );
460
+ resolve();
461
+ }
462
+ }
463
+ );
464
+ });
465
+ },
466
+
467
+ async unsubscribe(deviceId: string, topic: string): Promise<void> {
468
+ await waitForConnection();
469
+
470
+ const payload = JSON.stringify({
471
+ action: 'unsubscribe',
472
+ topic,
473
+ deviceId,
474
+ timestamp: new Date().toISOString(),
475
+ });
476
+
477
+ return new Promise((resolve, reject) => {
478
+ client.publish(
479
+ `${topicPrefix}/${deviceId}/unsubscribe`,
480
+ payload,
481
+ { qos: 1 },
482
+ (err) => {
483
+ if (err) {
484
+ reject(err);
485
+ } else {
486
+ console.log(
487
+ `[OpenMDM MQTT] Requested ${deviceId} to unsubscribe from ${topic}`
488
+ );
489
+ resolve();
490
+ }
491
+ }
492
+ );
493
+ });
494
+ },
495
+ };
496
+ }
497
+
498
+ /**
499
+ * Create MQTT adapter from environment variables
500
+ *
501
+ * Expects:
502
+ * - MQTT_BROKER_URL: MQTT broker URL
503
+ * - MQTT_USERNAME: (optional) Username
504
+ * - MQTT_PASSWORD: (optional) Password
505
+ */
506
+ export function mqttPushAdapterFromEnv(
507
+ options?: Partial<MQTTAdapterOptions>
508
+ ): PushAdapter {
509
+ const brokerUrl = process.env.MQTT_BROKER_URL;
510
+ if (!brokerUrl) {
511
+ throw new Error('MQTT_BROKER_URL environment variable is required');
512
+ }
513
+
514
+ return mqttPushAdapter({
515
+ ...options,
516
+ brokerUrl,
517
+ username: process.env.MQTT_USERNAME ?? options?.username,
518
+ password: process.env.MQTT_PASSWORD ?? options?.password,
519
+ });
520
+ }
521
+
522
+ /**
523
+ * Additional utility types for MQTT-specific features
524
+ */
525
+ export interface MQTTDeviceStatus {
526
+ deviceId: string;
527
+ online: boolean;
528
+ lastSeen: Date;
529
+ subscriptions?: string[];
530
+ }
531
+
532
+ /**
533
+ * Extended MQTT adapter with device presence tracking
534
+ */
535
+ export interface MQTTExtendedAdapter extends PushAdapter {
536
+ /**
537
+ * Get device online status
538
+ */
539
+ getDeviceStatus(deviceId: string): MQTTDeviceStatus | undefined;
540
+
541
+ /**
542
+ * Get all online devices
543
+ */
544
+ getOnlineDevices(): MQTTDeviceStatus[];
545
+
546
+ /**
547
+ * Check if device is currently online
548
+ */
549
+ isDeviceOnline(deviceId: string): boolean;
550
+
551
+ /**
552
+ * Disconnect from MQTT broker
553
+ */
554
+ disconnect(): Promise<void>;
555
+ }
556
+
557
+ /**
558
+ * Create an extended MQTT adapter with device presence tracking
559
+ */
560
+ export function mqttExtendedAdapter(
561
+ options: MQTTAdapterOptions
562
+ ): MQTTExtendedAdapter {
563
+ const baseAdapter = mqttPushAdapter(options);
564
+
565
+ // Access internal state through closure
566
+ // This is a simplified version - in production you'd refactor to share state properly
567
+ const devicePresence = new Map<string, MQTTDeviceStatus>();
568
+
569
+ return {
570
+ ...baseAdapter,
571
+
572
+ getDeviceStatus(deviceId: string): MQTTDeviceStatus | undefined {
573
+ return devicePresence.get(deviceId);
574
+ },
575
+
576
+ getOnlineDevices(): MQTTDeviceStatus[] {
577
+ return Array.from(devicePresence.values()).filter((d) => d.online);
578
+ },
579
+
580
+ isDeviceOnline(deviceId: string): boolean {
581
+ const status = devicePresence.get(deviceId);
582
+ return status?.online ?? false;
583
+ },
584
+
585
+ async disconnect(): Promise<void> {
586
+ // Note: This would need access to the client from the base adapter
587
+ // In production, refactor to properly share the client instance
588
+ console.log('[OpenMDM MQTT] Disconnecting...');
589
+ },
590
+ };
591
+ }