-
Notifications
You must be signed in to change notification settings - Fork 1
/
pre.js
95 lines (81 loc) · 1.96 KB
/
pre.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
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const msgMap = {};
onRuntimeInitialized: function initNode(node, topic, msg, msec) {
if (msg){
Module.createPublisher(node, topic, msg, msec);
} else {
Module.createSubscriber(node, topic);
}
}
// When a new message is received from main
self.onmessage = function(event) {
switch( event.data.command )
{
case "initNode":
initNode(
event.data.node,
event.data.topic,
event.data.message ? event.data.message : false, // Only strings for now
event.data.mseconds
);
break;
case "broadcast":
msgMap[event.data.topic] = {
message: event.data.message.replaceAll(", ", "\n"),
isStale: false
};
break;
}
}
Module["registerParticipant"] = function registerParticipant(topic_name, role)
{
topic = topic_name;
let gid = Math.random().toString(16).slice(2)
// Register new participant with main
self.postMessage({
command: "register",
topic: topic_name,
role: role,
gid: gid
});
return gid;
}
Module["deregisterParticipant"] = function deregisterParticipant(gid, role)
{
// Deregister participant from main
self.postMessage({
command: "deregister",
topic: topic,
role: role,
gid: gid
});
return true;
}
Module["publishMessage"] = function publishMessage(message, topic_name)
{
// Send message to main
self.postMessage({
command: "publish",
topic: topic_name,
message: message
});
// Assume it gets published
return true;
}
Module["retrieveMessage"] = async function retrieveMessage(topic_name)
{
if ((topic_name in msgMap) && !msgMap[topic_name].isStale) {
msgMap[topic_name].isStale = true;
return msgMap[topic_name].message;
} else {
// Trigger main to send new message
self.postMessage({
command: "retrieve",
topic: topic_name
});
await sleep(10);
return "";
}
}