-
Notifications
You must be signed in to change notification settings - Fork 0
/
moscaServer.ts
76 lines (66 loc) · 2.24 KB
/
moscaServer.ts
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
import * as mosca from 'mosca';
import {$log} from "ts-log-debug";
const fork = require('child_process').fork;
interface MoscaServerPubSubSettings {
type: string;
url: string;
pubsubCollection: string;
mongo: any
}
interface MoscaSettings {
port: number;
backend?: MoscaServerPubSubSettings;
factory?: any;
}
export class MoscaServer {
private mosca : any;
settings : MoscaSettings = {
port :1883,
factory:mosca.persistence.Memory
};
setup(settings : MoscaSettings) {
this.settings = settings;
}
start() : Promise<any> {
return new Promise<any>((resolve, reject) => {
this.mosca = new mosca.Server(this.settings, ((err, srv) => {
if (err) {
$log.error('Mosca Server start failed');
return reject(err);
}
resolve(srv);
}));
});
}
static Initialize(){
return new MoscaServer()
.start()
.then((server) => {
$log.info('Mosca Server started...');
server.on('clientConnected', (client) => {
$log.info('client connected', client.id);
});
// fired when a message is received
server.on('published', (packet, client) => {
$log.info('Published : ',packet.payload.toString());
});
// fired when a client subscribes to a topic
server.on('subscribed', (topic, client) => {
$log.info('subscribed : ', topic);
});
// fired when a client subscribes to a topic
server.on('unsubscribed', (topic, client) => {
$log.info('unsubscribed : ', topic);
});
// fired when a client is disconnecting
server.on('clientDisconnecting', (client) => {
$log.info('clientDisconnecting : ', client.id);
});
// fired when a client is disconnected
server.on('clientDisconnected', (client) => {
$log.info('clientDisconnected : ', client.id);
});
return server;
})
}
}