lightfall 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lightfall/__init__.py +8 -0
- lightfall/__main__.py +10 -0
- lightfall/_version.py +24 -0
- lightfall/acquire/__init__.py +74 -0
- lightfall/acquire/buffer.py +363 -0
- lightfall/acquire/device_wrapper.py +416 -0
- lightfall/acquire/engine/__init__.py +155 -0
- lightfall/acquire/engine/base.py +587 -0
- lightfall/acquire/engine/bluesky.py +358 -0
- lightfall/acquire/engine/mock.py +165 -0
- lightfall/acquire/engine/plugins/__init__.py +9 -0
- lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
- lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
- lightfall/acquire/engine/protocol.py +145 -0
- lightfall/acquire/engine/registry.py +152 -0
- lightfall/acquire/engine/state.py +32 -0
- lightfall/acquire/engine/waiting_hook.py +225 -0
- lightfall/acquire/nats_bridge.py +62 -0
- lightfall/acquire/plan_ui.py +78 -0
- lightfall/acquire/plans/__init__.py +38 -0
- lightfall/acquire/plans/adaptive.py +288 -0
- lightfall/acquire/plans/example_plans.py +995 -0
- lightfall/acquire/plans/lightfall_plans.py +587 -0
- lightfall/acquire/plans/registry.py +543 -0
- lightfall/acquire/plans/standard_plans.py +186 -0
- lightfall/acquire/plans/user_plans.py +470 -0
- lightfall/acquire/runengine.py +36 -0
- lightfall/acquire/signals.py +452 -0
- lightfall/acquire/triggers/__init__.py +16 -0
- lightfall/acquire/triggers/base.py +25 -0
- lightfall/acquire/triggers/filter.py +37 -0
- lightfall/acquire/triggers/manager.py +73 -0
- lightfall/acquire/triggers/manual.py +36 -0
- lightfall/acquire/triggers/run_end.py +74 -0
- lightfall/acquire/triggers/run_start.py +52 -0
- lightfall/auth/__init__.py +38 -0
- lightfall/auth/policy.py +518 -0
- lightfall/auth/providers/__init__.py +30 -0
- lightfall/auth/providers/base.py +124 -0
- lightfall/auth/providers/keycloak.py +1017 -0
- lightfall/auth/providers/local.py +319 -0
- lightfall/auth/providers/pam.py +250 -0
- lightfall/auth/service_key.py +173 -0
- lightfall/auth/service_key_auth.py +79 -0
- lightfall/auth/session.py +656 -0
- lightfall/claude/__init__.py +52 -0
- lightfall/claude/_internal/__init__.py +1 -0
- lightfall/claude/_internal/serialization.py +195 -0
- lightfall/claude/_internal/threading.py +61 -0
- lightfall/claude/_internal/worker.py +757 -0
- lightfall/claude/_session_assembly.py +124 -0
- lightfall/claude/agent.py +596 -0
- lightfall/claude/lightfall_core_tools.py +410 -0
- lightfall/claude/markdown.py +103 -0
- lightfall/claude/permission_manager.py +588 -0
- lightfall/claude/tools/__init__.py +45 -0
- lightfall/claude/tools/controller.py +143 -0
- lightfall/claude/tools/interaction.py +177 -0
- lightfall/claude/tools/introspection.py +127 -0
- lightfall/claude/tools/logs.py +155 -0
- lightfall/claude/tools/screenshot.py +87 -0
- lightfall/claude/widget.py +851 -0
- lightfall/claude/widgets/__init__.py +5 -0
- lightfall/claude/widgets/permission_request.py +282 -0
- lightfall/claude/widgets/question_request.py +227 -0
- lightfall/claude/widgets/task_card.py +223 -0
- lightfall/config/__init__.py +23 -0
- lightfall/config/layers.py +317 -0
- lightfall/config/manager.py +244 -0
- lightfall/config/schema.py +154 -0
- lightfall/core/__init__.py +23 -0
- lightfall/core/application.py +727 -0
- lightfall/core/services.py +235 -0
- lightfall/devices/__init__.py +53 -0
- lightfall/devices/backends/__init__.py +17 -0
- lightfall/devices/backends/bcs.py +448 -0
- lightfall/devices/backends/happi.py +986 -0
- lightfall/devices/backends/mock.py +646 -0
- lightfall/devices/base.py +338 -0
- lightfall/devices/catalog.py +1039 -0
- lightfall/devices/connection_manager.py +676 -0
- lightfall/devices/model.py +290 -0
- lightfall/devices/monitoring.py +442 -0
- lightfall/devices/sim/__init__.py +26 -0
- lightfall/devices/sim/areadetector.py +436 -0
- lightfall/devices/sim/generators.py +223 -0
- lightfall/devices/sim/plugins.py +116 -0
- lightfall/epics/__init__.py +28 -0
- lightfall/epics/ca/__init__.py +10 -0
- lightfall/epics/ca/context.py +100 -0
- lightfall/epics/ca/pv.py +303 -0
- lightfall/epics/widgets/__init__.py +49 -0
- lightfall/epics/widgets/areadetector/__init__.py +16 -0
- lightfall/epics/widgets/areadetector/areadetector.py +281 -0
- lightfall/epics/widgets/areadetector/controls.py +478 -0
- lightfall/epics/widgets/areadetector/image_view.py +447 -0
- lightfall/epics/widgets/auto.py +319 -0
- lightfall/epics/widgets/base.py +404 -0
- lightfall/epics/widgets/checkbox.py +239 -0
- lightfall/epics/widgets/combobox.py +202 -0
- lightfall/epics/widgets/label.py +176 -0
- lightfall/epics/widgets/lineedit.py +253 -0
- lightfall/epics/widgets/motor.py +694 -0
- lightfall/epics/widgets/ophyd_base.py +469 -0
- lightfall/epics/widgets/ophyd_combobox.py +86 -0
- lightfall/epics/widgets/ophyd_label.py +54 -0
- lightfall/epics/widgets/ophyd_lineedit.py +170 -0
- lightfall/epics/widgets/ophyd_spinbox.py +79 -0
- lightfall/epics/widgets/slider.py +272 -0
- lightfall/epics/widgets/status_indicator.py +98 -0
- lightfall/epics/widgets/style.py +188 -0
- lightfall/exporter/__init__.py +1 -0
- lightfall/exporter/cli.py +67 -0
- lightfall/exporter/converters/__init__.py +26 -0
- lightfall/exporter/converters/base.py +39 -0
- lightfall/exporter/converters/noop.py +39 -0
- lightfall/exporter/converters/nxsas.py +73 -0
- lightfall/exporter/service.py +200 -0
- lightfall/exporter/tiled_utils.py +92 -0
- lightfall/ipc/__init__.py +6 -0
- lightfall/ipc/service.py +701 -0
- lightfall/ipc/trust.py +144 -0
- lightfall/logbook/__init__.py +46 -0
- lightfall/logbook/action_dialog.py +207 -0
- lightfall/logbook/action_logger.py +432 -0
- lightfall/logbook/block_mapper.py +562 -0
- lightfall/logbook/client.py +799 -0
- lightfall/logbook/converter.py +273 -0
- lightfall/logbook/editors/__init__.py +19 -0
- lightfall/logbook/editors/highlighter.py +305 -0
- lightfall/logbook/editors/markdown_editor.py +319 -0
- lightfall/logbook/editors/richtext_editor.py +1397 -0
- lightfall/logbook/entry_widget.py +1065 -0
- lightfall/logbook/event_listener.py +221 -0
- lightfall/logbook/fragment_widgets.py +925 -0
- lightfall/logbook/position_mapper.py +320 -0
- lightfall/logbook/protection.py +402 -0
- lightfall/logbook/style.py +394 -0
- lightfall/logbook/url.py +29 -0
- lightfall/logbook/visual_protection.py +330 -0
- lightfall/logbook/widget.py +680 -0
- lightfall/main.py +1091 -0
- lightfall/pipelines/__init__.py +4 -0
- lightfall/pipelines/client.py +148 -0
- lightfall/plugins/__init__.py +119 -0
- lightfall/plugins/agent_plugin.py +106 -0
- lightfall/plugins/agents/__init__.py +10 -0
- lightfall/plugins/agents/_mcp_helpers.py +52 -0
- lightfall/plugins/agents/alignment.py +94 -0
- lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
- lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
- lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
- lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
- lightfall/plugins/agents/current_esaf.py +435 -0
- lightfall/plugins/agents/device_tools.py +1043 -0
- lightfall/plugins/agents/engine_tools.py +720 -0
- lightfall/plugins/agents/ipython_tools.py +444 -0
- lightfall/plugins/agents/panel_builder.py +637 -0
- lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
- lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
- lightfall/plugins/agents/panel_design.py +94 -0
- lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
- lightfall/plugins/agents/plan_design.py +90 -0
- lightfall/plugins/agents/plan_tools.py +878 -0
- lightfall/plugins/agents/scan_planning.py +101 -0
- lightfall/plugins/builtin_manifest.py +348 -0
- lightfall/plugins/controller_plugin.py +162 -0
- lightfall/plugins/engine_plugin.py +124 -0
- lightfall/plugins/errors.py +104 -0
- lightfall/plugins/info.py +112 -0
- lightfall/plugins/loader.py +878 -0
- lightfall/plugins/manifest.py +150 -0
- lightfall/plugins/panel_plugin.py +119 -0
- lightfall/plugins/plan_plugin.py +163 -0
- lightfall/plugins/registry.py +309 -0
- lightfall/plugins/settings_plugin.py +226 -0
- lightfall/plugins/statusbar_plugin.py +289 -0
- lightfall/plugins/theme_plugin.py +165 -0
- lightfall/plugins/types.py +136 -0
- lightfall/plugins/user_plugins.py +764 -0
- lightfall/project/__init__.py +37 -0
- lightfall/project/model.py +375 -0
- lightfall/project/service.py +427 -0
- lightfall/project/welcome.py +106 -0
- lightfall/resources/__init__.py +126 -0
- lightfall/resources/images/__init__.py +1 -0
- lightfall/resources/images/icon.ico +0 -0
- lightfall/resources/images/icon.png +0 -0
- lightfall/resources/images/logo.png +0 -0
- lightfall/services/__init__.py +33 -0
- lightfall/services/_alshub_client.py +73 -0
- lightfall/services/access_stamper.py +240 -0
- lightfall/services/als_beam_status.py +347 -0
- lightfall/services/ca_tunnel.py +325 -0
- lightfall/services/threaded_tiled_writer.py +174 -0
- lightfall/services/tiled_auth.py +21 -0
- lightfall/services/tiled_service.py +971 -0
- lightfall/services/tiled_writer_patch.py +301 -0
- lightfall/settings/__init__.py +1 -0
- lightfall/settings/image_helpers.py +30 -0
- lightfall/settings/user_settings_client.py +232 -0
- lightfall/ui/__init__.py +28 -0
- lightfall/ui/annotations.py +208 -0
- lightfall/ui/common/__init__.py +7 -0
- lightfall/ui/dialogs/__init__.py +26 -0
- lightfall/ui/dialogs/about_dialog.py +131 -0
- lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
- lightfall/ui/dialogs/base.py +44 -0
- lightfall/ui/dialogs/bug_report_dialog.py +353 -0
- lightfall/ui/dialogs/create_plan_dialog.py +189 -0
- lightfall/ui/dialogs/device_edit_dialog.py +183 -0
- lightfall/ui/dialogs/export_dialog.py +565 -0
- lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
- lightfall/ui/dialogs/login_dialog.py +756 -0
- lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
- lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
- lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
- lightfall/ui/docking/__init__.py +22 -0
- lightfall/ui/docking/icon_sidebar.py +806 -0
- lightfall/ui/docking/manager.py +682 -0
- lightfall/ui/docking/state.py +113 -0
- lightfall/ui/docking/theme.py +399 -0
- lightfall/ui/docking/widget.py +214 -0
- lightfall/ui/events.py +75 -0
- lightfall/ui/mainwindow.py +1006 -0
- lightfall/ui/models/__init__.py +49 -0
- lightfall/ui/models/device_selection.py +389 -0
- lightfall/ui/models/device_tree.py +1095 -0
- lightfall/ui/models/thread_model.py +667 -0
- lightfall/ui/models/tiled_model.py +384 -0
- lightfall/ui/panels/__init__.py +28 -0
- lightfall/ui/panels/base.py +525 -0
- lightfall/ui/panels/bluesky_panel.py +619 -0
- lightfall/ui/panels/claude/__init__.py +9 -0
- lightfall/ui/panels/claude/agent_registry.py +168 -0
- lightfall/ui/panels/claude_panel.py +887 -0
- lightfall/ui/panels/device_panel.py +370 -0
- lightfall/ui/panels/documents_panel.py +166 -0
- lightfall/ui/panels/ipython_panel.py +580 -0
- lightfall/ui/panels/logbook_entries_panel.py +84 -0
- lightfall/ui/panels/logbook_panel.py +627 -0
- lightfall/ui/panels/logging_panel.py +587 -0
- lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
- lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
- lightfall/ui/panels/plugins/__init__.py +34 -0
- lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
- lightfall/ui/panels/plugins/claude_plugin.py +29 -0
- lightfall/ui/panels/plugins/device_plugin.py +27 -0
- lightfall/ui/panels/plugins/documents_plugin.py +26 -0
- lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
- lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
- lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
- lightfall/ui/panels/plugins/logging_plugin.py +27 -0
- lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
- lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
- lightfall/ui/panels/plugins/queue_plugin.py +29 -0
- lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
- lightfall/ui/panels/plugins/threads_plugin.py +27 -0
- lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
- lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
- lightfall/ui/panels/queue.py +754 -0
- lightfall/ui/panels/registry.py +483 -0
- lightfall/ui/panels/synoptic/__init__.py +27 -0
- lightfall/ui/panels/synoptic/editors.py +481 -0
- lightfall/ui/panels/synoptic/items.py +556 -0
- lightfall/ui/panels/synoptic/models.py +336 -0
- lightfall/ui/panels/synoptic/panel.py +889 -0
- lightfall/ui/panels/synoptic/serialization.py +300 -0
- lightfall/ui/panels/synoptic/view.py +504 -0
- lightfall/ui/panels/threads_panel.py +621 -0
- lightfall/ui/panels/tiled_browser_panel.py +854 -0
- lightfall/ui/panels/visualization_panel.py +508 -0
- lightfall/ui/preferences/__init__.py +24 -0
- lightfall/ui/preferences/backend.py +148 -0
- lightfall/ui/preferences/builtin.py +220 -0
- lightfall/ui/preferences/claude_settings.py +762 -0
- lightfall/ui/preferences/device_settings.py +461 -0
- lightfall/ui/preferences/dialog.py +234 -0
- lightfall/ui/preferences/editor_settings.py +227 -0
- lightfall/ui/preferences/ipc_settings.py +226 -0
- lightfall/ui/preferences/logbook_settings.py +232 -0
- lightfall/ui/preferences/login_settings.py +183 -0
- lightfall/ui/preferences/manager.py +562 -0
- lightfall/ui/preferences/plugin_settings.py +392 -0
- lightfall/ui/preferences/proxy_settings.py +561 -0
- lightfall/ui/preferences/skill_settings.py +28 -0
- lightfall/ui/preferences/tiled_settings.py +469 -0
- lightfall/ui/preferences/tool_settings.py +393 -0
- lightfall/ui/preferences/user_portable_backend.py +131 -0
- lightfall/ui/preferences/user_profile_settings.py +316 -0
- lightfall/ui/preferences/visualization_settings.py +159 -0
- lightfall/ui/resources/__init__.py +1 -0
- lightfall/ui/resources/logo.png +0 -0
- lightfall/ui/statusbar/__init__.py +11 -0
- lightfall/ui/statusbar/manager.py +379 -0
- lightfall/ui/statusbar/plugins/__init__.py +28 -0
- lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
- lightfall/ui/statusbar/plugins/auth_status.py +116 -0
- lightfall/ui/statusbar/plugins/connection_status.py +100 -0
- lightfall/ui/statusbar/plugins/thread_status.py +556 -0
- lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
- lightfall/ui/statusbar/plugins/user_status.py +84 -0
- lightfall/ui/theater/__init__.py +28 -0
- lightfall/ui/theater/manager.py +124 -0
- lightfall/ui/theater/overlay.py +279 -0
- lightfall/ui/theater/proxy.py +111 -0
- lightfall/ui/theme/__init__.py +18 -0
- lightfall/ui/theme/builtin.py +1015 -0
- lightfall/ui/theme/manager.py +875 -0
- lightfall/ui/theme/registry.py +195 -0
- lightfall/ui/toast.py +221 -0
- lightfall/ui/tutorial.py +1100 -0
- lightfall/ui/widgets/__init__.py +110 -0
- lightfall/ui/widgets/base_control.py +259 -0
- lightfall/ui/widgets/camera/__init__.py +36 -0
- lightfall/ui/widgets/camera/base.py +815 -0
- lightfall/ui/widgets/camera/dark_frames.py +213 -0
- lightfall/ui/widgets/camera/image_view.py +649 -0
- lightfall/ui/widgets/camera/panels/__init__.py +14 -0
- lightfall/ui/widgets/camera/panels/cooler.py +320 -0
- lightfall/ui/widgets/camera/panels/temperature.py +192 -0
- lightfall/ui/widgets/camera/plan_based.py +202 -0
- lightfall/ui/widgets/compact_motor.py +522 -0
- lightfall/ui/widgets/controller_matcher.py +278 -0
- lightfall/ui/widgets/controller_registry.py +144 -0
- lightfall/ui/widgets/device_control.py +411 -0
- lightfall/ui/widgets/device_selector.py +438 -0
- lightfall/ui/widgets/device_tree_tab.py +461 -0
- lightfall/ui/widgets/document_stream.py +1028 -0
- lightfall/ui/widgets/favorites_tab.py +191 -0
- lightfall/ui/widgets/motor_control.py +1120 -0
- lightfall/ui/widgets/observers/__init__.py +8 -0
- lightfall/ui/widgets/observers/camera.py +48 -0
- lightfall/ui/widgets/observers/image_view.py +130 -0
- lightfall/ui/widgets/plan_config.py +954 -0
- lightfall/ui/widgets/plan_edit_dialog.py +294 -0
- lightfall/ui/widgets/plan_selector.py +452 -0
- lightfall/ui/widgets/profile_avatar.py +128 -0
- lightfall/ui/widgets/queue_view.py +647 -0
- lightfall/ui/widgets/runengine_control.py +549 -0
- lightfall/ui/widgets/signal_control.py +793 -0
- lightfall/ui/widgets/skill_trigger_button.py +183 -0
- lightfall/ui/widgets/tiled_filter_widget.py +314 -0
- lightfall/ui/widgets/tiled_status.py +149 -0
- lightfall/ui/widgets/warning_banner.py +185 -0
- lightfall/utils/__init__.py +53 -0
- lightfall/utils/crash_diagnostics.py +454 -0
- lightfall/utils/data_migration.py +22 -0
- lightfall/utils/editor_launcher.py +594 -0
- lightfall/utils/error_collector.py +245 -0
- lightfall/utils/git_tracker.py +197 -0
- lightfall/utils/log_buffer.py +233 -0
- lightfall/utils/logging.py +229 -0
- lightfall/utils/module_resolver.py +70 -0
- lightfall/utils/sentry.py +722 -0
- lightfall/utils/threads.py +991 -0
- lightfall/utils/tiled_helpers.py +96 -0
- lightfall/visualization/__init__.py +50 -0
- lightfall/visualization/base.py +5 -0
- lightfall/visualization/base_visualization.py +74 -0
- lightfall/visualization/fitting/__init__.py +24 -0
- lightfall/visualization/fitting/base.py +267 -0
- lightfall/visualization/fitting/fitters.py +325 -0
- lightfall/visualization/fitting/panel.py +265 -0
- lightfall/visualization/memory.py +392 -0
- lightfall/visualization/motor_mixin.py +524 -0
- lightfall/visualization/pg.py +156 -0
- lightfall/visualization/registry.py +144 -0
- lightfall/visualization/spec.py +79 -0
- lightfall/visualization/theme.py +266 -0
- lightfall/visualization/widgets/__init__.py +28 -0
- lightfall/visualization/widgets/adaptive/__init__.py +1 -0
- lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
- lightfall/visualization/widgets/adaptive/plot.py +233 -0
- lightfall/visualization/widgets/heatmap.py +264 -0
- lightfall/visualization/widgets/image_stack.py +316 -0
- lightfall/visualization/widgets/image_view_toolbar.py +227 -0
- lightfall/visualization/widgets/lazy_image_view.py +590 -0
- lightfall/visualization/widgets/plot_1d.py +262 -0
- lightfall/visualization/widgets/scatter.py +247 -0
- lightfall/visualization/widgets/table.py +221 -0
- lightfall/visualization/widgets/time_axis.py +93 -0
- lightfall-0.1.1.dist-info/METADATA +223 -0
- lightfall-0.1.1.dist-info/RECORD +388 -0
- lightfall-0.1.1.dist-info/WHEEL +4 -0
- lightfall-0.1.1.dist-info/entry_points.txt +6 -0
- lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
- lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Tiny async client for ALS hub API.
|
|
2
|
+
|
|
3
|
+
Used at write time to look up the active ESAF for a beamline. The
|
|
4
|
+
``/beamlines/{bl}/active-esaf`` route on alshub-api is public (no API
|
|
5
|
+
key required), so this client only needs the base URL and an optional
|
|
6
|
+
proxy.
|
|
7
|
+
|
|
8
|
+
The proxy hook exists for development setups where the Lightfall host is
|
|
9
|
+
off the LBL network and reaches ``*.lbl.gov`` through a SOCKS proxy
|
|
10
|
+
(typically ``socks5h://localhost:1080``). Beamline workstations inside
|
|
11
|
+
the LBL network leave it empty — direct access works.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AlshubClient:
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
base_url: str,
|
|
26
|
+
api_key: str | None = None,
|
|
27
|
+
timeout: float = 5.0,
|
|
28
|
+
proxy: str | None = None,
|
|
29
|
+
):
|
|
30
|
+
self.base_url = base_url.rstrip("/")
|
|
31
|
+
self.api_key = api_key
|
|
32
|
+
self._timeout = timeout
|
|
33
|
+
self._proxy = proxy or None
|
|
34
|
+
|
|
35
|
+
async def get_active_esaf(self, beamline: str) -> dict | None:
|
|
36
|
+
"""Return active-esaf payload, or None on 404. Raises on network errors.
|
|
37
|
+
|
|
38
|
+
Distinguishing "no schedule" (404) from "alshub down" (raise) lets
|
|
39
|
+
the caller (AccessStamper) flag the run as ``esaf_source="pending"``
|
|
40
|
+
when the lookup actually failed, vs ``esaf_source="none"`` when
|
|
41
|
+
there was just nothing scheduled.
|
|
42
|
+
"""
|
|
43
|
+
params = {}
|
|
44
|
+
if self.api_key:
|
|
45
|
+
params["api-key"] = self.api_key
|
|
46
|
+
|
|
47
|
+
client_kwargs = {"timeout": self._timeout}
|
|
48
|
+
if self._proxy:
|
|
49
|
+
# httpx supports socks5/socks5h via the `socksio` package.
|
|
50
|
+
client_kwargs["proxy"] = self._proxy
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
async with httpx.AsyncClient(**client_kwargs) as client:
|
|
54
|
+
resp = await client.get(
|
|
55
|
+
f"{self.base_url}/beamlines/{beamline}/active-esaf",
|
|
56
|
+
params=params,
|
|
57
|
+
)
|
|
58
|
+
if resp.status_code == 404:
|
|
59
|
+
return None
|
|
60
|
+
resp.raise_for_status()
|
|
61
|
+
return resp.json()
|
|
62
|
+
except httpx.HTTPStatusError:
|
|
63
|
+
return None
|
|
64
|
+
except (httpx.NetworkError, httpx.TimeoutException) as e:
|
|
65
|
+
# Some httpx exceptions stringify empty; log the class name too.
|
|
66
|
+
logger.warning(
|
|
67
|
+
"alshub get_active_esaf(%s) failed: %s: %s (proxy=%r)",
|
|
68
|
+
beamline,
|
|
69
|
+
type(e).__name__,
|
|
70
|
+
str(e) or "(no message)",
|
|
71
|
+
self._proxy,
|
|
72
|
+
)
|
|
73
|
+
raise
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""Build access_blob metadata for Tiled writes.
|
|
2
|
+
|
|
3
|
+
The stamper reads the operator's identity from SessionManager, the
|
|
4
|
+
active ESAF either from a SettingsPlugin admin override or from
|
|
5
|
+
alshub-api, and produces the blob shape expected by als-tiled's
|
|
6
|
+
ALSAccessPolicy. See docs/superpowers/specs/2026-04-26-als-tiled-per-
|
|
7
|
+
entry-authorization-design.md (in the als-tiled repo) for the spec.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from lightfall.services._alshub_client import AlshubClient
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class MissingSessionError(RuntimeError):
|
|
22
|
+
"""Raised when no Keycloak session is available — write must be aborted."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _now_iso() -> str:
|
|
26
|
+
return datetime.now(UTC).isoformat()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def compute_access_tags(blob: dict[str, Any]) -> list[str]:
|
|
30
|
+
"""Project the human-readable access blob into the flat tag list that
|
|
31
|
+
Tiled's PostgreSQL ``AccessBlobFilter`` actually queries.
|
|
32
|
+
|
|
33
|
+
``bluesky_tiled_plugins.TiledWriter`` pops a ``tiled_access_tags`` key
|
|
34
|
+
from the run-start doc and forwards it to ``client.create_container(
|
|
35
|
+
access_tags=...)``, which lands in Tiled's dedicated ``access_blob``
|
|
36
|
+
column as ``{"tags": [...]}``. Without that key the column stays
|
|
37
|
+
empty and every authenticated read filters down to nothing — the data
|
|
38
|
+
is in the catalog but invisible to the policy.
|
|
39
|
+
|
|
40
|
+
Tag schema MUST stay in lockstep with als_tiled.write_helpers.access_tags
|
|
41
|
+
(the symmetric reader-side tag minting in ALSAccessPolicy.filters).
|
|
42
|
+
|
|
43
|
+
esaf:<esaf_id>
|
|
44
|
+
beamline:<beamline>
|
|
45
|
+
participant:keycloak_sub:<sub>
|
|
46
|
+
participant:orcid:<orcid>
|
|
47
|
+
"""
|
|
48
|
+
tags: list[str] = []
|
|
49
|
+
if blob.get("esaf_id"):
|
|
50
|
+
tags.append(f"esaf:{blob['esaf_id']}")
|
|
51
|
+
if blob.get("beamline"):
|
|
52
|
+
tags.append(f"beamline:{blob['beamline']}")
|
|
53
|
+
for p in blob.get("participants") or []:
|
|
54
|
+
if not isinstance(p, dict):
|
|
55
|
+
continue
|
|
56
|
+
sub = p.get("keycloak_sub")
|
|
57
|
+
orcid = p.get("orcid")
|
|
58
|
+
if sub:
|
|
59
|
+
tags.append(f"participant:keycloak_sub:{sub}")
|
|
60
|
+
if orcid:
|
|
61
|
+
tags.append(f"participant:orcid:{orcid}")
|
|
62
|
+
return tags
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class AccessStamper:
|
|
66
|
+
"""Builds access_blob for Tiled writes."""
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
beamline: str,
|
|
71
|
+
alshub_client: AlshubClient,
|
|
72
|
+
session_provider: Callable[[], Any],
|
|
73
|
+
settings_provider: Callable[[], Any],
|
|
74
|
+
version: str = "lightfall:dev",
|
|
75
|
+
):
|
|
76
|
+
self.beamline = beamline
|
|
77
|
+
self._alshub = alshub_client
|
|
78
|
+
self._session_provider = session_provider
|
|
79
|
+
self._settings_provider = settings_provider
|
|
80
|
+
self._version = version
|
|
81
|
+
|
|
82
|
+
def _operator_identity(self) -> tuple[str | None, str | None]:
|
|
83
|
+
"""Pull (orcid, keycloak_sub) from the Keycloak session.
|
|
84
|
+
|
|
85
|
+
Decoded JWT claims live on ``session.user.attributes``, populated by
|
|
86
|
+
Lightfall's Keycloak provider at login. ``orcid`` is only present if the
|
|
87
|
+
Keycloak realm is configured to emit it; ``sub`` is always present
|
|
88
|
+
in any Keycloak token.
|
|
89
|
+
"""
|
|
90
|
+
session = self._session_provider()
|
|
91
|
+
# Auth-v2: bearer is discarded post-mint, so `session.token` is always
|
|
92
|
+
# None for an authenticated user. `session.user` (set by the provider in
|
|
93
|
+
# the same place as the token) is the canonical "logged in" signal.
|
|
94
|
+
if session is None or session.user is None:
|
|
95
|
+
raise MissingSessionError("No Keycloak session — refusing to stamp")
|
|
96
|
+
user = getattr(session, "user", None)
|
|
97
|
+
claims = getattr(user, "attributes", None) or {}
|
|
98
|
+
orcid = claims.get("orcid")
|
|
99
|
+
sub = claims.get("sub")
|
|
100
|
+
return orcid, sub
|
|
101
|
+
|
|
102
|
+
def _resolve_override(self) -> dict | None:
|
|
103
|
+
settings = self._settings_provider()
|
|
104
|
+
override = getattr(settings, "access_override", None)
|
|
105
|
+
if override is None:
|
|
106
|
+
return None
|
|
107
|
+
try:
|
|
108
|
+
now = datetime.now(UTC)
|
|
109
|
+
start = override.start
|
|
110
|
+
end = override.end
|
|
111
|
+
if start is None or end is None or override.esaf_id is None:
|
|
112
|
+
logger.warning("access_override missing fields; ignoring")
|
|
113
|
+
return None
|
|
114
|
+
if start.tzinfo is None:
|
|
115
|
+
start = start.replace(tzinfo=UTC)
|
|
116
|
+
if end.tzinfo is None:
|
|
117
|
+
end = end.replace(tzinfo=UTC)
|
|
118
|
+
if not (start <= now <= end):
|
|
119
|
+
return None
|
|
120
|
+
return {
|
|
121
|
+
"esaf_id": override.esaf_id,
|
|
122
|
+
"set_by": getattr(override, "set_by", None),
|
|
123
|
+
}
|
|
124
|
+
except Exception as e:
|
|
125
|
+
logger.warning("access_override malformed: %s; ignoring", e)
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
async def build_blob(self) -> dict[str, Any]:
|
|
129
|
+
operator_orcid, operator_sub = self._operator_identity()
|
|
130
|
+
|
|
131
|
+
override = self._resolve_override()
|
|
132
|
+
if override is not None:
|
|
133
|
+
esaf_id = override["esaf_id"]
|
|
134
|
+
proposal_id = self._derive_proposal(esaf_id)
|
|
135
|
+
esaf_source = "admin_override"
|
|
136
|
+
else:
|
|
137
|
+
try:
|
|
138
|
+
payload = await self._alshub.get_active_esaf(self.beamline)
|
|
139
|
+
except Exception as e:
|
|
140
|
+
logger.warning("alshub lookup failed: %s", e)
|
|
141
|
+
payload = None
|
|
142
|
+
esaf_source = "pending"
|
|
143
|
+
esaf_id = None
|
|
144
|
+
proposal_id = None
|
|
145
|
+
else:
|
|
146
|
+
if payload is None:
|
|
147
|
+
esaf_id = None
|
|
148
|
+
proposal_id = None
|
|
149
|
+
esaf_source = "none"
|
|
150
|
+
else:
|
|
151
|
+
esaf_id = payload.get("EsafFriendlyId")
|
|
152
|
+
proposal_id = payload.get("ProposalFriendlyId")
|
|
153
|
+
esaf_source = "schedule"
|
|
154
|
+
|
|
155
|
+
blob = {
|
|
156
|
+
"esaf_id": esaf_id,
|
|
157
|
+
"proposal_id": proposal_id,
|
|
158
|
+
"beamline": self.beamline,
|
|
159
|
+
"created_at": _now_iso(),
|
|
160
|
+
"stamped_by": self._version,
|
|
161
|
+
"esaf_source": esaf_source,
|
|
162
|
+
"participants": [{
|
|
163
|
+
"orcid": operator_orcid,
|
|
164
|
+
"keycloak_sub": operator_sub,
|
|
165
|
+
"role": "operator",
|
|
166
|
+
"added_at": _now_iso(),
|
|
167
|
+
"added_by": "lightfall",
|
|
168
|
+
}],
|
|
169
|
+
}
|
|
170
|
+
if esaf_source != "schedule":
|
|
171
|
+
logger.warning("blob stamped with esaf_source=%s for %s",
|
|
172
|
+
esaf_source, self.beamline)
|
|
173
|
+
return blob
|
|
174
|
+
|
|
175
|
+
@staticmethod
|
|
176
|
+
def _derive_proposal(esaf_id: str | None) -> str | None:
|
|
177
|
+
"""Derive proposal_id from esaf_id when possible.
|
|
178
|
+
|
|
179
|
+
ALS convention: ESAF IDs look like 'BLS-00480-001' where 'BLS-00480'
|
|
180
|
+
is the proposal. If the format doesn't match, return None and let
|
|
181
|
+
the operator/admin fix it via the override.
|
|
182
|
+
"""
|
|
183
|
+
if not esaf_id:
|
|
184
|
+
return None
|
|
185
|
+
parts = esaf_id.rsplit("-", 1)
|
|
186
|
+
if len(parts) == 2 and parts[1].isdigit():
|
|
187
|
+
return parts[0]
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def install_into_run_engine(stamper: AccessStamper, run_engine: Any) -> None:
|
|
192
|
+
"""Install the stamper as a bluesky preprocessor on the RunEngine.
|
|
193
|
+
|
|
194
|
+
On each ``RE(plan)`` call, the preprocessor builds a fresh access_blob
|
|
195
|
+
(so operator identity changes, override toggling, and alshub schedule
|
|
196
|
+
rolling are picked up live) and injects it into the run's ``open_run``
|
|
197
|
+
message via :func:`bluesky.preprocessors.inject_md_wrapper`. Bluesky
|
|
198
|
+
then merges that kwarg into the emitted start document.
|
|
199
|
+
|
|
200
|
+
Why a preprocessor and not ``RE.md``: bluesky inserts ``RE.md`` values
|
|
201
|
+
verbatim into the start doc — it does NOT evaluate callables. Storing
|
|
202
|
+
a function under ``RE.md["access_blob"]`` either fails to serialize or
|
|
203
|
+
embeds a function reference, neither of which is what we want.
|
|
204
|
+
Preprocessors are the supported per-run metadata mechanism.
|
|
205
|
+
|
|
206
|
+
Idempotent: if a stamper preprocessor was previously installed, it is
|
|
207
|
+
removed before the new one is appended (so reconfigure-and-reconnect
|
|
208
|
+
flows don't accumulate stamping passes).
|
|
209
|
+
"""
|
|
210
|
+
import asyncio
|
|
211
|
+
import concurrent.futures
|
|
212
|
+
|
|
213
|
+
from bluesky.preprocessors import inject_md_wrapper
|
|
214
|
+
|
|
215
|
+
existing = getattr(run_engine, "preprocessors", None) or []
|
|
216
|
+
run_engine.preprocessors = [
|
|
217
|
+
p for p in existing if not getattr(p, "_is_access_stamper", False)
|
|
218
|
+
]
|
|
219
|
+
|
|
220
|
+
def _build_blob_sync() -> dict[str, Any]:
|
|
221
|
+
# The RE owns an event loop; preprocessors execute inside it. A
|
|
222
|
+
# worker thread gives asyncio.run a fresh, loop-free context.
|
|
223
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
|
224
|
+
return pool.submit(asyncio.run, stamper.build_blob()).result(timeout=10)
|
|
225
|
+
|
|
226
|
+
def _stamping_preprocessor(plan):
|
|
227
|
+
blob = _build_blob_sync()
|
|
228
|
+
# `access_blob` lands in the start doc's metadata for human-readable
|
|
229
|
+
# audit (which ESAF, which participants, why); `tiled_access_tags`
|
|
230
|
+
# is what TiledWriter actually pops and routes to Tiled's dedicated
|
|
231
|
+
# access_blob column for the AccessBlobFilter SQL predicate. Both
|
|
232
|
+
# are needed: the former for traceability, the latter for the
|
|
233
|
+
# actual read-side gate.
|
|
234
|
+
tags = compute_access_tags(blob)
|
|
235
|
+
return (yield from inject_md_wrapper(
|
|
236
|
+
plan, {"access_blob": blob, "tiled_access_tags": tags},
|
|
237
|
+
))
|
|
238
|
+
|
|
239
|
+
_stamping_preprocessor._is_access_stamper = True # type: ignore[attr-defined]
|
|
240
|
+
run_engine.preprocessors.append(_stamping_preprocessor)
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""ALS beam status service for NCS.
|
|
2
|
+
|
|
3
|
+
Polls the ALS beam status API to provide real-time synchrotron
|
|
4
|
+
beam information including current, energy, lifetime, and availability.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from PySide6.QtCore import QObject, QTimer, Signal
|
|
15
|
+
|
|
16
|
+
from lightfall.utils.logging import logger
|
|
17
|
+
from lightfall.utils.threads import QThreadFuture
|
|
18
|
+
|
|
19
|
+
# API endpoint for ALS beam status
|
|
20
|
+
ALS_BEAM_STATUS_URL = "https://controls.als.lbl.gov/als-beamstatus/curvals"
|
|
21
|
+
|
|
22
|
+
# Polling interval in milliseconds (60 seconds)
|
|
23
|
+
POLL_INTERVAL_MS = 60000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _is_proxy_connection_error(error: BaseException) -> bool:
|
|
27
|
+
"""Check whether an error indicates a SOCKS proxy connection failure."""
|
|
28
|
+
exc: BaseException | None = error
|
|
29
|
+
while exc is not None:
|
|
30
|
+
name = type(exc).__name__
|
|
31
|
+
if "ProxyConnectionError" in name or "ProxyError" in name:
|
|
32
|
+
return True
|
|
33
|
+
if "could not connect to proxy" in str(exc).lower():
|
|
34
|
+
return True
|
|
35
|
+
exc = exc.__cause__ or exc.__context__
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class ALSBeamData:
|
|
41
|
+
"""Structured ALS beam status data.
|
|
42
|
+
|
|
43
|
+
Attributes:
|
|
44
|
+
beam_current: Ring current in mA.
|
|
45
|
+
beam_available: True if light is available (shutters open).
|
|
46
|
+
beam_energy: Beam energy in GeV.
|
|
47
|
+
lifetime: Beam lifetime in hours.
|
|
48
|
+
x_rms: Horizontal beam position stability (microns).
|
|
49
|
+
y_rms: Vertical beam position stability (microns).
|
|
50
|
+
comment: Operations status message.
|
|
51
|
+
timestamp: Time of the measurement.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
beam_current: float = 0.0
|
|
55
|
+
beam_available: bool = False
|
|
56
|
+
beam_energy: float = 0.0
|
|
57
|
+
lifetime: float = 0.0
|
|
58
|
+
x_rms: float = 0.0
|
|
59
|
+
y_rms: float = 0.0
|
|
60
|
+
comment: str = ""
|
|
61
|
+
timestamp: datetime | None = None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# Thread key for preventing duplicate concurrent fetches
|
|
65
|
+
_FETCH_THREAD_KEY = "als_beam_status_fetch"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ALSBeamStatusService(QObject):
|
|
69
|
+
"""Service for polling ALS beam status.
|
|
70
|
+
|
|
71
|
+
Provides real-time ALS synchrotron beam information by polling
|
|
72
|
+
the ALS beam status API. Supports automatic SOCKS5 proxy detection
|
|
73
|
+
for *.lbl.gov URLs.
|
|
74
|
+
|
|
75
|
+
Signals:
|
|
76
|
+
status_changed: Emitted when beam data is updated. Carries ALSBeamData.
|
|
77
|
+
connection_changed: Emitted when connection state changes. Carries bool.
|
|
78
|
+
|
|
79
|
+
Example:
|
|
80
|
+
>>> service = ALSBeamStatusService.get_instance()
|
|
81
|
+
>>> service.start_polling()
|
|
82
|
+
>>> print(service.current_data)
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
status_changed = Signal(object) # ALSBeamData
|
|
86
|
+
connection_changed = Signal(bool) # is_connected
|
|
87
|
+
|
|
88
|
+
_instance: ALSBeamStatusService | None = None
|
|
89
|
+
_lock = threading.RLock()
|
|
90
|
+
|
|
91
|
+
def __init__(self) -> None:
|
|
92
|
+
"""Initialize the ALS beam status service."""
|
|
93
|
+
super().__init__()
|
|
94
|
+
self._data: ALSBeamData | None = None
|
|
95
|
+
self._is_connected = False
|
|
96
|
+
self._last_error: str | None = None
|
|
97
|
+
self._polling = False
|
|
98
|
+
self._proxy_toast_shown = False
|
|
99
|
+
|
|
100
|
+
# Polling timer
|
|
101
|
+
self._poll_timer = QTimer(self)
|
|
102
|
+
self._poll_timer.timeout.connect(self._poll)
|
|
103
|
+
|
|
104
|
+
logger.debug("ALSBeamStatusService initialized")
|
|
105
|
+
|
|
106
|
+
@classmethod
|
|
107
|
+
def get_instance(cls) -> ALSBeamStatusService:
|
|
108
|
+
"""Get the singleton ALSBeamStatusService instance."""
|
|
109
|
+
if cls._instance is None:
|
|
110
|
+
with cls._lock:
|
|
111
|
+
if cls._instance is None:
|
|
112
|
+
cls._instance = cls()
|
|
113
|
+
return cls._instance
|
|
114
|
+
|
|
115
|
+
@classmethod
|
|
116
|
+
def reset(cls) -> None:
|
|
117
|
+
"""Reset the singleton instance (for testing)."""
|
|
118
|
+
with cls._lock:
|
|
119
|
+
if cls._instance is not None:
|
|
120
|
+
cls._instance.stop_polling()
|
|
121
|
+
cls._instance.deleteLater()
|
|
122
|
+
cls._instance = None
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def current_data(self) -> ALSBeamData | None:
|
|
126
|
+
"""Current beam status data, or None if not yet fetched."""
|
|
127
|
+
return self._data
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def is_connected(self) -> bool:
|
|
131
|
+
"""Whether the service has successfully connected to the API."""
|
|
132
|
+
return self._is_connected
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def last_error(self) -> str | None:
|
|
136
|
+
"""Last error message if connection failed."""
|
|
137
|
+
return self._last_error
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def is_polling(self) -> bool:
|
|
141
|
+
"""Whether the service is currently polling."""
|
|
142
|
+
return self._polling
|
|
143
|
+
|
|
144
|
+
def _get_proxy_url(self) -> str | None:
|
|
145
|
+
"""Get the proxy URL from centralized proxy settings.
|
|
146
|
+
|
|
147
|
+
Delegates to ProxySettingsProvider which respects user settings.
|
|
148
|
+
Proxy is disabled by default - users must enable it in settings.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
The proxy URL to use, or None if no proxy needed.
|
|
152
|
+
"""
|
|
153
|
+
from lightfall.ui.preferences.proxy_settings import ProxySettingsProvider
|
|
154
|
+
|
|
155
|
+
return ProxySettingsProvider.should_use_proxy_for_url(ALS_BEAM_STATUS_URL)
|
|
156
|
+
|
|
157
|
+
def start_polling(self) -> None:
|
|
158
|
+
"""Start polling the ALS beam status API."""
|
|
159
|
+
if self._polling:
|
|
160
|
+
return
|
|
161
|
+
|
|
162
|
+
logger.info("Starting ALS beam status polling")
|
|
163
|
+
self._polling = True
|
|
164
|
+
|
|
165
|
+
# Start the timer and schedule an immediate async poll
|
|
166
|
+
# Using QTimer.singleShot(0, ...) defers to the next event loop cycle
|
|
167
|
+
# so startup isn't blocked waiting for network I/O
|
|
168
|
+
self._poll_timer.start(POLL_INTERVAL_MS)
|
|
169
|
+
QTimer.singleShot(0, self._poll)
|
|
170
|
+
|
|
171
|
+
def stop_polling(self) -> None:
|
|
172
|
+
"""Stop polling the ALS beam status API."""
|
|
173
|
+
if not self._polling:
|
|
174
|
+
return
|
|
175
|
+
|
|
176
|
+
logger.info("Stopping ALS beam status polling")
|
|
177
|
+
self._polling = False
|
|
178
|
+
self._poll_timer.stop()
|
|
179
|
+
|
|
180
|
+
def _poll(self) -> None:
|
|
181
|
+
"""Poll the ALS beam status API asynchronously.
|
|
182
|
+
|
|
183
|
+
Launches a QThreadFuture to fetch data without blocking the main
|
|
184
|
+
Qt event loop. Using a thread key ensures that if a previous fetch
|
|
185
|
+
is still running, it gets cancelled before starting a new one.
|
|
186
|
+
"""
|
|
187
|
+
# Keep reference to prevent GC before signals fire
|
|
188
|
+
self._current_fetch = QThreadFuture(
|
|
189
|
+
self._fetch_beam_status,
|
|
190
|
+
callback_slot=self._on_fetch_success,
|
|
191
|
+
except_slot=self._on_fetch_error,
|
|
192
|
+
key=_FETCH_THREAD_KEY,
|
|
193
|
+
name="als_beam_status_fetch",
|
|
194
|
+
)
|
|
195
|
+
self._current_fetch.start()
|
|
196
|
+
|
|
197
|
+
def _on_fetch_success(self, data: ALSBeamData) -> None:
|
|
198
|
+
"""Handle successful fetch completion.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
data: Fetched beam data.
|
|
202
|
+
"""
|
|
203
|
+
self._data = data
|
|
204
|
+
self._proxy_toast_shown = False
|
|
205
|
+
self._set_connected(True)
|
|
206
|
+
self.status_changed.emit(data)
|
|
207
|
+
|
|
208
|
+
def _on_fetch_error(self, error: Exception) -> None:
|
|
209
|
+
"""Handle fetch error.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
error: The exception that occurred during fetch.
|
|
213
|
+
"""
|
|
214
|
+
logger.debug("Failed to fetch ALS beam status: {}", error)
|
|
215
|
+
self._last_error = str(error)
|
|
216
|
+
self._set_connected(False)
|
|
217
|
+
|
|
218
|
+
if not self._proxy_toast_shown and _is_proxy_connection_error(error):
|
|
219
|
+
self._proxy_toast_shown = True
|
|
220
|
+
try:
|
|
221
|
+
from lightfall.ui.toast import ToastManager
|
|
222
|
+
|
|
223
|
+
ToastManager.get_instance().warning(
|
|
224
|
+
"SOCKS proxy not reachable",
|
|
225
|
+
"Is your SSH tunnel or proxy running? "
|
|
226
|
+
"Check Preferences → Proxy to verify settings.",
|
|
227
|
+
)
|
|
228
|
+
except Exception:
|
|
229
|
+
pass
|
|
230
|
+
|
|
231
|
+
def _set_connected(self, connected: bool) -> None:
|
|
232
|
+
"""Update connection state and emit signal if changed."""
|
|
233
|
+
if self._is_connected != connected:
|
|
234
|
+
self._is_connected = connected
|
|
235
|
+
if connected:
|
|
236
|
+
self._last_error = None
|
|
237
|
+
self.connection_changed.emit(connected)
|
|
238
|
+
|
|
239
|
+
def _fetch_beam_status(self) -> ALSBeamData | None:
|
|
240
|
+
"""Fetch beam status from the ALS API.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
ALSBeamData with current values, or None on error.
|
|
244
|
+
"""
|
|
245
|
+
import httpx
|
|
246
|
+
|
|
247
|
+
# Build client with optional SOCKS proxy (look up dynamically for settings changes)
|
|
248
|
+
proxy_url = self._get_proxy_url()
|
|
249
|
+
transport = None
|
|
250
|
+
if proxy_url:
|
|
251
|
+
try:
|
|
252
|
+
from httpx_socks import SyncProxyTransport
|
|
253
|
+
|
|
254
|
+
transport = SyncProxyTransport.from_url(proxy_url)
|
|
255
|
+
except ImportError:
|
|
256
|
+
logger.debug("httpx-socks not available, trying without proxy")
|
|
257
|
+
|
|
258
|
+
with httpx.Client(transport=transport, timeout=10.0) as client:
|
|
259
|
+
response = client.get(ALS_BEAM_STATUS_URL)
|
|
260
|
+
response.raise_for_status()
|
|
261
|
+
return self._parse_response(response.json())
|
|
262
|
+
|
|
263
|
+
def _parse_response(self, data: list[dict[str, Any]]) -> ALSBeamData:
|
|
264
|
+
"""Parse the ALS API response into ALSBeamData.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
data: JSON array from the API.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
Parsed ALSBeamData object.
|
|
271
|
+
"""
|
|
272
|
+
# Build a lookup dict by label
|
|
273
|
+
values: dict[str, str] = {}
|
|
274
|
+
timestamp_str: str | None = None
|
|
275
|
+
|
|
276
|
+
for item in data:
|
|
277
|
+
label = item.get("label", "")
|
|
278
|
+
val = item.get("val", "")
|
|
279
|
+
values[label] = val
|
|
280
|
+
|
|
281
|
+
# Get timestamp from Beam Current entry
|
|
282
|
+
if label == "Beam Current" and "tstamp" in item:
|
|
283
|
+
timestamp_str = item["tstamp"]
|
|
284
|
+
|
|
285
|
+
# Parse timestamp
|
|
286
|
+
timestamp = None
|
|
287
|
+
if timestamp_str:
|
|
288
|
+
try:
|
|
289
|
+
timestamp = datetime.fromtimestamp(int(timestamp_str))
|
|
290
|
+
except (ValueError, OSError):
|
|
291
|
+
pass
|
|
292
|
+
|
|
293
|
+
return ALSBeamData(
|
|
294
|
+
beam_current=self._safe_float(values.get("Beam Current", "0")),
|
|
295
|
+
beam_available=values.get("Beam Available", "0") == "1",
|
|
296
|
+
beam_energy=self._safe_float(values.get("Beam Energy", "0")),
|
|
297
|
+
lifetime=self._safe_float(values.get("Lifetime", "0")),
|
|
298
|
+
x_rms=self._safe_float(values.get("X RMS Avg", "0")),
|
|
299
|
+
y_rms=self._safe_float(values.get("Y RMS Avg", "0")),
|
|
300
|
+
comment=values.get("Comment", ""),
|
|
301
|
+
timestamp=timestamp,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
def _safe_float(self, value: str) -> float:
|
|
305
|
+
"""Safely parse a float from a string.
|
|
306
|
+
|
|
307
|
+
Args:
|
|
308
|
+
value: String to parse.
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
Parsed float, or 0.0 on error.
|
|
312
|
+
"""
|
|
313
|
+
try:
|
|
314
|
+
return float(value)
|
|
315
|
+
except (ValueError, TypeError):
|
|
316
|
+
return 0.0
|
|
317
|
+
|
|
318
|
+
def force_refresh(self) -> None:
|
|
319
|
+
"""Force an immediate refresh of beam status."""
|
|
320
|
+
self._poll()
|
|
321
|
+
|
|
322
|
+
def get_introspection_data(self) -> dict[str, Any]:
|
|
323
|
+
"""Get introspection data for MCP tools.
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
Dictionary with current beam status information.
|
|
327
|
+
"""
|
|
328
|
+
result: dict[str, Any] = {
|
|
329
|
+
"is_connected": self._is_connected,
|
|
330
|
+
"is_polling": self._polling,
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if self._data:
|
|
334
|
+
result["beam_current_mA"] = self._data.beam_current
|
|
335
|
+
result["beam_available"] = self._data.beam_available
|
|
336
|
+
result["beam_energy_GeV"] = self._data.beam_energy
|
|
337
|
+
result["lifetime_hours"] = self._data.lifetime
|
|
338
|
+
result["x_rms_microns"] = self._data.x_rms
|
|
339
|
+
result["y_rms_microns"] = self._data.y_rms
|
|
340
|
+
result["comment"] = self._data.comment
|
|
341
|
+
if self._data.timestamp:
|
|
342
|
+
result["timestamp"] = self._data.timestamp.isoformat()
|
|
343
|
+
|
|
344
|
+
if self._last_error:
|
|
345
|
+
result["last_error"] = self._last_error
|
|
346
|
+
|
|
347
|
+
return result
|