Add component
This commit is contained in:
72
src/components/Global/MqttConnection.jsx
Normal file
72
src/components/Global/MqttConnection.jsx
Normal file
@@ -0,0 +1,72 @@
|
||||
// mqttService.js
|
||||
import mqtt from 'mqtt';
|
||||
|
||||
const mqttUrl = 'ws://36.66.16.49:9001';
|
||||
const topics = ['SYPIU_GGCP', 'SYPIU_GGCP/list-permit/changed','SYPIU_GGCP/list-user/changed'];
|
||||
|
||||
const options = {
|
||||
keepalive: 30,
|
||||
clientId: 'react_mqtt_' + Math.random().toString(16).substr(2, 8),
|
||||
protocolId: 'MQTT',
|
||||
protocolVersion: 4,
|
||||
clean: true,
|
||||
reconnectPeriod: 1000,
|
||||
connectTimeout: 30 * 1000,
|
||||
username: 'ide', // jika ada
|
||||
password: 'aremania', // jika ada
|
||||
};
|
||||
|
||||
const client = mqtt.connect(mqttUrl, options);
|
||||
|
||||
// Track connection status
|
||||
let isConnected = false;
|
||||
|
||||
client.on('connect', () => {
|
||||
console.log('MQTT Connected');
|
||||
isConnected = true;
|
||||
|
||||
// Subscribe default topic
|
||||
client.subscribe(topics, (err) => {
|
||||
if (err) console.error('Subscribe error:', err);
|
||||
else console.log(`Subscribed to topics: ${topics.join(', ')}`);
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', (err) => {
|
||||
console.error('Connection error: ', err);
|
||||
client.end();
|
||||
});
|
||||
|
||||
client.on('close', () => {
|
||||
console.log('MQTT Disconnected');
|
||||
isConnected = false;
|
||||
});
|
||||
|
||||
/**
|
||||
* Publish message to MQTT
|
||||
* @param {string} topic
|
||||
* @param {string} message
|
||||
*/
|
||||
const publishMessage = (topic, message) => {
|
||||
if (client && isConnected && message.trim() !== '') {
|
||||
client.publish(topic, message);
|
||||
} else {
|
||||
console.warn('MQTT not connected or message empty');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Listen to incoming messages
|
||||
* @param {function} callback - Function(topic, message)
|
||||
*/
|
||||
const listenMessage = (callback) => {
|
||||
client.on('message', (topic, message) => {
|
||||
callback(topic, message.toString());
|
||||
});
|
||||
};
|
||||
|
||||
export {
|
||||
publishMessage,
|
||||
listenMessage,
|
||||
client,
|
||||
};
|
||||
Reference in New Issue
Block a user