Compare commits

..

2 Commits

Author SHA1 Message Date
702da27468 more clean up 2025-04-17 21:27:54 -04:00
8e99669487 phase out old config stuff 2025-04-17 19:16:41 -04:00
26 changed files with 2762 additions and 521 deletions

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -1,11 +1,13 @@
<script setup>
import { lastSeenAnnouncementId, CURRENT_ANNOUNCEMENT_ID } from '@/config';
import { CURRENT_ANNOUNCEMENT_ID } from '@/config';
import { useUIStore } from '@/stores/uiStore';
import { useConfigStore } from '@/stores/configStore';
const ui = useUIStore();
const config = useConfigStore();
function dismissAnnouncement() {
if (lastSeenAnnouncementId.value != CURRENT_ANNOUNCEMENT_ID) {
lastSeenAnnouncementId.value = CURRENT_ANNOUNCEMENT_ID;
if (config.lastSeenAnnouncementId != CURRENT_ANNOUNCEMENT_ID) {
config.lastSeenAnnouncementId = CURRENT_ANNOUNCEMENT_ID;
}
ui.hideAnnouncement();
}

View File

@ -1,6 +1,6 @@
<script setup>
import { selectedNodeLatestPowerMetric } from '@/store.js';
import { selectedNodeLatestPowerMetric } from '@/store';
const props = defineProps({
channel: Number, // Channel number (1, 2, or 3)
});

View File

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

View File

@ -1,12 +1,13 @@
<script setup>
import { hasSeenInfoModal } from '@/config';
import { useConfigStore } from '@/stores/configStore';
import { useUIStore } from '@/stores/uiStore';
const ui = useUIStore();
const config = useConfigStore();
function dismissInfoModal() {
if (hasSeenInfoModal.value === false) {
hasSeenInfoModal.value = true;
if (config.hasSeenInfoModal === false) {
config.hasSeenInfoModal = true;
}
ui.hideInfoModal();
}

View File

@ -2,7 +2,7 @@
const props = defineProps(['node']);
import { computed } from 'vue';
import { state } from '@/store.js';
import { state } from '@/store';
import MetricsChart from '@/components/Chart/Metrics.vue';
const chartData = computed(() => {

View File

@ -1,14 +1,11 @@
<script setup>
const props = defineProps(['node']);
import { ref, computed, onMounted, watch } from 'vue';
import { useConfigStore } from '@/stores/configStore';
import { state } from '@/store.js';
import { formatTemperature } from '@/utils.js';
import { computed } from 'vue';
import { state } from '@/store';
import { formatTemperature } from '@/utils';
import MetricsChart from '@/components/Chart/Metrics.vue';
const configStore = useConfigStore();
// Chart data prep
const labels = computed(() => state.selectedNodeEnvironmentMetrics.map(m => m.created_at));
const temperatureMetrics = computed(() => state.selectedNodeEnvironmentMetrics.map(m => m.temperature));

View File

@ -1,5 +1,5 @@
<script setup>
import { getRegionFrequencyRange } from '@/utils.js';
import { getRegionFrequencyRange } from '@/utils';
const props = defineProps({
node: Object,
});

View File

@ -1,5 +1,5 @@
<script setup>
import { state } from '@/store.js';
import { state } from '@/store';
import moment from 'moment';
import { computed } from 'vue';

View File

@ -1,6 +1,6 @@
<script setup>
import { computed } from 'vue';
import { state, selectedNodeLatestPowerMetric } from '@/store.js';
import { state, selectedNodeLatestPowerMetric } from '@/store';
import MetricsChart from '@/components/Chart/Metrics.vue';
import ChannelData from '@/components/Chart/PowerMetrics/ChannelData.vue';

View File

@ -2,7 +2,7 @@
const props = defineProps({
node: Object,
});
import { getShareLinkForNode, copyShareLinkForNode } from '@/utils.js';
import { getShareLinkForNode, copyShareLinkForNode } from '@/utils';
</script>
<template>

View File

@ -1,7 +1,7 @@
<script setup>
const emit = defineEmits(['showTraceRoute']);
import moment from 'moment';
import { state } from '@/store.js';
import { state } from '@/store';
import { useMapStore } from '@/stores/mapStore';
const mapData = useMapStore();
</script>

View File

@ -4,11 +4,16 @@ import { state } from '@/store';
import CloseActionButton from '@/components/CloseActionButton.vue';
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>
<template>
@ -21,30 +26,30 @@ function dismissShowingNodeNeighbours() {
leave-from-class="translate-y-0"
leave-to-class="translate-y-full"
>
<div v-show="state.selectedNodeToShowNeighbours" 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-show="props.node !== null" class="fixed left-0 right-0 bottom-0">
<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="p-2">
<div class="flex items-start justify-between">
<div>
<h2 class="font-bold">
{{ state.selectedNodeToShowNeighbours.short_name }} Neighbors
{{ props.node.short_name }} Neighbors
</h2>
<h3
v-if="state.selectedNodeToShowNeighboursType === 'weHeard'"
v-if="state.neighborsModalType === 'weHeard'"
class="text-sm"
>
Nodes heard by {{ state.selectedNodeToShowNeighbours.short_name }}
Nodes heard by {{ props.node.short_name }}
</h3>
<h3
v-if="state.selectedNodeToShowNeighboursType === 'theyHeard'"
v-if="state.neighborsModalType === 'theyHeard'"
class="text-sm"
>
Nodes that heard {{ state.selectedNodeToShowNeighbours.short_name }}
Nodes that heard {{ props.node.short_name }}
</h3>
</div>
<CloseActionButton
@click="dismissShowingNodeNeighbours"
@click="$emit('dismiss')"
class="my-auto ml-3"
/>
</div>

View File

@ -1,13 +1,20 @@
<script setup>
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 moment from 'moment';
import { useUIStore } from '@/stores/uiStore';
const ui = useUIStore();
function dismissShowingNodePositionHistory() {
state.selectedNodePositionHistory = [];
state.selectedNodeToShowPositionHistory = null;
ui.collapsePositionHistoryModal();
emit('dismiss');
}
@ -44,8 +51,8 @@ function onPositionHistoryQuickRangeClick(range) {
leave-active-class="transition duration-300 ease-in-out transform"
leave-from-class="translate-y-0"
leave-to-class="translate-y-full">
<div v-show="state.selectedNodeToShowPositionHistory != 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-show="props.node != null" class="fixed left-0 right-0 bottom-0">
<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>
<div class="flex p-2">
@ -61,7 +68,7 @@ function onPositionHistoryQuickRangeClick(range) {
</div>
</a>
</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">
<a href="javascript:void(0)" class="rounded-full" @click="dismissShowingNodePositionHistory">
<div class="bg-gray-100 hover:bg-gray-200 p-1 rounded-full">

View File

@ -131,8 +131,8 @@ function formatDate(date) {
<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>
<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 />
<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>
</template>

View File

@ -1,11 +1,12 @@
import { useMapStore } from '@/stores/mapStore';
import moment from 'moment';
import { nodesMaxAge, nodesOfflineAge } from '@/config'; // TODO: use config store
import { useConfigStore } from '@/stores/configStore';
import { icons } from '@/map';
import { hasNodeUplinkedToMqttRecently, isValidCoordinates } from '@/utils';
export function useNodeProcessor() {
const mapStore = useMapStore(); // Access your mapStore from Pinia
const mapStore = useMapStore();
const config = useConfigStore();
// This function processes new node data
const processNewNodes = (newNodes) => {
@ -15,9 +16,9 @@ export function useNodeProcessor() {
for (const node of newNodes) {
// Skip nodes older than configured node max age
if (nodesMaxAge.value) {
if (config.nodesMaxAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > nodesMaxAge.value * 1000) {
if (lastUpdatedAgeInMillis > config.nodesMaxAge * 1000) {
continue;
}
}
@ -42,9 +43,9 @@ export function useNodeProcessor() {
let icon = icons.mqttDisconnected;
// Use offline icon for nodes older than configured node offline age
if (nodesOfflineAge.value) {
if (config.nodesOfflineAge !== null) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > nodesOfflineAge.value * 1000) {
if (lastUpdatedAgeInMillis > config.nodesOfflineAge * 1000) {
icon = icons.offline;
}
}

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,27 +1,3 @@
import { useStorage } from '@vueuse/core';
// static
export const CURRENT_ANNOUNCEMENT_ID = 1;
export const BASE_PATH = 'http://localhost:9090';
// boolean
export const autoUpdatePositionInUrl = useStorage('auto-update-url', true);
export const enableMapAnimations = useStorage('map-animations', true);
export const hasSeenInfoModal = useStorage('seen-info-modal', false);
// time in seconds
export const nodesMaxAge = useStorage('nodes-max-age', null);
export const nodesDisconnectedAge = useStorage('nodes-max-disconnected-age', 604800);
export const nodesOfflineAge = useStorage('nodes-offline-age', null);
export const waypointsMaxAge = useStorage('waypoints-max-age', 604800);
// number
export const goToNodeZoomLevel = useStorage('zoom-to-node', 15);
export const lastSeenAnnouncementId = useStorage('last-seen-announcement-id', 1);
// distance in meters
export const neighboursMaxDistance = useStorage('neighbors-distance', null);
// device info ranges
export const deviceMetricsTimeRange = useStorage('device-metrics-range', '3d');
export const powerMetricsTimeRange = useStorage('power-metrics-range', '3d');
export const environmentMetricsTimeRange = useStorage('environment-metrics-range', '3d');
// map config
export const enabledOverlayLayers = useStorage('enabled-overlay-layers', ['Legend', 'Position History']);
export const selectedTileLayerName = useStorage('selected-tile-layer', 'OpenStreetMap');
export const BASE_PATH = 'http://localhost:9090';

View File

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

View File

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

View File

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

View File

@ -21,7 +21,7 @@ export const useConfigStore = defineStore('config', {
lastSeenAnnouncementId: 1,
// Distance values (for max distances)
neighboursMaxDistance: null,
neighborsMaxDistance: null,
// Device info ranges (can be persisted)
deviceMetricsTimeRange: '3d',

View File

@ -1,55 +1,111 @@
import { defineStore } from 'pinia';
import RBush from 'rbush';
import { point, bbox, distance } from '@turf/turf';
export const useMapStore = defineStore('map', {
state: () => ({
nodes: [],
waypoints: [],
nodeMarkers: {},
waypointMarkers: [],
}),
actions: {
setNodes(nodes) {
this.nodes = nodes;
state: () => ({
// core stuff
nodes: [],
nodeIndex: new RBush(),
waypoints: [],
nodeMarkers: {},
waypointMarkers: [],
// temp stuff
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

@ -12,15 +12,18 @@ import NodeTooltip from '@/components/NodeTooltip.vue';
import { useUIStore } from '@/stores/uiStore';
import { useMapStore } from '@/stores/mapStore';
import { useConfigStore } from '@/stores/configStore';
import { useNodeProcessor } from '@/composables/useNodeProcessor';
import { useWaypointProcessor } from '@/composables/useWaypointProcessor';
import axios from 'axios';
import moment from 'moment';
import maplibregl from 'maplibre-gl';
import { point, distance } from '@turf/turf';
import LegendControl from '@/LegendControl';
import LayerControl from '@/LayerControl';
import { onMounted, useTemplateRef, ref, watch, markRaw, nextTick, createApp, shallowRef } from 'vue';
import { onMounted, useTemplateRef, ref, watch, createApp, shallowRef, onUnmounted } from 'vue';
import { state } from '@/store';
import {
layerGroups,
@ -32,30 +35,15 @@ import {
clearAllNeighbors,
clearAllWaypoints,
clearAllPositionHistory,
cleanUpPositionHistory,
closeAllTooltips,
closeAllPopups,
cleanUpNodeNeighbors,
clearNodeOutline,
clearMap,
setMap,
getMap,
unsetMap,
} from '@/map';
import {
nodesMaxAge,
nodesDisconnectedAge,
nodesOfflineAge,
waypointsMaxAge,
enableMapAnimations,
goToNodeZoomLevel,
autoUpdatePositionInUrl,
neighboursMaxDistance,
enabledOverlayLayers,
selectedTileLayerName,
hasSeenInfoModal,
lastSeenAnnouncementId,
CURRENT_ANNOUNCEMENT_ID,
} from '@/config';
import { CURRENT_ANNOUNCEMENT_ID } from '@/config';
import {
getColorForSnr,
getPositionPrecisionInMeters,
@ -75,18 +63,20 @@ const mapEl = useTemplateRef('appMap');
const popup = shallowRef(null); // Keep a single popup reference
const popupTarget = ref(null); // DOM container for Vue teleport
const isTooltipLocked = ref(false); // Locked open (via click)
const selectedNode = ref(null);
const selectedNode = ref(null); // related to tooltip only
const ui = useUIStore();
const mapData = useMapStore();
const config = useConfigStore();
const { parseNodesResponse } = useNodeProcessor();
const { parseWaypointsResponse } = useWaypointProcessor();
// watchers
watch(
() => state.positionHistoryDateTimeTo,
(newValue) => {
if (newValue != null) {
loadNodePositionHistory(state.selectedNodeToShowPositionHistory.node_id);
loadNodePositionHistory(state.positionHistoryNode.node_id);
}
}, {deep: true}
);
@ -94,30 +84,60 @@ watch(
() => state.positionHistoryDateTimeFrom,
(newValue) => {
if (newValue != null) {
loadNodePositionHistory(state.selectedNodeToShowPositionHistory.node_id);
loadNodePositionHistory(state.positionHistoryNode.node_id);
}
}, {deep: true}
);
watch(
() => mapData.nodeMarkers,
(newMarkers, oldMarkers) => {
(newMarkers) => {
// This will trigger whenever nodeMarkers change
updateMapNodeSource(newMarkers);
updateMapSourceData('nodes', newMarkers);
},
{ deep: true } // Ensure that nested changes are also observed
);
function updateMapNodeSource(markers) {
const source = getMap().getSource('nodes');
if (source) {
watch(
() => mapData.waypointMarkers,
(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({
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) {
// remove any existing node circle
clearNodeOutline();
@ -141,7 +161,6 @@ function showNodeOutline(id) {
let adjustedRadius = radiusInMeters * zoomFactor;
// Set a minimum radius (e.g., 10 meters) to avoid disappearing circles
adjustedRadius = Math.max(adjustedRadius, 10);
console.log(adjustedRadius)
// Create a circle as a GeoJSON feature
const geojsonCircle = {
@ -151,330 +170,125 @@ function showNodeOutline(id) {
coordinates: nodeMarker.geometry.coordinates,
},
properties: {
radius: adjustedRadius // You can store the radius in the properties if needed
radius: adjustedRadius,
}
};
getMap().getSource('node-outlines').setData(geojsonCircle);
}
}
function showNeighbors(type, id) {
let func = showNodeNeighboursThatHeardUs;
if (type === 'weHeard') func = showNodeNeighboursThatWeHeard;
func(id);
}
function showNodeNeighboursThatHeardUs(id) {
function showNodeNeighbors(id, direction = 'weHeard') {
cleanUpNodeNeighbors();
// find node
const node = mapData.findNodeById(id);
if (!node) {
return;
}
const node = useMapStore().findNodeById(id);
if (!node) return;
// find node marker
const nodeMarker = mapData.findNodeMarkerById(node.node_id);
if (!nodeMarker) {
return;
}
const nodeMarker = useMapStore().findNodeMarkerById(node.node_id);
if (!nodeMarker?.geometry?.coordinates) return;
// show overlay
state.selectedNodeToShowNeighbours = node;
state.selectedNodeToShowNeighboursType = 'theyHeard';
state.neighborsNode = node;
state.neighborsModalType = direction;
// find all nodes that have us as a neighbour
const neighbourNodeInfos = [];
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();
});
const neighborFeatures = [];
const neighbors = direction === 'weHeard' ? node.neighbors ?? [] : mapData.findNearbyNodes(node, config.neighborsMaxDistance, true);
// we exist as a neighbour
if (neighbour) {
neighbourNodeInfos.push({
node: nodeThatMayHaveHeardUs,
neighbour: neighbour,
});
}
}
// Process neighbors
neighbors.forEach((neighborData) => {
const neighborNode = direction === 'weHeard' ? neighborData : neighborData.node;
const neighbor = direction === 'weHeard' ? neighborData : neighborData.neighborData;
// ensure we have neighbours to show
if (neighbourNodeInfos.length === 0) {
return;
}
if (neighbor.snr === 0) return;
// add node neighbours
for (const neighbourNodeInfo of neighbourNodeInfos) {
const neighborNodeMarker = useMapStore().findNodeMarkerById(neighborNode.node_id);
if (!neighborNodeMarker?.geometry?.coordinates) return;
const neighbourNode = neighbourNodeInfo.node;
const neighbour = neighbourNodeInfo.neighbour;
// Calculate the distance in meters between the current node and the neighbor
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...
if (neighbour.snr === 0) {
continue;
// Enforce max distance for weHeaerd
if (config.neighborsMaxDistance != null && parseFloat(distanceInMeters) > config.neighborsMaxDistance && direction === 'weHeard') {
return;
}
// find neighbour node marker
const neighbourNodeMarker = mapData.findNodeMarkerById(neighbourNode.node_id);
if (!neighbourNodeMarker) {
continue;
// Create the neighbor feature
const feature = createNeighborFeature(node, neighborNode, neighbor.snr, direction, distanceInMeters);
if (feature) {
neighborFeatures.push(feature);
}
// calculate distance in meters between nodes (rounded to 2 decimal places)
const distanceInMeters = neighbourNodeMarker.getLatLng().distanceTo(nodeMarker.getLatLng()).toFixed(2);
// don't show this neighbour connection if further than config allows
if (neighboursMaxDistance.value != null && parseFloat(distanceInMeters) > neighboursMaxDistance.value) {
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();
});
}
});
if (neighborFeatures.length > 0) renderNeighborLines(neighborFeatures);
}
function showNodeNeighboursThatWeHeard(id) {
cleanUpNodeNeighbors();
// Create a GeoJSON feature for each neighbor
function createNeighborFeature(node, neighborNode, snr, direction, distanceInMeters) {
const neighborNodeMarker = useMapStore().findNodeMarkerById(neighborNode.node_id);
const nodeMarker = useMapStore().findNodeMarkerById(node.node_id);
// find node
const node = mapData.findNodeById(id);
if (!node) {
return;
}
// find node marker
const nodeMarker = mapData.findNodeMarkerById(node.node_id);
if (!nodeMarker) {
return;
}
// show overlay
state.selectedNodeToShowNeighbours = node;
state.selectedNodeToShowNeighboursType = 'weHeard';
// 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 (neighboursMaxDistance.value != null && parseFloat(distanceInMeters) > neighboursMaxDistance.value) {
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 (nodesMaxAge.value) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > nodesMaxAge.value * 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 (nodesOfflineAge.value) {
const lastUpdatedAgeInMillis = now.diff(moment(node.updated_at));
if (lastUpdatedAgeInMillis > nodesOfflineAge.value * 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),
});
}
// Create the GeoJSON line feature for the neighbor connection
return {
id: `line-${node.node_id}-${neighborNode.node_id}`,
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
neighborNodeMarker.geometry.coordinates, // from neighbor
nodeMarker.geometry.coordinates, // to our node
],
},
properties: {
snr,
color: getColorForSnr(snr),
tooltip: getNeighbourTooltipContent(direction, node, neighborNode, distanceInMeters, snr), // TODO
},
};
}
function onWaypointsUpdated(waypoints) {
const now = moment();
// clear cache
mapData.clearWaypoints();
// add waypoints
for (const waypoint of waypoints) {
// skip waypoints older than configured waypoint max age
if (waypointsMaxAge.value) {
const lastUpdatedAgeInMillis = now.diff(moment(waypoint.updated_at));
if (lastUpdatedAgeInMillis > waypointsMaxAge.value * 1000) {
continue;
}
}
function renderNeighborLines(features) {
const sourceId = 'node-neighbors';
const lineLayerId = 'node-neighbors-line';
// skip expired waypoints
if (waypoint.expire < Date.now() / 1000) {
continue;
}
// Cleanup any previous layers/sources
if (map.getLayer(lineLayerId)) map.removeLayer(lineLayerId);
if (map.getSource(sourceId)) map.removeSource(sourceId);
// 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(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({
// Add source
map.addSource(sourceId, {
type: 'geojson',
data: {
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
@ -567,7 +381,7 @@ function showNodePositionHistory(nodeId) {
// update ui
state.selectedNode = null;
state.selectedNodeToShowPositionHistory = node;
state.positionHistoryNode = node;
ui.expandPositionHistoryModal();
// close node info tooltip as position history shows under it
@ -583,7 +397,7 @@ function showNodePositionHistory(nodeId) {
}
function loadNodePositionHistory(nodeId) {
state.selectedNodePositionHistory = [];
mapStore.positionHistory = [];
axios.get(buildPath(`/api/v1/nodes/${nodeId}/position-history`), {
params: {
// parse from datetime-local format, and send as unix timestamp in milliseconds
@ -591,8 +405,8 @@ function loadNodePositionHistory(nodeId) {
time_to: moment(state.positionHistoryDateTimeTo, "YYYY-MM-DDTHH:mm").format("x"),
},
}).then((response) => {
state.selectedNodePositionHistory = response.data.position_history;
if (state.selectedNodeToShowPositionHistory != null) {
mapStore.positionHistory = response.data.position_history;
if (state.positionHistoryNode != null) {
clearAllPositionHistory();
onPositionHistoryUpdated(response.data.position_history);
};
@ -622,7 +436,7 @@ function goToNode(id, animate, zoom){
// find node
const node = mapData.findNodeById(id);
if (!node) {
alert("Could not find node: " + id);
alert('Could not find node: ' + id);
return false;
}
@ -641,7 +455,7 @@ function goToNode(id, animate, zoom){
const coords = nodeMarker.geometry.coordinates;
getMap().flyTo({
center: coords,
zoom: parseFloat(zoom || goToNodeZoomLevel.value)
zoom: parseFloat(zoom || config.goToNodeZoomLevel)
});
getMap().once('moveend', async () => {
// add position bubble for node
@ -670,6 +484,14 @@ function onSearchResultNodeClick(node) {
state.selectedNode = node;
}
onUnmounted(() => {
const map = getMap();
if (map !== null) {
map.remove();
unsetMap();
}
});
onMounted(() => {
const bounds = [
[-100, 70], // top left
@ -686,12 +508,10 @@ onMounted(() => {
layers: [],
glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf',
},
//center: [-15, 150],
center: [0, 0],
zoom: 2,
fadeDuration: 0,
renderWorldCopies: false
//maxBounds: [[-180, -85], [180, 85]]
});
setMap(map);
map.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right');
@ -704,7 +524,7 @@ onMounted(() => {
}), 'top-left');
const layerControl = new LayerControl({
maps: tileLayers,
initialMap: 'OpenStreetMap',
initialMap: config.selectedTileLayerName,
controls: {
Nodes: {
type: 'radio',
@ -712,7 +532,7 @@ onMounted(() => {
layers: {
'All': {
type: 'layer_control',
hideAllExcept: ['nodes', 'node-outlines'],
hideAllExcept: ['nodes', 'node-outlines', 'node-neighbors-line'],
disableCluster: 'nodes',
},
'Routers': {
@ -723,7 +543,7 @@ onMounted(() => {
},
'Clustered': {
type: 'layer_control',
hideAllExcept: ['clusters', 'unclustered-points', 'cluster-count', 'node-outlines'],
hideAllExcept: ['clusters', 'unclustered-points', 'cluster-count', 'node-outlines', 'node-neighbors-line'],
},
'None': {
type: 'layer_control',
@ -733,7 +553,7 @@ onMounted(() => {
},
Overlays: {
type: 'checkbox',
default: ['Legend', 'Position History'],
default: config.enabledOverlayLayers,
layers: {
'Legend': {
type: 'toggle_element',
@ -927,7 +747,6 @@ function measureTooltipSize(node) {
}
async function openLockedTooltipFromNode(feature) {
console.log('openLockedTooltipFromNode', feature);
const nodeId = feature?.properties?.id;
const node = mapData.findNodeById(nodeId ?? '');
const coordinates = feature?.geometry?.coordinates?.slice();
@ -1122,10 +941,10 @@ async function determineAnchorForNode(node, coordinates) {
}
onMounted(() => {
if (lastSeenAnnouncementId.value !== CURRENT_ANNOUNCEMENT_ID) {
if (config.lastSeenAnnouncementId !== CURRENT_ANNOUNCEMENT_ID) {
ui.showAnnouncement();
}
if (!isMobile() && hasSeenInfoModal.value === false) {
if (!isMobile() && config.hasSeenInfoModal === false) {
ui.showInfoModal();
}
})
@ -1149,10 +968,10 @@ onMounted(() => {
<HardwareModelList />
<Settings />
<NodeInfo @show-position-history="showNodePositionHistory"/>
<NodeNeighborsModal @dismiss="cleanUpNodeNeighbors" />
<NodePositionHistoryModal @dismiss="cleanUpPositionHistory" />
<NodeNeighborsModal @dismiss="resetNodeNeighbors" :node="state.neighborsNode"/>
<NodePositionHistoryModal @dismiss="resetPositionHistory" :node="state.positionHistoryNode"/>
<TracerouteInfo @go-to="goToNode" />
<Teleport v-if="popupTarget && selectedNode" :to="popupTarget">
<NodeTooltip :node="selectedNode" @show-neighbors="showNeighbors"/>
<NodeTooltip :node="selectedNode" @show-neighbors="showNodeNeighbors"/>
</Teleport>
</template>