forked from shehankonecranes/sp-react-native-mqtt
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
116 lines (89 loc) · 2.47 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import {
NativeEventEmitter,
NativeModules
} from 'react-native';
import { EventEmitter2 } from 'eventemitter2';
const Mqtt = NativeModules.Mqtt;
const emitter = new NativeEventEmitter(Mqtt);
class MqttClient extends EventEmitter2 {
constructor(options, clientRef) {
super();
this.options = options;
this.clientRef = clientRef;
this._emitterSubscription = emitter.addListener('mqtt_events', this._dispatchEvent.bind(this))
}
_dispatchEvent(data) {
if(data && data.clientRef === this.clientRef && data.event){
this.emit(data.event, data.message);
}
}
_destroy() {
emitter.removeSubscription(this._emitterSubscription);
Mqtt.removeClient(this.clientRef);
}
connect() {
Mqtt.connect(this.clientRef);
}
disconnect() {
Mqtt.disconnect(this.clientRef);
}
subscribe(topic, qos) {
Mqtt.subscribe(this.clientRef, topic, qos);
}
unsubscribe(topic) {
Mqtt.unsubscribe(this.clientRef, topic);
}
publish(topic, payload, qos, retain) {
Mqtt.publish(this.clientRef, topic, payload, qos, retain);
}
reconnect() {
Mqtt.reconnect(this.clientRef);
}
isConnected() {
return Mqtt.isConnected(this.clientRef);
}
getTopics() {
return Mqtt.getTopics(this.clientRef);
}
isSubbed(topic) {
return Mqtt.isSubbed(this.clientRef, topic);
}
}
module.exports = {
clients: [],
createClient: async function(options) {
if(options.uri) {
let pattern = /^((mqtt[s]?|ws[s]?)?:(\/\/)([0-9a-zA-Z_.\-]*):?(\d+))$/;
let matches = options.uri.match(pattern);
if (!matches) {
throw new Error(`Uri passed to createClient ${options.uri} doesn't match a known protocol (mqtt:// or ws://).`);
}
let protocol = matches[2];
let host = matches[4];
let port = matches[5];
options.port = parseInt(port, 10);
options.host = host;
options.protocol = 'tcp';
if(protocol === 'wss' || protocol === 'mqtts') {
options.tls = true;
}
if(protocol === 'ws' || protocol === 'wss') {
options.protocol = 'ws';
}
}
let clientRef = await Mqtt.createClient(options);
let client = new MqttClient(options, clientRef);
this.clients.push(client);
return client;
},
removeClient: function(client) {
let clientIdx = this.clients.indexOf(client);
if(clientIdx > -1) {
this.clients.splice(clientIdx, 1);
}
client._destroy();
},
disconnectAll: function () {
Mqtt.disconnectAll();
},
};