@vita-mojo/mqtt 1.0.6 → 1.0.7

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/client.cjs.js CHANGED
@@ -11,174 +11,183 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
11
11
  var mqtt__default = /*#__PURE__*/_interopDefaultLegacy(mqtt);
12
12
 
13
13
  const mqttContext = react.createContext({
14
- mqttClient: null,
15
- connected: false,
16
- logger: {
17
- log: (...args) => console.log('[MQTT]', ...args),
18
- error: (...args) => console.error('[MQTT]', ...args),
19
- warn: (...args) => console.warn('[MQTT]', ...args),
20
- },
14
+ mqttClient: null,
15
+ connected: false,
16
+ logger: {
17
+ log: (...args) => console.log('[MQTT]', ...args),
18
+ error: (...args) => console.error('[MQTT]', ...args),
19
+ warn: (...args) => console.warn('[MQTT]', ...args)
20
+ }
21
21
  });
22
- function MqttProvider({ children, url, username, password, storeUUID, tenantUUID, sessionDuration, clientId, extraOpts, logger = {
22
+ function MqttProvider({
23
+ children,
24
+ url,
25
+ username,
26
+ password,
27
+ storeUUID,
28
+ tenantUUID,
29
+ sessionDuration,
30
+ clientId,
31
+ extraOpts,
32
+ logger = {
23
33
  log: (...args) => console.log('[MQTT]', ...args),
24
34
  error: (...args) => console.error('[MQTT]', ...args),
25
- warn: (...args) => console.warn('[MQTT]', ...args),
26
- }, }) {
27
- const [client, setClient] = react.useState(null);
28
- const [connected, setConnected] = react.useState(false);
29
- react.useEffect(() => {
30
- const missingVariables = [
31
- !username && 'username',
32
- !password && 'password',
33
- !storeUUID && 'storeUUID',
34
- !tenantUUID && 'tenantUUID',
35
- !url && 'url',
36
- ].filter(Boolean);
37
- if (missingVariables.length > 0) {
38
- logger.warn(`MQTT connection will not be established: missing ${missingVariables.join(', ')}`);
39
- return;
40
- }
41
- if (sessionDuration && !clientId) {
42
- logger.warn(`MQTT connection will not be established: session duration is set but clientId is missing. We need clientId to keep the session persistent`);
43
- return;
44
- }
45
- const connectionOptions = Object.assign({ username: typeof username === 'function' ? username() : username, password: typeof password === 'function' ? password() : password, protocolVersion: 5, clean: true, keepalive: 10, connectTimeout: 15 * 1000 }, extraOpts);
46
- if (sessionDuration) {
47
- connectionOptions.clean = false;
48
- connectionOptions.clientId =
49
- typeof clientId === 'function' ? clientId() : clientId;
50
- connectionOptions.properties = {
51
- sessionExpiryInterval: sessionDuration,
52
- };
53
- }
54
- connectionOptions.properties = connectionOptions.properties || {};
55
- connectionOptions.properties.userProperties =
56
- connectionOptions.properties.userProperties || {};
57
- connectionOptions.properties.userProperties['store'] = storeUUID;
58
- connectionOptions.properties.userProperties['tenant'] = tenantUUID;
59
- const client = mqtt__default["default"].connect(url, connectionOptions);
60
- client.on('connect', (connack) => {
61
- if (connack.sessionPresent) {
62
- logger.log('MQTT connected with existing session');
63
- }
64
- else {
65
- logger.log('MQTT connected with new session');
66
- }
67
- setConnected(client.connected);
68
- });
69
- client.on('error', (error) => {
70
- logger.error('MQTT connection error:', error);
71
- setConnected(client.connected);
72
- });
73
- client.on('close', () => {
74
- logger.log('MQTT connection closed');
75
- setConnected(client.connected);
76
- });
77
- client.on('offline', () => {
78
- logger.log('MQTT client is offline');
79
- setConnected(client.connected);
80
- });
81
- client.on('reconnect', (...args) => {
82
- logger.log('MQTT client is reconnecting', ...args);
83
- setConnected(client.connected);
84
- });
85
- client.on('end', () => {
86
- logger.log('MQTT client ended');
87
- setConnected(client.connected);
88
- });
89
- setClient(client);
90
- return () => {
91
- const c = client;
92
- setClient(null); // we need to set state to null before disconnecting to avoid memory leaks and setting state after unmount
93
- c.end(true, () => {
94
- logger.log('MQTT client disconnected');
95
- });
96
- };
97
- }, [
98
- password,
99
- storeUUID,
100
- tenantUUID,
101
- url,
102
- username,
103
- extraOpts,
104
- sessionDuration,
105
- clientId,
106
- logger,
107
- ]);
108
- const value = react.useMemo(() => {
109
- return {
110
- mqttClient: client,
111
- connected,
112
- logger,
113
- };
114
- }, [client, connected]);
115
- return jsxRuntime.jsx(mqttContext.Provider, { value: value, children: children });
35
+ warn: (...args) => console.warn('[MQTT]', ...args)
36
+ }
37
+ }) {
38
+ const [client, setClient] = react.useState(null);
39
+ const [connected, setConnected] = react.useState(false);
40
+ react.useEffect(() => {
41
+ const missingVariables = [!username && 'username', !password && 'password', !storeUUID && 'storeUUID', !tenantUUID && 'tenantUUID', !url && 'url'].filter(Boolean);
42
+ if (missingVariables.length > 0) {
43
+ logger.warn(`MQTT connection will not be established: missing ${missingVariables.join(', ')}`);
44
+ return;
45
+ }
46
+ if (sessionDuration && !clientId) {
47
+ logger.warn(`MQTT connection will not be established: session duration is set but clientId is missing. We need clientId to keep the session persistent`);
48
+ return;
49
+ }
50
+ const connectionOptions = Object.assign({
51
+ username: typeof username === 'function' ? username() : username,
52
+ password: typeof password === 'function' ? password() : password,
53
+ protocolVersion: 5,
54
+ clean: true,
55
+ keepalive: 10,
56
+ connectTimeout: 15 * 1000
57
+ }, extraOpts);
58
+ if (sessionDuration) {
59
+ connectionOptions.clean = false;
60
+ connectionOptions.clientId = typeof clientId === 'function' ? clientId() : clientId;
61
+ connectionOptions.properties = {
62
+ sessionExpiryInterval: sessionDuration
63
+ };
64
+ }
65
+ connectionOptions.properties = connectionOptions.properties || {};
66
+ connectionOptions.properties.userProperties = connectionOptions.properties.userProperties || {};
67
+ connectionOptions.properties.userProperties['store'] = storeUUID;
68
+ connectionOptions.properties.userProperties['tenant'] = tenantUUID;
69
+ const client = mqtt__default["default"].connect(url, connectionOptions);
70
+ client.on('connect', connack => {
71
+ if (connack.sessionPresent) {
72
+ logger.log('MQTT connected with existing session');
73
+ } else {
74
+ logger.log('MQTT connected with new session');
75
+ }
76
+ setConnected(client.connected);
77
+ });
78
+ client.on('error', error => {
79
+ logger.error('MQTT connection error:', error);
80
+ setConnected(client.connected);
81
+ });
82
+ client.on('close', () => {
83
+ logger.log('MQTT connection closed');
84
+ setConnected(client.connected);
85
+ });
86
+ client.on('offline', () => {
87
+ logger.log('MQTT client is offline');
88
+ setConnected(client.connected);
89
+ });
90
+ client.on('reconnect', (...args) => {
91
+ logger.log('MQTT client is reconnecting', ...args);
92
+ setConnected(client.connected);
93
+ });
94
+ client.on('end', () => {
95
+ logger.log('MQTT client ended');
96
+ setConnected(client.connected);
97
+ });
98
+ setClient(client);
99
+ return () => {
100
+ const c = client;
101
+ setClient(null); // we need to set state to null before disconnecting to avoid memory leaks and setting state after unmount
102
+ c.end(true, () => {
103
+ logger.log('MQTT client disconnected');
104
+ });
105
+ };
106
+ }, [password, storeUUID, tenantUUID, url, username, extraOpts, sessionDuration, clientId, logger]);
107
+ const value = react.useMemo(() => {
108
+ return {
109
+ mqttClient: client,
110
+ connected,
111
+ logger
112
+ };
113
+ }, [client, connected]);
114
+ return jsxRuntime.jsx(mqttContext.Provider, {
115
+ value: value,
116
+ children: children
117
+ });
116
118
  }
117
119
  function useMqtt() {
118
- const context = react.useContext(mqttContext);
119
- return context;
120
+ const context = react.useContext(mqttContext);
121
+ return context;
120
122
  }
121
123
 
122
- function MQTTReconnect({ onReconnect }) {
123
- const { mqttClient } = useMqtt();
124
- const previouslyConnected = react.useRef(false);
125
- react.useEffect(() => {
126
- if (!mqttClient)
127
- return;
128
- const handler = (connack) => {
129
- // skip firing this event on initial connect
130
- if (!previouslyConnected.current) {
131
- previouslyConnected.current = true;
132
- return;
133
- }
134
- if (!connack.sessionPresent) {
135
- onReconnect === null || onReconnect === void 0 ? void 0 : onReconnect();
136
- }
137
- };
138
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.on('connect', handler);
139
- return () => {
140
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('connect', handler);
141
- };
142
- }, [mqttClient, onReconnect]);
143
- return null;
124
+ function MQTTReconnect({
125
+ onReconnect
126
+ }) {
127
+ const {
128
+ mqttClient
129
+ } = useMqtt();
130
+ const previouslyConnected = react.useRef(false);
131
+ react.useEffect(() => {
132
+ if (!mqttClient) return;
133
+ const handler = connack => {
134
+ // skip firing this event on initial connect
135
+ if (!previouslyConnected.current) {
136
+ previouslyConnected.current = true;
137
+ return;
138
+ }
139
+ if (!connack.sessionPresent) {
140
+ onReconnect === null || onReconnect === void 0 ? void 0 : onReconnect();
141
+ }
142
+ };
143
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.on('connect', handler);
144
+ return () => {
145
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('connect', handler);
146
+ };
147
+ }, [mqttClient, onReconnect]);
148
+ return null;
144
149
  }
145
150
 
146
- function MqttTopic({ topic, qos = 1, onChange }) {
147
- const { mqttClient, logger } = useMqtt();
148
- react.useEffect(() => {
149
- if (!mqttClient)
150
- return;
151
- mqttClient.subscribe(topic, { qos }, (err) => {
152
- if (err) {
153
- logger === null || logger === void 0 ? void 0 : logger.error(`Failed to subscribe to topic ${topic}:`, err);
154
- }
155
- else {
156
- logger === null || logger === void 0 ? void 0 : logger.log(`Subscribed to topic ${topic}`);
157
- }
158
- });
159
- const handler = (msgTopic, message) => {
160
- if (msgTopic !== topic)
161
- return;
162
- try {
163
- const payload = JSON.parse(message.toString());
164
- onChange === null || onChange === void 0 ? void 0 : onChange(payload);
165
- }
166
- catch (error) {
167
- logger === null || logger === void 0 ? void 0 : logger.error(`Failed to parse message for topic ${topic}:`, error);
168
- }
169
- };
170
- mqttClient.on('message', handler);
171
- return () => {
172
- try {
173
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
174
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('message', handler);
175
- }
176
- catch (error) {
177
- logger === null || logger === void 0 ? void 0 : logger.error(`Failed to unsubscribe and remove listener from topic ${topic}:`, error);
178
- }
179
- };
180
- }, [mqttClient, onChange, qos, topic]);
181
- return null;
151
+ function MqttTopic({
152
+ topic,
153
+ qos = 1,
154
+ onChange
155
+ }) {
156
+ const {
157
+ mqttClient,
158
+ logger
159
+ } = useMqtt();
160
+ react.useEffect(() => {
161
+ if (!mqttClient) return;
162
+ mqttClient.subscribe(topic, {
163
+ qos
164
+ }, err => {
165
+ if (err) {
166
+ logger === null || logger === void 0 ? void 0 : logger.error(`Failed to subscribe to topic ${topic}:`, err);
167
+ } else {
168
+ logger === null || logger === void 0 ? void 0 : logger.log(`Subscribed to topic ${topic}`);
169
+ }
170
+ });
171
+ const handler = (msgTopic, message) => {
172
+ if (msgTopic !== topic) return;
173
+ try {
174
+ const payload = JSON.parse(message.toString());
175
+ onChange === null || onChange === void 0 ? void 0 : onChange(payload);
176
+ } catch (error) {
177
+ logger === null || logger === void 0 ? void 0 : logger.error(`Failed to parse message for topic ${topic}:`, error);
178
+ }
179
+ };
180
+ mqttClient.on('message', handler);
181
+ return () => {
182
+ try {
183
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
184
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('message', handler);
185
+ } catch (error) {
186
+ logger === null || logger === void 0 ? void 0 : logger.error(`Failed to unsubscribe and remove listener from topic ${topic}:`, error);
187
+ }
188
+ };
189
+ }, [mqttClient, onChange, qos, topic]);
190
+ return null;
182
191
  }
183
192
 
184
193
  exports.MQTTReconnect = MQTTReconnect;
package/client.esm.js CHANGED
@@ -3,174 +3,183 @@ import mqtt from 'mqtt';
3
3
  import { createContext, useState, useEffect, useMemo, useContext, useRef } from 'react';
4
4
 
5
5
  const mqttContext = createContext({
6
- mqttClient: null,
7
- connected: false,
8
- logger: {
9
- log: (...args) => console.log('[MQTT]', ...args),
10
- error: (...args) => console.error('[MQTT]', ...args),
11
- warn: (...args) => console.warn('[MQTT]', ...args),
12
- },
6
+ mqttClient: null,
7
+ connected: false,
8
+ logger: {
9
+ log: (...args) => console.log('[MQTT]', ...args),
10
+ error: (...args) => console.error('[MQTT]', ...args),
11
+ warn: (...args) => console.warn('[MQTT]', ...args)
12
+ }
13
13
  });
14
- function MqttProvider({ children, url, username, password, storeUUID, tenantUUID, sessionDuration, clientId, extraOpts, logger = {
14
+ function MqttProvider({
15
+ children,
16
+ url,
17
+ username,
18
+ password,
19
+ storeUUID,
20
+ tenantUUID,
21
+ sessionDuration,
22
+ clientId,
23
+ extraOpts,
24
+ logger = {
15
25
  log: (...args) => console.log('[MQTT]', ...args),
16
26
  error: (...args) => console.error('[MQTT]', ...args),
17
- warn: (...args) => console.warn('[MQTT]', ...args),
18
- }, }) {
19
- const [client, setClient] = useState(null);
20
- const [connected, setConnected] = useState(false);
21
- useEffect(() => {
22
- const missingVariables = [
23
- !username && 'username',
24
- !password && 'password',
25
- !storeUUID && 'storeUUID',
26
- !tenantUUID && 'tenantUUID',
27
- !url && 'url',
28
- ].filter(Boolean);
29
- if (missingVariables.length > 0) {
30
- logger.warn(`MQTT connection will not be established: missing ${missingVariables.join(', ')}`);
31
- return;
32
- }
33
- if (sessionDuration && !clientId) {
34
- logger.warn(`MQTT connection will not be established: session duration is set but clientId is missing. We need clientId to keep the session persistent`);
35
- return;
36
- }
37
- const connectionOptions = Object.assign({ username: typeof username === 'function' ? username() : username, password: typeof password === 'function' ? password() : password, protocolVersion: 5, clean: true, keepalive: 10, connectTimeout: 15 * 1000 }, extraOpts);
38
- if (sessionDuration) {
39
- connectionOptions.clean = false;
40
- connectionOptions.clientId =
41
- typeof clientId === 'function' ? clientId() : clientId;
42
- connectionOptions.properties = {
43
- sessionExpiryInterval: sessionDuration,
44
- };
45
- }
46
- connectionOptions.properties = connectionOptions.properties || {};
47
- connectionOptions.properties.userProperties =
48
- connectionOptions.properties.userProperties || {};
49
- connectionOptions.properties.userProperties['store'] = storeUUID;
50
- connectionOptions.properties.userProperties['tenant'] = tenantUUID;
51
- const client = mqtt.connect(url, connectionOptions);
52
- client.on('connect', (connack) => {
53
- if (connack.sessionPresent) {
54
- logger.log('MQTT connected with existing session');
55
- }
56
- else {
57
- logger.log('MQTT connected with new session');
58
- }
59
- setConnected(client.connected);
60
- });
61
- client.on('error', (error) => {
62
- logger.error('MQTT connection error:', error);
63
- setConnected(client.connected);
64
- });
65
- client.on('close', () => {
66
- logger.log('MQTT connection closed');
67
- setConnected(client.connected);
68
- });
69
- client.on('offline', () => {
70
- logger.log('MQTT client is offline');
71
- setConnected(client.connected);
72
- });
73
- client.on('reconnect', (...args) => {
74
- logger.log('MQTT client is reconnecting', ...args);
75
- setConnected(client.connected);
76
- });
77
- client.on('end', () => {
78
- logger.log('MQTT client ended');
79
- setConnected(client.connected);
80
- });
81
- setClient(client);
82
- return () => {
83
- const c = client;
84
- setClient(null); // we need to set state to null before disconnecting to avoid memory leaks and setting state after unmount
85
- c.end(true, () => {
86
- logger.log('MQTT client disconnected');
87
- });
88
- };
89
- }, [
90
- password,
91
- storeUUID,
92
- tenantUUID,
93
- url,
94
- username,
95
- extraOpts,
96
- sessionDuration,
97
- clientId,
98
- logger,
99
- ]);
100
- const value = useMemo(() => {
101
- return {
102
- mqttClient: client,
103
- connected,
104
- logger,
105
- };
106
- }, [client, connected]);
107
- return jsx(mqttContext.Provider, { value: value, children: children });
27
+ warn: (...args) => console.warn('[MQTT]', ...args)
28
+ }
29
+ }) {
30
+ const [client, setClient] = useState(null);
31
+ const [connected, setConnected] = useState(false);
32
+ useEffect(() => {
33
+ const missingVariables = [!username && 'username', !password && 'password', !storeUUID && 'storeUUID', !tenantUUID && 'tenantUUID', !url && 'url'].filter(Boolean);
34
+ if (missingVariables.length > 0) {
35
+ logger.warn(`MQTT connection will not be established: missing ${missingVariables.join(', ')}`);
36
+ return;
37
+ }
38
+ if (sessionDuration && !clientId) {
39
+ logger.warn(`MQTT connection will not be established: session duration is set but clientId is missing. We need clientId to keep the session persistent`);
40
+ return;
41
+ }
42
+ const connectionOptions = Object.assign({
43
+ username: typeof username === 'function' ? username() : username,
44
+ password: typeof password === 'function' ? password() : password,
45
+ protocolVersion: 5,
46
+ clean: true,
47
+ keepalive: 10,
48
+ connectTimeout: 15 * 1000
49
+ }, extraOpts);
50
+ if (sessionDuration) {
51
+ connectionOptions.clean = false;
52
+ connectionOptions.clientId = typeof clientId === 'function' ? clientId() : clientId;
53
+ connectionOptions.properties = {
54
+ sessionExpiryInterval: sessionDuration
55
+ };
56
+ }
57
+ connectionOptions.properties = connectionOptions.properties || {};
58
+ connectionOptions.properties.userProperties = connectionOptions.properties.userProperties || {};
59
+ connectionOptions.properties.userProperties['store'] = storeUUID;
60
+ connectionOptions.properties.userProperties['tenant'] = tenantUUID;
61
+ const client = mqtt.connect(url, connectionOptions);
62
+ client.on('connect', connack => {
63
+ if (connack.sessionPresent) {
64
+ logger.log('MQTT connected with existing session');
65
+ } else {
66
+ logger.log('MQTT connected with new session');
67
+ }
68
+ setConnected(client.connected);
69
+ });
70
+ client.on('error', error => {
71
+ logger.error('MQTT connection error:', error);
72
+ setConnected(client.connected);
73
+ });
74
+ client.on('close', () => {
75
+ logger.log('MQTT connection closed');
76
+ setConnected(client.connected);
77
+ });
78
+ client.on('offline', () => {
79
+ logger.log('MQTT client is offline');
80
+ setConnected(client.connected);
81
+ });
82
+ client.on('reconnect', (...args) => {
83
+ logger.log('MQTT client is reconnecting', ...args);
84
+ setConnected(client.connected);
85
+ });
86
+ client.on('end', () => {
87
+ logger.log('MQTT client ended');
88
+ setConnected(client.connected);
89
+ });
90
+ setClient(client);
91
+ return () => {
92
+ const c = client;
93
+ setClient(null); // we need to set state to null before disconnecting to avoid memory leaks and setting state after unmount
94
+ c.end(true, () => {
95
+ logger.log('MQTT client disconnected');
96
+ });
97
+ };
98
+ }, [password, storeUUID, tenantUUID, url, username, extraOpts, sessionDuration, clientId, logger]);
99
+ const value = useMemo(() => {
100
+ return {
101
+ mqttClient: client,
102
+ connected,
103
+ logger
104
+ };
105
+ }, [client, connected]);
106
+ return jsx(mqttContext.Provider, {
107
+ value: value,
108
+ children: children
109
+ });
108
110
  }
109
111
  function useMqtt() {
110
- const context = useContext(mqttContext);
111
- return context;
112
+ const context = useContext(mqttContext);
113
+ return context;
112
114
  }
113
115
 
114
- function MQTTReconnect({ onReconnect }) {
115
- const { mqttClient } = useMqtt();
116
- const previouslyConnected = useRef(false);
117
- useEffect(() => {
118
- if (!mqttClient)
119
- return;
120
- const handler = (connack) => {
121
- // skip firing this event on initial connect
122
- if (!previouslyConnected.current) {
123
- previouslyConnected.current = true;
124
- return;
125
- }
126
- if (!connack.sessionPresent) {
127
- onReconnect === null || onReconnect === void 0 ? void 0 : onReconnect();
128
- }
129
- };
130
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.on('connect', handler);
131
- return () => {
132
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('connect', handler);
133
- };
134
- }, [mqttClient, onReconnect]);
135
- return null;
116
+ function MQTTReconnect({
117
+ onReconnect
118
+ }) {
119
+ const {
120
+ mqttClient
121
+ } = useMqtt();
122
+ const previouslyConnected = useRef(false);
123
+ useEffect(() => {
124
+ if (!mqttClient) return;
125
+ const handler = connack => {
126
+ // skip firing this event on initial connect
127
+ if (!previouslyConnected.current) {
128
+ previouslyConnected.current = true;
129
+ return;
130
+ }
131
+ if (!connack.sessionPresent) {
132
+ onReconnect === null || onReconnect === void 0 ? void 0 : onReconnect();
133
+ }
134
+ };
135
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.on('connect', handler);
136
+ return () => {
137
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('connect', handler);
138
+ };
139
+ }, [mqttClient, onReconnect]);
140
+ return null;
136
141
  }
137
142
 
138
- function MqttTopic({ topic, qos = 1, onChange }) {
139
- const { mqttClient, logger } = useMqtt();
140
- useEffect(() => {
141
- if (!mqttClient)
142
- return;
143
- mqttClient.subscribe(topic, { qos }, (err) => {
144
- if (err) {
145
- logger === null || logger === void 0 ? void 0 : logger.error(`Failed to subscribe to topic ${topic}:`, err);
146
- }
147
- else {
148
- logger === null || logger === void 0 ? void 0 : logger.log(`Subscribed to topic ${topic}`);
149
- }
150
- });
151
- const handler = (msgTopic, message) => {
152
- if (msgTopic !== topic)
153
- return;
154
- try {
155
- const payload = JSON.parse(message.toString());
156
- onChange === null || onChange === void 0 ? void 0 : onChange(payload);
157
- }
158
- catch (error) {
159
- logger === null || logger === void 0 ? void 0 : logger.error(`Failed to parse message for topic ${topic}:`, error);
160
- }
161
- };
162
- mqttClient.on('message', handler);
163
- return () => {
164
- try {
165
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
166
- mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('message', handler);
167
- }
168
- catch (error) {
169
- logger === null || logger === void 0 ? void 0 : logger.error(`Failed to unsubscribe and remove listener from topic ${topic}:`, error);
170
- }
171
- };
172
- }, [mqttClient, onChange, qos, topic]);
173
- return null;
143
+ function MqttTopic({
144
+ topic,
145
+ qos = 1,
146
+ onChange
147
+ }) {
148
+ const {
149
+ mqttClient,
150
+ logger
151
+ } = useMqtt();
152
+ useEffect(() => {
153
+ if (!mqttClient) return;
154
+ mqttClient.subscribe(topic, {
155
+ qos
156
+ }, err => {
157
+ if (err) {
158
+ logger === null || logger === void 0 ? void 0 : logger.error(`Failed to subscribe to topic ${topic}:`, err);
159
+ } else {
160
+ logger === null || logger === void 0 ? void 0 : logger.log(`Subscribed to topic ${topic}`);
161
+ }
162
+ });
163
+ const handler = (msgTopic, message) => {
164
+ if (msgTopic !== topic) return;
165
+ try {
166
+ const payload = JSON.parse(message.toString());
167
+ onChange === null || onChange === void 0 ? void 0 : onChange(payload);
168
+ } catch (error) {
169
+ logger === null || logger === void 0 ? void 0 : logger.error(`Failed to parse message for topic ${topic}:`, error);
170
+ }
171
+ };
172
+ mqttClient.on('message', handler);
173
+ return () => {
174
+ try {
175
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.unsubscribe(topic);
176
+ mqttClient === null || mqttClient === void 0 ? void 0 : mqttClient.removeListener('message', handler);
177
+ } catch (error) {
178
+ logger === null || logger === void 0 ? void 0 : logger.error(`Failed to unsubscribe and remove listener from topic ${topic}:`, error);
179
+ }
180
+ };
181
+ }, [mqttClient, onChange, qos, topic]);
182
+ return null;
174
183
  }
175
184
 
176
185
  export { MQTTReconnect, MqttProvider, MqttTopic, useMqtt };
package/index.cjs.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./src/index";
@@ -41,50 +41,55 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
41
41
  };
42
42
 
43
43
  class MqttPublisher {
44
- constructor(config) {
45
- this.instance = axios__default["default"].create({
46
- baseURL: config.mqttUrl,
47
- headers: {
48
- 'Content-Type': 'application/json',
49
- },
50
- auth: {
51
- username: config.mqttUsername,
52
- password: config.mqttPassword,
53
- },
54
- });
55
- }
56
- trigger(topic, data, params, errorCb) {
57
- return __awaiter(this, void 0, void 0, function* () {
58
- const publishParams = Object.assign({ topic, payload: typeof data === 'string' ? data : JSON.stringify(data) }, params);
59
- try {
60
- yield this.instance.post('/api/v5/publish', publishParams);
61
- }
62
- catch (error) {
63
- errorCb === null || errorCb === void 0 ? void 0 : errorCb(error);
64
- console.error('Error publishing MQTT message:', error);
65
- }
66
- });
67
- }
44
+ constructor(config) {
45
+ this.instance = axios__default["default"].create({
46
+ baseURL: config.mqttUrl,
47
+ headers: {
48
+ 'Content-Type': 'application/json'
49
+ },
50
+ auth: {
51
+ username: config.mqttUsername,
52
+ password: config.mqttPassword
53
+ }
54
+ });
55
+ }
56
+ trigger(topic, data, params, errorCb) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ const publishParams = Object.assign({
59
+ topic,
60
+ payload: typeof data === 'string' ? data : JSON.stringify(data)
61
+ }, params);
62
+ try {
63
+ yield this.instance.post('/api/v5/publish', publishParams);
64
+ } catch (error) {
65
+ errorCb === null || errorCb === void 0 ? void 0 : errorCb(error);
66
+ console.error('Error publishing MQTT message:', error);
67
+ }
68
+ });
69
+ }
68
70
  }
69
71
 
70
72
  class MqttService {
71
- constructor(config, extraMQTTOptions = {}) {
72
- this.instance = mqtt__default["default"].connect(config.mqttUrl, Object.assign({ username: config.mqttUsername, password: config.mqttPassword }, extraMQTTOptions));
73
- this.instance.on('error', (error) => {
74
- console.error('MQTT connection error:', error);
75
- });
76
- this.instance.on('disconnect', () => {
77
- console.warn('MQTT client disconnected');
78
- });
79
- }
80
- trigger(topic, data, options, cb) {
81
- this.instance.publish(topic, typeof data === 'string' ? data : JSON.stringify(data), options, (error) => {
82
- cb === null || cb === void 0 ? void 0 : cb(error);
83
- if (error) {
84
- console.error('Error publishing MQTT message:', error);
85
- }
86
- });
87
- }
73
+ constructor(config, extraMQTTOptions = {}) {
74
+ this.instance = mqtt__default["default"].connect(config.mqttUrl, Object.assign({
75
+ username: config.mqttUsername,
76
+ password: config.mqttPassword
77
+ }, extraMQTTOptions));
78
+ this.instance.on('error', error => {
79
+ console.error('MQTT connection error:', error);
80
+ });
81
+ this.instance.on('disconnect', () => {
82
+ console.warn('MQTT client disconnected');
83
+ });
84
+ }
85
+ trigger(topic, data, options, cb) {
86
+ this.instance.publish(topic, typeof data === 'string' ? data : JSON.stringify(data), options, error => {
87
+ cb === null || cb === void 0 ? void 0 : cb(error);
88
+ if (error) {
89
+ console.error('Error publishing MQTT message:', error);
90
+ }
91
+ });
92
+ }
88
93
  }
89
94
 
90
95
  exports.MqttPublisher = MqttPublisher;
package/index.esm.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./src/index";
@@ -32,50 +32,55 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
32
32
  };
33
33
 
34
34
  class MqttPublisher {
35
- constructor(config) {
36
- this.instance = axios.create({
37
- baseURL: config.mqttUrl,
38
- headers: {
39
- 'Content-Type': 'application/json',
40
- },
41
- auth: {
42
- username: config.mqttUsername,
43
- password: config.mqttPassword,
44
- },
45
- });
46
- }
47
- trigger(topic, data, params, errorCb) {
48
- return __awaiter(this, void 0, void 0, function* () {
49
- const publishParams = Object.assign({ topic, payload: typeof data === 'string' ? data : JSON.stringify(data) }, params);
50
- try {
51
- yield this.instance.post('/api/v5/publish', publishParams);
52
- }
53
- catch (error) {
54
- errorCb === null || errorCb === void 0 ? void 0 : errorCb(error);
55
- console.error('Error publishing MQTT message:', error);
56
- }
57
- });
58
- }
35
+ constructor(config) {
36
+ this.instance = axios.create({
37
+ baseURL: config.mqttUrl,
38
+ headers: {
39
+ 'Content-Type': 'application/json'
40
+ },
41
+ auth: {
42
+ username: config.mqttUsername,
43
+ password: config.mqttPassword
44
+ }
45
+ });
46
+ }
47
+ trigger(topic, data, params, errorCb) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ const publishParams = Object.assign({
50
+ topic,
51
+ payload: typeof data === 'string' ? data : JSON.stringify(data)
52
+ }, params);
53
+ try {
54
+ yield this.instance.post('/api/v5/publish', publishParams);
55
+ } catch (error) {
56
+ errorCb === null || errorCb === void 0 ? void 0 : errorCb(error);
57
+ console.error('Error publishing MQTT message:', error);
58
+ }
59
+ });
60
+ }
59
61
  }
60
62
 
61
63
  class MqttService {
62
- constructor(config, extraMQTTOptions = {}) {
63
- this.instance = mqtt.connect(config.mqttUrl, Object.assign({ username: config.mqttUsername, password: config.mqttPassword }, extraMQTTOptions));
64
- this.instance.on('error', (error) => {
65
- console.error('MQTT connection error:', error);
66
- });
67
- this.instance.on('disconnect', () => {
68
- console.warn('MQTT client disconnected');
69
- });
70
- }
71
- trigger(topic, data, options, cb) {
72
- this.instance.publish(topic, typeof data === 'string' ? data : JSON.stringify(data), options, (error) => {
73
- cb === null || cb === void 0 ? void 0 : cb(error);
74
- if (error) {
75
- console.error('Error publishing MQTT message:', error);
76
- }
77
- });
78
- }
64
+ constructor(config, extraMQTTOptions = {}) {
65
+ this.instance = mqtt.connect(config.mqttUrl, Object.assign({
66
+ username: config.mqttUsername,
67
+ password: config.mqttPassword
68
+ }, extraMQTTOptions));
69
+ this.instance.on('error', error => {
70
+ console.error('MQTT connection error:', error);
71
+ });
72
+ this.instance.on('disconnect', () => {
73
+ console.warn('MQTT client disconnected');
74
+ });
75
+ }
76
+ trigger(topic, data, options, cb) {
77
+ this.instance.publish(topic, typeof data === 'string' ? data : JSON.stringify(data), options, error => {
78
+ cb === null || cb === void 0 ? void 0 : cb(error);
79
+ if (error) {
80
+ console.error('Error publishing MQTT message:', error);
81
+ }
82
+ });
83
+ }
79
84
  }
80
85
 
81
86
  export { MqttPublisher, MqttService };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vita-mojo/mqtt",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "peerDependencies": {
5
5
  "axios": "*",
6
6
  "react": "*"
@@ -8,19 +8,22 @@
8
8
  "dependencies": {
9
9
  "mqtt": ">=5.13.1"
10
10
  },
11
+ "types": "./index.esm.d.ts",
11
12
  "exports": {
12
- "./package.json": "./package.json",
13
13
  ".": {
14
- "module": "./server.esm.js",
15
- "import": "./server.cjs.mjs",
16
- "default": "./server.cjs.js"
14
+ "types": "./index.esm.d.ts",
15
+ "import": "./index.esm.js",
16
+ "require": "./index.cjs.js",
17
+ "default": "./index.cjs.js"
17
18
  },
18
19
  "./client": {
19
- "module": "./client.esm.js",
20
- "import": "./client.cjs.mjs",
20
+ "types": "./client.esm.d.ts",
21
+ "import": "./client.esm.js",
22
+ "require": "./client.cjs.js",
21
23
  "default": "./client.cjs.js"
22
- }
24
+ },
25
+ "./package.json": "./package.json"
23
26
  },
24
- "module": "./server.esm.js",
25
- "main": "./server.cjs.js"
27
+ "module": "./index.esm.js",
28
+ "main": "./index.cjs.js"
26
29
  }
package/src/index.d.ts CHANGED
@@ -1,2 +1 @@
1
- export * from './client';
2
1
  export * from './server';
@@ -1 +0,0 @@
1
- exports._default = require('./client.cjs.js').default;
package/client.cjs.mjs DELETED
@@ -1,2 +0,0 @@
1
- export * from './client.cjs.js';
2
- export { _default as default } from './client.cjs.default.js';
package/server.cjs.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/server";
@@ -1 +0,0 @@
1
- exports._default = require('./server.cjs.js').default;
package/server.cjs.mjs DELETED
@@ -1,2 +0,0 @@
1
- export * from './server.cjs.js';
2
- export { _default as default } from './server.cjs.default.js';
package/server.esm.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./src/server";