more clean up

This commit is contained in:
2025-04-17 21:27:54 -04:00
parent 8e99669487
commit 702da27468
13 changed files with 2727 additions and 404 deletions

File diff suppressed because it is too large Load Diff

View File

@ -10,6 +10,7 @@
}, },
"dependencies": { "dependencies": {
"@tailwindcss/vite": "^4.1.4", "@tailwindcss/vite": "^4.1.4",
"@turf/turf": "^7.2.0",
"axios": "^1.8.4", "axios": "^1.8.4",
"chart.js": "^4.4.8", "chart.js": "^4.4.8",
"chartjs-adapter-moment": "^1.0.1", "chartjs-adapter-moment": "^1.0.1",
@ -18,6 +19,7 @@
"moment": "^2.30.1", "moment": "^2.30.1",
"pinia": "^3.0.2", "pinia": "^3.0.2",
"pinia-plugin-persistedstate": "^4.2.0", "pinia-plugin-persistedstate": "^4.2.0",
"rbush": "^4.0.1",
"tailwindcss": "^4.1.4", "tailwindcss": "^4.1.4",
"vue": "^3.5.13", "vue": "^3.5.13",
"vue-router": "^4.5.0" "vue-router": "^4.5.0"

View File

@ -143,15 +143,17 @@ export default class LayersControl {
} }
_hideLayer(name) { _hideLayer(name) {
console.debug('hideLayer: ', name); if (this._getLayers().includes(name)) {
this._disableLayerTransitions(name); this._disableLayerTransitions(name);
this._map.setLayoutProperty(name, 'visibility', 'none'); this._map.setLayoutProperty(name, 'visibility', 'none');
}
} }
_showLayer(name) { _showLayer(name) {
console.debug('showLayer: ', name); if (this._getLayers().includes(name)) {
this._disableLayerTransitions(name); this._disableLayerTransitions(name);
this._map.setLayoutProperty(name, 'visibility', 'visible'); this._map.setLayoutProperty(name, 'visibility', 'visible');
}
} }
_revertControlAction(config) { _revertControlAction(config) {

View File

@ -16,6 +16,8 @@ const search = computed({
get: () => ui.searchText, get: () => ui.searchText,
set: val => ui.search(val), set: val => ui.search(val),
}); });
// TODO: reload button is jumpy when it spins
</script> </script>
<template> <template>

View File

@ -4,11 +4,16 @@ import { state } from '@/store';
import CloseActionButton from '@/components/CloseActionButton.vue'; import CloseActionButton from '@/components/CloseActionButton.vue';
const emit = defineEmits(['dismiss']); const emit = defineEmits(['dismiss']);
const props = defineProps({
node: {
type: Object,
required: false,
validator(value) {
return value === null || typeof value === 'object';
},
}
});
function dismissShowingNodeNeighbours() {
state.selectedNodeToShowNeighbours = null;
emit('dismiss');
}
</script> </script>
<template> <template>
@ -21,30 +26,30 @@ function dismissShowingNodeNeighbours() {
leave-from-class="translate-y-0" leave-from-class="translate-y-0"
leave-to-class="translate-y-full" leave-to-class="translate-y-full"
> >
<div v-show="state.selectedNodeToShowNeighbours" class="fixed left-0 right-0 bottom-0"> <div v-show="props.node !== null" class="fixed left-0 right-0 bottom-0">
<div v-if="state.selectedNodeToShowNeighbours" class="mx-auto w-screen max-w-md p-4"> <div v-if="props.node !== null" class="mx-auto w-screen max-w-md p-4">
<div class="flex h-full flex-col bg-white shadow-xl rounded-xl border"> <div class="flex h-full flex-col bg-white shadow-xl rounded-xl border">
<div class="p-2"> <div class="p-2">
<div class="flex items-start justify-between"> <div class="flex items-start justify-between">
<div> <div>
<h2 class="font-bold"> <h2 class="font-bold">
{{ state.selectedNodeToShowNeighbours.short_name }} Neighbors {{ props.node.short_name }} Neighbors
</h2> </h2>
<h3 <h3
v-if="state.selectedNodeToShowNeighboursType === 'weHeard'" v-if="state.neighborsModalType === 'weHeard'"
class="text-sm" class="text-sm"
> >
Nodes heard by {{ state.selectedNodeToShowNeighbours.short_name }} Nodes heard by {{ props.node.short_name }}
</h3> </h3>
<h3 <h3
v-if="state.selectedNodeToShowNeighboursType === 'theyHeard'" v-if="state.neighborsModalType === 'theyHeard'"
class="text-sm" class="text-sm"
> >
Nodes that heard {{ state.selectedNodeToShowNeighbours.short_name }} Nodes that heard {{ props.node.short_name }}
</h3> </h3>
</div> </div>
<CloseActionButton <CloseActionButton
@click="dismissShowingNodeNeighbours" @click="$emit('dismiss')"
class="my-auto ml-3" class="my-auto ml-3"
/> />
</div> </div>

View File

@ -1,13 +1,20 @@
<script setup> <script setup>
const emit = defineEmits(['dismiss']); const emit = defineEmits(['dismiss']);
const props = defineProps({
node: {
type: Object,
required: false,
validator(value) {
return value === null || typeof value === 'object';
},
}
});
import { state } from '@/store'; import { state } from '@/store';
import moment from 'moment'; import moment from 'moment';
import { useUIStore } from '@/stores/uiStore'; import { useUIStore } from '@/stores/uiStore';
const ui = useUIStore(); const ui = useUIStore();
function dismissShowingNodePositionHistory() { function dismissShowingNodePositionHistory() {
state.selectedNodePositionHistory = [];
state.selectedNodeToShowPositionHistory = null;
ui.collapsePositionHistoryModal(); ui.collapsePositionHistoryModal();
emit('dismiss'); emit('dismiss');
} }
@ -44,8 +51,8 @@ function onPositionHistoryQuickRangeClick(range) {
leave-active-class="transition duration-300 ease-in-out transform" leave-active-class="transition duration-300 ease-in-out transform"
leave-from-class="translate-y-0" leave-from-class="translate-y-0"
leave-to-class="translate-y-full"> leave-to-class="translate-y-full">
<div v-show="state.selectedNodeToShowPositionHistory != null" class="fixed left-0 right-0 bottom-0"> <div v-show="props.node != null" class="fixed left-0 right-0 bottom-0">
<div v-if="state.selectedNodeToShowPositionHistory != null" class="mx-auto w-screen max-w-md p-4"> <div v-if="props.node != null" class="mx-auto w-screen max-w-md p-4">
<div class="flex h-full flex-col bg-white shadow-xl rounded-xl border"> <div class="flex h-full flex-col bg-white shadow-xl rounded-xl border">
<div> <div>
<div class="flex p-2"> <div class="flex p-2">
@ -61,7 +68,7 @@ function onPositionHistoryQuickRangeClick(range) {
</div> </div>
</a> </a>
</div> </div>
<div class="my-auto mr-auto font-bold">{{ state.selectedNodeToShowPositionHistory.short_name }} Position History</div> <div class="my-auto mr-auto font-bold">{{ props.node.short_name }} Position History</div>
<div class="flex my-auto ml-3 space-x-2"> <div class="flex my-auto ml-3 space-x-2">
<a href="javascript:void(0)" class="rounded-full" @click="dismissShowingNodePositionHistory"> <a href="javascript:void(0)" class="rounded-full" @click="dismissShowingNodePositionHistory">
<div class="bg-gray-100 hover:bg-gray-200 p-1 rounded-full"> <div class="bg-gray-100 hover:bg-gray-200 p-1 rounded-full">

View File

@ -131,8 +131,8 @@ function formatDate(date) {
<br /><br /> <br /><br />
<button @click="state.selectedNode = node" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Full Details</button> <button @click="state.selectedNode = node" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Full Details</button>
<br /> <br />
<button @click="$emit('showNeighbors', 'theyHeard', node.node_id)" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Neighbours (Heard Us)</button> <button @click="$emit('showNeighbors', node.node_id, 'theyHeard')" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200 mb-1">Show Neighbours (Heard Us)</button>
<br /> <br />
<button @click="$emit('showNeighbors', 'weHeard', node.node_id)" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200">Show Neighbours (We Heard)</button> <button @click="$emit('showNeighbors', node.node_id, 'weHeard')" class="border border-gray-300 bg-gray-100 p-1 w-full rounded-sm hover:bg-gray-200">Show Neighbours (We Heard)</button>
</div> </div>
</template> </template>

View File

@ -0,0 +1,84 @@
import moment from 'moment';
import { useMapStore } from '@/stores/mapStore';
import { useConfigStore } from '@/stores/configStore';
import { isValidCoordinates } from '@/utils';
export function useWaypointProcessor() {
const mapStore = useMapStore();
const config = useConfigStore();
// This function processes new waypoint data
const processNewWaypoints = (newWaypoints) => {
const now = moment();
const processedWaypoints = [];
const processedMarkers = [];
for (const waypoint of newWaypoints) {
// skip waypoints older than configured waypoint max age
if (config.waypointsMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(waypoint.updated_at));
if (lastUpdatedAgeInMillis > config.waypointsMaxAge * 1000) {
continue;
}
}
// skip expired waypoints
if (waypoint.expire < Date.now() / 1000) {
continue;
}
// skip waypoints without position
if (!waypoint.latitude || !waypoint.longitude) {
continue;
}
// skip nodes with invalid position
if (isNaN(waypoint.latitude) || isNaN(waypoint.longitude)) {
continue;
}
// fix lat long
waypoint.latitude = waypoint.latitude / 10000000;
waypoint.longitude = waypoint.longitude / 10000000;
// TODO: determine emoji to show as marker icon
const emoji = waypoint.icon === 0 ? 128205 : waypoint.icon;
const emojiText = String.fromCodePoint(emoji);
if (!isValidCoordinates(waypoint.latitude, waypoint.longitude)) {
continue;
}
// create waypoint marker
const marker = {
type: 'Feature',
properties: {
layer: 'waypoints',
},
geometry: {
type: 'Point',
coordinates: [waypoint.longitude, waypoint.latitude]
}
};
// add waypoint & marker to cache
processedWaypoints.push(waypoint);
processedMarkers.push(marker);
}
// Return processed data (waypoints and markers)
return { processedWaypoints, processedMarkers };
};
// Process new data and store it (bulk processing)
const parseWaypointsResponse = (newWaypoints) => {
const { processedWaypoints, processedMarkers } = processNewWaypoints(newWaypoints);
// Clear old data and update in bulk
mapStore.clearWaypoints();
mapStore.setWaypoints(processedWaypoints);
mapStore.setWaypointMarkers(processedMarkers);
};
return {
parseWaypointsResponse,
};
};

View File

@ -1,8 +1,6 @@
export default { export default {
mounted(el, binding) { mounted(el, binding) {
console.log('mounted')
el._clickOutsideHandler = (event) => { el._clickOutsideHandler = (event) => {
console.log('handler')
if (!(el === event.target || el.contains(event.target))) { if (!(el === event.target || el.contains(event.target))) {
binding.value(event); binding.value(event);
} }

View File

@ -11,6 +11,9 @@ export function setMap(map) {
export function getMap() { export function getMap() {
return instance; return instance;
} }
export function unsetMap() {
instance = null;
}
export const layerGroups = { export const layerGroups = {
nodes: {}, nodes: {},

View File

@ -9,12 +9,15 @@ export const state = reactive({
selectedNodeDeviceMetrics: [], selectedNodeDeviceMetrics: [],
selectedNodePowerMetrics: [], selectedNodePowerMetrics: [],
selectedNodeEnvironmentMetrics: [], selectedNodeEnvironmentMetrics: [],
selectedNodeToShowNeighbours: null,
selectedNodeToShowNeighbours: null, // new selected node stuff
selectedNodeToShowNeighboursType: null, positionHistoryNode: null,
neighborsNode: null,
// new modal specific stuff
neighborsModalType: null,
// position history // position history
selectedNodeToShowPositionHistory: null,
positionHistoryDateTimeTo: null, positionHistoryDateTimeTo: null,
positionHistoryDateTimeFrom: null, positionHistoryDateTimeFrom: null,
}); });

View File

@ -1,55 +1,111 @@
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import RBush from 'rbush';
import { point, bbox, distance } from '@turf/turf';
export const useMapStore = defineStore('map', { export const useMapStore = defineStore('map', {
state: () => ({ state: () => ({
nodes: [], // core stuff
waypoints: [], nodes: [],
nodeMarkers: {}, nodeIndex: new RBush(),
waypointMarkers: [], waypoints: [],
}), nodeMarkers: {},
actions: { waypointMarkers: [],
setNodes(nodes) { // temp stuff
this.nodes = nodes; positionHistory: [],
}),
actions: {
// Bulk set nodes and rebuild the spatial index
setNodes(nodes) {
this.nodes = nodes;
this.indexNodes(nodes); // Efficient reindexing after bulk update
},
// Bulk set node markers
setNodeMarkers(markers) {
this.nodeMarkers = markers;
},
// Clear nodes and markers
clearNodes() {
this.nodes = [];
this.nodeMarkers = {};
this.nodeIndex.clear(); // Clear the spatial index when nodes are cleared
},
// Bulk set waypoints
setWaypoints(waypoints) {
this.waypoints = waypoints;
},
// Bulk set waypoint markers
setWaypointMarkers(markers) {
this.waypointMarkers = markers;
},
// Clear waypoints and markers
clearWaypoints() {
this.waypoints = [];
this.waypointMarkers = [];
},
// Find a node by ID
findNodeById(id) {
return this.nodes.find(node => node.node_id.toString() === id.toString()) ?? null;
},
// Find a node marker by ID
findNodeMarkerById(id) {
return this.nodeMarkers[id] ?? null;
},
// Find a random node
findRandomNode() {
return this.nodes[Math.floor(Math.random() * this.nodes.length)] ?? null;
},
// Rebuild the spatial index for a set of nodes
indexNodes(nodes) {
// Clear the previous index
this.nodeIndex.clear();
// Rebuild the index for the new set of nodes
nodes.forEach((node) => {
const nodeMarker = this.findNodeMarkerById(node.node_id);
if (nodeMarker?.geometry?.coordinates) {
const coords = nodeMarker.geometry.coordinates;
const box = bbox(point(coords)); // Get the bounding box for the point
this.nodeIndex.insert({ minX: box[0], minY: box[1], maxX: box[2], maxY: box[3], node });
}
});
},
// Find nearby nodes within a specific distance
findNearbyNodes(node, maxDistance, checkForHeard) {
const nodeMarker = this.findNodeMarkerById(node.node_id);
if (!nodeMarker?.geometry?.coordinates) return [];
const coords = nodeMarker.geometry.coordinates;
const searchBox = bbox(point(coords)); // Get bounding box around the point
// Query the spatial index to find nearby nodes
const nearbyNodes = this.nodeIndex.search({
minX: searchBox[0], minY: searchBox[1], maxX: searchBox[2], maxY: searchBox[3]
});
return nearbyNodes.filter(({ node: nearbyNode }) => {
const nearbyNodeMarker = this.findNodeMarkerById(nearbyNode.node_id);
const distanceToNode = distance(nodeMarker, nearbyNodeMarker, { units: 'meters' });
// For 'theyHeard', check if current node is in the nearby node's neighbors
if (checkForHeard) {
const match = nearbyNode.neighbors?.find(n => n.node_id === node.node_id);
return match && distanceToNode <= maxDistance;
} else {
return distanceToNode <= maxDistance;
}
}).map(({ node: nearbyNode }) => ({
node: nearbyNode,
neighborData: nearbyNode.neighbors?.find(n => n.node_id === node.node_id),
}));
},
}, },
setNodeMarkers(markers) {
this.nodeMarkers = markers;
},
addNode(node, marker) {
// TODO do validation i.e. does it exist already?
this.nodes.push(node);
// allow undefined/null marker (nodes don't always have a marker)
if (typeof marker === 'object') this.addNodeMarker(marker);
},
addNodeMarker(marker) {
// TODO do validation checking here -- i.e. do we have the node? is marker.proprties.id set? does it exist already?
this.nodeMarkers[marker.properties.id] = marker;
},
clearNodes() {
this.nodes = [];
this.nodeMarkers = {};
},
setWaypoints(waypoints) {
this.waypoints = waypoints;
},
addWaypoint(waypoint, marker) {
this.waypoints.push(waypoint);
this.addWaypointMarker(marker);
},
addWaypointMarker(marker) {
this.waypointMarkers.push(marker);
},
clearWaypoints() {
this.waypoints = [];
this.waypointMarkers = [];
},
findNodeById(id) {
return this.nodes.find((node) => node.node_id.toString() === id.toString()) ?? null;
},
findNodeMarkerById(id) {
return this.nodeMarkers[id] ?? null;
},
findRandomNode() {
return this.nodes[Math.floor(Math.random() * this.nodes.length)] ?? null;
},
},
}); });

View File

@ -14,14 +14,16 @@ import { useUIStore } from '@/stores/uiStore';
import { useMapStore } from '@/stores/mapStore'; import { useMapStore } from '@/stores/mapStore';
import { useConfigStore } from '@/stores/configStore'; import { useConfigStore } from '@/stores/configStore';
import { useNodeProcessor } from '@/composables/useNodeProcessor'; import { useNodeProcessor } from '@/composables/useNodeProcessor';
import { useWaypointProcessor } from '@/composables/useWaypointProcessor';
import axios from 'axios'; import axios from 'axios';
import moment from 'moment'; import moment from 'moment';
import maplibregl from 'maplibre-gl'; import maplibregl from 'maplibre-gl';
import { point, distance } from '@turf/turf';
import LegendControl from '@/LegendControl'; import LegendControl from '@/LegendControl';
import LayerControl from '@/LayerControl'; import LayerControl from '@/LayerControl';
import { onMounted, useTemplateRef, ref, watch, createApp, shallowRef } from 'vue'; import { onMounted, useTemplateRef, ref, watch, createApp, shallowRef, onUnmounted } from 'vue';
import { state } from '@/store'; import { state } from '@/store';
import { import {
layerGroups, layerGroups,
@ -33,14 +35,13 @@ import {
clearAllNeighbors, clearAllNeighbors,
clearAllWaypoints, clearAllWaypoints,
clearAllPositionHistory, clearAllPositionHistory,
cleanUpPositionHistory,
closeAllTooltips, closeAllTooltips,
closeAllPopups, closeAllPopups,
cleanUpNodeNeighbors,
clearNodeOutline, clearNodeOutline,
clearMap, clearMap,
setMap, setMap,
getMap, getMap,
unsetMap,
} from '@/map'; } from '@/map';
import { CURRENT_ANNOUNCEMENT_ID } from '@/config'; import { CURRENT_ANNOUNCEMENT_ID } from '@/config';
import { import {
@ -68,13 +69,14 @@ const ui = useUIStore();
const mapData = useMapStore(); const mapData = useMapStore();
const config = useConfigStore(); const config = useConfigStore();
const { parseNodesResponse } = useNodeProcessor(); const { parseNodesResponse } = useNodeProcessor();
const { parseWaypointsResponse } = useWaypointProcessor();
// watchers // watchers
watch( watch(
() => state.positionHistoryDateTimeTo, () => state.positionHistoryDateTimeTo,
(newValue) => { (newValue) => {
if (newValue != null) { if (newValue != null) {
loadNodePositionHistory(state.selectedNodeToShowPositionHistory.node_id); loadNodePositionHistory(state.positionHistoryNode.node_id);
} }
}, {deep: true} }, {deep: true}
); );
@ -82,30 +84,60 @@ watch(
() => state.positionHistoryDateTimeFrom, () => state.positionHistoryDateTimeFrom,
(newValue) => { (newValue) => {
if (newValue != null) { if (newValue != null) {
loadNodePositionHistory(state.selectedNodeToShowPositionHistory.node_id); loadNodePositionHistory(state.positionHistoryNode.node_id);
} }
}, {deep: true} }, {deep: true}
); );
watch( watch(
() => mapData.nodeMarkers, () => mapData.nodeMarkers,
(newMarkers, oldMarkers) => { (newMarkers) => {
// This will trigger whenever nodeMarkers change // This will trigger whenever nodeMarkers change
updateMapNodeSource(newMarkers); updateMapSourceData('nodes', newMarkers);
}, },
{ deep: true } // Ensure that nested changes are also observed { deep: true } // Ensure that nested changes are also observed
); );
function updateMapNodeSource(markers) { watch(
const source = getMap().getSource('nodes'); () => mapData.waypointMarkers,
if (source) { (newMarkers) => {
// This will trigger whenever waypointMarkers change
updateMapSourceData('waypoints', newMarkers);
},
{ deep: true } // Ensure that nested changes are also observed
);
function updateMapSourceData(sourceName, features) {
const source = getMap().getSource(sourceName);
if (source !== null) {
source.setData({ source.setData({
type: 'FeatureCollection', type: 'FeatureCollection',
features: Object.values(markers), features: Object.values(features),
}); });
} }
} }
function resetNodeNeighbors() {
state.neighborsNode = null;
state.neighborsModalType = null;
cleanUpNodeNeighbors();
}
function cleanUpNodeNeighbors() {
// do map stuff (clean up markers and whatnot)
}
function resetPositionHistory() {
state.positionHistoryNode = null; // clear node, closes ui
mapStore.positionHistory = []; // clears out position history cache
cleanUpPositionHistory();
}
function cleanUpPositionHistory() {
// do map stuff (clean up markers and whatnot)
}
// TODO: this still scales pretty badly, also colors are off
function showNodeOutline(id) { function showNodeOutline(id) {
// remove any existing node circle // remove any existing node circle
clearNodeOutline(); clearNodeOutline();
@ -129,7 +161,6 @@ function showNodeOutline(id) {
let adjustedRadius = radiusInMeters * zoomFactor; let adjustedRadius = radiusInMeters * zoomFactor;
// Set a minimum radius (e.g., 10 meters) to avoid disappearing circles // Set a minimum radius (e.g., 10 meters) to avoid disappearing circles
adjustedRadius = Math.max(adjustedRadius, 10); adjustedRadius = Math.max(adjustedRadius, 10);
console.log(adjustedRadius)
// Create a circle as a GeoJSON feature // Create a circle as a GeoJSON feature
const geojsonCircle = { const geojsonCircle = {
@ -139,330 +170,125 @@ function showNodeOutline(id) {
coordinates: nodeMarker.geometry.coordinates, coordinates: nodeMarker.geometry.coordinates,
}, },
properties: { properties: {
radius: adjustedRadius // You can store the radius in the properties if needed radius: adjustedRadius,
} }
}; };
getMap().getSource('node-outlines').setData(geojsonCircle); getMap().getSource('node-outlines').setData(geojsonCircle);
} }
} }
function showNeighbors(type, id) { function showNodeNeighbors(id, direction = 'weHeard') {
let func = showNodeNeighboursThatHeardUs;
if (type === 'weHeard') func = showNodeNeighboursThatWeHeard;
func(id);
}
function showNodeNeighboursThatHeardUs(id) {
cleanUpNodeNeighbors(); cleanUpNodeNeighbors();
// find node const node = useMapStore().findNodeById(id);
const node = mapData.findNodeById(id); if (!node) return;
if (!node) {
return;
}
// find node marker const nodeMarker = useMapStore().findNodeMarkerById(node.node_id);
const nodeMarker = mapData.findNodeMarkerById(node.node_id); if (!nodeMarker?.geometry?.coordinates) return;
if (!nodeMarker) {
return;
}
// show overlay state.neighborsNode = node;
state.selectedNodeToShowNeighbours = node; state.neighborsModalType = direction;
state.selectedNodeToShowNeighboursType = 'theyHeard';
// find all nodes that have us as a neighbour const neighborFeatures = [];
const neighbourNodeInfos = []; const neighbors = direction === 'weHeard' ? node.neighbors ?? [] : mapData.findNearbyNodes(node, config.neighborsMaxDistance, true);
for (const nodeThatMayHaveHeardUs of mapData.nodes) {
// find our node in this nodes neighbours
const nodeNeighbours = nodeThatMayHaveHeardUs.neighbours ?? [];
const neighbour = nodeNeighbours.find(function(neighbour) {
return neighbour.node_id.toString() === node.node_id.toString();
});
// we exist as a neighbour // Process neighbors
if (neighbour) { neighbors.forEach((neighborData) => {
neighbourNodeInfos.push({ const neighborNode = direction === 'weHeard' ? neighborData : neighborData.node;
node: nodeThatMayHaveHeardUs, const neighbor = direction === 'weHeard' ? neighborData : neighborData.neighborData;
neighbour: neighbour,
});
}
}
// ensure we have neighbours to show if (neighbor.snr === 0) return;
if (neighbourNodeInfos.length === 0) {
return;
}
// add node neighbours const neighborNodeMarker = useMapStore().findNodeMarkerById(neighborNode.node_id);
for (const neighbourNodeInfo of neighbourNodeInfos) { if (!neighborNodeMarker?.geometry?.coordinates) return;
const neighbourNode = neighbourNodeInfo.node; // Calculate the distance in meters between the current node and the neighbor
const neighbour = neighbourNodeInfo.neighbour; const from = point(neighborNodeMarker.geometry.coordinates);
const to = point(nodeMarker.geometry.coordinates);
const distanceInMeters = distance(from, to, { units: 'meters' }).toFixed(2);
// fixme: skipping zero snr? saw some crazy long neighbours with zero snr... // Enforce max distance for weHeaerd
if (neighbour.snr === 0) { if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance && direction === 'weHeard') {
continue; return;
} }
// find neighbour node marker // Create the neighbor feature
const neighbourNodeMarker = mapData.findNodeMarkerById(neighbourNode.node_id); const feature = createNeighborFeature(node, neighborNode, neighbor.snr, direction, distanceInMeters);
if (!neighbourNodeMarker) { if (feature) {
continue; neighborFeatures.push(feature);
} }
});
// calculate distance in meters between nodes (rounded to 2 decimal places) if (neighborFeatures.length > 0) renderNeighborLines(neighborFeatures);
const distanceInMeters = neighbourNodeMarker.getLatLng().distanceTo(nodeMarker.getLatLng()).toFixed(2);
// don't show this neighbour connection if further than config allows
if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance) {
continue;
}
// add neighbour line to map
const line = L.polyline([
nodeMarker.getLatLng(), // from us
neighbourNodeMarker.getLatLng(), // to neighbour
], {
color: getColourForSnr(neighbour.snr),
opacity: 1,
}).arrowheads({
size: '10px',
fill: true,
offsets: {
start: '25px',
end: '25px',
},
}).addTo(layerGroups.nodeNeighbors);
const tooltip = getNeighbourTooltipContent('theyHeard', node, neighbourNode, distanceInMeters, neighbour.snr);
line.bindTooltip(tooltip, {
sticky: true,
opacity: 1,
interactive: true,
}).bindPopup(tooltip).on('click', function(event) {
// close tooltip on click to prevent tooltip and popup showing at same time
event.target.closeTooltip();
});
}
} }
function showNodeNeighboursThatWeHeard(id) { // Create a GeoJSON feature for each neighbor
cleanUpNodeNeighbors(); function createNeighborFeature(node, neighborNode, snr, direction, distanceInMeters) {
const neighborNodeMarker = useMapStore().findNodeMarkerById(neighborNode.node_id);
const nodeMarker = useMapStore().findNodeMarkerById(node.node_id);
// find node // Create the GeoJSON line feature for the neighbor connection
const node = mapData.findNodeById(id); return {
if (!node) { id: `line-${node.node_id}-${neighborNode.node_id}`,
return; type: 'Feature',
} geometry: {
type: 'LineString',
// find node marker coordinates: [
const nodeMarker = mapData.findNodeMarkerById(node.node_id); neighborNodeMarker.geometry.coordinates, // from neighbor
if (!nodeMarker) { nodeMarker.geometry.coordinates, // to our node
return; ],
} },
properties: {
// show overlay snr,
state.selectedNodeToShowNeighbours = node; color: getColorForSnr(snr),
state.selectedNodeToShowNeighboursType = 'weHeard'; tooltip: getNeighbourTooltipContent(direction, node, neighborNode, distanceInMeters, snr), // TODO
},
// ensure we have neighbours to show };
const neighbours = node.neighbours ?? [];
if (neighbours.length === 0) {
return;
}
for (const neighbour of neighbours) {
// fixme: skipping zero snr? saw some crazy long neighbours with zero snr...
if (neighbour.snr === 0) {
continue;
}
// find neighbor node
const neighbourNode = mapData.findNodeById(neighbour.node_id);
if (!neighbourNode) {
continue;
}
// find neighbor node marker
const neighbourNodeMarker = mapData.findNodeMarkerById(neighbour.node_id);
if (!neighbourNodeMarker) {
continue;
}
// calculate distance in meters between nodes (rounded to 2 decimal places)
const distanceInMeters = nodeMarker.getLatLng().distanceTo(neighbourNodeMarker.getLatLng()).toFixed(2);
if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance) {
continue;
}
// add neighbour line to map
const line = L.polyline([
neighbourNodeMarker.getLatLng(), // from neighbor
nodeMarker.getLatLng(), // to us
], {
color: getColorForSnr(neighbour.snr),
opacity: 1,
}).arrowheads({
size: '10px',
fill: true,
offsets: {
start: '25px',
end: '25px',
},
}).addTo(layerGroups.nodeNeighbors);
const tooltip = getNeighbourTooltipContent('weHeard', node, neighbourNode, distanceInMeters, neighbour.snr);
line.bindTooltip(tooltip, {
sticky: true,
opacity: 1,
interactive: true,
}).bindPopup(tooltip).on('click', function(event) {
// close tooltip on click to prevent tooltip and popup showing at same time
event.target.closeTooltip();
});
}
}
function onNodesUpdated(nodes) {
const now = moment();
// clear cach
mapData.clearNodes();
for (const node of nodes) {
// skip nodes older than configured node max age
if (config.nodesMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > config.nodesMaxAge * 1000) {
continue;
}
}
// add node to cache
mapData.addNode(node);
// skip nodes without position
if (!node.latitude || !node.longitude) {
continue;
}
// skip nodes with invalid position
if (isNaN(node.latitude) || isNaN(node.longitude)) {
continue;
}
// fix lat long
node.latitude = node.latitude / 10000000;
node.longitude = node.longitude / 10000000;
// icon based on mqtt connection state
let icon = icons.mqttDisconnected;
// use offline icon for nodes older than configured node offline age
if (config.nodesOfflineAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > config.nodesOfflineAge * 1000) {
icon = icons.offline;
}
}
// determine if node was recently heard uplinking packets to mqtt
const nodeHasUplinkedToMqttRecently = hasNodeUplinkedToMqttRecently(node);
if (nodeHasUplinkedToMqttRecently) {
icon = icons.mqttConnected;
}
if (!isValidCoordinates(node.latitude, node.longitude)) {
continue;
}
// create node marker
const marker = {
type: 'Feature',
properties: {
id: node.node_id,
role: node.role_name,
layer: 'nodes',
color: icon,
},
geometry: {
type: 'Point',
coordinates: [node.longitude, node.latitude]
}
};
// add marker to cache
mapData.addNodeMarker(marker);
}
// set data
const source = getMap().getSource('nodes');
if (source) {
source.setData({
type: 'FeatureCollection',
features: Object.values(mapData.nodeMarkers),
});
}
} }
function onWaypointsUpdated(waypoints) { function renderNeighborLines(features) {
const now = moment(); const sourceId = 'node-neighbors';
// clear cache const lineLayerId = 'node-neighbors-line';
mapData.clearWaypoints();
// add waypoints
for (const waypoint of waypoints) {
// skip waypoints older than configured waypoint max age
if (config.waypointsMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(waypoint.updated_at));
if (lastUpdatedAgeInMillis > config.waypointsMaxAge * 1000) {
continue;
}
}
// skip expired waypoints // Cleanup any previous layers/sources
if (waypoint.expire < Date.now() / 1000) { if (map.getLayer(lineLayerId)) map.removeLayer(lineLayerId);
continue; if (map.getSource(sourceId)) map.removeSource(sourceId);
}
// skip waypoints without position // Add source
if (!waypoint.latitude || !waypoint.longitude) { map.addSource(sourceId, {
continue; type: 'geojson',
} data: {
// skip nodes with invalid position
if (isNaN(waypoint.latitude) || isNaN(waypoint.longitude)) {
continue;
}
// fix lat long
waypoint.latitude = waypoint.latitude / 10000000;
waypoint.longitude = waypoint.longitude / 10000000;
// TODO: determine emoji to show as marker icon
const emoji = waypoint.icon === 0 ? 128205 : waypoint.icon;
const emojiText = String.fromCodePoint(emoji);
if (!isValidCoordinates(node.latitude, node.longitude)) {
continue;
}
// create waypoint marker
const marker = {
type: 'Feature',
properties: {
layer: 'waypoints',
},
geometry: {
type: 'Point',
coordinates: [waypoint.longitude, waypoint.latitude]
}
};
// add waypoint & marker to cache
mapData.addWaypoint(waypoint, marker);
}
// set data
const source = getMap().getSource('waypoints');
if (source) {
source.setData({
type: 'FeatureCollection', type: 'FeatureCollection',
features: Object.values(mapData.waypointMarkers), features,
}); },
} });
// Add solid line layer (no animation, no arrows)
map.addLayer({
id: lineLayerId,
type: 'line',
source: sourceId,
paint: {
'line-color': ['get', 'color'],
'line-width': 2,
},
});
// Interactivity: tooltips/popups
map.on('click', lineLayerId, (e) => {
const feature = e.features[0];
new maplibregl.Popup()
.setLngLat(e.lngLat)
.setHTML(feature.properties.tooltip)
.addTo(map);
});
map.on('mouseenter', lineLayerId, () => {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', lineLayerId, () => {
map.getCanvas().style.cursor = '';
});
} }
// TODO // TODO
@ -555,7 +381,7 @@ function showNodePositionHistory(nodeId) {
// update ui // update ui
state.selectedNode = null; state.selectedNode = null;
state.selectedNodeToShowPositionHistory = node; state.positionHistoryNode = node;
ui.expandPositionHistoryModal(); ui.expandPositionHistoryModal();
// close node info tooltip as position history shows under it // close node info tooltip as position history shows under it
@ -571,7 +397,7 @@ function showNodePositionHistory(nodeId) {
} }
function loadNodePositionHistory(nodeId) { function loadNodePositionHistory(nodeId) {
state.selectedNodePositionHistory = []; mapStore.positionHistory = [];
axios.get(buildPath(`/api/v1/nodes/${nodeId}/position-history`), { axios.get(buildPath(`/api/v1/nodes/${nodeId}/position-history`), {
params: { params: {
// parse from datetime-local format, and send as unix timestamp in milliseconds // parse from datetime-local format, and send as unix timestamp in milliseconds
@ -579,8 +405,8 @@ function loadNodePositionHistory(nodeId) {
time_to: moment(state.positionHistoryDateTimeTo, "YYYY-MM-DDTHH:mm").format("x"), time_to: moment(state.positionHistoryDateTimeTo, "YYYY-MM-DDTHH:mm").format("x"),
}, },
}).then((response) => { }).then((response) => {
state.selectedNodePositionHistory = response.data.position_history; mapStore.positionHistory = response.data.position_history;
if (state.selectedNodeToShowPositionHistory != null) { if (state.positionHistoryNode != null) {
clearAllPositionHistory(); clearAllPositionHistory();
onPositionHistoryUpdated(response.data.position_history); onPositionHistoryUpdated(response.data.position_history);
}; };
@ -610,7 +436,7 @@ function goToNode(id, animate, zoom){
// find node // find node
const node = mapData.findNodeById(id); const node = mapData.findNodeById(id);
if (!node) { if (!node) {
alert("Could not find node: " + id); alert('Could not find node: ' + id);
return false; return false;
} }
@ -658,6 +484,14 @@ function onSearchResultNodeClick(node) {
state.selectedNode = node; state.selectedNode = node;
} }
onUnmounted(() => {
const map = getMap();
if (map !== null) {
map.remove();
unsetMap();
}
});
onMounted(() => { onMounted(() => {
const bounds = [ const bounds = [
[-100, 70], // top left [-100, 70], // top left
@ -674,12 +508,10 @@ onMounted(() => {
layers: [], layers: [],
glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf', glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf',
}, },
//center: [-15, 150],
center: [0, 0], center: [0, 0],
zoom: 2, zoom: 2,
fadeDuration: 0, fadeDuration: 0,
renderWorldCopies: false renderWorldCopies: false
//maxBounds: [[-180, -85], [180, 85]]
}); });
setMap(map); setMap(map);
map.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right'); map.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right');
@ -692,7 +524,7 @@ onMounted(() => {
}), 'top-left'); }), 'top-left');
const layerControl = new LayerControl({ const layerControl = new LayerControl({
maps: tileLayers, maps: tileLayers,
initialMap: 'OpenStreetMap', initialMap: config.selectedTileLayerName,
controls: { controls: {
Nodes: { Nodes: {
type: 'radio', type: 'radio',
@ -700,7 +532,7 @@ onMounted(() => {
layers: { layers: {
'All': { 'All': {
type: 'layer_control', type: 'layer_control',
hideAllExcept: ['nodes', 'node-outlines'], hideAllExcept: ['nodes', 'node-outlines', 'node-neighbors-line'],
disableCluster: 'nodes', disableCluster: 'nodes',
}, },
'Routers': { 'Routers': {
@ -711,7 +543,7 @@ onMounted(() => {
}, },
'Clustered': { 'Clustered': {
type: 'layer_control', type: 'layer_control',
hideAllExcept: ['clusters', 'unclustered-points', 'cluster-count', 'node-outlines'], hideAllExcept: ['clusters', 'unclustered-points', 'cluster-count', 'node-outlines', 'node-neighbors-line'],
}, },
'None': { 'None': {
type: 'layer_control', type: 'layer_control',
@ -721,7 +553,7 @@ onMounted(() => {
}, },
Overlays: { Overlays: {
type: 'checkbox', type: 'checkbox',
default: ['Legend', 'Position History'], default: config.enabledOverlayLayers,
layers: { layers: {
'Legend': { 'Legend': {
type: 'toggle_element', type: 'toggle_element',
@ -1136,10 +968,10 @@ onMounted(() => {
<HardwareModelList /> <HardwareModelList />
<Settings /> <Settings />
<NodeInfo @show-position-history="showNodePositionHistory"/> <NodeInfo @show-position-history="showNodePositionHistory"/>
<NodeNeighborsModal @dismiss="cleanUpNodeNeighbors" /> <NodeNeighborsModal @dismiss="resetNodeNeighbors" :node="state.neighborsNode"/>
<NodePositionHistoryModal @dismiss="cleanUpPositionHistory" /> <NodePositionHistoryModal @dismiss="resetPositionHistory" :node="state.positionHistoryNode"/>
<TracerouteInfo @go-to="goToNode" /> <TracerouteInfo @go-to="goToNode" />
<Teleport v-if="popupTarget && selectedNode" :to="popupTarget"> <Teleport v-if="popupTarget && selectedNode" :to="popupTarget">
<NodeTooltip :node="selectedNode" @show-neighbors="showNeighbors"/> <NodeTooltip :node="selectedNode" @show-neighbors="showNodeNeighbors"/>
</Teleport> </Teleport>
</template> </template>