Merge branch 'main' into contrib/gods-next-31-gbfs-unknown-counts-20261013

This commit is contained in:
Said Turksever authored and GitHub committed 2026-10-16 10:57:09 +01:00
commit 792c984e63
91 files changed
+8631 -122

No files matched your search

+286
View File
@@ -0,0 +1,286 @@
import * as Cesium from 'cesium';
import {
AIR_QUALITY_BANDS,
AIR_QUALITY_OVERLAY_SOURCE_ID,
AIR_QUALITY_OVERLAY_COHORT_LIMIT,
AIR_QUALITY_OVERLAY_COLLISION_CAPACITY,
AIR_QUALITY_PROVIDERS,
createAirQualityOverlayEntry,
mapAnalystRecord,
newestObservation,
readingsAreStale,
readingsInView,
selectAirQualityOverlayCohort,
} from './model.js';
export * from './model.js';
export { createEcccAirQualitySource } from './source.js';
/** Station markers are a point reading, not an extent. */
const STATION_MARKER_RADIUS_M = 6_000;
/** Readings listed in the readout card. */
const READOUT_LIMIT = 5;
/** Own one air-quality display, its refresh lifecycle, and its readout card. */
export function createAirQualityLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Air quality requires a snapshot source');
if (!overlayHost) throw new TypeError('Air quality requires an overlay host');
let _viewer = null;
let _request = null;
let _dataSource = null;
let _readings = [];
let _count = 0;
let _lastUpdate = null;
let _lastError = null;
let _enabled = false;
let rowControlsListener = null;
const notify = () => rowControlsListener?.();
/** The camera's lon/lat rectangle in degrees, or null when unresolvable. */
const viewRectangle = () => {
const rectangle = _viewer?.camera?.computeViewRectangle?.();
if (!rectangle) return null;
const toDeg = Cesium.Math.toDegrees;
return {
west: toDeg(rectangle.west),
south: toDeg(rectangle.south),
east: toDeg(rectangle.east),
north: toDeg(rectangle.north),
};
};
const layer = {
id: 'air-quality',
name: 'Air quality',
icon: '◍',
source: 'ECCC MSC GeoMet',
updateInterval: 1_200_000,
init(viewer) {
if (_viewer) throw new Error('Air quality layer is already initialized');
_viewer = viewer;
_dataSource = new Cesium.CustomDataSource('air-quality');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
_readings = [];
_count = 0;
_lastUpdate = null;
_lastError = null;
_enabled = false;
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
},
enable() {
_enabled = true;
if (_dataSource) _dataSource.show = true;
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true);
notify();
},
disable() {
// Abort in flight: a response arriving after disable must not redraw.
_request?.abort();
_request = null;
_enabled = false;
if (_dataSource) _dataSource.show = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
notify();
},
async update() {
if (!_enabled || !_dataSource) return false;
_request?.abort();
const request = new AbortController();
_request = request;
try {
const readings = await source.getSnapshot({ signal: request.signal });
// A superseded or aborted request must not touch the scene, and neither
// must one that lands after the layer was switched off.
if (request.signal.aborted || _request !== request || !_enabled)
return false;
_readings = readings;
this._render();
_count = _readings.length;
_lastUpdate = Date.now();
_lastError = null;
notify();
return true;
} catch (error) {
if (request.signal.aborted || _request !== request) return false;
_lastError = error?.message || 'Air quality request failed';
console.warn('[Data:AirQuality] Refresh failed:', _lastError);
notify();
return false;
} finally {
if (_request === request) _request = null;
}
},
/** Rebuild entities and overlay labels from the current readings. */
_render() {
if (!_dataSource) return;
_dataSource.entities.removeAll();
const overlayEntries = [];
for (const reading of _readings) {
const position = Cesium.Cartesian3.fromDegrees(
reading.lon,
reading.lat,
);
const color = Cesium.Color.fromCssColorString(reading.color);
_dataSource.entities.add(
new Cesium.Entity({
id: `air-quality:${reading.id}`,
position,
ellipse: {
// Static axes, as in the earthquake layer: a per-frame axis
// re-tessellates the clamped ground primitive every frame.
semiMajorAxis: STATION_MARKER_RADIUS_M,
semiMinorAxis: STATION_MARKER_RADIUS_M,
material: new Cesium.ColorMaterialProperty(color.withAlpha(0.35)),
outline: true,
outlineColor: color.withAlpha(0.9),
outlineWidth: 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
properties: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
}),
);
overlayEntries.push(
createAirQualityOverlayEntry({
id: reading.id,
position,
title: `${reading.name} ${reading.label}`,
accent: reading.color,
value: reading.value,
}),
);
}
if (_enabled) {
overlayHost.setEntries(
AIR_QUALITY_OVERLAY_SOURCE_ID,
selectAirQualityOverlayCohort(overlayEntries),
{
cohortLimit: AIR_QUALITY_OVERLAY_COHORT_LIMIT,
collisionCapacity: AIR_QUALITY_OVERLAY_COLLISION_CAPACITY,
moving: false,
},
);
}
},
destroy(viewer = _viewer) {
_request?.abort();
_request = null;
_enabled = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
if (_dataSource) {
viewer?.dataSources?.remove(_dataSource, true);
_dataSource = null;
}
_viewer = null;
_readings = [];
_count = 0;
_lastUpdate = null;
_lastError = null;
rowControlsListener = null;
},
/**
* Readout descriptor for the Weather panel: the band legend, and the worst
* readings currently in view.
*
* `readout: true` renders the toggle and source line only; the card owns
* the rest. Coverage is stated plainly because this layer is not global.
*/
getRowControls() {
const provider = AIR_QUALITY_PROVIDERS.eccc;
const inView = readingsInView(_readings, viewRectangle(), READOUT_LIMIT);
const newest = _readings.reduce(
(max, reading) => Math.max(max, reading.observedMs || 0),
0,
);
return {
readout: true,
summary: {
label: provider.label,
coverage: provider.coverage,
validTime: newest ? new Date(newest).toISOString() : undefined,
detail: `${provider.network} · ${provider.scale}`,
status: _lastError
? _lastError
: _count === 0
? _lastUpdate === null
? 'No readings available'
: 'No current readings'
: `${_count} stations reporting`,
units: provider.scale,
},
legend: AIR_QUALITY_BANDS.map((band) => ({
color: band.color,
label: band.label,
})),
legendCategorical: true,
list: {
ariaLabel: 'Highest air-quality readings in view',
items: inView.map((reading, index) => ({
id: reading.id,
ordinal: index + 1,
lead: `${reading.scale} ${reading.label}`,
text: `${reading.name} · ${reading.risk}`,
accent: reading.color,
})),
},
};
},
setRowControlsListener(listener) {
rowControlsListener = typeof listener === 'function' ? listener : null;
},
/**
* Snapshot readings as JSON-safe records for the analyst query engine.
* @param {number} [maxCount=500]
* @returns {Array<object>}
*/
getAnalystRecords(maxCount = 500) {
if (!_enabled || !_readings.length) return [];
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 500;
return _readings
.slice(0, limit)
.map((reading, index) => mapAnalystRecord(reading, index));
},
getStats() {
// `lastUpdate` is when a response was received; `observedAt` is when the
// network actually measured. Freshness is judged on the latter, so a feed
// that keeps answering with hours-old observations reports STALE rather
// than being narrated as live by the HUD and voice provenance envelope.
return {
count: _count,
lastUpdate: _lastUpdate,
error: _lastError,
observedAt: newestObservation(_readings),
// Only a completed refresh can be stale; before one there is no feed.
stale: _lastUpdate !== null && readingsAreStale(_readings),
};
},
};
return layer;
}
+377
View File
@@ -0,0 +1,377 @@
/**
* @module layers/airQuality/model
*
* Air-quality readings, normalized across networks. Pure — no Cesium, no
* network.
*
* Air-quality indices are not interchangeable numbers. Canada's AQHI runs 1 to
* 10+ on health risk; the US AQI runs 0 to 500 on concentration breakpoints;
* Europe's EAQI is a five-step category. A reading is therefore carried as
* `{ provider, scale, value, band }` — who measured it, which index it is, the
* value on that index's own terms, and the band it falls in — so a second
* network can be added without retrofitting a shared numeric meaning that does
* not exist.
*
* Only ECCC's AQHI is implemented here; `AIR_QUALITY_PROVIDERS` is the seam a
* later provider registers against.
*/
/** Band identifiers shared across providers, in ascending severity. */
export const AIR_QUALITY_BANDS = Object.freeze([
Object.freeze({ id: 'low', label: 'Low', color: '#4cc9f0' }),
Object.freeze({ id: 'moderate', label: 'Moderate', color: '#ffd43b' }),
Object.freeze({ id: 'high', label: 'High', color: '#ff6b35' }),
Object.freeze({ id: 'very-high', label: 'Very High', color: '#c1121f' }),
]);
const BAND_BY_ID = new Map(AIR_QUALITY_BANDS.map((band) => [band.id, band]));
/** Colour used when a station reports no usable reading. */
export const AIR_QUALITY_UNKNOWN_COLOR = '#6b7785';
export const AIR_QUALITY_OVERLAY_SOURCE_ID = 'air-quality';
export const AIR_QUALITY_OVERLAY_COHORT_LIMIT = 48;
export const AIR_QUALITY_OVERLAY_COLLISION_CAPACITY = 32;
/**
* A reading this old is stale enough that displaying it would misinform.
* AQHI publishes hourly, so six hours is five missed publications.
*/
export const OBSERVATION_MAX_AGE_MS = 6 * 60 * 60 * 1000;
/**
* How old the newest observation may be before the layer reports itself stale.
*
* This is deliberately separate from the age at which a reading is dropped.
* `lastUpdate` records when we last *received* a response, which stays current
* even when the network publishes nothing new; freshness has to be judged on
* the source's own observation time instead. AQHI publishes hourly, so a newest
* reading beyond two hours means at least one publication was missed and the
* feed should not be described as live.
*/
export const STALE_AFTER_MS = 2 * 60 * 60 * 1000;
/**
* The newest observation time across a set of readings, or null when empty.
* @param {Array<object>} readings
* @returns {number|null} Epoch ms.
*/
export function newestObservation(readings) {
if (!Array.isArray(readings) || readings.length === 0) return null;
let newest = null;
for (const reading of readings) {
const at = Number(reading?.observedMs);
if (Number.isFinite(at) && (newest === null || at > newest)) newest = at;
}
return newest;
}
/**
* Is a set of readings stale, judged on source observation time? An empty
* set is stale: a refresh that kept no current observation has nothing live.
* @param {Array<object>} readings
* @param {number} [now=Date.now()]
* @returns {boolean}
*/
export function readingsAreStale(readings, now = Date.now()) {
const newest = newestObservation(readings);
// No current observation at all — every row was dropped as too old or
// unusable — is the stalest a feed can be, not a nominal one.
if (newest === null) return true;
return now - newest > STALE_AFTER_MS;
}
/**
* Registered provider descriptors. `coverage` is stated plainly because the
* layer is not global and the row must say so.
*/
export const AIR_QUALITY_PROVIDERS = Object.freeze({
eccc: Object.freeze({
id: 'eccc',
scale: 'AQHI',
label: 'Air quality',
network: 'Environment and Climate Change Canada',
coverage: 'Canada only · ECCC AQHI network',
/** ECCC's published band thresholds, evaluated in order. */
bands: Object.freeze([
Object.freeze({ id: 'low', max: 3 }),
Object.freeze({ id: 'moderate', max: 6 }),
Object.freeze({ id: 'high', max: 10 }),
Object.freeze({ id: 'very-high', max: Infinity }),
]),
}),
});
/** Band descriptor for an id, or null. */
export function airQualityBandById(bandId) {
return BAND_BY_ID.get(String(bandId ?? '')) || null;
}
/** Accent colour for a band id, falling back to neutral grey. */
export function airQualityColor(bandId) {
return airQualityBandById(bandId)?.color || AIR_QUALITY_UNKNOWN_COLOR;
}
/**
* The published AQHI value for a raw ECCC reading: an integer from 1 up.
*
* ECCC reports whole numbers with a floor of 1 — there is no "AQHI 0" and no
* "AQHI 1.08". A raw value below 1 is a legitimate low reading, not an error,
* and is published as 1.
*
* @param {number|string|null|undefined} raw - Raw `aqhi` value from the API.
* @returns {number|null} Published integer AQHI, or null when unusable.
*/
export function aqhiDisplayValue(raw) {
// Guard the empty forms BEFORE coercing: Number(null) and Number('') are both
// 0, which would otherwise floor to a confident "AQHI 1" for a station that
// reported nothing at all.
if (raw === null || raw === undefined || raw === '') return null;
if (typeof raw !== 'number' && typeof raw !== 'string') return null;
if (typeof raw === 'string' && raw.trim() === '') return null;
const value = Number(raw);
if (!Number.isFinite(value) || value < 0) return null;
return Math.max(1, Math.round(value));
}
/**
* The band id for a value on a provider's scale.
* @param {string} providerId
* @param {number|null} value - Already in the provider's published form.
* @returns {string|null}
*/
export function bandForValue(providerId, value) {
const provider = AIR_QUALITY_PROVIDERS[String(providerId ?? '')];
if (!provider || !Number.isFinite(value)) return null;
return provider.bands.find((band) => value <= band.max)?.id ?? null;
}
/**
* Display text for a value on a provider's scale.
* AQHI collapses everything above ten into the open-ended "10+".
* @param {string} providerId
* @param {number|null} value
* @returns {string}
*/
export function valueLabel(providerId, value) {
if (!Number.isFinite(value)) return '--';
if (providerId === 'eccc') return value > 10 ? '10+' : String(value);
return String(value);
}
/** Plain-language risk phrase for a band id. */
export function bandRiskText(bandId) {
const band = airQualityBandById(bandId);
return band ? `${band.label} health risk` : null;
}
/**
* Validate a station FeatureCollection into an id-keyed catalog.
*
* Atomic: a structurally broken response returns null so the caller keeps its
* last good catalog. A station missing coordinates is skipped, since one
* unusable station is not evidence the catalog is broken.
*
* @param {object} geojson - GeoJSON FeatureCollection from `aqhi-stations`.
* @returns {Map<string, object>|null} Stations by location_id, or null.
*/
export function normalizeAqhiStations(geojson) {
if (!Array.isArray(geojson?.features)) return null;
const stations = new Map();
for (const feature of geojson.features) {
const properties = feature?.properties;
if (
!properties ||
typeof properties !== 'object' ||
Array.isArray(properties)
)
return null;
const coordinates = feature?.geometry?.coordinates;
if (!Array.isArray(coordinates) || coordinates.length < 2) continue;
const [lon, lat] = coordinates.map(Number);
if (!Number.isFinite(lon) || !Number.isFinite(lat)) continue;
if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return null;
const id = String(properties.location_id ?? feature.id ?? '').trim();
if (!id) continue;
stations.set(id, {
id,
name: String(properties.location_name_en || id).trim(),
// ECCC's administrative zone: atl, que, ont, pnr, pyr.
zone: String(properties['eccc_administrative-zone'] || '').trim(),
lat,
lon,
});
}
return stations;
}
/**
* Join latest ECCC observations onto known stations into provider-shaped rows.
*
* The catalog is the only thing that supplies a reading its coordinates, so an
* observation without a matching station cannot be placed and is dropped.
* Readings older than OBSERVATION_MAX_AGE_MS are dropped too — a six-hour-old
* air-quality number presented as current is worse than no number.
*
* @param {object} geojson - FeatureCollection from `aqhi-observations-realtime`.
* @param {Map<string, object>} stations - Known stations by location_id.
* @param {number} [now=Date.now()] - Clock seam for tests.
* @returns {Array<object>|null} Normalized readings, or null when malformed.
*/
export function normalizeAqhiObservations(geojson, stations, now = Date.now()) {
if (!Array.isArray(geojson?.features)) return null;
if (!(stations instanceof Map)) return null;
const provider = AIR_QUALITY_PROVIDERS.eccc;
const newest = new Map();
for (const feature of geojson.features) {
const properties = feature?.properties;
if (
!properties ||
typeof properties !== 'object' ||
Array.isArray(properties)
)
return null;
const stationId = String(properties.location_id ?? '').trim();
const station = stations.get(stationId);
if (!station) continue;
const value = aqhiDisplayValue(properties.aqhi);
if (value === null) continue;
const observedMs = Date.parse(properties.observation_datetime);
if (!Number.isFinite(observedMs)) continue;
if (now - observedMs > OBSERVATION_MAX_AGE_MS) continue;
const previous = newest.get(stationId);
if (previous && previous.observedMs >= observedMs) continue;
const band = bandForValue(provider.id, value);
newest.set(stationId, {
id: `${provider.id}:${stationId}`,
provider: provider.id,
scale: provider.scale,
value,
band,
stationId,
name: station.name,
zone: station.zone,
lat: station.lat,
lon: station.lon,
observedMs,
color: airQualityColor(band),
label: valueLabel(provider.id, value),
risk: bandRiskText(band),
note: String(properties.special_notes_en || '').trim() || null,
});
}
return [...newest.values()].sort(
(a, b) => b.value - a.value || a.stationId.localeCompare(b.stationId),
);
}
/**
* Build the source-owned presentation for one station label.
* @param {object} input
* @returns {object}
*/
export function createAirQualityOverlayEntry({
id,
position,
title,
accent,
value,
}) {
return {
id: String(id),
position,
variant: 'label',
title,
accent,
// Worse air wins the label budget — the reading people need to see first.
priority: Math.round(Number(value) || 0) * 1000,
collisionGroup: 'ambient-label',
paintLane: 'ambient-label',
interactive: false,
edgeFade: 'keyhole',
horizonCull: true,
terrainOcclusion: false,
gapPx: 14,
verticalOnly: true,
placement: 'above',
};
}
/** Keep the worst readings, with stable identity as the tie-break. */
export function selectAirQualityOverlayCohort(
entries,
limit = AIR_QUALITY_OVERLAY_COHORT_LIMIT,
) {
const cap = Math.max(
0,
Math.min(AIR_QUALITY_OVERLAY_COHORT_LIMIT, Math.floor(Number(limit) || 0)),
);
if (!Array.isArray(entries) || cap === 0) return [];
return entries
.slice()
.sort(
(a, b) =>
b.priority - a.priority || String(a.id).localeCompare(String(b.id)),
)
.slice(0, cap);
}
/**
* The worst readings inside a lon/lat rectangle, for the readout card.
*
* A null rectangle means the camera could not resolve one (a fully oblique or
* space-level view); everything is then in scope rather than nothing, so the
* card degrades to the worst readings overall instead of going blank.
*
* @param {Array<object>} readings
* @param {?{west:number, south:number, east:number, north:number}} rect - Degrees.
* @param {number} [limit=5]
* @returns {Array<object>}
*/
export function readingsInView(readings, rect, limit = 5) {
if (!Array.isArray(readings)) return [];
const cap = Math.max(0, Math.floor(Number(limit) || 0));
if (cap === 0) return [];
const inside = !rect
? readings
: readings.filter((reading) => {
if (reading.lat < rect.south || reading.lat > rect.north) return false;
// A rectangle crossing the antimeridian has west > east.
return rect.west <= rect.east
? reading.lon >= rect.west && reading.lon <= rect.east
: reading.lon >= rect.west || reading.lon <= rect.east;
});
return inside
.slice()
.sort((a, b) => b.value - a.value || a.stationId.localeCompare(b.stationId))
.slice(0, cap);
}
/**
* Map one reading to a JSON-safe analyst record. Pure — no Cesium types.
* @param {object|null|undefined} raw
* @param {number} [index=0]
* @returns {object}
*/
export function mapAnalystRecord(raw, index = 0) {
const num = (v) => (Number.isFinite(v) ? v : null);
const text = (v) => {
const t = String(v ?? '').trim();
return t || null;
};
return {
id: text(raw?.id) || `AIR-${String(index).padStart(4, '0')}`,
provider: text(raw?.provider),
scale: text(raw?.scale),
value: num(raw?.value),
band: text(raw?.band),
name: text(raw?.name),
zone: text(raw?.zone),
risk: text(raw?.risk),
lat: num(raw?.lat),
lon: num(raw?.lon),
observedMs: num(raw?.observedMs),
};
}
+269
View File
@@ -0,0 +1,269 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
AIR_QUALITY_BANDS,
AIR_QUALITY_PROVIDERS,
AIR_QUALITY_UNKNOWN_COLOR,
OBSERVATION_MAX_AGE_MS,
STALE_AFTER_MS,
airQualityColor,
aqhiDisplayValue,
bandForValue,
bandRiskText,
mapAnalystRecord,
normalizeAqhiObservations,
normalizeAqhiStations,
readingsAreStale,
readingsInView,
selectAirQualityOverlayCohort,
valueLabel,
} from './model.js';
const NOW = Date.parse('2026-09-24T18:30:00Z');
const RECENT = '2026-09-24T18:00:00Z';
const collection = (features) => ({ type: 'FeatureCollection', features });
const station = (id, name, zone, lon, lat) => ({
type: 'Feature',
geometry: { type: 'Point', coordinates: [lon, lat] },
properties: {
location_id: id,
location_name_en: name,
'eccc_administrative-zone': zone,
},
});
const observation = (id, aqhi, when = RECENT) => ({
type: 'Feature',
properties: { location_id: id, aqhi, observation_datetime: when },
});
const STATIONS = collection([
station('IAKID', 'Calgary', 'pnr', -114.0575, 51.0458),
station('OAAAA', 'Toronto', 'ont', -79.3832, 43.6532),
station('AAAAA', 'Halifax', 'atl', -63.5752, 44.6488),
]);
// ── provider-shaped records ────────────────────────────────────────────────
test('readings carry the provider-neutral {provider, scale, value, band} shape', () => {
// Indices are not interchangeable numbers: AQHI is 1-10+ on health risk,
// US AQI is 0-500 on concentration. The shape names which index a value is on
// so a second network can be added without inventing a shared meaning.
const stations = normalizeAqhiStations(STATIONS);
const [row] = normalizeAqhiObservations(
collection([observation('IAKID', 2.32)]),
stations,
NOW,
);
assert.equal(row.provider, 'eccc');
assert.equal(row.scale, 'AQHI');
assert.equal(row.value, 2);
assert.equal(row.band, 'low');
});
test('bands map from a value on a named provider scale', () => {
assert.equal(bandForValue('eccc', 1), 'low');
assert.equal(bandForValue('eccc', 3), 'low');
assert.equal(bandForValue('eccc', 4), 'moderate');
assert.equal(bandForValue('eccc', 7), 'high');
assert.equal(bandForValue('eccc', 11), 'very-high');
// An unregistered provider cannot be banded rather than being guessed at.
assert.equal(bandForValue('unknown-network', 5), null);
assert.equal(bandForValue('eccc', null), null);
});
test('the provider states its coverage plainly', () => {
assert.match(AIR_QUALITY_PROVIDERS.eccc.coverage, /Canada only/);
assert.equal(AIR_QUALITY_PROVIDERS.eccc.scale, 'AQHI');
});
test("values above ten collapse to the scale's open-ended label", () => {
assert.equal(valueLabel('eccc', 10), '10');
assert.equal(valueLabel('eccc', 11), '10+');
assert.equal(valueLabel('eccc', null), '--');
});
test('every band has a distinct colour, and an unknown band is neutral', () => {
const colors = AIR_QUALITY_BANDS.map((b) => b.color);
assert.equal(new Set(colors).size, colors.length);
assert.equal(airQualityColor('nonsense'), AIR_QUALITY_UNKNOWN_COLOR);
assert.equal(bandRiskText('high'), 'High health risk');
assert.equal(bandRiskText(null), null);
});
// ── published form ─────────────────────────────────────────────────────────
test('AQHI rounds to the published integer form and floors at 1', () => {
assert.equal(aqhiDisplayValue(1.08), 1);
assert.equal(aqhiDisplayValue(3.5), 4);
assert.equal(aqhiDisplayValue(0), 1);
assert.equal(aqhiDisplayValue('3'), 3);
});
test('an absent reading never becomes a confident AQHI 1', () => {
// Number(null) and Number('') are both 0, which would floor to 1.
for (const empty of [null, undefined, '', ' ', NaN, true, {}, [], -1]) {
assert.equal(aqhiDisplayValue(empty), null, `${JSON.stringify(empty)}`);
}
});
// ── snapshot validation ────────────────────────────────────────────────────
test('stations normalize into an id-keyed catalog carrying their zone', () => {
const stations = normalizeAqhiStations(STATIONS);
assert.equal(stations.size, 3);
assert.equal(stations.get('OAAAA').zone, 'ont');
});
test('malformed payloads are rejected atomically', () => {
assert.equal(normalizeAqhiStations(null), null);
assert.equal(normalizeAqhiStations(collection([{ properties: null }])), null);
const stations = normalizeAqhiStations(STATIONS);
assert.equal(normalizeAqhiObservations(null, stations, NOW), null);
assert.equal(
normalizeAqhiObservations(collection([]), 'not a map', NOW),
null,
);
});
test('an observation with no matching station is dropped', () => {
const stations = normalizeAqhiStations(STATIONS);
const rows = normalizeAqhiObservations(
collection([observation('IAKID', 2), observation('ZZZZZ', 9)]),
stations,
NOW,
);
assert.equal(rows.length, 1);
});
test('a stale reading is dropped rather than shown as current', () => {
const stations = normalizeAqhiStations(STATIONS);
const old = new Date(NOW - OBSERVATION_MAX_AGE_MS - 60_000).toISOString();
const rows = normalizeAqhiObservations(
collection([observation('IAKID', 3, old), observation('OAAAA', 4)]),
stations,
NOW,
);
assert.deepEqual(
rows.map((r) => r.stationId),
['OAAAA'],
);
});
test('a snapshot whose every observation was too old is stale, not nominal', () => {
const stations = normalizeAqhiStations(STATIONS);
const old = new Date(NOW - OBSERVATION_MAX_AGE_MS - 60_000).toISOString();
const rows = normalizeAqhiObservations(
collection([observation('IAKID', 3, old), observation('OAAAA', 4, old)]),
stations,
NOW,
);
assert.deepEqual(rows, []);
assert.equal(readingsAreStale(rows, NOW), true);
assert.equal(readingsAreStale([{ observedMs: NOW - 60_000 }], NOW), false);
assert.equal(
readingsAreStale([{ observedMs: NOW - STALE_AFTER_MS - 1 }], NOW),
true,
);
});
test('the newest reading per station wins and worst air sorts first', () => {
const stations = normalizeAqhiStations(STATIONS);
const rows = normalizeAqhiObservations(
collection([
observation('IAKID', 3, '2026-09-24T16:00:00Z'),
observation('IAKID', 7, '2026-09-24T18:00:00Z'),
observation('OAAAA', 5),
]),
stations,
NOW,
);
assert.deepEqual(
rows.map((r) => r.value),
[7, 5],
);
});
// ── readout selection ──────────────────────────────────────────────────────
const reading = (id, value, lat, lon) => ({
id,
stationId: id,
value,
lat,
lon,
name: id,
});
test('the readout lists the worst readings inside the view rectangle', () => {
const rows = [
reading('west', 9, 51.0, -114.0),
reading('east', 4, 43.6, -79.3),
reading('mild', 2, 51.1, -114.1),
];
const inView = readingsInView(
rows,
{ west: -115, south: 50, east: -113, north: 52 },
5,
);
assert.deepEqual(
inView.map((r) => r.id),
['west', 'mild'],
);
});
test('an unresolvable view rectangle degrades to the worst overall, not to blank', () => {
// A space-level or fully oblique camera cannot produce a rectangle; the card
// should still say something useful.
const rows = [reading('a', 3, 0, 0), reading('b', 8, 10, 10)];
assert.deepEqual(
readingsInView(rows, null, 5).map((r) => r.id),
['b', 'a'],
);
assert.deepEqual(readingsInView(rows, null, 0), []);
assert.deepEqual(readingsInView(null, null, 5), []);
});
test('a view rectangle crossing the antimeridian still selects correctly', () => {
// west > east is how a dateline-crossing rectangle is expressed.
const rows = [reading('near', 5, 0, 179), reading('far', 9, 0, 100)];
const inView = readingsInView(
rows,
{ west: 170, south: -10, east: -170, north: 10 },
5,
);
assert.deepEqual(
inView.map((r) => r.id),
['near'],
);
});
test('the overlay cohort is capped and deterministic', () => {
const entries = Array.from({ length: 120 }, (_, i) => ({
id: `s${i}`,
priority: i % 11,
}));
const cohort = selectAirQualityOverlayCohort(entries);
assert.ok(cohort.length <= 48);
assert.deepEqual(
cohort.map((e) => e.id),
selectAirQualityOverlayCohort(entries).map((e) => e.id),
);
});
test('analyst records are JSON-safe and name the provider and scale', () => {
const stations = normalizeAqhiStations(STATIONS);
const [row] = normalizeAqhiObservations(
collection([observation('IAKID', 2)]),
stations,
NOW,
);
const record = mapAnalystRecord(row, 0);
assert.deepEqual(JSON.parse(JSON.stringify(record)), record);
assert.equal(record.provider, 'eccc');
assert.equal(record.scale, 'AQHI');
const empty = mapAnalystRecord(undefined, 7);
assert.equal(empty.id, 'AIR-0007');
for (const [key, value] of Object.entries(empty)) {
assert.notEqual(value, undefined, `${key} must not be undefined`);
}
});
+275
View File
@@ -0,0 +1,275 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createAirQualityLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { STALE_AFTER_MS } from './model.js';
function harness(source) {
const sources = [];
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const layer = createAirQualityLayer({
source,
overlayHost: {
setEntries(...args) {
events.push(args);
},
setVisible() {},
clearSource() {},
},
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
}
const reading = (id, value, overrides = {}) => ({
id: `eccc:${id}`,
provider: 'eccc',
scale: 'AQHI',
value,
band: 'low',
stationId: id,
name: id,
zone: 'ont',
lat: 43.65,
lon: -79.38,
observedMs: 1_700_000_000_000,
color: '#4cc9f0',
label: String(value),
risk: 'Low health risk',
note: null,
...overrides,
});
const staticSource = (rows) => ({ getSnapshot: async () => rows });
test('a layer requires both a snapshot source and an overlay host', () => {
assert.throws(() => createAirQualityLayer(), /snapshot source/);
assert.throws(
() => createAirQualityLayer({ source: staticSource([]) }),
/overlay host/,
);
});
test('initialization is single-use and owns exactly one data source', () => {
const { layer, viewer, sources } = harness(staticSource([]));
assert.equal(sources.length, 1);
assert.throws(() => layer.init(viewer), /already initialized/);
layer.destroy(viewer);
assert.equal(sources.length, 0);
});
test('a refresh renders readings and publishes an overlay cohort', async () => {
const { layer, events } = harness(
staticSource([reading('A', 2), reading('B', 7)]),
);
assert.equal(await layer.update(), true);
assert.equal(layer.getStats().count, 2);
assert.equal(layer.getStats().error, null);
assert.equal(events.at(-1)[0], 'air-quality');
});
// ── the abort + enabled guard ──────────────────────────────────────────────
test('a response landing after disable cannot redraw the scene', async () => {
// The failure this prevents: disable() clears the overlay, then an in-flight
// response resolves and repopulates it behind the user's back.
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const { layer, events } = harness({
getSnapshot: async ({ signal } = {}) => {
await gate;
signal?.throwIfAborted();
return [reading('A', 5)];
},
});
const pending = layer.update();
layer.disable();
const publishedBefore = events.length;
release();
assert.equal(await pending, false, 'a late response must not be applied');
assert.equal(
events.length,
publishedBefore,
'no overlay write after disable',
);
assert.equal(layer.getStats().count, 0);
});
test('disable aborts the request in flight', async () => {
let seenSignal = null;
const { layer } = harness({
getSnapshot: async ({ signal } = {}) => {
seenSignal = signal;
await new Promise((resolve) => setTimeout(resolve, 40));
signal?.throwIfAborted();
return [];
},
});
const pending = layer.update();
layer.disable();
await pending;
assert.ok(seenSignal, 'a signal was passed through to the source');
assert.equal(seenSignal.aborted, true);
});
test('a superseded refresh does not clobber the newer one', async () => {
let call = 0;
const { layer } = harness({
getSnapshot: async ({ signal } = {}) => {
call += 1;
const mine = call;
await new Promise((resolve) => setTimeout(resolve, mine === 1 ? 40 : 1));
signal?.throwIfAborted();
return [reading(`call-${mine}`, mine)];
},
});
const first = layer.update();
const second = layer.update();
const [firstResult, secondResult] = await Promise.all([first, second]);
assert.equal(firstResult, false, 'the superseded call reports no update');
assert.equal(secondResult, true);
assert.equal(layer.getAnalystRecords()[0].name, 'call-2');
});
test('update is a no-op while the layer is disabled', async () => {
const { layer } = harness(staticSource([reading('A', 2)]));
layer.disable();
assert.equal(await layer.update(), false);
assert.equal(layer.getStats().count, 0);
});
// ── readout descriptor ─────────────────────────────────────────────────────
test('the readout descriptor carries the band legend and coverage', async () => {
const { layer } = harness(staticSource([reading('A', 2), reading('B', 9)]));
await layer.update();
const controls = layer.getRowControls();
assert.equal(controls.readout, true);
assert.match(controls.summary.coverage, /Canada only/);
// The Weather panel's legend shape: one {color, label} per band.
assert.equal(controls.legendCategorical, true);
assert.deepEqual(
controls.legend.map((entry) => entry.label),
['Low', 'Moderate', 'High', 'Very High'],
);
assert.ok(
controls.legend.every((entry) => /^#[0-9a-f]{6}$/i.test(entry.color)),
);
// Worst first, and every item keyed.
assert.deepEqual(
controls.list.items.map((i) => i.text),
['B · Low health risk', 'A · Low health risk'],
);
assert.ok(controls.list.items.every((i) => i.id));
assert.match(controls.summary.status, /2 stations reporting/);
});
test('the readout reports an error rather than a silent empty card', async () => {
const { layer } = harness({
getSnapshot: async () => {
throw new Error('ECCC HTTP 503');
},
});
await layer.update();
assert.match(layer.getRowControls().summary.status, /503/);
});
test('row-control listeners are notified on refresh and teardown-safe', async () => {
const { layer, viewer } = harness(staticSource([reading('A', 2)]));
let calls = 0;
layer.setRowControlsListener(() => {
calls += 1;
});
await layer.update();
assert.ok(calls >= 1, 'a refresh notifies the card');
layer.destroy(viewer);
const after = calls;
layer.setRowControlsListener(() => {
calls += 1;
});
assert.equal(calls, after);
});
// ── feed-state honesty ─────────────────────────────────────────────────────
test('freshness is judged on observation time, not on when we last fetched', async () => {
// lastUpdate stays current every time the network answers, even when it
// answers with nothing new. Judging freshness on it would let the HUD and
// voice describe hours-old air quality as live.
const aged = Date.now() - STALE_AFTER_MS - 60_000;
const { layer } = harness(
staticSource([reading('A', 2, { observedMs: aged })]),
);
await layer.update();
const stats = layer.getStats();
assert.ok(
stats.lastUpdate >= Date.now() - 5_000,
'we did just receive a response',
);
assert.equal(stats.observedAt, aged, 'but the observation itself is old');
assert.equal(stats.stale, true);
assert.equal(
layerFeedState(stats),
'stale',
'provenance must not read this as nominal',
);
});
test('a current reading reports nominal', async () => {
const { layer } = harness(
staticSource([reading('A', 2, { observedMs: Date.now() - 10 * 60_000 })]),
);
await layer.update();
const stats = layer.getStats();
assert.equal(stats.stale, false);
assert.equal(layerFeedState(stats), 'nominal');
});
test('a refresh that kept no current observation reports stale, not nominal', async () => {
// Every observation older than OBSERVATION_MAX_AGE_MS is dropped, so a feed
// that only has hours-old rows yields an empty snapshot. That is the
// stalest a feed can be; it must not read as a healthy empty layer.
const { layer } = harness(staticSource([]));
assert.equal(layer.getStats().stale, false, 'no refresh yet, no verdict');
await layer.update();
const stats = layer.getStats();
assert.equal(stats.count, 0);
assert.equal(stats.observedAt, null);
assert.equal(stats.stale, true);
assert.equal(layerFeedState(stats), 'stale');
assert.equal(layer.getRowControls().summary.status, 'No current readings');
});
test('a failed refresh over good readings reports degraded, not nominal', async () => {
let fail = false;
const { layer } = harness({
getSnapshot: async () => {
if (fail) throw new Error('ECCC HTTP 503');
return [reading('A', 2, { observedMs: Date.now() - 10 * 60_000 })];
},
});
await layer.update();
assert.equal(layerFeedState(layer.getStats()), 'nominal');
fail = true;
await layer.update();
const stats = layer.getStats();
assert.ok(stats.count > 0, 'the previous readings are still displayed');
assert.equal(
layerFeedState(stats),
'degraded',
'showing old data after a failure is degraded',
);
});
+104
View File
@@ -0,0 +1,104 @@
import { readResponseJsonCapped } from '../../sources/httpBody.js';
import { normalizeAqhiStations, normalizeAqhiObservations } from './model.js';
const COLLECTIONS_ROOT = 'https://api.weather.gc.ca/collections';
const STATIONS_URL = `${COLLECTIONS_ROOT}/aqhi-stations/items`;
const OBSERVATIONS_URL = `${COLLECTIONS_ROOT}/aqhi-observations-realtime/items`;
/** Comfortably above Canada's ~134 stations without inviting a huge page. */
const STATION_LIMIT = 500;
const OBSERVATION_LIMIT = 500;
/** Station geometry is near-static — a few changes a year. Refetch twice a day. */
const STATION_TTL_MS = 12 * 60 * 60 * 1000;
/** A full 500-row GeoJSON page is a few hundred KB; anything past this is not a page. */
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
/**
* Request and validate a complete ECCC AQHI snapshot before it can replace
* displayed readings. The first registered air-quality provider.
*
* Two collections are involved. `aqhi-stations` is the catalog — it supplies
* every reading its coordinates and is cached for twelve hours because it
* barely changes. `aqhi-observations-realtime` is the hourly reading feed,
* requested with `latest=true` so the response is current values rather than
* the full observation history, which is roughly 2,000 rows nationally.
*
* The station catalog is only replaced when a refresh actually returns
* stations, so a transient empty response cannot blank the layer.
*
* @param {object} [options]
* @param {Function} [options.fetchImpl] - Injected fetch, for tests.
* @param {() => number} [options.now] - Clock seam, for tests.
* @param {number} [options.timeoutMs=15000] - Deadline for each request.
* @returns {{getSnapshot: Function}}
*/
export function createEcccAirQualitySource({
fetchImpl = (...args) => globalThis.fetch(...args),
now = () => Date.now(),
timeoutMs = 15_000,
} = {}) {
/** @type {Map<string, object>} */
let stations = new Map();
let stationsFetchedAt = 0;
/** One bounded GeoJSON page: deadline, caller abort, byte cap, row cap. */
const getJson = async (url, limit, signal) => {
const controller = new AbortController();
const abort = () => controller.abort(signal.reason);
signal?.addEventListener('abort', abort, { once: true });
const timer = setTimeout(
() => controller.abort(new Error('ECCC request timed out')),
timeoutMs,
);
try {
signal?.throwIfAborted();
const response = await fetchImpl(url, {
headers: { Accept: 'application/json' },
signal: controller.signal,
});
if (!response.ok) throw new Error(`ECCC HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
MAX_RESPONSE_BYTES,
controller.signal,
);
// The server's `limit` is a request, not a guarantee.
if (Array.isArray(payload?.features) && payload.features.length > limit)
return { ...payload, features: payload.features.slice(0, limit) };
return payload;
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', abort);
}
};
return {
async getSnapshot({ signal } = {}) {
const clock = now();
if (stations.size === 0 || clock - stationsFetchedAt > STATION_TTL_MS) {
const payload = await getJson(
`${STATIONS_URL}?f=json&limit=${STATION_LIMIT}`,
STATION_LIMIT,
signal,
);
const next = normalizeAqhiStations(payload);
if (!next) throw new Error('Malformed AQHI station response');
// An empty refresh must not wipe a good catalog.
if (next.size > 0) {
stations = next;
stationsFetchedAt = clock;
}
}
if (stations.size === 0) throw new Error('No AQHI stations available');
const payload = await getJson(
`${OBSERVATIONS_URL}?f=json&latest=true&limit=${OBSERVATION_LIMIT}`,
OBSERVATION_LIMIT,
signal,
);
const readings = normalizeAqhiObservations(payload, stations, clock);
if (!readings) throw new Error('Malformed AQHI observation response');
return readings;
},
};
}
+197
View File
@@ -0,0 +1,197 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createEcccAirQualitySource } from './source.js';
const NOW = Date.parse('2026-09-24T18:30:00Z');
const HOUR = 60 * 60 * 1000;
const station = (id) => ({
type: 'Feature',
geometry: { type: 'Point', coordinates: [-79.38, 43.65] },
properties: { location_id: id, location_name_en: id },
});
const observation = (id, at = NOW, aqhi = 3) => ({
type: 'Feature',
properties: {
location_id: id,
aqhi,
observation_datetime: new Date(at - 10 * 60_000).toISOString(),
},
});
const json = (body, init) =>
new Response(JSON.stringify(body), {
headers: { 'content-type': 'application/json' },
...init,
});
/** A fetch that serves the station catalog and observations from mutable state. */
function feed() {
const state = {
clock: NOW,
stations: [station('A')],
stationIds: null,
urls: [],
};
state.source = createEcccAirQualitySource({
now: () => state.clock,
fetchImpl: async (url) => {
state.urls.push(url);
return json({
type: 'FeatureCollection',
// Every known station reports ten minutes before the current clock.
features: url.includes('aqhi-stations')
? state.stations
: (state.stationIds || ['A']).map((id) =>
observation(id, state.clock),
),
});
},
});
state.stationRequests = () =>
state.urls.filter((url) => url.includes('aqhi-stations')).length;
return state;
}
test('the station catalog is cached for twelve hours, then refetched', async () => {
const state = feed();
await state.source.getSnapshot();
state.clock = NOW + 12 * HOUR;
await state.source.getSnapshot();
assert.equal(state.stationRequests(), 1, 'within the TTL the cache serves');
state.clock = NOW + 12 * HOUR + 1;
await state.source.getSnapshot();
assert.equal(
state.stationRequests(),
2,
'past the TTL the catalog refreshes',
);
});
test('an empty catalog refresh keeps the previous catalog', async () => {
const state = feed();
await state.source.getSnapshot();
state.stations = [];
state.clock = NOW + 13 * HOUR;
const readings = await state.source.getSnapshot();
assert.deepEqual(
readings.map((reading) => reading.stationId),
['A'],
);
// The empty refresh did not count as fresh, so the next call retries it.
await state.source.getSnapshot();
assert.equal(state.stationRequests(), 3);
});
test('an empty first catalog is an error, not an empty layer', async () => {
const state = feed();
state.stations = [];
await assert.rejects(state.source.getSnapshot(), /No AQHI stations/);
});
test('requests ask for JSON, the latest observations only, and a bounded page', async () => {
const state = feed();
await state.source.getSnapshot();
const [stations, observations] = state.urls.map((url) => new URL(url));
assert.equal(stations.pathname, '/collections/aqhi-stations/items');
assert.equal(stations.searchParams.get('f'), 'json');
assert.equal(stations.searchParams.get('limit'), '500');
assert.equal(
observations.pathname,
'/collections/aqhi-observations-realtime/items',
);
// Without latest=true the collection returns the full history (~2,000 rows).
assert.equal(observations.searchParams.get('latest'), 'true');
assert.equal(observations.searchParams.get('limit'), '500');
});
test('rows past the requested limit are ignored', async () => {
const state = feed();
state.stations = Array.from({ length: 600 }, (_, index) =>
station(`S${String(index).padStart(3, '0')}`),
);
state.stationIds = state.stations.map((row) => row.properties.location_id);
const readings = await state.source.getSnapshot();
assert.equal(readings.length, 500);
});
test('a malformed catalog and HTTP errors reject', async () => {
await assert.rejects(
createEcccAirQualitySource({
fetchImpl: async () => json({ features: 'no' }),
}).getSnapshot(),
/Malformed AQHI station/,
);
await assert.rejects(
createEcccAirQualitySource({
fetchImpl: async () => json({}, { status: 503 }),
}).getSnapshot(),
/ECCC HTTP 503/,
);
});
test('an oversized response is refused before it is parsed', async () => {
const big = 'x'.repeat(4 * 1024 * 1024 + 1);
await assert.rejects(
createEcccAirQualitySource({
fetchImpl: async () =>
new Response(new Blob([big]).stream(), {
headers: { 'content-type': 'application/json' },
}),
}).getSnapshot(),
(error) => error.code === 'RESPONSE_TOO_LARGE',
);
await assert.rejects(
createEcccAirQualitySource({
fetchImpl: async () =>
json({}, { headers: { 'content-length': String(5 * 1024 * 1024) } }),
}).getSnapshot(),
(error) => error.code === 'RESPONSE_TOO_LARGE',
);
});
test('a caller abort cancels the request and detaches its listener', async () => {
const caller = new AbortController();
let requestSignal = null;
const source = createEcccAirQualitySource({
fetchImpl: (_url, { signal }) => {
requestSignal = signal;
return new Promise((_resolve, reject) =>
signal.addEventListener('abort', () => reject(signal.reason), {
once: true,
}),
);
},
});
const pending = source.getSnapshot({ signal: caller.signal });
caller.abort(new Error('layer disabled'));
await assert.rejects(pending, /layer disabled/);
assert.equal(requestSignal.aborted, true);
const already = new AbortController();
already.abort(new Error('before start'));
let calls = 0;
await assert.rejects(
createEcccAirQualitySource({
fetchImpl: async () => {
calls += 1;
return json({ features: [] });
},
}).getSnapshot({ signal: already.signal }),
/before start/,
);
assert.equal(calls, 0);
});
test('a request that outlives its deadline is aborted', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const source = createEcccAirQualitySource({
timeoutMs: 1_000,
fetchImpl: (_url, { signal }) =>
new Promise((_resolve, reject) =>
signal.addEventListener('abort', () => reject(signal.reason), {
once: true,
}),
),
});
const pending = source.getSnapshot();
t.mock.timers.tick(1_000);
await assert.rejects(pending, /ECCC request timed out/);
});
@@ -0,0 +1,73 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { CITY_BY_ID } from './registry.js';
import { createModel } from './model.js';
import { createViewport } from './viewport.js';
import { isAllowedGbfsHost, isAllowedGbfsPath } from '../../data/gbfsSource.js';
// Each Bike Itaú city's PBSC host, and the station farthest from its
// registered centre in the live feed (checked 2026-10-15).
const CITIES = {
'sao-paulo-bike-itau': {
host: 'saopaulo.publicbikesystem.net',
stations: [{ name: '260 - P3', lat: -23.568235, lon: -46.740715 }],
},
'rio-de-janeiro-bike-itau': {
host: 'riodejaneiro.publicbikesystem.net',
stations: [{ name: '293 - Praia da Macumba', lat: -23.03135, lon: -43.479584 }],
},
'salvador-bike-itau': {
host: 'salvador.publicbikesystem.net',
stations: [{ name: '49 - Stella Maris', lat: -12.93645, lon: -38.32701 }],
},
'recife-bike-itau': {
host: 'recife.publicbikesystem.net',
stations: [{ name: '69 - Praia de Piedade', lat: -8.186205, lon: -34.918371 }],
},
'porto-alegre-bike-itau': {
host: 'portoalegre.publicbikesystem.net',
stations: [{ name: '72 - Avenida Tramandaí', lat: -30.135915, lon: -51.22684 }],
},
'brasilia-bike-itau': {
host: 'brasilia.publicbikesystem.net',
stations: [{ name: "60 - Parque Olhos d'Água", lat: -15.7431, lon: -47.88667 }],
},
'curitiba-bike-itau': {
host: 'curitiba.publicbikesystem.net',
stations: [{ name: '42 - Terminal Portão', lat: -25.476885, lon: -49.292608 }],
},
};
// The production range check, with no viewer or fetches behind it.
const parts = { model: createModel({ state: {}, services: {}, parts: {}, source: null }) };
const { computeInRangeCities } = createViewport({
state: {},
services: { render: { governorRequestRender() {} } },
parts,
source: null,
});
test('the Bike Itaú systems are registered and readable through the proxy', () => {
for (const [id, expected] of Object.entries(CITIES)) {
const city = CITY_BY_ID.get(id);
assert.ok(city, `${id} is registered`);
assert.equal(city.provider, 'Bike Itaú');
assert.deepEqual(city.hosts, [expected.host]);
for (const feed of [city.stationInformationUrl, city.stationStatusUrl]) {
const url = new URL(feed);
assert.ok(isAllowedGbfsHost(url.hostname), `${id} host ${url.hostname}`);
assert.ok(isAllowedGbfsPath(url.pathname), `${id} path ${url.pathname}`);
}
}
});
test('a camera over each outermost station activates its system', () => {
for (const [id, expected] of Object.entries(CITIES)) {
for (const station of expected.stations) {
assert.ok(
computeInRangeCities({ lat: station.lat, lon: station.lon }).has(id),
`${station.name} activates ${id}`,
);
}
}
});
+84
View File
@@ -246,6 +246,90 @@ const RAW_GBFS_CITY_REGISTRY = [
'https://chat.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Chattanooga',
},
{
id: 'sao-paulo-bike-itau',
city: 'São Paulo, SP',
centerLat: -23.5505,
centerLon: -46.6333,
loadRadiusKm: 100,
stationInformationUrl:
'https://saopaulo.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://saopaulo.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'rio-de-janeiro-bike-itau',
city: 'Rio de Janeiro, RJ',
centerLat: -22.9068,
centerLon: -43.1729,
loadRadiusKm: 100,
stationInformationUrl:
'https://riodejaneiro.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://riodejaneiro.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'salvador-bike-itau',
city: 'Salvador, BA',
centerLat: -12.9777,
centerLon: -38.5016,
loadRadiusKm: 90,
stationInformationUrl:
'https://salvador.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://salvador.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'recife-bike-itau',
city: 'Recife, PE',
centerLat: -8.0476,
centerLon: -34.877,
loadRadiusKm: 90,
stationInformationUrl:
'https://recife.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://recife.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'porto-alegre-bike-itau',
city: 'Porto Alegre, RS',
centerLat: -30.0346,
centerLon: -51.2177,
loadRadiusKm: 90,
stationInformationUrl:
'https://portoalegre.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://portoalegre.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'brasilia-bike-itau',
city: 'Brasília, DF',
centerLat: -15.7939,
centerLon: -47.8828,
loadRadiusKm: 90,
stationInformationUrl:
'https://brasilia.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://brasilia.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'curitiba-bike-itau',
city: 'Curitiba, PR',
centerLat: -25.4284,
centerLon: -49.2733,
loadRadiusKm: 90,
stationInformationUrl:
'https://curitiba.publicbikesystem.net/customer/gbfs/v2/en/station_information.json',
stationStatusUrl:
'https://curitiba.publicbikesystem.net/customer/gbfs/v2/en/station_status.json',
provider: 'Bike Itaú',
},
{
id: 'toronto-bike-share',
city: 'Toronto, ON',
+57
View File
@@ -1,4 +1,41 @@
import { CAMERA_SEEDS, SOURCE_ENDPOINT } from './policy.js';
import {
lookupModelSpec,
horizontalFovRangeDeg,
fixedHorizontalFovDeg,
} from './modelSpecs.js';
/**
* Applies datasheet enrichment to a camera in place: when it names a known
* hardware `model` (and, when published, a matching `manufacturer`), the spec
* record is attached for the HUD and the datasheet's horizontal FOV range
* rides along as `specFovMinDeg`/`specFovMaxDeg`. Only fixed-lens hardware
* fills the FOV, and only when none was given: an explicit source/seed
* `fovDeg` or a curated pose is never overwritten. A PTZ/varifocal range says
* what the lens CAN do, not where it is zoomed now.
* Unknown models — the common case — change nothing.
* @param {Object} camera - Camera being built (mutated).
* @param {{model?:string, manufacturer?:string, explicitFov?:boolean}} hardware
* - Hardware model/manufacturer from a source or seed, and whether that
* source or seed stated its own `fovDeg`.
* @param {(v:number,min:number,max:number)=>number} clamp - Pose clamp helper.
*/
function applyModelEnrichment(camera, hardware, clamp) {
const { model, manufacturer, explicitFov } = hardware;
const spec = model ? lookupModelSpec(model, manufacturer) : null;
if (!spec) return;
const range = horizontalFovRangeDeg(spec);
if (range) {
camera.specFovMinDeg = range.minDeg;
camera.specFovMaxDeg = range.maxDeg;
}
const fixedFov = fixedHorizontalFovDeg(spec);
if (fixedFov && !explicitFov && camera.poseSource !== 'curated') {
camera.fovDeg = clamp(fixedFov, 20, 125);
camera.fovSource = 'datasheet';
}
camera.spec = spec;
}
export function createCatalog({ state: layerState, services, parts, source }) {
const { CITY_POIS } = services.locations;
@@ -45,6 +82,11 @@ export function createCatalog({ state: layerState, services, parts, source }) {
parts.model.clamp(seed.elevationM ?? 22, 8, 80),
pitchDeg: parts.model.clamp(seed.pitchDeg ?? -17, -40, -4),
};
applyModelEnrichment(
camera,
{ model: seed.model, explicitFov: seed.fovDeg != null },
parts.model.clamp,
);
parts.model.ensureCameraPose(camera);
catalog.push(camera);
}
@@ -204,7 +246,22 @@ export function createCatalog({ state: layerState, services, parts, source }) {
? source.groundHeights
: null,
poseSource,
model: String(source.model || ''),
manufacturer: String(source.manufacturer || ''),
};
applyModelEnrichment(
camera,
{
model: source.model || seed?.model,
manufacturer: source.model ? source.manufacturer : '',
explicitFov:
(source.fovDeg != null && Number.isFinite(Number(source.fovDeg))) ||
CAMERA_SEEDS.some(
(entry) => entry.id === id && entry.fovDeg != null,
),
},
parts.model.clamp,
);
parts.model.ensureCameraPose(camera);
catalog.push(camera);
}
+531
View File
@@ -0,0 +1,531 @@
/**
* @module cctvModelSpecs
*
* Hardware-model spec enrichment for the CCTV layer.
*
* When a catalog camera names its hardware model (source packs may set
* `model`; hand-authored seeds may too), the model resolves to a datasheet
* record and the HUD meta line gains the model's real specs. A fixed-lens
* model's horizontal FOV replaces the frustum's estimate; a PTZ/varifocal or
* multi-sensor range is carried as capability metadata beside the estimate,
* because the lens's current zoom is unknown.
* Cameras without an identified model are untouched — unknown never implies
* anything.
*
* Spec records are vendored verbatim from the CCTV Camera Database
* (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) — an open dataset
* of 28,000+ camera models transcribed from manufacturer datasheets (84% with
* FOV, as of v2.26.0). This module vendors the records that the currently integrated public
* catalogs publish hardware for — King County WA (Cohu, Bosch AUTODOME, Axis
* Q6135-LE), plus the Bosch AUTODOME and Axis PTZ/multisensor models that
* appear in Sarasota County FL and Sioux Falls SD open data; packs that
* publish other hardware models can grow it, or vendor the full extract.
*
* Scope guardrail: records describe camera PRODUCTS (optics, resolution,
* night vision) — never endpoints, stream paths, or access/config data.
*/
/** Verbatim records from the dataset's model-enrichment extract (v2.26.0). */
const RECORDS = [
{
id: 'axis-q6135-le',
brand: 'Axis',
model: 'Q6135-LE',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/axis-q6135-le/',
aliases: ['01959-004'],
fov_deg: '58.3-2.4 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' },
ptz: true,
autotracking: true,
varifocal: true,
night_vision: { type: 'ir', range_m: 250 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'hanwha-xnp-6400rw',
brand: 'Hanwha',
model: 'XNP-6400RW',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/hanwha-xnp-6400rw/',
aliases: ['Wisenet PTZ Plus 2MP 40x IR PTZ'],
fov_deg: '65.66-1.88 horizontal / 39.4-1.09 vertical',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' },
ptz: true,
autotracking: true,
varifocal: true,
night_vision: { type: 'ir', range_m: 200 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'hikvision-ds-2cd2087g3-li2uy',
brand: 'Hikvision',
model: 'DS-2CD2087G3-LI2UY',
type: 'bullet',
url: 'https://www.cctv-database.com/camera/hikvision-ds-2cd2087g3-li2uy/',
fov_deg: '108.8 horizontal (2.8mm) / 93.3 horizontal (4mm)',
resolution: { mp: 8, w: 3840, h: 2160, label: '8MP (4K)' },
night_vision: { type: 'color', range_m: 40 },
environment: ['outdoor'],
ndaa_compliant: false,
},
{
id: 'axis-f4105-lre',
brand: 'Axis',
model: 'F4105-LRE',
type: 'dome',
url: 'https://www.cctv-database.com/camera/axis-f4105-lre/',
fov_deg: '110 horizontal, 60 vertical',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' },
night_vision: { type: 'ir', range_m: 10 },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'axis-p3707-pe',
brand: 'Axis',
model: 'P3707-PE',
type: 'panoramic',
url: 'https://www.cctv-database.com/camera/axis-p3707-pe/',
aliases: ['AXIS P3707-PE', 'P3707-PE'],
fov_deg: '108-54 horizontal per sensor (4x 1080p)',
resolution: {
mp: 8,
w: 1920,
h: 1080,
label: '4x 2MP (8MP total; 4x 1080p)',
},
lens_count: 4,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'axis-q6000-e-mk-ii',
brand: 'Axis',
model: 'Q6000-E Mk II',
type: 'panoramic',
url: 'https://www.cctv-database.com/camera/axis-q6000-e-mk-ii/',
aliases: [
'AXIS Q6000-E Mk II',
'Q6000-E Mk II 50 Hz',
'Q6000-E Mk II 60 Hz',
],
fov_deg: 'up to 360 combined; 113-152 horizontal per sensor',
resolution: {
mp: 8,
w: 1920,
h: 1080,
label: '4x 2MP (8MP total; 4x 1080p)',
},
lens_count: 4,
environment: ['outdoor'],
},
{
id: 'axis-q6054-e',
brand: 'Axis',
model: 'Q6054-E',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/axis-q6054-e/',
aliases: ['AXIS Q6054-E', 'Q6054-E 50 Hz', 'Q6054-E 60 Hz'],
fov_deg: '62.9-2.2 horizontal',
resolution: { mp: 1, w: 1280, h: 720, label: '720p HD' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'axis-q6155-e',
brand: 'Axis',
model: 'Q6155-E',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/axis-q6155-e/',
aliases: ['AXIS Q6155-E', 'Q6155-E 50 Hz', 'Q6155-E 60 Hz'],
fov_deg: '66.7-2.36 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-autodome-500i',
brand: 'Bosch',
model: 'AutoDome 500i Series (VG4)',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-autodome-500i/',
aliases: [
'VG4 AUTODOME',
'VG4 AUTODOME H.264',
'AutoDome 500i',
'AutoDome 500i Series',
'VG4-500i',
'VG4-500',
],
fov_deg: '57.8-1.7 horizontal',
resolution: { mp: 0.4, label: '540 TVL (NTSC/PAL)' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-autodome-ip-dynamic-7000-hd',
brand: 'Bosch',
model: 'AUTODOME IP dynamic 7000 HD',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-autodome-ip-dynamic-7000-hd/',
aliases: ['AUTODOME IP dynamic 7000 HD', 'AUTODOME 7000 dynamic HD'],
fov_deg: '65-2.3 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD (2MP)' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-autodome-ip-starlight-7000-hd',
brand: 'Bosch',
model: 'AUTODOME IP starlight 7000 HD',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-autodome-ip-starlight-7000-hd/',
aliases: [
'AUTODOME IP starlight 7000 HD',
'Starlight 7000HD',
'VG5-7130-CPT4',
'VG5-7130',
],
fov_deg: '59-2.1 horizontal',
resolution: { mp: 1, w: 1280, h: 720, label: '720p HD (1.3MP sensor)' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-ndp-5502-30',
brand: 'Bosch',
model: 'AUTODOME IP 5000i (NDP-5502-Z30)',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-ndp-5502-30/',
aliases: [
'AUTODOME IP 5000i',
'NDP-5502-Z30',
'NDP-5502-Z30C',
'NDP-5502-30',
],
fov_deg: '60.9-2.4 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD (2MP)' },
ptz: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-ndp-7512-z30',
brand: 'Bosch',
model: 'AUTODOME IP starlight 7000i (NDP-7512-Z30)',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-ndp-7512-z30/',
aliases: [
'AUTODOME IP starlight 7000i',
'NDP-7512-Z30',
'NDP-7512-Z30C',
'NDP-7512-Z30K',
],
fov_deg: '64.7-2.3 horizontal',
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD (2MP)' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-vg5-836-ecev',
brand: 'Bosch',
model: 'AUTODOME 800 Series HD PTZ (VG5-836-ECEV)',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-vg5-836-ecev/',
aliases: ['VG5-836-ECEV', 'VG5-836', 'AUTODOME 800 Series'],
resolution: { mp: 2, label: '1080p' },
ptz: true,
autotracking: true,
environment: ['outdoor'],
},
{
id: 'cohu-3920-idome',
brand: 'Cohu',
model: '3920 iDome',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/cohu-3920-idome/',
aliases: [
'3920',
'3920 Series',
'3923',
'3925',
'3925 Dome',
'iDome 3925',
'Cohu iDome 3920 Series',
],
resolution: { mp: 0.4, label: 'NTSC / 470 TVL' },
ptz: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'cohu-3950-iview',
brand: 'Cohu',
model: '3950 iVIEW',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/cohu-3950-iview/',
aliases: ['3950', '3950 Series', 'Cohu 3950 Series iVIEW'],
resolution: { mp: 0.4, label: 'NTSC / 470 TVL' },
ptz: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'cohu-3960',
brand: 'Cohu',
model: '3960',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/cohu-3960/',
aliases: ['3960 Series', '3964', '3965', 'Cohu 3960 iView'],
resolution: { mp: 0.4, label: 'NTSC/PAL / 470 TVL' },
ptz: true,
varifocal: true,
environment: ['outdoor'],
},
];
/** Lowercase + collapse whitespace, the shared normal form for matching. */
function normalize(value) {
return String(value || '')
.trim()
.toLowerCase()
.replace(/\s+/g, ' ');
}
/**
* Whitespace words of a name, lowercased, with surrounding punctuation trimmed
* so "(NDP-7512-Z30)" reads as "ndp-7512-z30". Inner hyphens and dots stay:
* "f4105-lre-unknown" is one word, never "f4105-lre" plus noise.
* @param {string} value
* @returns {string[]}
*/
function words(value) {
return normalize(value)
.split(' ')
.map((raw) => raw.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ''))
.filter(Boolean);
}
/**
* Descriptor words that never identify hardware: product-type nouns, codec
* and resolution/zoom/frequency tokens ("h.264", "2mp", "40x", "1080p").
*/
const GENERIC_WORDS = new Set([
'network',
'camera',
'cam',
'ip',
'ptz',
'dome',
'bullet',
'box',
'hd',
'ir',
'outdoor',
'indoor',
'series',
]);
function isGeneric(word) {
return (
GENERIC_WORDS.has(word) ||
/^h\.?\d+$/.test(word) ||
/^\d+(?:\.\d+)?(?:mp|p|k|x|mm|hz|tvl)$/.test(word)
);
}
/** A model code: letters AND digits, and not a generic descriptor. */
function isModelCode(word) {
return /[a-z]/.test(word) && /\d/.test(word) && !isGeneric(word);
}
/** Hyphenated variant suffixes that do not change the hardware. */
const VARIANT_SUFFIXES = new Set(['50hz', '60hz', 'ntsc', 'pal']);
/** "q6155-e-60hz" → "q6155-e"; "f4105-lre-unknown" is left as is. */
function stripVariantSuffix(word) {
let out = word;
for (;;) {
const cut = out.lastIndexOf('-');
if (cut <= 0 || !VARIANT_SUFFIXES.has(out.slice(cut + 1))) return out;
out = out.slice(0, cut);
}
}
/** Manufacturer names (lowercased words) accepted for each record brand. */
const BRAND_ALIASES = {
Hanwha: ['wisenet', 'samsung'],
Hikvision: ['hiwatch'],
};
function brandWords(record) {
return new Set([
...words(record.brand),
...(BRAND_ALIASES[record.brand] || []),
]);
}
/**
* One entry per record name (model + aliases). `required` is every
* non-generic word of the name — all must appear in a query, so a generation
* or suffix ("Mk II", "7000i" vs "7000") is never dropped. `hasCode` marks
* names carrying a letter+digit model code; names without one ("3950",
* "01959-004", "AUTODOME 800 Series") match only when the brand does.
*/
const NAME_INDEX = RECORDS.flatMap((record) => {
const brand = brandWords(record);
return [record.model, ...(record.aliases || [])].map((name) => {
const nameWords = words(name);
return {
record,
brand,
allowed: new Set(nameWords),
required: nameWords.filter((word) => !isGeneric(word)),
hasCode: nameWords.some(isModelCode),
};
});
});
/**
* Looks up a spec record for a hardware-model string.
*
* A record name matches when every non-generic word of that name appears in
* the query (case-insensitive, punctuation-trimmed) and every other query word
* is generic or the record's brand. That lets a VERBOSE registry string
* resolve — "AXIS Q6155-E PTZ Dome Network Camera" finds the Q6155-E — while
* an unrelated code ("Q1615"), a generation suffix ("Mk II") or a longer part
* number ("F4105-LRE-UNKNOWN") rejects the match. Codec, resolution and
* product-type words never identify hardware on their own. A name with no
* letter+digit model code ("3950") needs the brand, from `manufacturer` or the
* query itself. A `manufacturer` that is not the record's brand always
* rejects. Matches on two different records are ambiguous → null (never
* guesses).
* @param {string} model - Hardware model as named by a source pack or seed.
* @param {string} [manufacturer] - The source's manufacturer, when published.
* @returns {Object|null} The verbatim spec record, or null when unknown.
*/
export function lookupModelSpec(model, manufacturer) {
const query = words(model).map(stripVariantSuffix);
if (!query.length) return null;
const maker = words(manufacturer);
const found = new Set();
for (const entry of NAME_INDEX) {
const makerMatches = maker.some((word) => entry.brand.has(word));
if (maker.length && !makerMatches) continue;
if (
!entry.hasCode &&
!makerMatches &&
!query.some((word) => entry.brand.has(word))
)
continue;
if (!entry.required.length) continue;
if (!entry.required.every((word) => query.includes(word))) continue;
if (
!query.every(
(word) =>
entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word),
)
)
continue;
found.add(entry.record);
}
return found.size === 1 ? [...found][0] : null;
}
/**
* Datasheet horizontal FOV as the range the hardware can cover. Only
* segments stating a horizontal figure count — vertical and "combined"
* panoramic figures never do — and parenthesized lens/sensor notes are
* ignored. A zoom ('58.3-2.4 horizontal') and a lens-option list
* ('108.8 horizontal (2.8mm) / 93.3 horizontal (4mm)') both yield a range.
* @param {Object} spec - A record from this module.
* @returns {{minDeg:number, maxDeg:number}|null} Null when unstated.
*/
export function horizontalFovRangeDeg(spec) {
const values = [];
for (const segment of String(spec?.fov_deg || '').split(/[/;,]/)) {
if (!/horizontal/i.test(segment)) continue;
const figures = segment.replace(/\([^)]*\)/g, '').split(/horizontal/i)[0];
for (const match of figures.matchAll(/\d+(?:\.\d+)?/g)) {
const value = Number(match[0]);
if (Number.isFinite(value) && value > 0) values.push(value);
}
}
if (!values.length) return null;
return { minDeg: Math.min(...values), maxDeg: Math.max(...values) };
}
/**
* The datasheet horizontal FOV as the camera's CURRENT optical state, which
* holds only for fixed single-lens hardware stating one figure. PTZ,
* varifocal and multi-sensor models publish a capability range whose in-use
* value is unknown — known hardware capability is not known pose state — so
* they return null and keep their estimated FOV.
* @param {Object} spec - A record from this module.
* @returns {number|null} Fixed horizontal FOV in degrees, or null.
*/
export function fixedHorizontalFovDeg(spec) {
if (!spec || spec.ptz || spec.varifocal || (spec.lens_count || 1) > 1)
return null;
const range = horizontalFovRangeDeg(spec);
return range && range.minDeg === range.maxDeg ? range.minDeg : null;
}
/**
* True when the camera's CURRENT FOV is the datasheet figure: it was filled
* from a fixed-lens datasheet and no manual calibration offset has moved it.
* @param {Object} camera - Catalog camera (see applyModelEnrichment).
* @returns {boolean}
*/
export function isDatasheetFov(camera) {
return camera?.fovSource === 'datasheet' && !camera.calibration?.fovDeg;
}
/**
* HUD token for a datasheet FOV that describes capability rather than the
* camera's current state, e.g. 'SPEC FOV 2.4–58° (CAPABILITY)'.
* @param {Object} camera - Catalog camera (see applyModelEnrichment).
* @returns {string|null} Null when the datasheet FOV already IS the camera's
* FOV (fixed lens) or no datasheet range is known.
*/
export function specFovCapabilityToken(camera) {
if (!camera || camera.fovSource === 'datasheet') return null;
const { specFovMinDeg: min, specFovMaxDeg: max } = camera;
if (!Number.isFinite(min) || !Number.isFinite(max)) return null;
const fmt = (deg) => (deg < 10 ? deg.toFixed(1) : String(Math.round(deg)));
const span = min === max ? fmt(max) : `${fmt(min)}–${fmt(max)}`;
return `SPEC FOV ${span}° (CAPABILITY)`;
}
/**
* One-line spec summary for HUD meta text.
* @param {Object} spec - A record from this module.
* @returns {string} e.g. 'Axis Q6135-LE · 1080p · IR 250m · PTZ' ('' for null).
*/
export function specSummary(spec) {
if (!spec) return '';
const parts = [`${spec.brand} ${spec.model}`];
if (spec.resolution?.label) parts.push(spec.resolution.label);
if (spec.night_vision) {
parts.push(
`${spec.night_vision.type.toUpperCase()}${spec.night_vision.range_m ? ` ${spec.night_vision.range_m}m` : ''}`,
);
}
if (spec.ptz) parts.push('PTZ');
return parts.join(' · ');
}
+301
View File
@@ -0,0 +1,301 @@
// src/layers/cctv/modelSpecs.test.mjs
// Hardware-model spec enrichment: lookup semantics (case-insensitive, alias
// matching, unknown → null — never a guess), datasheet-FOV parsing across the
// real fov_deg string shapes, and the HUD spec-summary line.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
lookupModelSpec,
horizontalFovRangeDeg,
fixedHorizontalFovDeg,
specFovCapabilityToken,
isDatasheetFov,
specSummary,
} from './modelSpecs.js';
import { createCatalog } from './catalog.js';
test('lookupModelSpec matches case-insensitively and trims', () => {
const spec = lookupModelSpec(' q6135-le ');
assert.ok(spec);
assert.equal(spec.brand, 'Axis');
assert.equal(lookupModelSpec('Q6135-LE'), spec);
});
test('lookupModelSpec matches aliases', () => {
// A part number without letters needs the brand.
const byAlias = lookupModelSpec('01959-004', 'Axis');
assert.ok(byAlias);
assert.equal(byAlias.model, 'Q6135-LE');
});
test('vendored table covers the integrated catalogs published hardware', () => {
// Models the live packs publish: King County (Cohu, AUTODOME IP 5000i),
// Sarasota (Bosch AUTODOME 7000/VG4), Sioux Falls (Axis).
// King County publishes "3950" with Manufacturer "Cohu".
const cohu = lookupModelSpec('3950', 'Cohu');
assert.equal(cohu?.brand, 'Cohu');
const autodome = lookupModelSpec('AUTODOME IP 5000i');
assert.ok(autodome && horizontalFovRangeDeg(autodome).maxDeg > 0);
const vg4 = lookupModelSpec('VG4 AUTODOME H.264'); // Sarasota's string
assert.ok(vg4);
const axis = lookupModelSpec('Q6155-E'); // Sioux Falls
assert.deepEqual(horizontalFovRangeDeg(axis), { minDeg: 2.36, maxDeg: 66.7 });
});
test('verbose registry strings resolve via distinctive-token fallback', () => {
// Sioux Falls publishes the full product title, not the bare model.
assert.equal(
lookupModelSpec('AXIS Q6155-E PTZ Dome Network Camera')?.model,
'Q6155-E',
);
assert.equal(lookupModelSpec('AXIS Q6000-E Mk II')?.model, 'Q6000-E Mk II');
assert.equal(
lookupModelSpec('AUTODOME IP starlight 7000i camera')?.id,
'bosch-ndp-7512-z30',
);
// Punctuation around the model token doesn't defeat the match.
assert.equal(
lookupModelSpec('camera (P3707-PE), outdoor')?.model,
'P3707-PE',
);
});
test('token fallback never matches on generic words or wrong models', () => {
// Only generic descriptors — no distinctive hardware token — stays null.
assert.equal(lookupModelSpec('PTZ Dome Camera'), null);
assert.equal(lookupModelSpec('HD Network Camera'), null);
assert.equal(lookupModelSpec('Outdoor Dome Camera'), null);
// A real-looking but unknown model resolves to nothing, not a near neighbour.
assert.equal(lookupModelSpec('AXIS FooBar-9 Network Camera'), null);
// A generation token alone must not collide with a similar one: "7000"
// belongs to two records (dynamic / starlight 7000 HD), so a bare
// "AUTODOME 7000" is ambiguous → null rather than an arbitrary pick.
assert.equal(lookupModelSpec('AUTODOME 7000'), null);
});
test('exact match still wins over the token fallback', () => {
// "3965" is an alias of the 3960, not the 3950.
assert.equal(lookupModelSpec('3965', 'Cohu')?.id, 'cohu-3960');
assert.equal(lookupModelSpec('AUTODOME IP 5000i')?.id, 'bosch-ndp-5502-30');
});
test('lookupModelSpec returns null for unknown or empty input — never guesses', () => {
assert.equal(lookupModelSpec('NOT-A-REAL-MODEL'), null);
assert.equal(lookupModelSpec(''), null);
assert.equal(lookupModelSpec(null), null);
assert.equal(lookupModelSpec(undefined), null);
});
test('horizontalFovRangeDeg reads the full range across real fov_deg shapes', () => {
const range = (model) => horizontalFovRangeDeg(lookupModelSpec(model));
// PTZ zoom: both ends, not just the wide one.
assert.deepEqual(range('Q6135-LE'), { minDeg: 2.4, maxDeg: 58.3 });
// Vertical figures never count.
assert.deepEqual(range('XNP-6400RW'), { minDeg: 1.88, maxDeg: 65.66 });
// Lens options: parenthesized focal lengths are not FOV figures.
assert.deepEqual(range('DS-2CD2087G3-LI2UY'), {
minDeg: 93.3,
maxDeg: 108.8,
});
assert.deepEqual(range('F4105-LRE'), { minDeg: 110, maxDeg: 110 });
// The "360 combined" panoramic figure is not a horizontal lens FOV.
assert.deepEqual(range('Q6000-E Mk II'), { minDeg: 113, maxDeg: 152 });
assert.deepEqual(range('P3707-PE'), { minDeg: 54, maxDeg: 108 });
});
test('horizontalFovRangeDeg returns null when no numeric FOV is stated', () => {
assert.equal(horizontalFovRangeDeg({ fov_deg: '' }), null);
assert.equal(horizontalFovRangeDeg({ fov_deg: 'wide dynamic range' }), null);
assert.equal(horizontalFovRangeDeg({ fov_deg: '60 vertical' }), null);
assert.equal(horizontalFovRangeDeg({}), null);
assert.equal(horizontalFovRangeDeg(null), null);
});
test('fixedHorizontalFovDeg is the current FOV only for fixed single-lens hardware', () => {
// Fixed dome, one horizontal figure: the datasheet IS the optical state.
assert.equal(fixedHorizontalFovDeg(lookupModelSpec('F4105-LRE')), 110);
// Known hardware capability != known pose state: PTZ, multi-sensor, and a
// model sold in several lens options all stay estimated.
for (const model of [
'Q6135-LE',
'XNP-6400RW',
'AUTODOME IP 5000i',
'P3707-PE',
'Q6000-E Mk II',
'DS-2CD2087G3-LI2UY',
]) {
assert.equal(fixedHorizontalFovDeg(lookupModelSpec(model)), null, model);
}
assert.equal(fixedHorizontalFovDeg(null), null);
});
test('specFovCapabilityToken labels a datasheet range as capability, never as current FOV', () => {
assert.equal(
specFovCapabilityToken({ specFovMinDeg: 2.4, specFovMaxDeg: 58.3 }),
'SPEC FOV 2.4–58° (CAPABILITY)',
);
assert.equal(
specFovCapabilityToken({ specFovMinDeg: 113, specFovMaxDeg: 113 }),
'SPEC FOV 113° (CAPABILITY)',
);
// Already the camera's FOV (fixed lens) or nothing known: no token.
assert.equal(
specFovCapabilityToken({
fovSource: 'datasheet',
specFovMinDeg: 110,
specFovMaxDeg: 110,
}),
null,
);
assert.equal(specFovCapabilityToken({}), null);
assert.equal(specFovCapabilityToken(null), null);
});
/** Browser catalog with the pose math stubbed: only enrichment is under test. */
function browserCatalog() {
const model = {
safeNumber: (value, fallback = NaN) =>
Number.isFinite(Number(value)) ? Number(value) : fallback,
normalizeHeading: (deg) => ((deg % 360) + 360) % 360,
clamp: (value, lo, hi) => Math.min(hi, Math.max(lo, value)),
headingFromId: () => 0,
normalizeFeedType: (type) => type,
ensureCameraPose: () => {},
};
return createCatalog({
state: {},
services: { locations: { CITY_POIS: {} } },
parts: { model },
source: {},
});
}
test('catalog keeps the estimated FOV for PTZ hardware and fills only fixed-lens datasheets', () => {
const [ptz, fixed, unknown] = browserCatalog().buildCatalogFromSources([
{ id: 'ptz', lat: 47.7, lon: -122, fovDeg: 44, model: 'Q6135-LE' },
{ id: 'fixed', lat: 47.7, lon: -122, model: 'F4105-LRE' },
{ id: 'unknown', lat: 47.7, lon: -122, fovDeg: 44, model: 'NOPE-1' },
]);
// PTZ: the frustum keeps its estimate; the datasheet range is metadata.
assert.equal(ptz.fovDeg, 44);
assert.equal(ptz.fovSource, undefined);
assert.equal(ptz.specFovMinDeg, 2.4);
assert.equal(ptz.specFovMaxDeg, 58.3);
assert.equal(ptz.spec.model, 'Q6135-LE');
// Fixed lens: the datasheet figure is the optical state.
assert.equal(fixed.fovDeg, 110);
assert.equal(fixed.fovSource, 'datasheet');
// Unknown hardware changes nothing.
assert.equal(unknown.fovDeg, 44);
assert.equal(unknown.spec, undefined);
assert.equal(unknown.specFovMaxDeg, undefined);
});
test('codec, format and product words never identify hardware', () => {
// "h.264" is in the VG4 AUTODOME alias; it is a codec, not a model code.
assert.equal(lookupModelSpec('Axis Q1615 H.264 Network Camera'), null);
assert.equal(lookupModelSpec('H.264 Network Camera'), null);
assert.equal(lookupModelSpec('H.265 IP Camera'), null);
});
test('generation and suffix distinctions are preserved', () => {
// A Mk II is not the vendored (Mk I) Q6135-LE.
assert.equal(lookupModelSpec('AXIS Q6135-LE Mk II'), null);
// A longer part number is a different product...
assert.equal(lookupModelSpec('F4105-LRE-UNKNOWN'), null);
// ...unless the rest is a mains-frequency variant suffix.
assert.equal(lookupModelSpec('Q6155-E-60Hz')?.id, 'axis-q6155-e');
});
test('manufacturer must agree with the record brand', () => {
// Purely numeric models need a brand match.
assert.equal(lookupModelSpec('3950'), null);
assert.equal(lookupModelSpec('Pelco 3950'), null);
assert.equal(lookupModelSpec('3950', 'Pelco'), null);
// A model code under the wrong manufacturer is not that record either.
assert.equal(lookupModelSpec('Q6135-LE', 'Hikvision'), null);
// Case-insensitive, with company suffixes and aliases.
assert.equal(lookupModelSpec('3950', 'COHU')?.id, 'cohu-3950-iview');
assert.equal(
lookupModelSpec('Q6135-LE', 'Axis Communications AB')?.id,
'axis-q6135-le',
);
assert.equal(
lookupModelSpec('XNP-6400RW', 'Hanwha Vision')?.id,
'hanwha-xnp-6400rw',
);
assert.equal(
lookupModelSpec('XNP-6400RW', 'Wisenet')?.id,
'hanwha-xnp-6400rw',
);
});
test('King County snapshot model strings still resolve', () => {
// Model/Manufacturer pairs as published in the King County feed.
assert.equal(lookupModelSpec('3950', 'Cohu')?.id, 'cohu-3950-iview');
assert.equal(lookupModelSpec('3965', 'Cohu')?.id, 'cohu-3960');
assert.equal(lookupModelSpec('3925 Dome', 'Cohu')?.id, 'cohu-3920-idome');
assert.equal(lookupModelSpec('Q6135-LE', 'Axis')?.id, 'axis-q6135-le');
assert.equal(
lookupModelSpec('AUTODOME IP 5000i', 'BOSCH')?.id,
'bosch-ndp-5502-30',
);
});
test('catalog never overwrites an explicit FOV or a curated pose', () => {
const [explicit, curated, cohu, pelco] =
browserCatalog().buildCatalogFromSources([
{ id: 'explicit', lat: 47.7, lon: -122, fovDeg: 44, model: 'F4105-LRE' },
{
id: 'curated',
lat: 47.7,
lon: -122,
model: 'F4105-LRE',
poseSource: 'curated',
},
{ id: 'cohu', lat: 47.7, lon: -122, model: '3950', manufacturer: 'Cohu' },
{
id: 'pelco',
lat: 47.7,
lon: -122,
model: '3950',
manufacturer: 'Pelco',
},
]);
assert.equal(explicit.fovDeg, 44);
assert.equal(explicit.fovSource, undefined);
assert.equal(explicit.spec.model, 'F4105-LRE');
assert.equal(curated.fovDeg, 74);
assert.equal(curated.fovSource, undefined);
// The source's manufacturer reaches the lookup.
assert.equal(cohu.spec?.id, 'cohu-3950-iview');
assert.equal(pelco.spec, undefined);
});
test('the DATASHEET label drops once calibration moves the FOV', () => {
const camera = { fovSource: 'datasheet', fovDeg: 110 };
assert.equal(isDatasheetFov(camera), true);
assert.equal(isDatasheetFov({ ...camera, calibration: { fovDeg: 0 } }), true);
assert.equal(
isDatasheetFov({ ...camera, calibration: { fovDeg: 6 } }),
false,
);
assert.equal(isDatasheetFov({ fovDeg: 74 }), false);
assert.equal(isDatasheetFov(null), false);
});
test('specSummary renders the HUD line and degrades by omission', () => {
assert.equal(
specSummary(lookupModelSpec('Q6135-LE')),
'Axis Q6135-LE · 1080p · IR 250m · PTZ',
);
// No night vision / no PTZ → those segments are simply absent.
assert.equal(
specSummary({ brand: 'Axis', model: 'X', resolution: { label: '4K' } }),
'Axis X · 4K',
);
assert.equal(specSummary(null), '');
});
+24 -1
View File
@@ -1,6 +1,11 @@
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
import { ACTIVE_FRAME_REFRESH_MS, IDLE_FRAME_REFRESH_MS } from './policy.js';
import { headingHudToken, isHeadingEstimated } from './headingConfidence.js';
import {
specSummary,
specFovCapabilityToken,
isDatasheetFov,
} from './modelSpecs.js';
export function createPresentation({
state: layerState,
@@ -39,7 +44,12 @@ export function createPresentation({
// A synthetic bearing (headingConfidence 'low', no human calibration)
// is tagged so a hashed guess never reads as a surveyed facing (#639).
headingHudToken(active.camera),
`FOV ${Math.round(active.camera.fovDeg)}°`,
// Identified hardware labels its FOV as datasheet-sourced (catalog.js)
// only while no manual calibration offset has moved it.
`FOV ${Math.round(active.camera.fovDeg)}°${isDatasheetFov(active.camera) ? ' (DATASHEET)' : ''}`,
// A PTZ/varifocal datasheet range is what the lens can do, not its
// current zoom, so it is shown beside the estimate, never as it.
specFovCapabilityToken(active.camera),
`COVERAGE ${area.toFixed(2)}km²`,
overlapCount > 0 ? `OVERLAP ${overlapCount} cams` : 'ISOLATED VIEW',
`PROJ ${layerState._showProjection ? 'MONITOR' : 'OFF'}`,
@@ -49,6 +59,10 @@ export function createPresentation({
? `SRC ${String(health.sourceKind).toUpperCase()}`
: `SRC ${String(active.camera.feedType || 'image').toUpperCase()}`,
`${viewBand.toUpperCase()} CONTEXT`,
// Identified hardware: append the model's datasheet specs + attribution.
active.camera.spec
? `${specSummary(active.camera.spec).toUpperCase()} · SPECS: CCTV-DATABASE.COM`
: null,
]
.filter(Boolean)
.join(' · ');
@@ -86,6 +100,15 @@ export function createPresentation({
headingEstimated: isHeadingEstimated(camera),
pitchDeg: camera.pitchDeg,
fovDeg: camera.fovDeg,
// Identified-hardware enrichment passthrough (catalog.js / modelSpecs.js).
fovSource: isDatasheetFov(camera)
? 'datasheet'
: camera.fovSource === 'datasheet'
? 'calibrated'
: camera.fovSource || 'estimated',
specFovMinDeg: camera.specFovMinDeg ?? null,
specFovMaxDeg: camera.specFovMaxDeg ?? null,
spec: camera.spec || null,
rangeM: camera.rangeM,
elevationM: camera.absoluteHeightM,
mountHeightM: camera.mountHeightM,
+1
View File
@@ -386,6 +386,7 @@ export function createCyclonesLayer({
})),
},
chips: [],
legendCategorical: true,
legend: storm
? [
{ label: 'Advisory center / forecast track', color: '#7fe6ed' },
+5 -3
View File
@@ -275,10 +275,12 @@ export class FlightRecords {
return { icao24, prevMeta, meta, groundFlipped, fixEpochMs };
}
absence(id, { complete, likelyLanded }) {
// Partial admissions do not prove absence, but retention remains bounded.
absence(id, { complete, retainIds, likelyLanded }) {
// Partial admissions and position-less rows do not prove absence, but
// retention remains bounded; a likely-landed position-less contact
// still takes the landed limit.
if (
!complete &&
(!complete || (retainIds?.has(id) && !likelyLanded)) &&
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
)
return 'retain';
+24
View File
@@ -107,6 +107,30 @@ test('ground transitions preserve last render height while a surface cell is col
assert.equal(next.meta.wasAirborne, true);
});
test('complete snapshots age out vanished aircraft and retain position-less ones unless landed', () => {
const store = records();
for (const id of ['abc123', 'def456', 'ghi789'])
store.receive(observation({ id, reference: id }), view());
// abc123 and ghi789 are still listed without a position; def456 vanished.
const absent = (id, likelyLanded = false) =>
store.absence(id, {
complete: true,
retainIds: new Set(['abc123', 'ghi789']),
likelyLanded,
});
assert.deepEqual(
[absent('def456'), absent('def456'), absent('def456')],
['stale', 'stale', 'remove'],
);
assert.equal(absent('abc123'), 'retain');
assert.equal(store.missingPolls.has('abc123'), false);
// A landed contact that lost its position takes the landed fast-cull.
assert.equal(absent('ghi789', true), 'remove');
// Position-less retention stays bounded like partial admission.
store.data.get('abc123').observedReceiptMs = Date.now() - 300001;
assert.equal(absent('abc123'), 'stale');
});
test('civil emergency status follows the latest poll instead of sticking', () => {
const store = records();
const first = store.receive(observation({ squawk: '7700' }), view());
+1
View File
@@ -243,6 +243,7 @@ export function createFlightSnapshotRenderer({
if (currentIcaos.has(icao24)) continue;
const absence = records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
});
if (absence === 'retain') continue;
+6 -2
View File
@@ -221,8 +221,12 @@ export function createIngestion({ state, services, parts, source }) {
for (const record of records) {
if (isStaleVehicleFix(record, now, fetchedAt)) continue;
const key = transitVehicleKey(feed.id, record.id);
const mode = transitModeFor(feed, record.routeId);
const modeInferred = !transitModeResolved(feed, record.routeId);
const mode = transitModeFor(feed, record.routeId, record.id);
const modeInferred = !transitModeResolved(
feed,
record.routeId,
record.id,
);
// A stamp ahead of the fetch is a clock fault; the fetch time bounds it.
const stamped = vehicleReportTimeMs(record, fetchedAt);
const reportAt =
+51 -8
View File
@@ -4,7 +4,10 @@
* scene state, no network: everything here is exercised by node:test.
*/
import { TRANSIT_MODE_ICON } from '../../data/transitFeeds.js';
import {
TRANSIT_MODE_ICON,
transitRouteLabel,
} from '../../data/transitFeeds.js';
import { displayMotion, playbackPosition } from './movement.js';
export const TRANSIT_SELECTED_OVERLAY_SOURCE_ID = 'transit-selected';
@@ -337,7 +340,7 @@ export function buildTransitSelectionCopy(
) {
const icon = TRANSIT_MODE_ICON[mode] || TRANSIT_MODE_ICON.unknown;
const routeLabel = record.routeId
? `Route ${record.routeId}`
? `Route ${transitRouteLabel(feed, record.routeId)}`
: record.label
? `Vehicle ${record.label}`
: `Vehicle ${record.id}`;
@@ -345,7 +348,7 @@ export function buildTransitSelectionCopy(
// The mode is said in words on its own line. A glyph and a route id do not
// tell a reader that the dot on Tremont Street is a subway train, and a
// subway drawn on a street reads as a bug until the card says what it is.
const kindWord = TRANSIT_MODE_WORD[mode] || TRANSIT_MODE_WORD.unknown;
const kindWord = transitModeWord(mode, feed);
const details = [`${kindWord} · ${feed.name} · ${feed.region}`];
const motion = [];
// What the SCREEN is doing leads, because that is what the reader can check.
@@ -479,17 +482,50 @@ export const TRANSIT_MODE_ABBR = Object.freeze({
unknown: 'TRANSIT',
});
/**
* The mode in the operator's own vocabulary. A Toronto 501 and a Helsinki 1010
* are both the `tram` mode, but only one of them is called a tram by the people
* who ride it. A feed may name the modes it runs; everything else falls through
* to the shared table, so an override renames one word and nothing else.
* @param {string} mode Resolved transit mode.
* @param {object|null} [feed] Registry entry.
* @returns {string}
*/
export function transitModeWord(mode, feed = null) {
return (
feed?.modeWords?.[mode]?.word ||
TRANSIT_MODE_WORD[mode] ||
TRANSIT_MODE_WORD.unknown
);
}
/**
* The operator's short mode word for the fixed-width detection fields.
* @param {string} mode Resolved transit mode.
* @param {object|null} [feed] Registry entry.
* @returns {string}
*/
export function transitModeAbbr(mode, feed = null) {
return (
feed?.modeWords?.[mode]?.abbr ||
TRANSIT_MODE_ABBR[mode] ||
TRANSIT_MODE_ABBR.unknown
);
}
/**
* The bright first line of a vehicle's detection label: its route when the feed
* names one, else the fleet number, else the raw id. What a person standing at
* the stop would call it.
* @param {object} record Normalized vehicle record.
* @param {object|null} [feed] Registry entry, for feeds whose route ids are
* internal keys rather than the number on the vehicle.
* @returns {string}
*/
export function transitDetectionId(record) {
export function transitDetectionId(record, feed = null) {
const route =
typeof record?.routeId === 'string' ? record.routeId.trim() : '';
if (route) return elideRouteText(route);
if (route) return elideRouteText(transitRouteLabel(feed, route));
const label = typeof record?.label === 'string' ? record.label.trim() : '';
if (label) return elideRouteText(label);
return elideRouteText(String(record?.id || 'TRANSIT'));
@@ -521,7 +557,7 @@ export function elideRouteText(text) {
* @returns {string}
*/
export function transitDetectionClass(mode, feed) {
const kind = TRANSIT_MODE_ABBR[mode] || TRANSIT_MODE_ABBR.unknown;
const kind = transitModeAbbr(mode, feed);
const operator =
typeof feed?.name === 'string' ? feed.name.toUpperCase() : '';
return operator ? `${kind} ${operator}`.slice(0, 20) : kind;
@@ -538,10 +574,17 @@ export function transitDetectionClass(mode, feed) {
*
* @param {object} record Normalized vehicle record.
* @param {string} mode Resolved transit mode.
* @param {number} [nowMs]
* @param {object|null} [feed] Registry entry, for its own mode vocabulary.
* @returns {string}
*/
export function transitDetectionMetric(entry, mode, nowMs = Date.now()) {
const kind = TRANSIT_MODE_ABBR[mode] || TRANSIT_MODE_ABBR.unknown;
export function transitDetectionMetric(
entry,
mode,
nowMs = Date.now(),
feed = null,
) {
const kind = transitModeAbbr(mode, feed);
const state = transitVehicleState(entry, nowMs);
return state ? `${kind} ${state}` : kind;
}
+29 -6
View File
@@ -12,6 +12,20 @@ import {
} from '../../data/transitFeeds.js';
import { transitModeTier } from '../../data/transitPresetStyle.js';
/**
* The registry entry behind a vehicle. Live feeds answer first so a feed the
* session disabled stops supplying vocabulary; the registry is the fallback,
* because a vehicle can outlive the poll that brought it.
* @param {object} state Layer state.
* @param {object} entry Vehicle entry.
* @returns {object|null}
*/
function feedForEntry(state, entry) {
const id = entry?.feedId;
if (!id) return null;
return state._activeFeeds.get(id) || getRegisteredTransitFeed(id) || null;
}
/**
* The layer row's answer to "what is on screen and is it honest?".
* @param {object} context
@@ -101,6 +115,7 @@ export function createQueries({ state, parts }) {
contact._entry,
contact._entry.mode,
now,
feedForEntry(state, contact._entry),
);
return;
}
@@ -128,14 +143,17 @@ export function createQueries({ state, parts }) {
// Route and operator text change with the record and the mode, both of
// which arrive on polls — the same events that rebuild this list.
if (!entry.labelId || entry.labelRecord !== entry.record) {
entry.labelId = transitDetectionId(entry.record);
entry.labelId = transitDetectionId(
entry.record,
feedForEntry(state, entry),
);
entry.labelRecord = entry.record;
}
if (!entry.labelClass || entry.labelMode !== entry.mode) {
const feed =
state._activeFeeds.get(entry.feedId) ||
getRegisteredTransitFeed(entry.feedId);
entry.labelClass = transitDetectionClass(entry.mode, feed);
entry.labelClass = transitDetectionClass(
entry.mode,
feedForEntry(state, entry),
);
entry.labelMode = entry.mode;
}
const contact = {
@@ -146,7 +164,12 @@ export function createQueries({ state, parts }) {
id: entry.labelId,
type: 'VEH',
klass: entry.labelClass,
metric: transitDetectionMetric(entry, entry.mode, now),
metric: transitDetectionMetric(
entry,
entry.mode,
now,
feedForEntry(state, entry),
),
// The bracket carries the mode colour in every preset: the detection
// canvas sits above the post-FX chain, where the sprites' own colour
// is lost under NVG and FLIR. Keyless too — the feeds are keyless.
+76
View File
@@ -0,0 +1,76 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
buildTransitSelectionCopy,
transitDetectionClass,
transitDetectionId,
transitDetectionMetric,
transitModeAbbr,
transitModeWord,
} from './policy.js';
import { getTransitFeed } from '../../data/transitFeeds.js';
const ttc = () => getTransitFeed('ttc-toronto');
const hsl = () => getTransitFeed('hsl-helsinki');
test('an operator that names its own vehicles overrides the shared mode word', () => {
// A Toronto 501 is a streetcar. A Helsinki 1010 is a tram. Both are the
// `tram` mode, so the word a reader sees has to come from the operator,
// not from the mode.
assert.equal(transitModeWord('tram', ttc()), 'Streetcar');
assert.equal(transitModeAbbr('tram', ttc()), 'STREETCAR');
assert.equal(transitModeWord('tram', hsl()), 'Tram');
assert.equal(transitModeAbbr('tram', hsl()), 'TRAM');
});
test('an override renames one mode, never the rest of the feed', () => {
assert.equal(transitModeWord('bus', ttc()), 'Bus');
assert.equal(transitModeWord('subway', ttc()), 'Subway');
assert.equal(transitModeAbbr('bus', ttc()), 'BUS');
});
test('a missing feed or unknown mode falls back to the shared table', () => {
assert.equal(transitModeWord('tram', null), 'Tram');
assert.equal(transitModeWord('spaceship', ttc()), 'Transit vehicle');
assert.equal(transitModeAbbr('spaceship', ttc()), 'TRANSIT');
assert.equal(transitModeWord('tram', { name: 'No override' }), 'Tram');
});
test('the selection card calls a Toronto 501 a streetcar', () => {
const record = { id: '4400', routeId: '501', timestamp: 0 };
const copy = buildTransitSelectionCopy(ttc(), record, 'tram', 0, null, null);
assert.match(copy.details.join(' | '), /Streetcar · TTC/);
assert.doesNotMatch(copy.details.join(' | '), /Tram/);
});
test('detection labels carry the operator vocabulary within the field width', () => {
const klass = transitDetectionClass('tram', ttc());
assert.equal(klass, 'STREETCAR TTC');
assert.ok(klass.length <= 20, 'fits the detection class field');
assert.equal(transitDetectionClass('tram', hsl()), 'TRAM HSL');
const metric = transitDetectionMetric({ mode: 'tram' }, 'tram', 0, ttc());
assert.match(metric, /^STREETCAR/);
});
test('a Guelph vehicle is labelled with the number on the bus, not the database key', () => {
const guelph = getTransitFeed('guelph-transit');
const record = { id: '196', routeId: '2991', timestamp: 0 };
const copy = buildTransitSelectionCopy(guelph, record, 'bus', 0, null, null);
assert.match(copy.title, /Route 1\b/);
assert.doesNotMatch(copy.title, /2991/);
assert.equal(transitDetectionId(record, guelph), '1');
});
test('a feed that already speaks rider route numbers is untouched', () => {
const record = { id: '4400', routeId: '501', timestamp: 0 };
assert.equal(transitDetectionId(record, ttc()), '501');
const copy = buildTransitSelectionCopy(ttc(), record, 'tram', 0, null, null);
assert.match(copy.title, /Route 501/);
// No feed at all still renders the raw route rather than throwing.
assert.equal(transitDetectionId(record), '501');
});
test('a vehicle with no route still falls back to its fleet number', () => {
const guelph = getTransitFeed('guelph-transit');
assert.equal(transitDetectionId({ id: '196', label: '196' }, guelph), '196');
});