-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprobe.js
212 lines (187 loc) · 5.93 KB
/
probe.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import { readFileSync } from 'node:fs';
import YAML from 'yaml';
import MQTT from 'mqtt';
function formatHex(v) {
return v.toString(16).padStart(8, '0');
}
function formatNodeId(v) {
return '!' + formatHex(v);
}
function parseNodeId(v) {
if (v === undefined || !v.startsWith('!')) {
return undefined;
}
const id = parseInt(v.slice(1), 16);
if (typeof id !== 'number') {
return undefined;
}
return id;
}
function random32() {
return Math.floor(Math.random() * (2 ** 32 - 1));
}
const ProbeStatus = {
Success: 0,
Timeout: 1,
NotTransmitted: 2,
};
class ProbeEngine {
constructor(client, config) {
const uplinkPrefix = `${config.topic}/2/json/${config.uplinkChannel}/`;
client.subscribe(`${uplinkPrefix}+`);
this.client = client;
this.config = config;
this.uplinkPrefixLength = uplinkPrefix.length;
}
async probe() {
const id = random32();
const extraLoad = '.'.repeat(this.config.extraLoad);
let onMessage;
return new Promise((resolve, _reject) => {
// ID of the on-air packet from source to target.
let packetId;
// The time the source reports its transmission.
let txTime;
// Start a timeout timer.
const timer = setTimeout(() => {
if (packetId === undefined) {
resolve({ status: ProbeStatus.NotTransmitted });
} else {
resolve({ status: ProbeStatus.Timeout });
}
}, this.config.timeout);
onMessage = (topic, message) => {
let json;
try {
json = JSON.parse(message.toString());
// Omitted numerical fields have zero value.
if (json.rssi === undefined) {
json.rssi = 0;
}
if (json.snr === undefined) {
json.snr = 0;
}
} catch {
// Skip if parsing failed.
return;
}
if (json.from != this.config.from ||
json.to != 0 ||
json.payload === null ||
json.payload.text != `${formatHex(id)}${extraLoad}`) {
// Skip if the message is not the probe.
return;
}
const target = topic.slice(this.uplinkPrefixLength);
if (packetId === undefined) {
// First, register a source transmission report.
if (target == formatNodeId(this.config.from)) {
packetId = json.id;
txTime = Date.now();
}
} else if (json.id == packetId) {
// Second, register a target one.
if (target == formatNodeId(this.config.to)) {
clearTimeout(timer);
resolve({
status: ProbeStatus.Success,
res: {
delay: Date.now() - txTime,
packetId: packetId,
rssi: json.rssi,
snr: json.snr,
}
});
}
}
};
// Start listening for packets.
this.client.on('message', onMessage);
// Initiate the measuring by making the source transmit a probe packet:
// - set destination to zero so that the target won't push it to the phone,
// - set hop limit to zero to deny transmission by any other node except the source.
const probe = `{
"from": ${this.config.from},
"to": 0,
"hopLimit": 0,
"payload": "${formatHex(id)}${extraLoad}",
"type": "sendtext"
}`;
this.client.publish(`${this.config.topic}/2/json/mqtt/` +
`${formatNodeId(this.config.from)}`, probe);
}).finally(() => {
// Stop listening for packets.
this.client.removeListener('message', onMessage);
});
}
async loop() {
let go = true;
while (go) {
const startTime = new Date().toISOString();
const probePromise = this.probe().then((value) => {
if (value.status === ProbeStatus.Success) {
const delay = value.res.delay.toString().padStart(6, ' ');
const packetId = formatHex(value.res.packetId);
const rssi = value.res.rssi.toString().padStart(4, ' ');
const snr = value.res.snr.toString().padStart(6, ' ');
console.log(`${startTime} ${delay} ${packetId} ${rssi} ${snr}`);
} else if (value.status === ProbeStatus.Timeout) {
console.log(`${startTime} timeout (no rx report)`);
} else if (value.status === ProbeStatus.NotTransmitted) {
console.log(`${startTime} failure (no tx report)`);
} else {
console.log(`${startTime} failure (internal error)`);
}
});
const intervalPromise = new Promise((resolve, _reject) => {
setTimeout(resolve, this.config.interval);
});
// Run interval timer and probe in parallel.
await Promise.all([probePromise, intervalPromise]).catch((error) => {
console.error(`${startTime} ${error}`);
go = false;
});
}
}
}
class ProbeConfig {
constructor(filename) {
let configData = readFileSync(filename, 'utf8');
let config = YAML.parse(configData);
this.url = config.url;
this.topic = config.topic;
this.uplinkChannel = config.uplinkChannel;
this.from = parseNodeId(config.from);
this.to = parseNodeId(config.to);
this.extraLoad = parseInt(config.extraLoad);
this.timeout = parseInt(config.timeout);
this.interval = parseInt(config.interval);
this.sanitize();
}
sanitize() {
// TODO
}
}
if (process.argv.length > 3 || (process.argv.length == 3 && process.argv[2] == '-h')) {
console.log(`Usage: node probe.js [<config-yaml>]`);
process.exit(0);
}
let configFilename = 'probe.yaml';
if (process.argv.length == 3) {
configFilename = process.argv[2];
}
let config;
try {
config = new ProbeConfig(configFilename);
} catch (error) {
console.error(error.message);
process.exit(1);
}
await MQTT.connectAsync(config.url, { connectTimeout: 5000 })
.then((client) => {
return new ProbeEngine(client, config).loop();
})
.catch((reason) => {
console.error(reason.message);
process.exit(2);
});