GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / tools/satnav

SatNav Convergence Browser and 2 more files

A Python command-line tool in the tools folder of GridAtlas that checks asset actions (`check_asset_actions`) and opens walk panel (`open_walk_panel`) (units: kV), covering 11kV and substations.

595 lines of Python from gridatlas, in 3 files. Topic: Maps, GIS and field navigation. Section 672 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. SatNav Compact Browser render · gridatlas / tools/satnav/compact-browser.py lines 1–170
  2. SatNav Compass Browser render · gridatlas / tools/satnav/compass-browser.py lines 1–206
  3. SatNav Convergence Browser render · gridatlas / tools/satnav/convergence-browser.py lines 1–219

SatNav Compact Browser

A Python command-line tool in the tools folder of GridAtlas using data from the SatNav repository. It maps canvas tap (`map_canvas_tap`) and checks browser (`check_browser`).

rendergridatlas / tools/satnav/compact-browser.py · lines 1–170 of 170 · Entry point · pattern surface_distance (shared by 2 files)

What it does
Defines surface_distance, leg_point, map_canvas_tap, overlay_roles, check_browser. Uses libraries math, os, re, urllib.parse, playwright.sync_api. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Compact SatNav acceptance against the real GridAtlas composer.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav · Python CLI
Uses
math, os, re, urllib.parse, playwright.sync_api
Used by
none found
Produces
surface_distance, leg_point, map_canvas_tap, overlay_roles, check_browser
Defines here
surface_distance, leg_point, map_canvas_tap, overlay_roles, check_browser
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/compact-browser.py:1-170 · blob f8738d5fd48746d77d5eddd9de7665fd56f6772e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Compact SatNav acceptance against the real GridAtlas composer."""

import math
import os
import re
from urllib.parse import parse_qs, urlsplit

from playwright.sync_api import expect, sync_playwright


SITE = os.environ.get(
    'LINE_TEST_URL', 'http://127.0.0.1:8873/atlas/v/satnav-compact-202611281237/'
)
P1 = 'https://ventusltd.github.io/satnav/preview/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/'
SOURCE = 'gridatlas-satnav-compact'
SECTION = 'selected-section'
MEASURED = 'measured-gps'
RING = 'gps-accuracy'
NEAREST = 'nearest-on-section'

GPS_SPY = """(() => {
  let nextId = 0;
  const watches = new Map();
  const records = { starts: [], stops: [] };
  Object.defineProperty(navigator, 'geolocation', {
    configurable: true,
    value: {
      watchPosition(success, error) {
        const id = ++nextId;
        watches.set(id, { success, error });
        records.starts.push(id);
        return id;
      },
      clearWatch(id) {
        records.stops.push(id);
        watches.delete(id);
      },
    },
  });
  window.__lineGpsTest = {
    records,
    deny() { for (const { error } of [...watches.values()]) error({code:1}); },
    emit(coordinates, accuracy, age = 0) {
      const coords = { longitude: coordinates[0], latitude: coordinates[1], accuracy };
      const result = { coords, timestamp: Date.now() - age };
      for (const { success } of watches.values()) success(result);
    },
  };
})()"""


def surface_distance(first, second):
    lon1, lat1 = map(math.radians, first)
    lon2, lat2 = map(math.radians, second)
    a = math.sin((lat2 - lat1) / 2) ** 2
    b = math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
    return 6_371_000 * 2 * math.asin(min(1, math.sqrt(a + b)))


def leg_point(start, end, fraction, offset):
    lon, lat = [a + (b - a) * fraction for a, b in zip(start, end)]
    x_scale = 111_195 * math.cos(math.radians(lat))
    y_scale = 111_195
    east = (end[0] - start[0]) * x_scale
    north = (end[1] - start[1]) * y_scale
    norm = math.hypot(east, north)
    return [lon + offset * north / (norm * x_scale), lat - offset * east / (norm * y_scale)]


def map_canvas_tap(page, excluded=None):
    target = page.wait_for_function("""excluded => {
      const map = window.__GRIDATLAS_V9_MAP__;
      if (map.isMoving()) return null;
      const canvas = map.getCanvas();
      const rect = canvas.getBoundingClientRect();
      for (const fraction of [.83, .74, .65, .54, .44]) {
        const y = Math.round(rect.top + rect.height * fraction);
        for (const side of [.24, .7, .42, .57]) {
          const x = Math.round(rect.left + rect.width * side);
          if (excluded && Math.hypot(x - excluded.x, y - excluded.y) < 90) continue;
          if (document.elementFromPoint(x, y) !== canvas) continue;
          return {x, y, coordinates: map.unproject([x - rect.left, y - rect.top]).toArray()};
        }
      }
      return null;
    }""", arg=excluded, timeout=15000).json_value()
    page.touchscreen.tap(target['x'], target['y'])
    return target


def overlay_roles(page, required, absent=()):
    data = page.wait_for_function("""({source, required, absent}) => {
      const data = window.__GRIDATLAS_V9_MAP__?.getSource(source)?.serialize()?.data;
      if (!Array.isArray(data?.features)) return null;
      const found = Object.fromEntries(data.features.map(feature => [feature.properties.role, feature]));
      return required.every(role => found[role]) && absent.every(role => !found[role]) ? found : null;
    }""", arg={'source': SOURCE, 'required': required, 'absent': absent}, timeout=15000)
    return data.json_value()


def check_browser(browser, label, width, height):
    context = browser.new_context(viewport={'width': width, 'height': height},
                                  is_mobile=True, has_touch=True)
    context.add_init_script(GPS_SPY)
    page = context.new_page()
    errors = []
    page.on('pageerror', lambda error: errors.append(str(error)))
    page.goto(SITE, wait_until='domcontentloaded')
    page.wait_for_function("window.__GRIDATLAS_V9_MAP__?.getLayer('l-sat')", timeout=45000)
    expect(page.locator('#satnav-from')).to_be_enabled(timeout=45000)
    expect(page.locator('#satnav-to')).to_be_enabled()
    assert page.evaluate('window.__lineGpsTest.records.starts') == []
    canvas = page.locator('#map canvas.maplibregl-canvas').first.bounding_box()
    assert canvas and canvas['width'] * canvas['height'] >= width * height * .85, canvas
    page.evaluate("window.__GRIDATLAS_V9_MAP__.jumpTo({center: [-1.5, 51.5], zoom: 16})")
    page.locator('#satnav-to').tap()
    second = map_canvas_tap(page)
    page.locator('#satnav-from').tap()
    first = map_canvas_tap(page, second)
    found = overlay_roles(page, ['start-point', 'destination-point', SECTION])
    start = found['start-point']['geometry']['coordinates']
    end = found['destination-point']['geometry']['coordinates']
    assert surface_distance(start, first['coordinates']) < 2
    assert surface_distance(end, second['coordinates']) < 2
    # GPS denial must not erase either manual endpoint.
    page.locator('#satnav-location').tap()
    page.evaluate('window.__lineGpsTest.deny()')
    found = overlay_roles(page, ['start-point', 'destination-point'])
    assert found['start-point']['geometry']['coordinates'] == start
    assert found['destination-point']['geometry']['coordinates'] == end
    page.locator('#satnav-location').tap()
    page.evaluate('at => window.__lineGpsTest.emit(at, 8)', start)
    found = overlay_roles(page, [MEASURED, RING, 'start-point', 'destination-point'])
    assert found[MEASURED]['geometry']['coordinates'] == start
    assert found['destination-point']['geometry']['coordinates'] == end
    page.locator('#satnav-from').tap()
    map_canvas_tap(page, second)
    found = overlay_roles(page, ['start-point', 'destination-point', MEASURED])
    revised = found['start-point']['geometry']['coordinates']
    assert found['destination-point']['geometry']['coordinates'] == end
    page.locator('#satnav-to').tap()
    map_canvas_tap(page, first)
    found = overlay_roles(page, ['start-point', 'destination-point', MEASURED])
    assert found['start-point']['geometry']['coordinates'] == revised
    assert page.evaluate('window.__lineGpsTest.records.starts') == [1, 2]
    assert page.evaluate('window.__lineGpsTest.records.stops') == [1]
    next_fix = [start[0] + .0001, start[1]]
    page.evaluate('at => window.__lineGpsTest.emit(at, 8)', next_fix)
    page.wait_for_function("(at) => window.__GRIDATLAS_V9_MAP__.getSource('gridatlas-satnav-compact').serialize().data.features.some(f => f.properties.role === 'measured-gps' && JSON.stringify(f.geometry.coordinates) === JSON.stringify(at))", arg=next_fix)
    page.evaluate('at => window.__lineGpsTest.emit(at, 75)', next_fix)
    overlay_roles(page, [MEASURED, RING])
    page.evaluate('at => window.__lineGpsTest.emit(at, 8, 12000)', next_fix)
    overlay_roles(page, ['start-point', 'destination-point'], absent=[MEASURED, RING])
    page.locator('#satnav-stop').tap()
    assert page.evaluate('window.__lineGpsTest.records.stops') == [1, 2]
    assert not errors, errors
    print(f'{label} {width}x{height}: real taps, full map, opt-in/denial, endpoint replacement, GPS and Stop passed', flush=True)
    context.close()


if __name__ == '__main__':
    with sync_playwright() as playwright:
        for engine in os.environ.get('LINE_TEST_BROWSERS', 'chromium,webkit').split(','):
            options = {'args': ['--enable-webgl', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']} if engine == 'chromium' else {}
            browser = getattr(playwright, engine).launch(**options)
            try:
                for width, height in [(390, 664), (664, 390)]:
                    check_browser(browser, engine, width, height)
            finally:
                browser.close()

SatNav Compass Browser

A Python command-line tool in the tools folder of GridAtlas that checks notice (`check_notice`) and heading (`check_heading`), checks viewport (`check_viewport`) and calculates angles.

rendergridatlas / tools/satnav/compass-browser.py · lines 1–206 of 206 · Entry point · pattern sample (shared by 18 files)

What it does
It draws its content. Defines 6 functions or classes, including initial_bearing, expect_true_bearing, check_notice, sample, check_heading. Uses libraries importlib.util, math, os, pathlib, re. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'compass'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the initial bearing helper (`initial_bearing`), the expect true bearing helper (`expect_true_bearing`) and the sample step (`sample`). Touch-test the real GridAtlas compass page, using simulated heading and GPS samples.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav · Python CLI
Uses
importlib.util, math, os, pathlib, re, playwright.sync_api
Used by
none found
Produces
initial_bearing, expect_true_bearing, check_notice, sample, check_heading, check_viewport
Defines here
initial_bearing, expect_true_bearing, check_notice, sample, check_heading, check_viewport
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/compass-browser.py:1-206 · blob b0f93632e7ff4fd00ffc2efb7d6a0841a479b6a4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Touch-test the real GridAtlas compass page, using simulated heading and GPS samples."""

import importlib.util
import math
import os
from pathlib import Path
import re

from playwright.sync_api import expect, sync_playwright


HERE = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location('satnav_compact_browser', HERE / 'compact-browser.py')
compact = importlib.util.module_from_spec(spec)
spec.loader.exec_module(compact)

SITE = os.environ.get('LINE_TEST_URL', 'http://127.0.0.1:8873/atlas/v/satnav-compass-202611281255/')
SENSOR = """(() => {
  let answer = 'granted';
  let resolvePending;
  const requests = [];
  const Orientation = window.DeviceOrientationEvent || class extends Event {};
  if (!window.DeviceOrientationEvent) {
    Object.defineProperty(window, 'DeviceOrientationEvent', {configurable: true, value: Orientation});
  }
  Object.defineProperty(Orientation, 'requestPermission', {
    configurable: true,
    value(absolute) {
      requests.push(absolute);
      return answer === 'pending' ? new Promise(resolve => { resolvePending = resolve; }) : Promise.resolve(answer);
    },
  });
  window.__fieldSensorTest = {
    requests,
    isolate() {
      for (const type of ['deviceorientation', 'deviceorientationabsolute']) {
        window.addEventListener(type, event => { if (event.isTrusted) event.stopImmediatePropagation(); }, true);
      }
    },
    permission(value) { answer = value; },
    release() { resolvePending('granted'); },
    sample(type, properties) {
      const event = new Event(type);
      for (const [key, value] of Object.entries(properties)) {
        Object.defineProperty(event, key, {value});
      }
      window.dispatchEvent(event);
    },
  };
})()"""


def initial_bearing(from_point, to_point):
    lon1, lat1, lon2, lat2 = map(math.radians, [*from_point, *to_point])
    delta = lon2 - lon1
    east = math.sin(delta) * math.cos(lat2)
    north = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(delta)
    return math.degrees(math.atan2(east, north)) % 360


def expect_true_bearing(reading, origin_label, start, end):
    degree = round(initial_bearing(start, end))
    # The real geodesy module and the map tap projection can round at a degree boundary.
    values = '|'.join(f'{(degree + offset) % 360:03d}' for offset in (-1, 0, 1))
    expect(reading).to_have_text(re.compile(rf'{origin_label} to TO (?:{values})° true'))


def check_notice(page):
    notice = page.locator('#field-land-access')
    summary = notice.locator('summary')
    expect(summary).to_be_visible()
    expect(notice.locator('p')).to_be_hidden()
    summary.tap()
    expect(notice.locator('p')).to_contain_text(re.compile(r'access.*permission.*restrictions.*work safely', re.I))
    summary.tap()
    # The reusable cartridge must defer to a successor map that already supplies its own notice.
    page.evaluate("""() => {
      const sibling = document.createElement('details');
      sibling.id = 'satnav-access';
      sibling.innerHTML = '<summary>Check access before entry</summary>';
      document.body.append(sibling);
    }""")
    expect(notice).to_be_hidden()
    expect(page.locator('#satnav-access summary')).to_be_visible()
    page.locator('#satnav-access').evaluate('element => element.remove()')
    expect(summary).to_be_visible()


def sample(page, event_type, **properties):
    page.evaluate('([type, properties]) => window.__fieldSensorTest.sample(type, properties)',
                  [event_type, properties])


def check_heading(page):
    # The composer replaces the document and clears listeners installed on the loader.
    page.evaluate("window.__fieldSensorTest.isolate()")
    toggle = page.locator('#field-compass-toggle')
    reading = page.locator('#field-compass-reading')
    angle = page.evaluate('screen.orientation?.angle ?? window.orientation ?? 0')
    assert page.evaluate('window.__fieldSensorTest.requests') == []
    page.evaluate("window.__fieldSensorTest.permission('denied')")
    toggle.tap()
    expect(reading).to_contain_text(re.compile('permission denied', re.I))
    expect(toggle).to_have_attribute('aria-pressed', 'false')
    page.evaluate("window.__fieldSensorTest.permission('granted')")
    toggle.tap()
    expect(toggle).to_have_attribute('aria-pressed', 'true')
    assert page.evaluate('window.__fieldSensorTest.requests') == [True, True]
    before = reading.inner_text()
    sample(page, 'deviceorientation', alpha=37, beta=0, gamma=0, absolute=False)
    expect(reading).to_have_text(before)
    sample(page, 'deviceorientation', webkitCompassHeading=134, webkitCompassAccuracy=4, beta=0, gamma=0)
    expect(reading).to_have_text(f'Heading {(134 + angle) % 360:03d}° magnetic')
    sample(page, 'deviceorientation', webkitCompassHeading=57, webkitCompassAccuracy=-1, beta=0, gamma=0)
    expect(reading).to_contain_text(re.compile('unavailable', re.I))
    sample(page, 'deviceorientationabsolute', alpha=270, beta=0, gamma=0, absolute=True)
    expect(reading).to_have_text(f'Heading {(90 + angle) % 360:03d}° sensor')
    assert page.evaluate('window.__lineGpsTest.records.starts') == []


def check_viewport(browser, label, width, height):
    with browser.new_context(viewport={'width': width, 'height': height}, is_mobile=True, has_touch=True) as context:
        context.add_init_script(compact.GPS_SPY)
        context.add_init_script(SENSOR)
        page = context.new_page()
        # Heading expiry and Stop must use the same timer implementation.
        page.clock.install()
        errors = []
        page.on('pageerror', lambda error: errors.append(str(error)))
        page.goto(SITE, wait_until='domcontentloaded')
        page.wait_for_function("window.__GRIDATLAS_V9_MAP__?.getLayer('l-sat')", timeout=90000)
        expect(page.locator('#satnav-from')).to_be_enabled(timeout=30000)
        expect(page.locator('#field-compass-toggle')).to_be_visible()
        canvas = page.locator('#map canvas.maplibregl-canvas').first.bounding_box()
        assert canvas and canvas['width'] * canvas['height'] >= width * height * .85, canvas
        check_notice(page)
        check_heading(page)

        page.evaluate("window.__GRIDATLAS_V9_MAP__.jumpTo({center: [-1.5, 51.5], zoom: 16})")
        page.locator('#satnav-to').tap()
        to_tap = compact.map_canvas_tap(page)
        page.locator('#satnav-from').tap()
        from_tap = compact.map_canvas_tap(page, to_tap)
        overlay = compact.overlay_roles(page, ['start-point', 'destination-point', compact.SECTION])
        start = overlay['start-point']['geometry']['coordinates']
        end = overlay['destination-point']['geometry']['coordinates']
        assert compact.surface_distance(start, from_tap['coordinates']) < 2
        assert compact.surface_distance(end, to_tap['coordinates']) < 2
        bearing = page.locator('#field-target-bearing')
        expect_true_bearing(bearing, 'FROM', start, end)

        page.locator('#satnav-location').tap()
        page.evaluate('window.__lineGpsTest.deny()')
        overlay = compact.overlay_roles(page, ['start-point', 'destination-point'])
        assert overlay['start-point']['geometry']['coordinates'] == start
        assert overlay['destination-point']['geometry']['coordinates'] == end
        page.locator('#satnav-location').tap()
        page.evaluate('at => window.__lineGpsTest.emit(at, 8)', start)
        compact.overlay_roles(page, [compact.MEASURED, compact.RING])
        # Deliberately move away from the line so the live bearing differs from the planned bearing.
        moved = compact.leg_point(start, end, .5, 50)
        page.evaluate('at => window.__lineGpsTest.emit(at, 8)', moved)
        expect_true_bearing(bearing, 'GPS', moved, end)
        page.evaluate('at => window.__lineGpsTest.emit(at, 75)', moved)
        expect(bearing).to_contain_text(re.compile('accurate GPS fix', re.I))
        page.evaluate('at => window.__lineGpsTest.emit(at, 8)', end)
        expect(bearing).to_contain_text(re.compile('within GPS accuracy', re.I))
        # A fresh heading has its own expiry, independent of the existing GPS watch.
        reading = page.locator('#field-compass-reading')
        sample(page, 'deviceorientation', webkitCompassHeading=15, webkitCompassAccuracy=3)
        expect(reading).to_contain_text('magnetic')
        page.clock.fast_forward(10001)
        expect(reading).to_have_text('Waiting for a fresh heading')
        assert page.evaluate('window.__lineGpsTest.records') == {'starts': [1, 2], 'stops': [1]}
        page.locator('#satnav-stop').tap()
        expect(page.locator('#field-compass-toggle')).to_have_attribute('aria-pressed', 'false')
        sample(page, 'deviceorientation', webkitCompassHeading=247, webkitCompassAccuracy=2)
        expect(reading).to_have_text('')
        assert page.evaluate('window.__lineGpsTest.records.stops') == [1, 2]
        compact.overlay_roles(page, ['start-point', 'destination-point'], absent=[compact.MEASURED, compact.RING])
        # The same cartridge subscribes to the successor panel's non-bubbling Stop.
        page.evaluate("window.__fieldSensorTest.permission('pending')")
        page.locator('#field-compass-toggle').tap()
        page.evaluate("""() => {
          document.querySelector('#satnav-compact').dispatchEvent(new Event('satnav:stop'));
          window.__fieldSensorTest.release();
        }""")
        expect(page.locator('#field-compass-toggle')).to_have_attribute('aria-pressed', 'false')
        sample(page, 'deviceorientation', webkitCompassHeading=247, webkitCompassAccuracy=2)
        expect(reading).to_have_text('')
        assert not errors, errors
        print(f'{label} {width}x{height}: real map taps, access notice, opt-in heading, bearing, accuracy and Stop passed', flush=True)


if __name__ == '__main__':
    with sync_playwright() as playwright:
        for engine in os.environ.get('LINE_TEST_BROWSERS', 'chromium,webkit').split(','):
            engine = engine.strip()
            options = {'args': ['--enable-webgl', '--use-gl=angle', '--use-angle=swiftshader',
                                '--enable-unsafe-swiftshader']} if engine == 'chromium' else {}
            browser = getattr(playwright, engine).launch(**options)
            try:
                for size in [(390, 664), (664, 390)]:
                    check_viewport(browser, engine, *size)
            finally:
                browser.close()

SatNav Convergence Browser

A Python command-line tool in the tools folder of GridAtlas that checks asset actions (`check_asset_actions`) and opens walk panel (`open_walk_panel`) (units: kV), covering 11kV and substations.

rendergridatlas / tools/satnav/convergence-browser.py · lines 1–219 of 219 · Entry point

What it does
It lists and searches 11kV and substations. Defines check_asset_actions, walk_diagnostic, open_walk_panel, check. Uses libraries os, json, pathlib, runpy, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work. Domain terms in the code: 11kV, substations.
Inputs & outputs
Voltage levels named: 11kV.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the walk diagnostic helper (`walk_diagnostic`) and the check step (`check`). Combined regional/SatNav browser acceptance; uses the existing GPS boundary spy.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gridatlas · tools/satnav · Python CLI
Uses
os, json, pathlib, runpy, playwright.sync_api, traceback
Used by
none found
Produces
check_asset_actions, walk_diagnostic, open_walk_panel, check
Defines here
check_asset_actions, walk_diagnostic, open_walk_panel, check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/convergence-browser.py:1-219 · blob 58f7500d43f9453446072c3b2d6a91f0e32829c4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Combined regional/SatNav browser acceptance; uses the existing GPS boundary spy."""
import os
import json
from pathlib import Path
from runpy import run_path
from playwright.sync_api import expect, sync_playwright

compact = run_path(str(Path(__file__).resolve().parent / 'compact-browser.py'))
SITE = os.environ.get('WALK_TEST_URL', 'http://127.0.0.1:8873/atlas/v/satnav-convergence-ci/')
READY = """() => {
 const s=document.querySelector('#satnav-compact')?.satnavSurvey;
 return s?.getMap()?.getLayer('l-ukpn_secondary') && s.getMap().getLayer('l-11kv')
 && !document.querySelector('#satnav-ukpn').disabled && !document.querySelector('#satnav-osm11').disabled;
}"""
LINE = """() => {
 const m=window.__GRIDATLAS_V9_MAP__, id='gridatlas-satnav-waypoints-line';
 const layer=m?.getLayer(id), order=m?.getStyle().layers.map(l=>l.id) || [];
 const data=m?.getSource('gridatlas-satnav-waypoints')?.serialize().data;
 return !!layer && m.getLayoutProperty(id,'visibility')!=='none'
 && data?.features?.some(f=>f.properties.role==='selected-section')
 && order.indexOf(id)>order.indexOf('l-ukpn_secondary')
 && order.indexOf(id)>order.indexOf('l-11kv');
}"""

def check_asset_actions(page):
    # UKPN OFF evicts its source. Re-enable is asynchronous; await a real
    # point before selecting it. A missing point remains a test failure.
    page.wait_for_function("""() => {
      const m=window.__GRIDATLAS_V9_MAP__, d=window.__GRIDATLAS_UKPN_DATA__;
      return d?.viewportQueries>0 && m.getSource('src-ukpn_secondary')
        ?.serialize().data?.features?.some(f=>f.geometry?.type==='Point');
    }""",timeout=120000)
    # Actual UKPN source and Grid Engine; GPS is the sole simulated sensor.
    page.evaluate("""() => {
      const m=window.__GRIDATLAS_V9_MAP__;
      const first=m.getSource('src-ukpn_secondary').serialize().data.features[0];
      m.jumpTo({center:first.geometry.coordinates,zoom:16.1});
      // Centre can be obscured by the compact SatNav controls on mobile.
      // Move the real point into an exposed canvas area, without hiding UI.
      const c=m.getCanvas(),r=c.getBoundingClientRect(),p=m.project(first.geometry.coordinates);
      const free=[];
      for(const fx of [.8,.7,.9,.6,.5])for(const fy of [.5,.65,.35,.8,.2]){
        const x=r.width*fx,y=r.height*fy;
        if(document.elementFromPoint(r.left+x,r.top+y)===c)free.push({x,y});
      }
      if(!free.length)throw Error('No exposed map canvas for UKPN selection');
      m.panBy([p.x-free[0].x,p.y-free[0].y],{duration:0});
    }""")
    # Do not pre-enable Grid Engine data: the real button must acquire it.
    print('UKPN selection geometry:',page.evaluate("""() => {const m=window.__GRIDATLAS_V9_MAP__,c=m.getCanvas(),r=c.getBoundingClientRect();return {zoom:m.getZoom(),center:m.getCenter().toArray(),canvas:[r.x,r.y,r.width,r.height],visibility:m.getLayoutProperty('l-ukpn_secondary','visibility'),source:m.getSource('src-ukpn_secondary').serialize().data.features.length};}"""),flush=True)
    hit=page.wait_for_function("""() => {
      const m=window.__GRIDATLAS_V9_MAP__,c=m.getCanvas(),r=c.getBoundingClientRect();
      if(m.isMoving())return false;
      for(const f of m.queryRenderedFeatures({layers:['l-ukpn_secondary']})){
        const p=m.project(f.geometry.coordinates),x=r.left+p.x,y=r.top+p.y;
        if(x<8||y<8||x>innerWidth-8||y>innerHeight-8||document.elementFromPoint(x,y)!==c)continue;
        if(m.queryRenderedFeatures(p,{layers:['l-ukpn_secondary']})[0]?.properties?.name!==f.properties.name)continue;
        return {x,y,site:f.properties.name,origin:f.geometry.coordinates};
      }
      return false;
    }""",timeout=60000).json_value()
    # Verify the rendered feature is an actual native source row before
    # opening its card; subsequent movement may evict that viewport.
    assert page.evaluate("""hit=>{
      const m=window.__GRIDATLAS_V9_MAP__;
      return m.getSource('src-ukpn_secondary').serialize().data.features
        .some(f=>String(f.id)===hit.site &&
          JSON.stringify(f.geometry.coordinates)===JSON.stringify(hit.origin));
    }""",hit)
    page.mouse.click(hit['x'],hit['y'])
    card=page.locator('[data-ukpn-detail][data-site]')
    expect(card).to_have_attribute('data-site',hit['site'],timeout=15000)
    actions=card.locator('[data-satnav-asset-actions]')
    engine=actions.get_by_role('button',name='Ventus Grid Engine',exact=True)
    expect(engine).to_be_visible(timeout=15000)
    engine.click()
    picks=actions.get_by_role('button',name='Use this destination',exact=True)
    expect(picks.first).to_be_visible(timeout=90000)
    target=page.evaluate("""origin => {
      const e=window.__GRIDATLAS_NEON_LINKS__;
      const distance=typeof e.measure?.distanceKm==='function' ? (...args)=>e.measure.distanceKm(...args) : (...args)=>globalThis.VentusGridCompute.distanceKm(...args);
      return e.substations.filter(n=>n.at?.length===2 && n.at.every(Number.isFinite) && n.kv?.some?.(v=>Number.isFinite(v)&&v>=33))
        .map(n=>({name:String(n.name||'Unnamed mapped substation'),at:n.at,km:distance(...origin,...n.at)}))
        .filter(n=>Number.isFinite(n.km)&&n.km>0).sort((a,b)=>a.km-b.km||a.name.localeCompare(b.name))[0];
    }""",hit['origin'])
    assert target and target['km']>0
    expect(picks.first.locator('..')).to_contain_text(target['name'])
    get_plan="document.querySelector('#satnav-compact').satnavSurvey.getEndpoints()"
    previous=page.evaluate(get_plan)
    # Real destination; simulated pedestrian position approximately 111 m away.
    near=[target['at'][0],target['at'][1]+.001]
    page.evaluate("at=>window.__lineGpsTest.emit(at,75)",near)
    picks.first.click()
    assert page.evaluate(get_plan)==previous
    assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[]}
    page.evaluate("at=>window.__lineGpsTest.emit(at,4)",near)
    picks.first.click()
    page.wait_for_function("""at=>JSON.stringify(document.querySelector('#satnav-compact').satnavSurvey.getEndpoints())===JSON.stringify(at)""",
                           arg=[near,target['at']],timeout=15000)
    page.wait_for_function(LINE,timeout=15000)
    assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[]}
    assert page.evaluate("document.querySelector('#satnav-compact').satnavSurvey.isTracking()")
    actions.get_by_role('button',name='Vicinity',exact=True).click()
    vicinity=page.get_by_role('group',name='Selected vicinity asset')
    expect(vicinity).to_contain_text('UKPN secondary',timeout=60000)
    expect(vicinity).to_contain_text(hit['site'])
    assert page.evaluate(get_plan)==[near,target['at']]
    assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[]}
    page.wait_for_function(LINE,timeout=15000)
    print('Real UKPN card, Grid Engine destination transfer and secondary Vicinity: PASS',flush=True)


def walk_diagnostic(page, engine, viewport):
    return {"engine":engine,"viewport":viewport,"state":page.evaluate("""() => {
      const ids=['satnav-compact','satnav-toggle','satnav-walk-start','satnav-walk-stop','satnav-infrastructure'];
      const elements=Object.fromEntries(ids.map(id=>{const e=document.getElementById(id);
        return [id,e?{hidden:e.hidden,display:getComputedStyle(e).display,rect:e.getBoundingClientRect().toJSON(),
          expanded:e.getAttribute('aria-expanded'),disabled:!!e.disabled}:null]}));
      const s=document.querySelector('#satnav-compact')?.satnavSurvey;
      return {elements,endpoints:s?.getEndpoints(),tracking:s?.isTracking(),gps:window.__lineGpsTest?.records};
    }""")}

def open_walk_panel(page):
    panel=page.locator('#satnav-compact')
    toggle=page.locator('#satnav-toggle')
    if not panel.is_visible():
        expect(toggle).to_be_visible()
        toggle.click()
    expect(panel).to_be_visible()
    expect(toggle).to_have_attribute('aria-expanded','true')

def check(browser, engine, viewport):
    with browser.new_context(viewport=viewport, is_mobile=True, has_touch=True) as ctx:
        ctx.add_init_script(compact['GPS_SPY'])
        page=ctx.new_page()
        page.goto(SITE,wait_until='domcontentloaded',timeout=90000)
        page.wait_for_function(READY,timeout=120000)
        page.evaluate("""() => {
          const s=document.querySelector('#satnav-compact').satnavSurvey;
          // Same pinned real UKPN coverage exercised by g203-viewport-browser.py.
          s.getMap().jumpTo({center:[0.1,51.5],zoom:13});
          s.replacePlan([[0.1,51.5],[0.1,51.505]]);
        }""")
        print('Before opening walking controls:',json.dumps(walk_diagnostic(page,engine,viewport)),flush=True)
        open_walk_panel(page)
        page.locator('#satnav-walk-mode').select_option('direct')
        start=page.locator('#satnav-walk-start')
        expect(start).to_be_visible()
        expect(start).to_be_enabled()
        print('Before Start Walk:',json.dumps(walk_diagnostic(page,engine,viewport)),flush=True)
        start.tap()
        page.evaluate("window.__lineGpsTest.emit([0.1,51.5005],4)")
        guidance=page.locator('#satnav-walk-guidance')
        expect(guidance).to_contain_text('Direct to pin',timeout=15000)
        page.wait_for_function(LINE,timeout=15000)
        before=guidance.inner_text()
        # GPS may have followed at street zoom. Establish the known real
        # acquisition viewport while retaining the active walk and line.
        page.evaluate("()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[0.1,51.5],zoom:13})")
        page.locator('#satnav-infrastructure summary').tap()
        for key, native in [('ukpn','ukpn_secondary'),('osm11','11kv')]:
            control=page.locator('#satnav-'+key)
            checkbox=page.locator('#scada-ui-container input[data-layer-id="'+native+'"]')
            if checkbox.is_checked():
                control.tap()
            control.tap()
            expect(control).to_have_attribute('aria-pressed','true')
            assert checkbox.is_checked()
            print('Awaiting native layer:',native,page.evaluate("""() => {
              const m=window.__GRIDATLAS_V9_MAP__;
              return {center:m.getCenter().toArray(),zoom:m.getZoom(),
                ukpn:window.__GRIDATLAS_UKPN_DATA__};
            }"""),flush=True)
            page.wait_for_function("""id => window.__GRIDATLAS_V9_MAP__.getSource('src-'+id)
                ?.serialize().data?.features?.length>0""",arg=native,timeout=120000)
            page.wait_for_function(LINE,timeout=15000)
            assert page.evaluate('window.__lineGpsTest.records') == {'starts':[1],'stops':[]}
            assert page.evaluate("document.querySelector('#satnav-compact').satnavSurvey.isTracking()")
            page.evaluate("window.__lineGpsTest.emit([0.1,51.501],4)")
            expect(guidance).to_contain_text('Direct to pin')
        expect(guidance).not_to_have_text(before)
        for key,native in [('osm11','11kv'),('ukpn','ukpn_secondary')]:
            page.locator('#satnav-'+key).tap()
            assert not page.locator('#scada-ui-container input[data-layer-id="'+native+'"]').is_checked()
            page.wait_for_function(LINE,timeout=15000)
        # Confirm eviction before requesting a fresh viewport; no stale
        # feature can satisfy the subsequent real-asset selection.
        page.wait_for_function("""()=>window.__GRIDATLAS_V9_MAP__
          .getSource('src-ukpn_secondary').serialize().data.features.length===0""",timeout=30000)
        page.evaluate("()=>window.__GRIDATLAS_V9_MAP__.jumpTo({center:[0.1,51.5],zoom:13})")
        page.locator('#satnav-ukpn').tap()
        expect(page.locator('#satnav-ukpn')).to_have_attribute('aria-pressed','true')
        page.locator('#satnav-infrastructure summary').tap()
        check_asset_actions(page)
        open_walk_panel(page)
        stop=page.locator('#satnav-walk-stop')
        expect(stop).to_be_visible()
        stop.tap()
        assert page.evaluate('window.__lineGpsTest.records') == {'starts':[1],'stops':[1]}
        print(f'{engine} {viewport}: combined candidate, native layer hydration, protected direct line and one GPS watch PASS',flush=True)

if __name__=='__main__':
    failures=[]
    with sync_playwright() as p:
        for name in os.environ.get('LINE_TEST_BROWSERS','chromium,webkit').split(','):
            options={'args':['--use-gl=angle','--use-angle=swiftshader','--enable-webgl','--enable-unsafe-swiftshader']} if name=='chromium' else {}
            browser=getattr(p,name).launch(**options)
            try:
                for viewport in [{'width':393,'height':852},{'width':852,'height':393}]:
                    try:
                        check(browser,name,viewport)
                    except Exception as exc:
                        failures.append((name,viewport,str(exc)))
                        import traceback
                        traceback.print_exc()
                        print('FAIL',failures[-1],flush=True)
            finally:
                browser.close()
    assert not failures, failures