-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcommon.ts
45 lines (38 loc) · 1.12 KB
/
common.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
interface IEvent<T> {
on(handler: { (data?: T): void }) : void;
off(handler: { (data?: T): void }) : void;
}
class EventHandler<T> implements IEvent<T> {
private handlers: { (data?: T): void; }[] = [];
public on(handler: { (data?: T): void }) {
this.handlers.push(handler);
}
public off(handler: { (data?: T): void }) {
this.handlers = this.handlers.filter(h => h !== handler);
}
public trigger(data?: T) {
this.handlers.slice(0).forEach(h => h(data));
}
}
class Message {
public payload: string;
public bytes: ArrayBuffer;
public topic: string;
public qos: number;
constructor(mqttMessage: any){
this.payload = mqttMessage.payloadString || '';
this.bytes = mqttMessage.payloadBytes || null;
this.topic = mqttMessage.destinationName || '';
this.qos = mqttMessage.qos || 0;
}
}
let guid = () => {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
export { IEvent, EventHandler, guid, Message };