-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
mqtt.js
1390 lines (1205 loc) · 48.7 KB
/
mqtt.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const crypto = require("crypto");
const path = require("path");
const mqtt = require("mqtt");
const protobufjs = require("protobufjs");
const commandLineArgs = require("command-line-args");
const commandLineUsage = require("command-line-usage");
const PositionUtil = require("./utils/position_util");
// create prisma db client
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
// meshtastic bitfield flags
const BITFIELD_OK_TO_MQTT_SHIFT = 0;
const BITFIELD_OK_TO_MQTT_MASK = (1 << BITFIELD_OK_TO_MQTT_SHIFT);
const optionsList = [
{
name: 'help',
alias: 'h',
type: Boolean,
description: 'Display this usage guide.'
},
{
name: "mqtt-broker-url",
type: String,
description: "MQTT Broker URL (e.g: mqtt://mqtt.meshtastic.org)",
},
{
name: "mqtt-username",
type: String,
description: "MQTT Username (e.g: meshdev)",
},
{
name: "mqtt-password",
type: String,
description: "MQTT Password (e.g: large4cats)",
},
{
name: "mqtt-client-id",
type: String,
description: "MQTT Client ID (e.g: map.example.com)",
},
{
name: "mqtt-topic",
type: String,
multiple: true,
typeLabel: '<topic> ...',
description: "MQTT Topic to subscribe to (e.g: msh/#)",
},
{
name: "allowed-portnums",
type: Number,
multiple: true,
typeLabel: '<portnum> ...',
description: "If provided, only packets with these portnums will be processed.",
},
{
name: "log-unknown-portnums",
type: Boolean,
description: "This option will log packets for unknown portnums to the console.",
},
{
name: "collect-service-envelopes",
type: Boolean,
description: "This option will save all received service envelopes to the database.",
},
{
name: "collect-positions",
type: Boolean,
description: "This option will save all received positions to the database.",
},
{
name: "collect-text-messages",
type: Boolean,
description: "This option will save all received text messages to the database.",
},
{
name: "ignore-direct-messages",
type: Boolean,
description: "This option will prevent saving direct messages to the database.",
},
{
name: "collect-waypoints",
type: Boolean,
description: "This option will save all received waypoints to the database.",
},
{
name: "collect-neighbour-info",
type: Boolean,
description: "This option will save all received neighbour infos to the database.",
},
{
name: "collect-map-reports",
type: Boolean,
description: "This option will save all received map reports to the database.",
},
{
name: "decryption-keys",
type: String,
multiple: true,
typeLabel: '<base64DecryptionKey> ...',
description: "Decryption keys encoded in base64 to use when decrypting service envelopes.",
},
{
name: "drop-packets-not-ok-to-mqtt",
type: Boolean,
description: "This option will drop all packets that have 'OK to MQTT' set to false.",
},
{
name: "drop-portnums-without-bitfield",
type: Number,
multiple: true,
typeLabel: '<portnum> ...',
description: "If provided, packets with these portnums will be dropped if they don't have a bitfield. (bitfield available from firmware v2.5+)",
},
{
name: "old-firmware-position-precision",
type: Number,
description: "If provided, position packets from firmware v2.4 and older will be truncated to this many decimal places.",
},
{
name: "forget-outdated-node-positions-after-seconds",
type: Number,
description: "If provided, nodes that haven't sent a position report in this time will have their current position cleared.",
},
{
name: "purge-interval-seconds",
type: Number,
description: "How long to wait between each automatic database purge.",
},
{
name: "purge-device-metrics-after-seconds",
type: Number,
description: "Device Metrics older than this many seconds will be purged from the database.",
},
{
name: "purge-environment-metrics-after-seconds",
type: Number,
description: "Environment Metrics older than this many seconds will be purged from the database.",
},
{
name: "purge-power-metrics-after-seconds",
type: Number,
description: "Power Metrics older than this many seconds will be purged from the database.",
},
{
name: "purge-map-reports-after-seconds",
type: Number,
description: "Map reports older than this many seconds will be purged from the database.",
},
{
name: "purge-neighbour-infos-after-seconds",
type: Number,
description: "Neighbour infos older than this many seconds will be purged from the database.",
},
{
name: "purge-nodes-unheard-for-seconds",
type: Number,
description: "Nodes that haven't been heard from in this many seconds will be purged from the database.",
},
{
name: "purge-positions-after-seconds",
type: Number,
description: "Positions older than this many seconds will be purged from the database.",
},
{
name: "purge-service-envelopes-after-seconds",
type: Number,
description: "Service envelopes older than this many seconds will be purged from the database.",
},
{
name: "purge-text-messages-after-seconds",
type: Number,
description: "Text Messages older than this many seconds will be purged from the database.",
},
{
name: "purge-traceroutes-after-seconds",
type: Number,
description: "Traceroutes older than this many seconds will be purged from the database.",
},
{
name: "purge-waypoints-after-seconds",
type: Number,
description: "Waypoints older than this many seconds will be purged from the database.",
},
];
// parse command line args
const options = commandLineArgs(optionsList);
// show help
if(options.help){
const usage = commandLineUsage([
{
header: 'Meshtastic MQTT Collector',
content: 'Collects and processes service envelopes from a Meshtastic MQTT server.',
},
{
header: 'Options',
optionList: optionsList,
},
]);
console.log(usage);
return;
}
// get options and fallback to default values
const mqttBrokerUrl = options["mqtt-broker-url"] ?? "mqtt://mqtt.meshtastic.org";
const mqttUsername = options["mqtt-username"] ?? "meshdev";
const mqttPassword = options["mqtt-password"] ?? "large4cats";
const mqttClientId = options["mqtt-client-id"] ?? null;
const mqttTopics = options["mqtt-topic"] ?? ["msh/#"];
const allowedPortnums = options["allowed-portnums"] ?? null;
const logUnknownPortnums = options["log-unknown-portnums"] ?? false;
const collectServiceEnvelopes = options["collect-service-envelopes"] ?? false;
const collectPositions = options["collect-positions"] ?? false;
const collectTextMessages = options["collect-text-messages"] ?? false;
const ignoreDirectMessages = options["ignore-direct-messages"] ?? false;
const collectWaypoints = options["collect-waypoints"] ?? false;
const collectNeighbourInfo = options["collect-neighbour-info"] ?? false;
const collectMapReports = options["collect-map-reports"] ?? false;
const decryptionKeys = options["decryption-keys"] ?? [
"1PG7OiApB1nwvP+rz05pAQ==", // add default "AQ==" decryption key
];
const dropPacketsNotOkToMqtt = options["drop-packets-not-ok-to-mqtt"] ?? false;
const dropPortnumsWithoutBitfield = options["drop-portnums-without-bitfield"] ?? null;
const oldFirmwarePositionPrecision = options["old-firmware-position-precision"] ?? null;
const forgetOutdatedNodePositionsAfterSeconds = options["forget-outdated-node-positions-after-seconds"] ?? null;
const purgeIntervalSeconds = options["purge-interval-seconds"] ?? 10;
const purgeNodesUnheardForSeconds = options["purge-nodes-unheard-for-seconds"] ?? null;
const purgeDeviceMetricsAfterSeconds = options["purge-device-metrics-after-seconds"] ?? null;
const purgeEnvironmentMetricsAfterSeconds = options["purge-environment-metrics-after-seconds"] ?? null;
const purgeMapReportsAfterSeconds = options["purge-map-reports-after-seconds"] ?? null;
const purgeNeighbourInfosAfterSeconds = options["purge-neighbour-infos-after-seconds"] ?? null;
const purgePowerMetricsAfterSeconds = options["purge-power-metrics-after-seconds"] ?? null;
const purgePositionsAfterSeconds = options["purge-positions-after-seconds"] ?? null;
const purgeServiceEnvelopesAfterSeconds = options["purge-service-envelopes-after-seconds"] ?? null;
const purgeTextMessagesAfterSeconds = options["purge-text-messages-after-seconds"] ?? null;
const purgeTraceroutesAfterSeconds = options["purge-traceroutes-after-seconds"] ?? null;
const purgeWaypointsAfterSeconds = options["purge-waypoints-after-seconds"] ?? null;
// create mqtt client
const client = mqtt.connect(mqttBrokerUrl, {
username: mqttUsername,
password: mqttPassword,
clientId: mqttClientId,
});
// load protobufs
const root = new protobufjs.Root();
root.resolvePath = (origin, target) => path.join(__dirname, "protos", target);
root.loadSync('meshtastic/mqtt.proto');
const Data = root.lookupType("Data");
const ServiceEnvelope = root.lookupType("ServiceEnvelope");
const MapReport = root.lookupType("MapReport");
const NeighborInfo = root.lookupType("NeighborInfo");
const Position = root.lookupType("Position");
const RouteDiscovery = root.lookupType("RouteDiscovery");
const Telemetry = root.lookupType("Telemetry");
const User = root.lookupType("User");
const Waypoint = root.lookupType("Waypoint");
// run automatic purge if configured
if(purgeIntervalSeconds){
setInterval(async () => {
await purgeUnheardNodes();
await purgeOldDeviceMetrics();
await purgeOldEnvironmentMetrics();
await purgeOldMapReports();
await purgeOldNeighbourInfos();
await purgeOldPowerMetrics();
await purgeOldPositions();
await purgeOldServiceEnvelopes();
await purgeOldTextMessages();
await purgeOldTraceroutes();
await purgeOldWaypoints();
await forgetOutdatedNodePositions();
}, purgeIntervalSeconds * 1000);
}
/**
* Purges all nodes from the database that haven't been heard from within the configured timeframe.
*/
async function purgeUnheardNodes() {
// make sure seconds provided
if(!purgeNodesUnheardForSeconds){
return;
}
// delete all nodes that were last updated before configured purge time
try {
await prisma.node.deleteMany({
where: {
updated_at: {
// last updated before x seconds ago
lt: new Date(Date.now() - purgeNodesUnheardForSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all device metrics from the database that are older than the configured timeframe.
*/
async function purgeOldDeviceMetrics() {
// make sure seconds provided
if(!purgeDeviceMetricsAfterSeconds){
return;
}
// delete all device metrics that are older than the configured purge time
try {
await prisma.deviceMetric.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeDeviceMetricsAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all environment metrics from the database that are older than the configured timeframe.
*/
async function purgeOldEnvironmentMetrics() {
// make sure seconds provided
if(!purgeEnvironmentMetricsAfterSeconds){
return;
}
// delete all environment metrics that are older than the configured purge time
try {
await prisma.environmentMetric.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeEnvironmentMetricsAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all power metrics from the database that are older than the configured timeframe.
*/
async function purgeOldMapReports() {
// make sure seconds provided
if(!purgeMapReportsAfterSeconds){
return;
}
// delete all map reports that are older than the configured purge time
try {
await prisma.mapReport.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeMapReportsAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all neighbour infos from the database that are older than the configured timeframe.
*/
async function purgeOldNeighbourInfos() {
// make sure seconds provided
if(!purgeNeighbourInfosAfterSeconds){
return;
}
// delete all neighbour infos that are older than the configured purge time
try {
await prisma.neighbourInfo.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeNeighbourInfosAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all power metrics from the database that are older than the configured timeframe.
*/
async function purgeOldPowerMetrics() {
// make sure seconds provided
if(!purgePowerMetricsAfterSeconds){
return;
}
// delete all power metrics that are older than the configured purge time
try {
await prisma.powerMetric.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgePowerMetricsAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all positions from the database that are older than the configured timeframe.
*/
async function purgeOldPositions() {
// make sure seconds provided
if(!purgePositionsAfterSeconds){
return;
}
// delete all positions that are older than the configured purge time
try {
await prisma.position.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgePositionsAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all service envelopes from the database that are older than the configured timeframe.
*/
async function purgeOldServiceEnvelopes() {
// make sure seconds provided
if(!purgeServiceEnvelopesAfterSeconds){
return;
}
// delete all service envelopes that are older than the configured purge time
try {
await prisma.serviceEnvelope.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeServiceEnvelopesAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all text messages from the database that are older than the configured timeframe.
*/
async function purgeOldTextMessages() {
// make sure seconds provided
if(!purgeTextMessagesAfterSeconds){
return;
}
// delete all text messages that are older than the configured purge time
try {
await prisma.textMessage.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeTextMessagesAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all traceroutes from the database that are older than the configured timeframe.
*/
async function purgeOldTraceroutes() {
// make sure seconds provided
if(!purgeTraceroutesAfterSeconds){
return;
}
// delete all traceroutes that are older than the configured purge time
try {
await prisma.traceRoute.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeTraceroutesAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Purges all waypoints from the database that are older than the configured timeframe.
*/
async function purgeOldWaypoints() {
// make sure seconds provided
if(!purgeWaypointsAfterSeconds){
return;
}
// delete all waypoints that are older than the configured purge time
try {
await prisma.waypoint.deleteMany({
where: {
created_at: {
// created before x seconds ago
lt: new Date(Date.now() - purgeWaypointsAfterSeconds * 1000),
},
}
});
} catch(e) {
// do nothing
}
}
/**
* Clears the current position stored for nodes if the position hasn't been updated within the configured timeframe.
* This allows the node position to drop off the map if the user disabled position reporting, but still wants telemetry lookup etc
*/
async function forgetOutdatedNodePositions() {
// make sure seconds provided
if(!forgetOutdatedNodePositionsAfterSeconds){
return;
}
// clear latitude/longitude/altitude for nodes that haven't updated their position in the configured timeframe
try {
await prisma.node.updateMany({
where: {
position_updated_at: {
// position_updated_at before x seconds ago
lt: new Date(Date.now() - forgetOutdatedNodePositionsAfterSeconds * 1000),
},
// don't forget outdated node positions for nodes that don't actually have a position set
// otherwise the updated_at is updated, when nothing changed
NOT: {
latitude: null,
longitude: null,
altitude: null,
},
},
data: {
latitude: null,
longitude: null,
altitude: null,
},
});
} catch(e) {
// do nothing
}
}
function createNonce(packetId, fromNode) {
// Expand packetId to 64 bits
const packetId64 = BigInt(packetId);
// Initialize block counter (32-bit, starts at zero)
const blockCounter = 0;
// Create a buffer for the nonce
const buf = Buffer.alloc(16);
// Write packetId, fromNode, and block counter to the buffer
buf.writeBigUInt64LE(packetId64, 0);
buf.writeUInt32LE(fromNode, 8);
buf.writeUInt32LE(blockCounter, 12);
return buf;
}
/**
* References:
* https://github.com/crypto-smoke/meshtastic-go/blob/develop/radio/aes.go#L42
* https://github.com/pdxlocations/Meshtastic-MQTT-Connect/blob/main/meshtastic-mqtt-connect.py#L381
*/
function decrypt(packet) {
// attempt to decrypt with all available decryption keys
for(const decryptionKey of decryptionKeys){
try {
// convert encryption key to buffer
const key = Buffer.from(decryptionKey, "base64");
// create decryption iv/nonce for this packet
const nonceBuffer = createNonce(packet.id, packet.from);
// determine algorithm based on key length
var algorithm = null;
if(key.length === 16){
algorithm = "aes-128-ctr";
} else if(key.length === 32){
algorithm = "aes-256-ctr";
} else {
// skip this key, try the next one...
console.error(`Skipping decryption key with invalid length: ${key.length}`);
continue;
}
// create decipher
const decipher = crypto.createDecipheriv(algorithm, key, nonceBuffer);
// decrypt encrypted packet
const decryptedBuffer = Buffer.concat([decipher.update(packet.encrypted), decipher.final()]);
// parse as data message
return Data.decode(decryptedBuffer);
} catch(e){}
}
// couldn't decrypt
return null;
}
/**
* converts hex id to numeric id, for example: !FFFFFFFF to 4294967295
* @param hexId a node id in hex format with a prepended "!"
* @returns {bigint} the node id in numeric form
*/
function convertHexIdToNumericId(hexId) {
return BigInt('0x' + hexId.replaceAll("!", ""));
}
// subscribe to everything when connected
client.on("connect", () => {
for(const mqttTopic of mqttTopics){
client.subscribe(mqttTopic);
}
});
// handle message received
client.on("message", async (topic, message) => {
try {
// decode service envelope
const envelope = ServiceEnvelope.decode(message);
if(!envelope.packet){
return;
}
// attempt to decrypt encrypted packets
const isEncrypted = envelope.packet.encrypted?.length > 0;
if(isEncrypted){
const decoded = decrypt(envelope.packet);
if(decoded){
envelope.packet.decoded = decoded;
}
}
// get portnum from decoded packet
const portnum = envelope.packet?.decoded?.portnum;
// get bitfield from decoded packet
// bitfield was added in v2.5 of meshtastic firmware
// this value will be null for packets from v2.4.x and below, and will be an integer in v2.5.x and above
const bitfield = envelope.packet?.decoded?.bitfield;
// check if we can see the decrypted packet data
if(envelope.packet.decoded != null){
// check if bitfield is available (v2.5.x firmware or newer)
if(bitfield != null){
// drop packets where "OK to MQTT" is false
const isOkToMqtt = bitfield & BITFIELD_OK_TO_MQTT_MASK;
if(dropPacketsNotOkToMqtt && !isOkToMqtt){
return;
}
}
// if bitfield is not available for this packet, check if we want to drop this portnum
if(bitfield == null){
// drop packet if portnum is in drop list
// this is useful for dropping specific packet types from firmware older than v2.5
if(dropPortnumsWithoutBitfield != null && dropPortnumsWithoutBitfield.includes(portnum)){
return;
}
}
}
// create service envelope in db
if(collectServiceEnvelopes){
try {
await prisma.serviceEnvelope.create({
data: {
mqtt_topic: topic,
channel_id: envelope.channelId,
gateway_id: envelope.gatewayId ? convertHexIdToNumericId(envelope.gatewayId) : null,
to: envelope.packet.to,
from: envelope.packet.from,
protobuf: message,
},
});
} catch (e) {
console.error(e, {
envelope: envelope.packet,
});
}
}
// track when a node last gated a packet to mqtt
try {
await prisma.node.updateMany({
where: {
node_id: convertHexIdToNumericId(envelope.gatewayId),
},
data: {
mqtt_connection_state_updated_at: new Date(),
},
});
} catch(e) {
// don't care if updating mqtt timestamp fails
}
const logKnownPacketTypes = false;
// if allowed portnums are configured, ignore portnums that are not in the list
if(allowedPortnums != null && !allowedPortnums.includes(portnum)){
return;
}
if(portnum === 1) {
if(!collectTextMessages){
return;
}
// check if we want to ignore direct messages
if(ignoreDirectMessages && envelope.packet.to !== 0xFFFFFFFF){
return;
}
if(logKnownPacketTypes) {
console.log("TEXT_MESSAGE_APP", {
to: envelope.packet.to.toString(16),
from: envelope.packet.from.toString(16),
text: envelope.packet.decoded.payload.toString(),
});
}
try {
await prisma.textMessage.create({
data: {
to: envelope.packet.to,
from: envelope.packet.from,
channel: envelope.packet.channel,
packet_id: envelope.packet.id,
channel_id: envelope.channelId,
gateway_id: envelope.gatewayId ? convertHexIdToNumericId(envelope.gatewayId) : null,
text: envelope.packet.decoded.payload.toString(),
rx_time: envelope.packet.rxTime,
rx_snr: envelope.packet.rxSnr,
rx_rssi: envelope.packet.rxRssi,
hop_limit: envelope.packet.hopLimit,
},
});
} catch (e) {
console.error(e);
}
}
else if(portnum === 3) {
const position = Position.decode(envelope.packet.decoded.payload);
if(logKnownPacketTypes){
console.log("POSITION_APP", {
from: envelope.packet.from.toString(16),
position: position,
});
}
// process position
if(position.latitudeI != null && position.longitudeI){
// if bitfield is not available, we are on firmware v2.4 or below
// if configured, position packets should have their precision reduced
if(bitfield == null && oldFirmwarePositionPrecision != null){
// adjust precision of latitude and longitude
position.latitudeI = PositionUtil.setPositionPrecision(position.latitudeI, oldFirmwarePositionPrecision);
position.longitudeI = PositionUtil.setPositionPrecision(position.longitudeI, oldFirmwarePositionPrecision);
// update position precision on packet to show that it is no longer full precision
position.precisionBits = oldFirmwarePositionPrecision;
}
// update node position in db
try {
await prisma.node.updateMany({
where: {
node_id: envelope.packet.from,
},
data: {
position_updated_at: new Date(),
latitude: position.latitudeI,
longitude: position.longitudeI,
altitude: position.altitude !== 0 ? position.altitude : null,
position_precision: position.precisionBits,
},
});
} catch (e) {
console.error(e);
}
}
// don't collect position history if not enabled, but we still want to update the node above
if(!collectPositions){
return;
}
try {
// find an existing position with duplicate information created in the last 60 seconds
const existingDuplicatePosition = await prisma.position.findFirst({
where: {
node_id: envelope.packet.from,
packet_id: envelope.packet.id,
created_at: {
gte: new Date(Date.now() - 60000), // created in the last 60 seconds
},
}
});
// create position if no duplicates found
if(!existingDuplicatePosition){
await prisma.position.create({
data: {
node_id: envelope.packet.from,
to: envelope.packet.to,
from: envelope.packet.from,
channel: envelope.packet.channel,
packet_id: envelope.packet.id,
channel_id: envelope.channelId,
gateway_id: envelope.gatewayId ? convertHexIdToNumericId(envelope.gatewayId) : null,
latitude: position.latitudeI,
longitude: position.longitudeI,
altitude: position.altitude,
},
});
}
} catch (e) {
console.error(e);
}
}
else if(portnum === 4) {
const user = User.decode(envelope.packet.decoded.payload);
if(logKnownPacketTypes) {
console.log("NODEINFO_APP", {
from: envelope.packet.from.toString(16),
user: user,
});
}
// create or update node in db
try {
await prisma.node.upsert({
where: {
node_id: envelope.packet.from,
},
create: {
node_id: envelope.packet.from,
long_name: user.longName,
short_name: user.shortName,
hardware_model: user.hwModel,
is_licensed: user.isLicensed === true,
role: user.role,
},
update: {
long_name: user.longName,
short_name: user.shortName,
hardware_model: user.hwModel,
is_licensed: user.isLicensed === true,
role: user.role,
},
});
} catch (e) {
console.error(e);
}
}
else if(portnum === 8) {
if(!collectWaypoints){
return;
}
const waypoint = Waypoint.decode(envelope.packet.decoded.payload);
if(logKnownPacketTypes) {
console.log("WAYPOINT_APP", {
to: envelope.packet.to.toString(16),
from: envelope.packet.from.toString(16),
waypoint: waypoint,
});
}
try {
await prisma.waypoint.create({
data: {
to: envelope.packet.to,
from: envelope.packet.from,
waypoint_id: waypoint.id,
latitude: waypoint.latitudeI,
longitude: waypoint.longitudeI,
expire: waypoint.expire,
locked_to: waypoint.lockedTo,
name: waypoint.name,
description: waypoint.description,
icon: waypoint.icon,
channel: envelope.packet.channel,
packet_id: envelope.packet.id,
channel_id: envelope.channelId,
gateway_id: envelope.gatewayId ? convertHexIdToNumericId(envelope.gatewayId) : null,
},
});
} catch (e) {
console.error(e);
}
}
else if(portnum === 71) {
const neighbourInfo = NeighborInfo.decode(envelope.packet.decoded.payload);
if(logKnownPacketTypes) {
console.log("NEIGHBORINFO_APP", {
from: envelope.packet.from.toString(16),