Сделал подписи RSSI на canvas с непрозрачной подложкой

This commit is contained in:
Ilgiz Kalmetyev 2026-07-03 19:41:28 +05:00
parent 8acf7e66c2
commit a7539c13c2
3 changed files with 1882 additions and 126 deletions

1682
cache/bssid_locations.json vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,10 +2,9 @@
const DEFAULT_API_BASE = "http://127.0.0.1:8080";
const DEFAULT_RENDER_INTERVAL_MS = 500;
const DEFAULT_TAIL_LENGTH = 60;
const DEFAULT_BSSID_PULSE_MS = 8000;
const RECONNECT_DELAY_MS = 2000;
const CANVAS_PADDING = 36;
const GRID_STEPS = 8;
const GRID_STEP_METERS = 2;
const elements = {
apiBaseInput: document.getElementById("api-base-input"),
@ -30,7 +29,6 @@
catalogById: new Map(),
liveById: new Map(),
historyById: new Map(),
bssidEventsById: new Map(),
selectedObjectId: null,
socket: null,
renderTimerId: null,
@ -88,7 +86,6 @@
rssiDbm: null,
observedAtUnixMs: null,
updatedAtUnixMs: null,
changedAtUnixMs: null,
});
}
state.catalogById = nextCatalog;
@ -145,7 +142,6 @@
function applySnapshot(objects) {
const nextLiveById = new Map();
for (const objectState of objects) {
const previous = state.liveById.get(objectState.object_id) || null;
const current = {
objectId: objectState.object_id,
objectType: getCatalogEntry(objectState.object_id).objectType,
@ -157,12 +153,7 @@
rssiDbm: typeof objectState.rssi_dbm === "number" ? objectState.rssi_dbm : null,
observedAtUnixMs: objectState.observed_at_unix_ms || null,
updatedAtUnixMs: objectState.updated_at_unix_ms || null,
changedAtUnixMs: previous ? previous.changedAtUnixMs : null,
};
if (shouldRecordBssidChange(previous, current)) {
current.changedAtUnixMs = Date.now();
appendBssidChangeEvent(previous, current);
}
nextLiveById.set(current.objectId, current);
appendHistoryPoint(current);
}
@ -173,43 +164,6 @@
renderSidebar();
}
function shouldRecordBssidChange(previous, current) {
return (
previous !== null &&
isComparableBssid(previous.bssid) &&
isComparableBssid(current.bssid) &&
previous.bssid !== current.bssid
);
}
function appendBssidChangeEvent(previous, current) {
if (!current.location || current.observedAtUnixMs === null) {
return;
}
const events = state.bssidEventsById.get(current.objectId) || [];
const lastEvent = events.length > 0 ? events[events.length - 1] : null;
const nextEvent = {
x: current.location.x,
y: current.location.y,
observedAtUnixMs: current.observedAtUnixMs,
fromBssid: previous.bssid,
toBssid: current.bssid,
};
if (
lastEvent &&
lastEvent.observedAtUnixMs === nextEvent.observedAtUnixMs &&
lastEvent.fromBssid === nextEvent.fromBssid &&
lastEvent.toBssid === nextEvent.toBssid
) {
return;
}
events.push(nextEvent);
while (events.length > state.tailLength) {
events.shift();
}
state.bssidEventsById.set(current.objectId, events);
}
function appendHistoryPoint(objectState) {
if (!objectState.location || objectState.observedAtUnixMs === null) {
return;
@ -217,6 +171,8 @@
const entry = {
x: objectState.location.x,
y: objectState.location.y,
bssid: objectState.bssid,
rssiDbm: objectState.rssiDbm,
observedAtUnixMs: objectState.observedAtUnixMs,
};
const history = state.historyById.get(objectState.objectId) || [];
@ -315,24 +271,32 @@
const bounds = computeBounds(visibleObjects);
const project = createProjector(bounds, width, height);
drawGrid(ctx, width, height);
drawGrid(ctx, bounds, project, width, height);
drawOriginMarker(ctx, project);
drawTrajectories(ctx, visibleObjects, project);
drawBssidChangeMarkers(ctx, visibleObjects, project);
drawObjects(ctx, visibleObjects, project);
}
function drawGrid(ctx, width, height) {
function drawGrid(ctx, bounds, project, width, height) {
ctx.save();
ctx.strokeStyle = "#d9dfcf";
ctx.lineWidth = 1;
for (let i = 0; i <= GRID_STEPS; i += 1) {
const x = Math.round((width / GRID_STEPS) * i) + 0.5;
const y = Math.round((height / GRID_STEPS) * i) + 0.5;
const minGridX = Math.floor(bounds.minX / GRID_STEP_METERS) * GRID_STEP_METERS;
const maxGridX = Math.ceil(bounds.maxX / GRID_STEP_METERS) * GRID_STEP_METERS;
const minGridY = Math.floor(bounds.minY / GRID_STEP_METERS) * GRID_STEP_METERS;
const maxGridY = Math.ceil(bounds.maxY / GRID_STEP_METERS) * GRID_STEP_METERS;
for (let gridX = minGridX; gridX <= maxGridX; gridX += GRID_STEP_METERS) {
const x = Math.round(project(gridX, 0).x) + 0.5;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.stroke();
}
for (let gridY = minGridY; gridY <= maxGridY; gridY += GRID_STEP_METERS) {
const y = Math.round(project(0, gridY).y) + 0.5;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
@ -360,6 +324,8 @@
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.font = "12px Segoe UI, sans-serif";
ctx.textBaseline = "middle";
const textWidth = ctx.measureText(label).width;
roundRect(ctx, origin.x + 10, origin.y - 18, textWidth + 10, 18, 7);
ctx.fillStyle = "rgba(255, 255, 255, 0.9)";
@ -375,59 +341,40 @@
if (history.length < 2) {
continue;
}
ctx.save();
ctx.beginPath();
for (let index = 0; index < history.length; index += 1) {
const point = history[index];
const projected = project(point.x, point.y);
if (index === 0) {
ctx.moveTo(projected.x, projected.y);
} else {
ctx.lineTo(projected.x, projected.y);
}
}
const selected = objectState.objectId === state.selectedObjectId;
ctx.strokeStyle = selected ? "rgba(11, 111, 85, 0.95)" : "rgba(39, 89, 181, 0.28)";
ctx.lineWidth = selected ? 3 : 1.5;
ctx.stroke();
ctx.restore();
}
}
function drawBssidChangeMarkers(ctx, objects, project) {
for (const objectState of objects) {
const events = state.bssidEventsById.get(objectState.objectId) || [];
if (events.length === 0) {
continue;
}
const selected = objectState.objectId === state.selectedObjectId;
for (const event of events) {
const projected = project(event.x, event.y);
ctx.save();
ctx.save();
for (let index = 1; index < history.length; index += 1) {
const previousPoint = history[index - 1];
const currentPoint = history[index];
const previousProjected = project(previousPoint.x, previousPoint.y);
const currentProjected = project(currentPoint.x, currentPoint.y);
ctx.beginPath();
ctx.arc(projected.x, projected.y, selected ? 7 : 5, 0, Math.PI * 2);
ctx.fillStyle = selected ? "rgba(226, 111, 27, 0.35)" : "rgba(226, 111, 27, 0.2)";
ctx.fill();
ctx.lineWidth = selected ? 3 : 2;
ctx.strokeStyle = selected ? "#d65f12" : "#e27b32";
ctx.moveTo(previousProjected.x, previousProjected.y);
ctx.lineTo(currentProjected.x, currentProjected.y);
ctx.strokeStyle = trajectoryColorForBssid(currentPoint.bssid, selected);
ctx.lineWidth = selected ? 3 : 1.5;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(projected.x - 4, projected.y - 4);
ctx.lineTo(projected.x + 4, projected.y + 4);
ctx.moveTo(projected.x - 4, projected.y + 4);
ctx.lineTo(projected.x + 4, projected.y - 4);
ctx.lineWidth = 1.5;
ctx.strokeStyle = selected ? "#8f3d08" : "#b04c10";
ctx.stroke();
ctx.restore();
}
ctx.fillStyle = selected ? "#384331" : "#56624d";
ctx.font = selected ? "11px Segoe UI, sans-serif" : "10px Segoe UI, sans-serif";
ctx.textBaseline = "bottom";
for (const point of history) {
if (typeof point.rssiDbm !== "number") {
continue;
}
const projected = project(point.x, point.y);
drawRssiTag(ctx, projected.x + 6, projected.y - 6, formatRssiShort(point.rssiDbm), selected);
}
ctx.restore();
}
}
function drawObjects(ctx, objects, project) {
ctx.font = "12px Segoe UI, sans-serif";
ctx.textBaseline = "middle";
const nowUnixMs = Date.now();
for (const objectState of objects) {
const selected = objectState.objectId === state.selectedObjectId;
const projected = project(objectState.location.x, objectState.location.y);
@ -437,7 +384,6 @@
const secondaryLabel = "BSSID " + formatBssid(objectState.bssid) + " · RSSI " + formatRssi(objectState.rssiDbm);
ctx.save();
drawBssidPulse(ctx, projected, objectState, nowUnixMs);
ctx.beginPath();
ctx.arc(projected.x, projected.y, selected ? 8 : 6, 0, Math.PI * 2);
ctx.fillStyle = markerColor;
@ -466,20 +412,17 @@
}
}
function drawBssidPulse(ctx, projected, objectState, nowUnixMs) {
if (!isPulseActive(objectState.changedAtUnixMs, nowUnixMs)) {
return;
}
const ageMs = nowUnixMs - objectState.changedAtUnixMs;
const progress = Math.min(ageMs / DEFAULT_BSSID_PULSE_MS, 1);
const radius = 12 + progress * 16;
const alpha = 0.45 * (1 - progress);
function drawRssiTag(ctx, x, y, text, selected) {
const textWidth = ctx.measureText(text).width;
const paddingX = 4;
const height = selected ? 16 : 14;
const top = y - height + 2;
ctx.save();
ctx.beginPath();
ctx.arc(projected.x, projected.y, radius, 0, Math.PI * 2);
ctx.lineWidth = 3;
ctx.strokeStyle = "rgba(226, 111, 27, " + alpha.toFixed(3) + ")";
ctx.stroke();
roundRect(ctx, x - paddingX, top, textWidth + paddingX * 2, height, 6);
ctx.fillStyle = selected ? "rgba(255, 252, 244, 0.96)" : "rgba(255, 255, 255, 0.92)";
ctx.fill();
ctx.fillStyle = selected ? "#384331" : "#56624d";
ctx.fillText(text, x, y);
ctx.restore();
}
@ -496,7 +439,6 @@
location: live ? live.location : null,
bssid: live ? live.bssid : catalog.bssid,
rssiDbm: live ? live.rssiDbm : catalog.rssiDbm,
changedAtUnixMs: live ? live.changedAtUnixMs : null,
speedMps: computeSpeedMps(objectId),
});
}
@ -551,10 +493,6 @@
maxY = Math.max(maxY, objectState.location.y);
}
if (!Number.isFinite(minX) || !Number.isFinite(minY)) {
return { minX: 0, minY: 0, maxX: 1, maxY: 1 };
}
if (minX === maxX) {
minX -= 1;
maxX += 1;
@ -611,11 +549,6 @@
state.historyById.set(objectId, history.slice(-state.tailLength));
}
}
for (const [objectId, events] of state.bssidEventsById.entries()) {
if (events.length > state.tailLength) {
state.bssidEventsById.set(objectId, events.slice(-state.tailLength));
}
}
}
function resizeCanvasToDisplaySize() {
@ -642,6 +575,24 @@
}
}
function trajectoryColorForBssid(bssid, selected) {
if (typeof bssid !== "string" || bssid.trim() === "") {
return selected ? "rgba(11, 111, 85, 0.95)" : "rgba(39, 89, 181, 0.28)";
}
const hue = hashStringToHue(bssid);
const alpha = selected ? 0.95 : 0.5;
const lightness = selected ? 38 : 48;
return "hsla(" + hue + ", 72%, " + lightness + "%, " + alpha + ")";
}
function hashStringToHue(value) {
let hash = 0;
for (let index = 0; index < value.length; index += 1) {
hash = (hash * 31 + value.charCodeAt(index)) % 360;
}
return hash;
}
function formatSpeed(speedMps) {
return speedMps > 0 ? speedMps.toFixed(2) + " m/s" : "0.00 m/s";
}
@ -654,12 +605,8 @@
return typeof rssiDbm === "number" ? rssiDbm.toFixed(0) + " dBm" : "n/a";
}
function isComparableBssid(bssid) {
return typeof bssid === "string" && bssid.trim() !== "";
}
function isPulseActive(changedAtUnixMs, nowUnixMs) {
return typeof changedAtUnixMs === "number" && nowUnixMs - changedAtUnixMs < DEFAULT_BSSID_PULSE_MS;
function formatRssiShort(rssiDbm) {
return typeof rssiDbm === "number" ? rssiDbm.toFixed(0) : "";
}
function setConnectionStatus(status) {
@ -710,7 +657,6 @@
rssiDbm: null,
observedAtUnixMs: null,
updatedAtUnixMs: null,
changedAtUnixMs: null,
};
state.catalogById.set(objectId, fallback);
return fallback;

View File

@ -0,0 +1,128 @@
#!/usr/bin/env python3
import argparse
import json
from collections import defaultdict
def rssi_to_weight(rssi, rssi_max, power=2.0):
"""
RSSI отрицательный: -50 сильнее, чем -80.
Нормируем относительно максимального RSSI для данного BSSID.
"""
linear = 10 ** ((rssi - rssi_max) / 10.0)
return linear**power
def extract_measurements(path):
measurements = defaultdict(list)
with open(path, "r", encoding="utf-8") as f:
for line_no, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
payload = row["event"]["payload"]["payload"]
location = payload["location"]
x = float(location["x"])
y = float(location["y"])
for ap in payload.get("scan_results", []):
bssid = ap.get("bssid")
ssid = ap.get("ssid")
freq = ap.get("frequency")
rssi = ap.get("signal_level")
if not bssid or rssi is None:
continue
measurements[bssid.lower()].append(
{
"x": x,
"y": y,
"rssi": float(rssi),
"ssid": ssid,
"frequency": freq,
"line_no": line_no,
}
)
except Exception as e:
print(f"skip line {line_no}: {e}")
return measurements
def estimate_bssid_locations(measurements, min_points=3, top_n=10):
results = []
for bssid, points in measurements.items():
if len(points) < min_points:
continue
# Берём только самые сильные измерения, чтобы дальние слабые точки не размазывали оценку
points_sorted = sorted(points, key=lambda p: p["rssi"], reverse=True)
selected = points_sorted[:top_n]
rssi_max = max(p["rssi"] for p in selected)
weights = []
for p in selected:
weights.append(rssi_to_weight(p["rssi"], rssi_max))
sw = sum(weights)
if sw == 0:
continue
x = sum(p["x"] * w for p, w in zip(selected, weights)) / sw
y = sum(p["y"] * w for p, w in zip(selected, weights)) / sw
best = selected[0]
results.append(
{
"bssid": bssid,
"ssid": best.get("ssid"),
"frequency": best.get("frequency"),
"estimated_x": round(x, 3),
"estimated_y": round(y, 3),
"max_rssi": best["rssi"],
"best_measurement_x": best["x"],
"best_measurement_y": best["y"],
"measurements_total": len(points),
"measurements_used": len(selected),
}
)
return sorted(results, key=lambda r: r["bssid"])
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input", help="scan_results.ndjson")
parser.add_argument("-o", "--output", default="bssid_locations.json")
parser.add_argument("--min-points", type=int, default=3)
parser.add_argument("--top-n", type=int, default=10)
args = parser.parse_args()
measurements = extract_measurements(args.input)
results = estimate_bssid_locations(
measurements,
min_points=args.min_points,
top_n=args.top_n,
)
with open(args.output, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"BSSID found: {len(measurements)}")
print(f"BSSID estimated: {len(results)}")
print(f"Output: {args.output}")
if __name__ == "__main__":
main()