From c43f58dc3f41f881f4dcbeae63ca86159448696c Mon Sep 17 00:00:00 2001 From: Trygve Hemminghytt <274629477+trygvehhh@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:46:20 +0200 Subject: [PATCH] feat: Kartverket ground heights for Statens vegvesen cameras The Vegvesen camera feed is 2D, so every camera shared one flat 150 m ground prior and mountain-pass cameras could sit hundreds of metres below the terrain where neither the point-height prior nor the ground snap resolves. Each camera now gets its terrain height from Kartverket's keyless point-height API (CC BY 4.0): ~840 of ~845 cameras. - 50 points per request, six in flight; points a full batch answers null for are retried once in batches of 10 (the API drops points from large batches). - Sea-floor depths (dybdekurver / Havflate) under bridges and quays count as the water surface, 0 m. - Heights are cached by position, so the 15-minute refresh only asks about new or moved cameras. A catalog load waits at most 12 s; a slower lookup keeps filling the cache for the next refresh. - CCTV_VEGVESEN_HEIGHTS=0 turns it off; Kartverket is credited beside Statens vegvesen in the attribution popover. Follow-up to #929. Co-Authored-By: Claude Opus 5.5 --- .env.example | 1 + CHANGELOG.md | 10 ++ DATA_SOURCES.md | 2 + docs/CURRENT-STATE.md | 2 +- server/providers/cctv/constants.js | 24 +++ server/providers/cctv/sources.js | 225 ++++++++++++++++++++++++++++- src/data/cctvVegvesen.test.mjs | 223 +++++++++++++++++++++++++++- src/data/dataCredits.js | 3 +- 8 files changed, 479 insertions(+), 11 deletions(-) diff --git a/.env.example b/.env.example index ee7620be9..99a3ff88b 100644 --- a/.env.example +++ b/.env.example @@ -195,6 +195,7 @@ AISSTREAM_API_KEY= # CCTV_VEGVESEN_ENABLED=1 # set 0 to disable the Statens vegvesen (Norway) road cameras # CCTV_VEGVESEN_MAX_SOURCES=900 # cap cameras loaded from Statens vegvesen (default loads all ~850 live; max 1000) # CCTV_VEGVESEN_VIDEO=1 # set 0 to show stills instead of live HLS for Statens vegvesen video cameras +# CCTV_VEGVESEN_HEIGHTS=1 # set 0 to skip Kartverket ground heights for Statens vegvesen cameras (flat prior instead) # CCTV_VEGVESEN_URL= # override the Statens vegvesen catalog URL # CCTV_MAX_SOURCES=4000 # catalog-wide ceiling, shared round-robin across packs # CCTV_PREFER_AUSTIN=1 # prioritize Austin cameras in the registry diff --git a/CHANGELOG.md b/CHANGELOG.md index b433f8c06..86cda068c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## [Unreleased] +- Give each Statens vegvesen camera its own ground height from Kartverket's + keyless point-height API (CC BY 4.0) instead of one flat 150 m prior, so + mountain-pass cameras no longer sit hundreds of metres below the terrain + where neither the point-height prior nor the ground snap resolves. About + 840 of ~845 cameras get a height; the rest keep the old prior. Bridge and + quay cameras over water use the sea surface, not the sea-floor depth the + API returns there. A catalog load waits at most 12 s for heights, and a + lookup still running then fills a cache the next refresh applies. + `CCTV_VEGVESEN_HEIGHTS=0` turns the lookup off. Follow-up to #929. + - Add Norway's road cameras from Statens vegvesen as a CCTV pack. The camera list is one keyless GeoJSON request to the agency's OGC API view of its DATEX 3.1 CCTV table, so no DATEX account is needed. Every working camera diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 734e35a69..4959c1c75 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -55,6 +55,7 @@ How to read this: | **DriveBC** (Government of British Columbia) | CCTV camera catalog + frames, British Columbia highways | [Open Government Licence – British Columbia](https://www2.gov.bc.ca/gov/content/data/open-data/open-government-licence-bc) — attribution REQUIRED | "DriveBC. Contains information licensed under the Open Government Licence – British Columbia" | | **Open Calgary** (`data.calgary.ca`) | CCTV camera catalog + frames, Calgary | [Open Government Licence – City of Calgary](https://data.calgary.ca/stories/s/Open-Calgary-Terms-of-Use/u45n-7awa) — attribution REQUIRED | "Contains information licensed under the Open Government Licence – City of Calgary" | | **Statens vegvesen** (catalog `ogckart-sn1.atlas.vegvesen.no`, frames `kamera.atlas.vegvesen.no`, HLS `kamera.vegvesen.no`) | CCTV camera catalog + frames + live HLS video, Norway road cameras | [NLOD 2.0](https://data.norge.no/nlod/en/2.0) — attribution REQUIRED | "Contains data under the Norwegian licence for Open Government data (NLOD) distributed by Statens vegvesen" | +| **Kartverket** (`ws.geonorge.no/hoydedata/v1/punkt`) | Terrain heights (NN2000) used as the ground prior for Statens vegvesen cameras | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — attribution REQUIRED | "© Kartverket" | | **GBFS (Lyft / BCycle)** | Bikeshare availability | Per-feed (attribution-only) | Credit the operator (e.g. Austin BCycle) + its `license_url` | | **MBTA / MassDOT** (cdn.mbta.com) | Transit layer live vehicles and up to 15 minutes of recently observed positions, Greater Boston | MBTA / MassDOT open realtime vehicle data, used for the live view and up to fifteen minutes of recently observed positions; published for developer use and not against their use. | Attribution to MBTA / MassDOT (courtesy text) | | **CapMetro** (data.texas.gov) | Transit layer live vehicles, Austin TX | CapMetro open realtime vehicle data, used for the live view; published for developer use and not against their use. | Attribution to CapMetro (courtesy text) | @@ -90,6 +91,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei - **Live Traffic NSW cameras.** The camera list is the keyless public `data.livetraffic.com/cameras/traffic-cam.json` feed (Transport for NSW open data, CC BY 4.0); frames are stills on `webcams.transport.nsw.gov.au`, and only that host is registered. That image host answers non-browser clients with an HTML placeholder, so the proxy identifies as a browser for that one host and as itself everywhere else. Frames are fetched at request time and never stored or redistributed. Disable with `CCTV_NSW_ENABLED=0`. - **Open Calgary traffic cameras.** Keyless. The camera list is the public Socrata dataset `k7p9-kppz` on `data.calgary.ca`; frames are stills on the city's own `trafficcam.calgary.ca` host, and only that host is registered. Most rows publish an `http://` frame URL and the host redirects those to HTTPS, so URLs are upgraded and pinned to that origin before registration. Frames are fetched at request time and never stored or redistributed. The dataset publishes no camera facing: the `quadrant` field and the quadrant suffix on each camera name are Calgary's address grid, not a bearing, so headings use the shared id-hash fallback at low confidence and are corrected with the in-app calibration gizmo. The licence requires the attribution statement above. Disable with `CCTV_CALGARY_ENABLED=0`. - **Statens vegvesen road cameras.** Keyless. The camera list is one GeoJSON request to the OGC API Features view of the official DATEX 3.1 CCTV site table (`ogckart-sn1.atlas.vegvesen.no/ogc/features/v1/collections/datex_3_1:CctvSimple/items`), so no DATEX account is needed; frames are stills on `kamera.atlas.vegvesen.no/api/images/`, and only that exact path per camera is registered. Cameras the feed reports as faulty are dropped. About 135 working cameras also publish live HLS (`kamera.vegvesen.no/public//manifest.m3u8`, MPEG-TS); those play as live video through the bounded in-memory HLS relay, with the still as the snapshot fallback, and only that exact manifest path per camera is registered. `CCTV_VEGVESEN_VIDEO=0` keeps every camera on stills. `orientationDescription` names the place a camera faces, not a bearing, so it goes into the label and headings use the id-hash fallback at low confidence. By default every live camera loads (~850); `CCTV_VEGVESEN_MAX_SOURCES` (8–1000) lowers the cap, keeping the cameras nearest Oslo, Bergen, Stavanger, Trondheim, Kristiansand, Bodø and Tromsø and `CCTV_VEGVESEN_ENABLED=0` turns the pack off. Frames are fetched at request time and never stored or redistributed. The NLOD attribution is registered in the Data attribution popover. +- **Kartverket ground heights for Statens vegvesen cameras.** The camera feed's points are 2D, so the loader asks Kartverket's keyless point-height API (`ws.geonorge.no/hoydedata/v1/punkt`, CC BY 4.0) for the terrain height at each camera, 50 points per request with up to six in flight (about 17 requests, ~5 s, for the whole country). Points a full batch answers `null` for are retried once in batches of 10, since the API sometimes drops points from large batches; points still without data keep the flat 150 m prior. Over water the API returns the sea-floor depth (`dybdekurver` / `Havflate`), which is replaced by 0 m, the water surface. Heights are cached in memory by position, so the 15-minute catalog refresh only asks about new or moved cameras. A catalog load waits at most 12 s; a slower lookup keeps filling the cache for the next refresh. Only coordinates are sent. `CCTV_VEGVESEN_HEIGHTS=0` turns the lookup off. The Kartverket credit is shown beside the Statens vegvesen entry in the Data attribution popover. - **Camera frame content.** Public camera frames can contain people, vehicles and license plates, and the camera layer does nothing with them beyond putting them on the map. A successful upstream response is relayed as the provider served it: nothing in the camera pipeline blurs, redacts, enhances or restores it, and nothing there runs face, plate or object detection or otherwise recognises or classifies what is in the picture. (The ALPR layer described below maps where plate-reader cameras are, from locations contributors tagged in OpenStreetMap; it reads nothing from any camera frame.) When an upstream has no frame for a camera, what you see instead is a Google Street View still or the app's own placeholder card; the panel's source badge names which of them you are looking at, and a refresh that fails after a frame has arrived leaves the last good picture on screen rather than replacing it. The browser resamples each frame for display: onto a fixed 1920x1080 surface for the camera's projection plane in the scene, and onto a 192x108 canvas for the small ambient card. That scaling is the only change made to the picture, and the only pixels the camera layer reads back are a 64x36 downscale hashed to tell whether the picture has changed. Live streams are piped through; the still path reads the image into memory to pass it on — TxDOT wraps its JPEG in a JSON envelope, which is decoded there — and no frame is written to disk (the disk cache, `.gev-cache/`, holds feed JSON for other layers and never camera imagery). Outside that pipeline, the voice assistant is the one feature that sends imagery anywhere: when it answers a question about what is in view it may attach a downscaled screenshot of the rendered scene — including any camera plane on screen — to the request it sends to the voice model. Frames are fetched only from server-registered camera URLs — a client cannot hand the proxy a URL (see [SECURITY.md](SECURITY.md)). What the app does stays inside the line README draws: no named-person search, no face recognition, no tracking individuals. - **Transit (GTFS-Realtime).** The proxy requests only registered operator feeds, validates redirects, bounds responses, and uses conditional requests, short snapshot caching and failure backoff. All seven registered regions are live-enabled; each can be disabled independently. Vehicles use delayed playback between reports, with report age and waiting states shown separately. Session-local selected trails are available for every feed. MBTA additionally retains up to 15 minutes of recently observed positions in the running proxy, so available history can survive a browser reload; server restart clears it. History reads never fetch upstream, and other feeds have no proxy retention. Nothing is archived to disk or collected in the background. Operator text credits are included as a courtesy and do not imply endorsement. Heights are aligned to work with Google 3D tiles; subway markers are shown at street level because these feeds do not supply depth. - **Radio Browser.** `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; schema-valid responses whose rows all fail the product's health policy do not count as successful queries. A usable partial cold catalog is explicitly `DEGRADED`, and malformed or empty successful payloads are rejected atomically. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index d4fe022a8..c5bf9df9e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2919,7 +2919,7 @@ its criteria cannot be silently ignored. | Satellites | CelesTrak | `src/data/satellites.js` | `/api/celestrak` | 120s | | Space Missions (30d) | Launch Library 2 + CelesTrak | `src/data/rocketLaunches.js` | `/api/launches` + `/api/celestrak/active` | 5 min | | Traffic | Selectable TomTom / OpenStreetMap / Hybrid roads; optional TomTom flow (BYOK) | `src/data/traffic.js` | browser-direct OpenFreeMap tiles; `/api/tomtom` for flow | viewport-driven; capped tile cache | -| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | +| CCTV | Austin + Caltrans (CA) + TfL London + Ontario 511 + Fintraffic (FI) + DriveBC (BC) + TxDOT (TX) + Estonia (Tallinn, Tarktee) + Live Traffic NSW + Open Calgary Open Data + Statens vegvesen (NO, stills + live HLS, Kartverket ground heights) + Street View fallback | `src/data/cctv.js` | `/api/cctv` | 10s (active) | | Radio | Radio Browser (public-domain station directory) | `src/data/radio.js` | `/api/radio/stations`, `/api/radio/click/:uuid` | 45 min directory refresh | | Transit 🚌 | Operator GTFS-Realtime VehiclePositions (7 keyless regions, `src/data/transitFeeds.js`) | `src/layers/transit/` via `src/app/layers/transit.js` | `/api/transit` | 15s (poll + delayed playback) | | Bikeshare 🚲 | GBFS (Lyft + BCycle) | `src/data/bikeshare.js` | `/api/gbfs` | 60s | diff --git a/server/providers/cctv/constants.js b/server/providers/cctv/constants.js index 6298e86a0..7609a3fc5 100644 --- a/server/providers/cctv/constants.js +++ b/server/providers/cctv/constants.js @@ -267,6 +267,30 @@ export const NORWAY_ANCHORS = [ { lat: 69.6492, lon: 18.9553 }, // Tromsø ]; +/** Kartverket's keyless point-height API (CC BY 4.0): terrain height above + * sea level (NN2000) for up to 50 points per request, used as the Vegvesen + * cameras' ground prior because the camera feed's points are 2D. */ +export const KARTVERKET_HEIGHT_URL = + 'https://ws.geonorge.no/hoydedata/v1/punkt'; +export const KARTVERKET_MAX_POINTS = 50; +/** Batch size for the one retry of points a full batch answered null for. */ +export const KARTVERKET_RETRY_POINTS = 10; +/** Batches in flight at once. The whole country is ~17 batches of ~2 s each + * (spread-out points are slow to resolve), so six keep a cold lookup ~6 s. */ +export const KARTVERKET_CONCURRENCY = 6; +/** Deadline for one complete lookup, shared by every batch. */ +export const KARTVERKET_LOOKUP_TIMEOUT_MS = 30 * 1000; +/** How long a catalog load waits for heights. Kept under the per-provider + * fetch timeout so this pack is never the catalog's slowest lane; a lookup + * still running after this keeps filling the cache, and the next refresh + * applies the rest. At app start, with every pack loading at once, a cold + * lookup takes ~10 s. */ +export const KARTVERKET_CATALOG_WAIT_MS = 12 * 1000; +export const KARTVERKET_MAX_RESPONSE_BYTES = 256 * 1024; +/** Plausible Norwegian terrain: below sea level only at the shore, and no road + * camera sits above ~1,500 m. Anything outside is treated as no answer. */ +export const KARTVERKET_HEIGHT_RANGE_M = Object.freeze({ min: -20, max: 2500 }); + /** DelDOT CCTV: one keyless statewide JSON catalog; live video via RTMP-over-HTTP (rtmpt:80). */ export const DELDOT_CCTV_URL = 'https://tmc.deldot.gov/json/videocamera.json'; export const DEFAULT_DELDOT_MAX_SOURCES = 300; diff --git a/server/providers/cctv/sources.js b/server/providers/cctv/sources.js index 7ecd3434d..281ddde85 100644 --- a/server/providers/cctv/sources.js +++ b/server/providers/cctv/sources.js @@ -65,6 +65,14 @@ import { DEFAULT_VEGVESEN_MAX_SOURCES, VEGVESEN_MAX_CATALOG_BYTES, NORWAY_ANCHORS, + KARTVERKET_HEIGHT_URL, + KARTVERKET_MAX_POINTS, + KARTVERKET_RETRY_POINTS, + KARTVERKET_CONCURRENCY, + KARTVERKET_LOOKUP_TIMEOUT_MS, + KARTVERKET_CATALOG_WAIT_MS, + KARTVERKET_MAX_RESPONSE_BYTES, + KARTVERKET_HEIGHT_RANGE_M, } from './constants.js'; import { toFiniteNumber, @@ -1779,14 +1787,11 @@ export function vegvesenCameraToSource(feature) { fovDeg: 44, rangeM: 145, mountHeightM: 8, - // KNOWN LIMITATION: the feed's coordinates are 2D, so this is one flat - // prior for the whole country, while cameras run from sea level to - // mountain passes near 1,000 m (Haukelifjell, Sjonfjellet, Rugeldalen). - // The point-height prior and the client's one-shot ground snap correct it - // where they resolve; on a stack where neither does (no 3D tiles), a pass - // camera stays hundreds of metres below the terrain, the same risk the - // Caltrans pack documents. A per-camera height (e.g. Kartverket's keyless - // point-height API) would remove it. + // The feed's coordinates are 2D. The loader replaces this flat prior with + // Kartverket's terrain height for each camera (applyVegvesenGroundHeights); + // it only survives when that lookup fails, and then a mountain-pass camera + // can sit below the terrain on a stack without 3D tiles, the same risk the + // Caltrans pack documents. groundElevationM: 150, feedType: videoUrl ? 'hls' : 'image', url: videoUrl || imageUrl, @@ -1851,6 +1856,7 @@ export async function loadVegvesenSourcesFromOpenData() { ? Math.max(8, Math.min(1000, Math.floor(maxRaw))) : DEFAULT_VEGVESEN_MAX_SOURCES; const prioritized = prioritizeSources(cameras, maxCount, NORWAY_ANCHORS); + await applyVegvesenGroundHeights(prioritized); console.log( `[CCTV] Loaded Vegvesen camera sources: ${cameras.length} (using nearest ${prioritized.length})`, ); @@ -1863,3 +1869,206 @@ export async function loadVegvesenSourcesFromOpenData() { return []; } } + +/** + * Terrain heights already resolved, keyed by rounded position. Camera + * positions rarely change, so after the first catalog load a 15-minute refresh + * asks Kartverket only for new or moved cameras. Bounded well above the ~900 + * cameras the pack can load. + */ +const kartverketHeightCache = new Map(); +const KARTVERKET_CACHE_LIMIT = 5000; +/** The lookup in flight, so overlapping catalog loads never start a second. */ +let kartverketPending = null; + +/** Cache key for one position, at the ~0.1 m precision the request sends. */ +const kartverketKey = (lon, lat) => `${lon.toFixed(6)},${lat.toFixed(6)}`; + +/** Forget cached heights and any lookup in flight. Tests only. */ +export function clearKartverketHeightCache() { + kartverketHeightCache.clear(); + kartverketPending = null; +} + +/** + * Terrain heights above sea level (NN2000) from Kartverket's keyless + * point-height API, in batches of up to 50 points. Answers are matched back by + * the coordinates the API echoes, not by position in the list. Each answer is + * written to `into` as its batch lands, so a caller that stops waiting still + * keeps what has arrived. One deadline covers every request. + * + * Two quirks of the live API are handled here: + * - A large batch sometimes answers `z: null` for a point it resolves when + * asked again (Valdresflye: null in a 50-point batch, 1,390.7 m alone), so + * every point still missing after the first pass is retried once in batches + * of KARTVERKET_RETRY_POINTS. A point still null then has no data. + * - Over water `/punkt` returns the depth of the sea floor (`dybdekurver`, + * terrain `Havflate`; −547 m under Nordhordlandsbrua). A camera on a bridge + * or quay stands over the water surface, so those answers count as 0 m. + * + * @param {Array<{lon:number, lat:number}>} points + * @param {{into?: Map, timeoutMs?: number}} [options] + * @returns {Promise>} kartverketKey(lon, lat) → metres. + */ +export async function fetchKartverketHeights( + points, + { into = new Map(), timeoutMs = KARTVERKET_LOOKUP_TIMEOUT_MS } = {}, +) { + const unique = Array.from( + new Map( + (points || []) + .filter((p) => isLikelyNorwayCoordinate(p?.lat, p?.lon)) + .map((p) => [kartverketKey(p.lon, p.lat), p]), + ).values(), + ); + if (!unique.length) return into; + const signal = AbortSignal.timeout(timeoutMs); + const fetchBatch = async (batch) => { + const url = new URL(KARTVERKET_HEIGHT_URL); + url.searchParams.set( + 'punkter', + JSON.stringify( + batch.map((p) => [Number(p.lon.toFixed(6)), Number(p.lat.toFixed(6))]), + ), + ); + url.searchParams.set('koordsys', '4258'); + const resp = await fetch(url, { + headers: { Accept: 'application/json' }, + redirect: 'error', + signal, + }); + if (!resp.ok) { + try { + await resp.body?.cancel(); + } catch { + /* no-op */ + } + throw new Error(`HTTP ${resp.status}`); + } + const payload = await readResponseJsonCapped( + resp, + KARTVERKET_MAX_RESPONSE_BYTES, + ); + for (const point of Array.isArray(payload?.punkter) + ? payload.punkter + : []) { + // `z: null` means no answer for that point; Number(null) would read 0. + if (point?.z === null || point?.z === undefined || point?.z === '') + continue; + const x = toFiniteNumber(point?.x); + const y = toFiniteNumber(point?.y); + let z = toFiniteNumber(point?.z); + if (![x, y, z].every(Number.isFinite)) continue; + if (point?.datakilde === 'dybdekurver' || point?.terreng === 'Havflate') + z = 0; + if ( + z < KARTVERKET_HEIGHT_RANGE_M.min || + z > KARTVERKET_HEIGHT_RANGE_M.max + ) + continue; + into.set(kartverketKey(x, y), z); + } + }; + let failed = 0; + const runPass = async (list, size) => { + const batches = []; + for (let i = 0; i < list.length; i += size) { + batches.push(list.slice(i, i + size)); + } + let next = 0; + const worker = async () => { + while (next < batches.length && !signal.aborted) { + const batch = batches[next++]; + try { + await fetchBatch(batch); + } catch (error) { + failed += 1; + if (failed === 1) { + console.warn( + '[CCTV] Kartverket height lookup failed:', + error?.message || error, + ); + } + } + } + }; + await Promise.all( + Array.from( + { length: Math.min(KARTVERKET_CONCURRENCY, batches.length) }, + worker, + ), + ); + }; + await runPass(unique, KARTVERKET_MAX_POINTS); + const missing = unique.filter((p) => !into.has(kartverketKey(p.lon, p.lat))); + if (missing.length && !signal.aborted) { + await runPass(missing, KARTVERKET_RETRY_POINTS); + } + return into; +} + +/** + * Give each Vegvesen camera its own terrain height as the ground prior, in + * place. Waits at most `waitMs` for heights it does not have cached; a lookup + * still running then keeps filling the cache for the next catalog refresh. + * Cameras without a height keep the flat prior. Never throws: a failed lookup + * only means the old behavior. CCTV_VEGVESEN_HEIGHTS=0 turns it off. + * + * @param {Array} cameras - Sources from vegvesenCameraToSource(). + * @param {{waitMs?: number}} [options] + * @returns {Promise} How many cameras got a terrain height. + */ +export async function applyVegvesenGroundHeights( + cameras, + { waitMs = KARTVERKET_CATALOG_WAIT_MS } = {}, +) { + if (String(process.env.CCTV_VEGVESEN_HEIGHTS || '1').trim() === '0') return 0; + const list = Array.isArray(cameras) ? cameras : []; + const missing = list.filter( + (c) => !kartverketHeightCache.has(kartverketKey(c.lon, c.lat)), + ); + if (missing.length) { + if (!kartverketPending) { + if ( + kartverketHeightCache.size + missing.length > + KARTVERKET_CACHE_LIMIT + ) { + kartverketHeightCache.clear(); + } + kartverketPending = fetchKartverketHeights(missing, { + into: kartverketHeightCache, + }) + .catch((error) => { + console.warn( + '[CCTV] Kartverket height lookup error:', + error?.message || error, + ); + }) + .finally(() => { + kartverketPending = null; + }); + } + let timer; + await Promise.race([ + kartverketPending, + new Promise((resolve) => { + timer = setTimeout(resolve, waitMs); + timer.unref?.(); + }), + ]); + clearTimeout(timer); + } + let applied = 0; + for (const camera of list) { + const z = kartverketHeightCache.get(kartverketKey(camera.lon, camera.lat)); + if (!Number.isFinite(z)) continue; + camera.groundElevationM = Math.round(z * 10) / 10; + applied += 1; + } + if (list.length) { + console.log( + `[CCTV] Kartverket ground heights: ${applied}/${list.length} Vegvesen cameras`, + ); + } + return applied; +} diff --git a/src/data/cctvVegvesen.test.mjs b/src/data/cctvVegvesen.test.mjs index 457fecbda..ffb25aec3 100644 --- a/src/data/cctvVegvesen.test.mjs +++ b/src/data/cctvVegvesen.test.mjs @@ -2,11 +2,17 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { + applyVegvesenGroundHeights, + clearKartverketHeightCache, + fetchKartverketHeights, loadVegvesenSourcesFromOpenData, vegvesenCameraToSource, } from '../../server/providers/cctv/sources.js'; import { DEFAULT_VEGVESEN_CCTV_URL, + KARTVERKET_HEIGHT_URL, + KARTVERKET_MAX_POINTS, + KARTVERKET_RETRY_POINTS, VEGVESEN_IMAGE_ORIGIN, } from '../../server/providers/cctv/constants.js'; import { createCctvCatalog } from '../../server/providers/cctv/catalog.js'; @@ -104,6 +110,8 @@ test('faulty cameras, off-host frames and bad geometry are dropped', () => { }); test('the loader dedupes, and failures degrade to an empty pack', async (t) => { + clearKartverketHeightCache(); + t.after(clearKartverketHeightCache); t.mock.method(console, 'log', () => {}); t.mock.method(console, 'warn', () => {}); const requested = []; @@ -127,7 +135,11 @@ test('the loader dedupes, and failures degrade to an empty pack', async (t) => { }); }); const cameras = await loadVegvesenSourcesFromOpenData(); - assert.deepEqual(requested, [DEFAULT_VEGVESEN_CCTV_URL]); + // The catalog first; the rest is the Kartverket height lookup. + assert.equal(requested[0], DEFAULT_VEGVESEN_CCTV_URL); + assert.ok( + requested.slice(1).every((url) => url.startsWith(KARTVERKET_HEIGHT_URL)), + ); // Nearest-to-anchor first: Oslo leads. assert.deepEqual( cameras.map((c) => c.id), @@ -200,3 +212,212 @@ test('CCTV_VEGVESEN_ENABLED=0 keeps the lane from being loaded', async (t) => { ); }); }); + +/** Answer a Kartverket request the way the live API does: echo every point, + * with the height `heightFor(x, y)` returns (null = outside coverage). */ +const kartverketResponse = (url, heightFor) => { + const points = JSON.parse(new URL(url).searchParams.get('punkter')); + return Response.json({ + koordsys: 4258, + punkter: points.map(([x, y]) => ({ x, y, z: heightFor(x, y) })), + }); +}; + +/** Cameras at distinct Norwegian positions. */ +const cameraAt = (i) => ({ + id: `no-vegvesen-${i}`, + lat: 60 + i * 0.001, + lon: 7 + i * 0.001, + groundElevationM: 150, +}); + +const withHeightsEnv = (t) => { + const saved = process.env.CCTV_VEGVESEN_HEIGHTS; + delete process.env.CCTV_VEGVESEN_HEIGHTS; + clearKartverketHeightCache(); + t.after(() => { + clearKartverketHeightCache(); + if (saved === undefined) delete process.env.CCTV_VEGVESEN_HEIGHTS; + else process.env.CCTV_VEGVESEN_HEIGHTS = saved; + }); + t.mock.method(console, 'log', () => {}); + t.mock.method(console, 'warn', () => {}); +}; + +test('Kartverket heights come in batches of 50, matched by echoed coordinates', async (t) => { + withHeightsEnv(t); + const requested = []; + t.mock.method(globalThis, 'fetch', async (url) => { + requested.push(String(url)); + assert.ok(String(url).startsWith(KARTVERKET_HEIGHT_URL)); + // Reply in reverse order: matching must not depend on list position. + const response = kartverketResponse(url, (x) => + x > 7.05 ? null : Math.round((x - 7) * 10000), + ); + const body = await response.json(); + body.punkter.reverse(); + return Response.json(body); + }); + const points = Array.from({ length: 120 }, (_, i) => cameraAt(i)); + const heights = await fetchKartverketHeights(points); + const sizes = requested.map( + (url) => JSON.parse(new URL(url).searchParams.get('punkter')).length, + ); + // Three full batches, then one retry pass over the 69 points with no height. + assert.deepEqual(sizes.slice(0, 3), [KARTVERKET_MAX_POINTS, 50, 20]); + assert.equal( + sizes.slice(3).reduce((a, b) => a + b, 0), + 69, + ); + assert.ok(sizes.slice(3).every((n) => n <= KARTVERKET_RETRY_POINTS)); + for (const url of requested) { + assert.equal(new URL(url).searchParams.get('koordsys'), '4258'); + } + // Points past x = 7.05 have no height (outside coverage) and are left out. + assert.equal(heights.size, 51); + assert.equal(heights.get('7.010000,60.010000'), 100); +}); + +test('points a full batch answers null for are retried once in small batches', async (t) => { + withHeightsEnv(t); + const sizes = []; + t.mock.method(globalThis, 'fetch', async (url) => { + const points = JSON.parse(new URL(url).searchParams.get('punkter')); + sizes.push(points.length); + // A full batch drops the first two points; a small batch answers them, + // except the one point that has no data at all. + const full = points.length > KARTVERKET_RETRY_POINTS; + return kartverketResponse(url, (x) => { + if (Math.abs(x - 7.002) < 1e-9) return null; + if (full && x < 7.002) return null; + return 500; + }); + }); + const heights = await fetchKartverketHeights( + Array.from({ length: 60 }, (_, i) => cameraAt(i)), + ); + assert.deepEqual(sizes, [50, 10, 3]); + assert.equal(heights.size, 59); + assert.equal(heights.get('7.000000,60.000000'), 500); + assert.equal(heights.has('7.002000,60.002000'), false); +}); + +test('a sea-floor depth counts as the water surface', async (t) => { + withHeightsEnv(t); + t.mock.method(globalThis, 'fetch', async (url) => { + const points = JSON.parse(new URL(url).searchParams.get('punkter')); + return Response.json({ + koordsys: 4258, + punkter: points.map(([x, y], i) => + i === 0 + ? { x, y, z: -547.1, datakilde: 'dybdekurver', terreng: 'Havflate' } + : { x, y, z: -0.2, datakilde: 'dtm1', terreng: 'ÅpentOmråde' }, + ), + }); + }); + const heights = await fetchKartverketHeights([cameraAt(0), cameraAt(1)]); + // Under a bridge: the surface, not the sea floor. A quay just below the + // datum on land data stays as measured. + assert.equal(heights.get('7.000000,60.000000'), 0); + assert.equal(heights.get('7.001000,60.001000'), -0.2); +}); + +test('implausible heights and points outside Norway are ignored', async (t) => { + withHeightsEnv(t); + const requested = []; + t.mock.method(globalThis, 'fetch', async (url) => { + requested.push(String(url)); + return kartverketResponse(url, () => 99999); + }); + const heights = await fetchKartverketHeights([ + cameraAt(1), + { lat: 55.68, lon: 12.57 }, // Copenhagen: never sent + ]); + assert.equal(heights.size, 0); + // The first pass and its one retry, each carrying only the Norway point. + assert.equal(requested.length, 2); + for (const url of requested) { + assert.equal( + JSON.parse(new URL(url).searchParams.get('punkter')).length, + 1, + ); + } +}); + +test('cameras get their terrain height, and a refresh reuses the cache', async (t) => { + withHeightsEnv(t); + let calls = 0; + t.mock.method(globalThis, 'fetch', async (url) => { + calls += 1; + return kartverketResponse(url, (x) => (x < 7.002 ? 1043.26 : null)); + }); + const cameras = [cameraAt(0), cameraAt(1), cameraAt(5)]; + assert.equal(await applyVegvesenGroundHeights(cameras), 2); + assert.deepEqual( + cameras.map((c) => c.groundElevationM), + [1043.3, 1043.3, 150], + ); + // One full pass plus one retry for the point with no height. + assert.equal(calls, 2); + // Same positions on the next catalog refresh: answered from the cache. + const again = [cameraAt(0), cameraAt(1)]; + assert.equal(await applyVegvesenGroundHeights(again), 2); + assert.equal(calls, 2); +}); + +test('a failed or disabled lookup keeps the flat prior', async (t) => { + withHeightsEnv(t); + const fetchMock = t.mock.method(globalThis, 'fetch', async () => { + throw new Error('offline'); + }); + const cameras = [cameraAt(0)]; + assert.equal(await applyVegvesenGroundHeights(cameras), 0); + assert.equal(cameras[0].groundElevationM, 150); + + fetchMock.mock.mockImplementation( + async () => new Response('nope', { status: 503 }), + ); + assert.equal(await applyVegvesenGroundHeights(cameras), 0); + assert.equal(cameras[0].groundElevationM, 150); + + process.env.CCTV_VEGVESEN_HEIGHTS = '0'; + fetchMock.mock.resetCalls(); + assert.equal(await applyVegvesenGroundHeights(cameras), 0); + assert.equal(fetchMock.mock.callCount(), 0); +}); + +test('a slow lookup does not hold the catalog; the next refresh applies it', async (t) => { + withHeightsEnv(t); + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + t.mock.method(globalThis, 'fetch', async (url) => { + await gate; + return kartverketResponse(url, () => 812); + }); + const first = [cameraAt(0)]; + assert.equal(await applyVegvesenGroundHeights(first, { waitMs: 20 }), 0); + assert.equal(first[0].groundElevationM, 150); + release(); + // The lookup kept running and filled the cache for the next refresh. + await new Promise((resolve) => setTimeout(resolve, 20)); + const next = [cameraAt(0)]; + assert.equal(await applyVegvesenGroundHeights(next, { waitMs: 20 }), 1); + assert.equal(next[0].groundElevationM, 812); +}); + +test('the loader applies Kartverket heights to the cameras it returns', async (t) => { + withHeightsEnv(t); + t.mock.method(globalThis, 'fetch', async (url) => { + if (String(url).startsWith(KARTVERKET_HEIGHT_URL)) { + return kartverketResponse(url, () => 987.6); + } + return Response.json({ type: 'FeatureCollection', features: [feature()] }); + }); + const cameras = await loadVegvesenSourcesFromOpenData(); + assert.deepEqual( + cameras.map((c) => [c.id, c.groundElevationM]), + [['no-vegvesen-3000063_1', 987.6]], + ); +}); diff --git a/src/data/dataCredits.js b/src/data/dataCredits.js index 2967f0a2b..8ad585eca 100644 --- a/src/data/dataCredits.js +++ b/src/data/dataCredits.js @@ -245,7 +245,8 @@ export const DATA_CREDITS = [ html: 'Road cameras (Norway): contains data under the ' + 'Norwegian licence for Open Government data (NLOD) ' + - 'distributed by Statens vegvesen', + 'distributed by Statens vegvesen · camera ground heights © ' + + 'Kartverket (CC BY 4.0)', }, { key: 'gbfs',