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.
Files changed (388) hide show
  1. lightfall/__init__.py +8 -0
  2. lightfall/__main__.py +10 -0
  3. lightfall/_version.py +24 -0
  4. lightfall/acquire/__init__.py +74 -0
  5. lightfall/acquire/buffer.py +363 -0
  6. lightfall/acquire/device_wrapper.py +416 -0
  7. lightfall/acquire/engine/__init__.py +155 -0
  8. lightfall/acquire/engine/base.py +587 -0
  9. lightfall/acquire/engine/bluesky.py +358 -0
  10. lightfall/acquire/engine/mock.py +165 -0
  11. lightfall/acquire/engine/plugins/__init__.py +9 -0
  12. lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
  13. lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
  14. lightfall/acquire/engine/protocol.py +145 -0
  15. lightfall/acquire/engine/registry.py +152 -0
  16. lightfall/acquire/engine/state.py +32 -0
  17. lightfall/acquire/engine/waiting_hook.py +225 -0
  18. lightfall/acquire/nats_bridge.py +62 -0
  19. lightfall/acquire/plan_ui.py +78 -0
  20. lightfall/acquire/plans/__init__.py +38 -0
  21. lightfall/acquire/plans/adaptive.py +288 -0
  22. lightfall/acquire/plans/example_plans.py +995 -0
  23. lightfall/acquire/plans/lightfall_plans.py +587 -0
  24. lightfall/acquire/plans/registry.py +543 -0
  25. lightfall/acquire/plans/standard_plans.py +186 -0
  26. lightfall/acquire/plans/user_plans.py +470 -0
  27. lightfall/acquire/runengine.py +36 -0
  28. lightfall/acquire/signals.py +452 -0
  29. lightfall/acquire/triggers/__init__.py +16 -0
  30. lightfall/acquire/triggers/base.py +25 -0
  31. lightfall/acquire/triggers/filter.py +37 -0
  32. lightfall/acquire/triggers/manager.py +73 -0
  33. lightfall/acquire/triggers/manual.py +36 -0
  34. lightfall/acquire/triggers/run_end.py +74 -0
  35. lightfall/acquire/triggers/run_start.py +52 -0
  36. lightfall/auth/__init__.py +38 -0
  37. lightfall/auth/policy.py +518 -0
  38. lightfall/auth/providers/__init__.py +30 -0
  39. lightfall/auth/providers/base.py +124 -0
  40. lightfall/auth/providers/keycloak.py +1017 -0
  41. lightfall/auth/providers/local.py +319 -0
  42. lightfall/auth/providers/pam.py +250 -0
  43. lightfall/auth/service_key.py +173 -0
  44. lightfall/auth/service_key_auth.py +79 -0
  45. lightfall/auth/session.py +656 -0
  46. lightfall/claude/__init__.py +52 -0
  47. lightfall/claude/_internal/__init__.py +1 -0
  48. lightfall/claude/_internal/serialization.py +195 -0
  49. lightfall/claude/_internal/threading.py +61 -0
  50. lightfall/claude/_internal/worker.py +757 -0
  51. lightfall/claude/_session_assembly.py +124 -0
  52. lightfall/claude/agent.py +596 -0
  53. lightfall/claude/lightfall_core_tools.py +410 -0
  54. lightfall/claude/markdown.py +103 -0
  55. lightfall/claude/permission_manager.py +588 -0
  56. lightfall/claude/tools/__init__.py +45 -0
  57. lightfall/claude/tools/controller.py +143 -0
  58. lightfall/claude/tools/interaction.py +177 -0
  59. lightfall/claude/tools/introspection.py +127 -0
  60. lightfall/claude/tools/logs.py +155 -0
  61. lightfall/claude/tools/screenshot.py +87 -0
  62. lightfall/claude/widget.py +851 -0
  63. lightfall/claude/widgets/__init__.py +5 -0
  64. lightfall/claude/widgets/permission_request.py +282 -0
  65. lightfall/claude/widgets/question_request.py +227 -0
  66. lightfall/claude/widgets/task_card.py +223 -0
  67. lightfall/config/__init__.py +23 -0
  68. lightfall/config/layers.py +317 -0
  69. lightfall/config/manager.py +244 -0
  70. lightfall/config/schema.py +154 -0
  71. lightfall/core/__init__.py +23 -0
  72. lightfall/core/application.py +727 -0
  73. lightfall/core/services.py +235 -0
  74. lightfall/devices/__init__.py +53 -0
  75. lightfall/devices/backends/__init__.py +17 -0
  76. lightfall/devices/backends/bcs.py +448 -0
  77. lightfall/devices/backends/happi.py +986 -0
  78. lightfall/devices/backends/mock.py +646 -0
  79. lightfall/devices/base.py +338 -0
  80. lightfall/devices/catalog.py +1039 -0
  81. lightfall/devices/connection_manager.py +676 -0
  82. lightfall/devices/model.py +290 -0
  83. lightfall/devices/monitoring.py +442 -0
  84. lightfall/devices/sim/__init__.py +26 -0
  85. lightfall/devices/sim/areadetector.py +436 -0
  86. lightfall/devices/sim/generators.py +223 -0
  87. lightfall/devices/sim/plugins.py +116 -0
  88. lightfall/epics/__init__.py +28 -0
  89. lightfall/epics/ca/__init__.py +10 -0
  90. lightfall/epics/ca/context.py +100 -0
  91. lightfall/epics/ca/pv.py +303 -0
  92. lightfall/epics/widgets/__init__.py +49 -0
  93. lightfall/epics/widgets/areadetector/__init__.py +16 -0
  94. lightfall/epics/widgets/areadetector/areadetector.py +281 -0
  95. lightfall/epics/widgets/areadetector/controls.py +478 -0
  96. lightfall/epics/widgets/areadetector/image_view.py +447 -0
  97. lightfall/epics/widgets/auto.py +319 -0
  98. lightfall/epics/widgets/base.py +404 -0
  99. lightfall/epics/widgets/checkbox.py +239 -0
  100. lightfall/epics/widgets/combobox.py +202 -0
  101. lightfall/epics/widgets/label.py +176 -0
  102. lightfall/epics/widgets/lineedit.py +253 -0
  103. lightfall/epics/widgets/motor.py +694 -0
  104. lightfall/epics/widgets/ophyd_base.py +469 -0
  105. lightfall/epics/widgets/ophyd_combobox.py +86 -0
  106. lightfall/epics/widgets/ophyd_label.py +54 -0
  107. lightfall/epics/widgets/ophyd_lineedit.py +170 -0
  108. lightfall/epics/widgets/ophyd_spinbox.py +79 -0
  109. lightfall/epics/widgets/slider.py +272 -0
  110. lightfall/epics/widgets/status_indicator.py +98 -0
  111. lightfall/epics/widgets/style.py +188 -0
  112. lightfall/exporter/__init__.py +1 -0
  113. lightfall/exporter/cli.py +67 -0
  114. lightfall/exporter/converters/__init__.py +26 -0
  115. lightfall/exporter/converters/base.py +39 -0
  116. lightfall/exporter/converters/noop.py +39 -0
  117. lightfall/exporter/converters/nxsas.py +73 -0
  118. lightfall/exporter/service.py +200 -0
  119. lightfall/exporter/tiled_utils.py +92 -0
  120. lightfall/ipc/__init__.py +6 -0
  121. lightfall/ipc/service.py +701 -0
  122. lightfall/ipc/trust.py +144 -0
  123. lightfall/logbook/__init__.py +46 -0
  124. lightfall/logbook/action_dialog.py +207 -0
  125. lightfall/logbook/action_logger.py +432 -0
  126. lightfall/logbook/block_mapper.py +562 -0
  127. lightfall/logbook/client.py +799 -0
  128. lightfall/logbook/converter.py +273 -0
  129. lightfall/logbook/editors/__init__.py +19 -0
  130. lightfall/logbook/editors/highlighter.py +305 -0
  131. lightfall/logbook/editors/markdown_editor.py +319 -0
  132. lightfall/logbook/editors/richtext_editor.py +1397 -0
  133. lightfall/logbook/entry_widget.py +1065 -0
  134. lightfall/logbook/event_listener.py +221 -0
  135. lightfall/logbook/fragment_widgets.py +925 -0
  136. lightfall/logbook/position_mapper.py +320 -0
  137. lightfall/logbook/protection.py +402 -0
  138. lightfall/logbook/style.py +394 -0
  139. lightfall/logbook/url.py +29 -0
  140. lightfall/logbook/visual_protection.py +330 -0
  141. lightfall/logbook/widget.py +680 -0
  142. lightfall/main.py +1091 -0
  143. lightfall/pipelines/__init__.py +4 -0
  144. lightfall/pipelines/client.py +148 -0
  145. lightfall/plugins/__init__.py +119 -0
  146. lightfall/plugins/agent_plugin.py +106 -0
  147. lightfall/plugins/agents/__init__.py +10 -0
  148. lightfall/plugins/agents/_mcp_helpers.py +52 -0
  149. lightfall/plugins/agents/alignment.py +94 -0
  150. lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
  151. lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
  152. lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
  153. lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
  154. lightfall/plugins/agents/current_esaf.py +435 -0
  155. lightfall/plugins/agents/device_tools.py +1043 -0
  156. lightfall/plugins/agents/engine_tools.py +720 -0
  157. lightfall/plugins/agents/ipython_tools.py +444 -0
  158. lightfall/plugins/agents/panel_builder.py +637 -0
  159. lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
  160. lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
  161. lightfall/plugins/agents/panel_design.py +94 -0
  162. lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
  163. lightfall/plugins/agents/plan_design.py +90 -0
  164. lightfall/plugins/agents/plan_tools.py +878 -0
  165. lightfall/plugins/agents/scan_planning.py +101 -0
  166. lightfall/plugins/builtin_manifest.py +348 -0
  167. lightfall/plugins/controller_plugin.py +162 -0
  168. lightfall/plugins/engine_plugin.py +124 -0
  169. lightfall/plugins/errors.py +104 -0
  170. lightfall/plugins/info.py +112 -0
  171. lightfall/plugins/loader.py +878 -0
  172. lightfall/plugins/manifest.py +150 -0
  173. lightfall/plugins/panel_plugin.py +119 -0
  174. lightfall/plugins/plan_plugin.py +163 -0
  175. lightfall/plugins/registry.py +309 -0
  176. lightfall/plugins/settings_plugin.py +226 -0
  177. lightfall/plugins/statusbar_plugin.py +289 -0
  178. lightfall/plugins/theme_plugin.py +165 -0
  179. lightfall/plugins/types.py +136 -0
  180. lightfall/plugins/user_plugins.py +764 -0
  181. lightfall/project/__init__.py +37 -0
  182. lightfall/project/model.py +375 -0
  183. lightfall/project/service.py +427 -0
  184. lightfall/project/welcome.py +106 -0
  185. lightfall/resources/__init__.py +126 -0
  186. lightfall/resources/images/__init__.py +1 -0
  187. lightfall/resources/images/icon.ico +0 -0
  188. lightfall/resources/images/icon.png +0 -0
  189. lightfall/resources/images/logo.png +0 -0
  190. lightfall/services/__init__.py +33 -0
  191. lightfall/services/_alshub_client.py +73 -0
  192. lightfall/services/access_stamper.py +240 -0
  193. lightfall/services/als_beam_status.py +347 -0
  194. lightfall/services/ca_tunnel.py +325 -0
  195. lightfall/services/threaded_tiled_writer.py +174 -0
  196. lightfall/services/tiled_auth.py +21 -0
  197. lightfall/services/tiled_service.py +971 -0
  198. lightfall/services/tiled_writer_patch.py +301 -0
  199. lightfall/settings/__init__.py +1 -0
  200. lightfall/settings/image_helpers.py +30 -0
  201. lightfall/settings/user_settings_client.py +232 -0
  202. lightfall/ui/__init__.py +28 -0
  203. lightfall/ui/annotations.py +208 -0
  204. lightfall/ui/common/__init__.py +7 -0
  205. lightfall/ui/dialogs/__init__.py +26 -0
  206. lightfall/ui/dialogs/about_dialog.py +131 -0
  207. lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
  208. lightfall/ui/dialogs/base.py +44 -0
  209. lightfall/ui/dialogs/bug_report_dialog.py +353 -0
  210. lightfall/ui/dialogs/create_plan_dialog.py +189 -0
  211. lightfall/ui/dialogs/device_edit_dialog.py +183 -0
  212. lightfall/ui/dialogs/export_dialog.py +565 -0
  213. lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
  214. lightfall/ui/dialogs/login_dialog.py +756 -0
  215. lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
  216. lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
  217. lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
  218. lightfall/ui/docking/__init__.py +22 -0
  219. lightfall/ui/docking/icon_sidebar.py +806 -0
  220. lightfall/ui/docking/manager.py +682 -0
  221. lightfall/ui/docking/state.py +113 -0
  222. lightfall/ui/docking/theme.py +399 -0
  223. lightfall/ui/docking/widget.py +214 -0
  224. lightfall/ui/events.py +75 -0
  225. lightfall/ui/mainwindow.py +1006 -0
  226. lightfall/ui/models/__init__.py +49 -0
  227. lightfall/ui/models/device_selection.py +389 -0
  228. lightfall/ui/models/device_tree.py +1095 -0
  229. lightfall/ui/models/thread_model.py +667 -0
  230. lightfall/ui/models/tiled_model.py +384 -0
  231. lightfall/ui/panels/__init__.py +28 -0
  232. lightfall/ui/panels/base.py +525 -0
  233. lightfall/ui/panels/bluesky_panel.py +619 -0
  234. lightfall/ui/panels/claude/__init__.py +9 -0
  235. lightfall/ui/panels/claude/agent_registry.py +168 -0
  236. lightfall/ui/panels/claude_panel.py +887 -0
  237. lightfall/ui/panels/device_panel.py +370 -0
  238. lightfall/ui/panels/documents_panel.py +166 -0
  239. lightfall/ui/panels/ipython_panel.py +580 -0
  240. lightfall/ui/panels/logbook_entries_panel.py +84 -0
  241. lightfall/ui/panels/logbook_panel.py +627 -0
  242. lightfall/ui/panels/logging_panel.py +587 -0
  243. lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
  244. lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
  245. lightfall/ui/panels/plugins/__init__.py +34 -0
  246. lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
  247. lightfall/ui/panels/plugins/claude_plugin.py +29 -0
  248. lightfall/ui/panels/plugins/device_plugin.py +27 -0
  249. lightfall/ui/panels/plugins/documents_plugin.py +26 -0
  250. lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
  251. lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
  252. lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
  253. lightfall/ui/panels/plugins/logging_plugin.py +27 -0
  254. lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
  255. lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
  256. lightfall/ui/panels/plugins/queue_plugin.py +29 -0
  257. lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
  258. lightfall/ui/panels/plugins/threads_plugin.py +27 -0
  259. lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
  260. lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
  261. lightfall/ui/panels/queue.py +754 -0
  262. lightfall/ui/panels/registry.py +483 -0
  263. lightfall/ui/panels/synoptic/__init__.py +27 -0
  264. lightfall/ui/panels/synoptic/editors.py +481 -0
  265. lightfall/ui/panels/synoptic/items.py +556 -0
  266. lightfall/ui/panels/synoptic/models.py +336 -0
  267. lightfall/ui/panels/synoptic/panel.py +889 -0
  268. lightfall/ui/panels/synoptic/serialization.py +300 -0
  269. lightfall/ui/panels/synoptic/view.py +504 -0
  270. lightfall/ui/panels/threads_panel.py +621 -0
  271. lightfall/ui/panels/tiled_browser_panel.py +854 -0
  272. lightfall/ui/panels/visualization_panel.py +508 -0
  273. lightfall/ui/preferences/__init__.py +24 -0
  274. lightfall/ui/preferences/backend.py +148 -0
  275. lightfall/ui/preferences/builtin.py +220 -0
  276. lightfall/ui/preferences/claude_settings.py +762 -0
  277. lightfall/ui/preferences/device_settings.py +461 -0
  278. lightfall/ui/preferences/dialog.py +234 -0
  279. lightfall/ui/preferences/editor_settings.py +227 -0
  280. lightfall/ui/preferences/ipc_settings.py +226 -0
  281. lightfall/ui/preferences/logbook_settings.py +232 -0
  282. lightfall/ui/preferences/login_settings.py +183 -0
  283. lightfall/ui/preferences/manager.py +562 -0
  284. lightfall/ui/preferences/plugin_settings.py +392 -0
  285. lightfall/ui/preferences/proxy_settings.py +561 -0
  286. lightfall/ui/preferences/skill_settings.py +28 -0
  287. lightfall/ui/preferences/tiled_settings.py +469 -0
  288. lightfall/ui/preferences/tool_settings.py +393 -0
  289. lightfall/ui/preferences/user_portable_backend.py +131 -0
  290. lightfall/ui/preferences/user_profile_settings.py +316 -0
  291. lightfall/ui/preferences/visualization_settings.py +159 -0
  292. lightfall/ui/resources/__init__.py +1 -0
  293. lightfall/ui/resources/logo.png +0 -0
  294. lightfall/ui/statusbar/__init__.py +11 -0
  295. lightfall/ui/statusbar/manager.py +379 -0
  296. lightfall/ui/statusbar/plugins/__init__.py +28 -0
  297. lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
  298. lightfall/ui/statusbar/plugins/auth_status.py +116 -0
  299. lightfall/ui/statusbar/plugins/connection_status.py +100 -0
  300. lightfall/ui/statusbar/plugins/thread_status.py +556 -0
  301. lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
  302. lightfall/ui/statusbar/plugins/user_status.py +84 -0
  303. lightfall/ui/theater/__init__.py +28 -0
  304. lightfall/ui/theater/manager.py +124 -0
  305. lightfall/ui/theater/overlay.py +279 -0
  306. lightfall/ui/theater/proxy.py +111 -0
  307. lightfall/ui/theme/__init__.py +18 -0
  308. lightfall/ui/theme/builtin.py +1015 -0
  309. lightfall/ui/theme/manager.py +875 -0
  310. lightfall/ui/theme/registry.py +195 -0
  311. lightfall/ui/toast.py +221 -0
  312. lightfall/ui/tutorial.py +1100 -0
  313. lightfall/ui/widgets/__init__.py +110 -0
  314. lightfall/ui/widgets/base_control.py +259 -0
  315. lightfall/ui/widgets/camera/__init__.py +36 -0
  316. lightfall/ui/widgets/camera/base.py +815 -0
  317. lightfall/ui/widgets/camera/dark_frames.py +213 -0
  318. lightfall/ui/widgets/camera/image_view.py +649 -0
  319. lightfall/ui/widgets/camera/panels/__init__.py +14 -0
  320. lightfall/ui/widgets/camera/panels/cooler.py +320 -0
  321. lightfall/ui/widgets/camera/panels/temperature.py +192 -0
  322. lightfall/ui/widgets/camera/plan_based.py +202 -0
  323. lightfall/ui/widgets/compact_motor.py +522 -0
  324. lightfall/ui/widgets/controller_matcher.py +278 -0
  325. lightfall/ui/widgets/controller_registry.py +144 -0
  326. lightfall/ui/widgets/device_control.py +411 -0
  327. lightfall/ui/widgets/device_selector.py +438 -0
  328. lightfall/ui/widgets/device_tree_tab.py +461 -0
  329. lightfall/ui/widgets/document_stream.py +1028 -0
  330. lightfall/ui/widgets/favorites_tab.py +191 -0
  331. lightfall/ui/widgets/motor_control.py +1120 -0
  332. lightfall/ui/widgets/observers/__init__.py +8 -0
  333. lightfall/ui/widgets/observers/camera.py +48 -0
  334. lightfall/ui/widgets/observers/image_view.py +130 -0
  335. lightfall/ui/widgets/plan_config.py +954 -0
  336. lightfall/ui/widgets/plan_edit_dialog.py +294 -0
  337. lightfall/ui/widgets/plan_selector.py +452 -0
  338. lightfall/ui/widgets/profile_avatar.py +128 -0
  339. lightfall/ui/widgets/queue_view.py +647 -0
  340. lightfall/ui/widgets/runengine_control.py +549 -0
  341. lightfall/ui/widgets/signal_control.py +793 -0
  342. lightfall/ui/widgets/skill_trigger_button.py +183 -0
  343. lightfall/ui/widgets/tiled_filter_widget.py +314 -0
  344. lightfall/ui/widgets/tiled_status.py +149 -0
  345. lightfall/ui/widgets/warning_banner.py +185 -0
  346. lightfall/utils/__init__.py +53 -0
  347. lightfall/utils/crash_diagnostics.py +454 -0
  348. lightfall/utils/data_migration.py +22 -0
  349. lightfall/utils/editor_launcher.py +594 -0
  350. lightfall/utils/error_collector.py +245 -0
  351. lightfall/utils/git_tracker.py +197 -0
  352. lightfall/utils/log_buffer.py +233 -0
  353. lightfall/utils/logging.py +229 -0
  354. lightfall/utils/module_resolver.py +70 -0
  355. lightfall/utils/sentry.py +722 -0
  356. lightfall/utils/threads.py +991 -0
  357. lightfall/utils/tiled_helpers.py +96 -0
  358. lightfall/visualization/__init__.py +50 -0
  359. lightfall/visualization/base.py +5 -0
  360. lightfall/visualization/base_visualization.py +74 -0
  361. lightfall/visualization/fitting/__init__.py +24 -0
  362. lightfall/visualization/fitting/base.py +267 -0
  363. lightfall/visualization/fitting/fitters.py +325 -0
  364. lightfall/visualization/fitting/panel.py +265 -0
  365. lightfall/visualization/memory.py +392 -0
  366. lightfall/visualization/motor_mixin.py +524 -0
  367. lightfall/visualization/pg.py +156 -0
  368. lightfall/visualization/registry.py +144 -0
  369. lightfall/visualization/spec.py +79 -0
  370. lightfall/visualization/theme.py +266 -0
  371. lightfall/visualization/widgets/__init__.py +28 -0
  372. lightfall/visualization/widgets/adaptive/__init__.py +1 -0
  373. lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
  374. lightfall/visualization/widgets/adaptive/plot.py +233 -0
  375. lightfall/visualization/widgets/heatmap.py +264 -0
  376. lightfall/visualization/widgets/image_stack.py +316 -0
  377. lightfall/visualization/widgets/image_view_toolbar.py +227 -0
  378. lightfall/visualization/widgets/lazy_image_view.py +590 -0
  379. lightfall/visualization/widgets/plot_1d.py +262 -0
  380. lightfall/visualization/widgets/scatter.py +247 -0
  381. lightfall/visualization/widgets/table.py +221 -0
  382. lightfall/visualization/widgets/time_axis.py +93 -0
  383. lightfall-0.1.1.dist-info/METADATA +223 -0
  384. lightfall-0.1.1.dist-info/RECORD +388 -0
  385. lightfall-0.1.1.dist-info/WHEEL +4 -0
  386. lightfall-0.1.1.dist-info/entry_points.txt +6 -0
  387. lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
  388. lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
@@ -0,0 +1,986 @@
1
+ """Happi device backend.
2
+
3
+ This backend loads devices from a Happi database (JSON file or other
4
+ Happi-supported backends). Happi is the standard device metadata store
5
+ used at LCLS and other photon science facilities.
6
+
7
+ See: https://github.com/pcdshub/happi
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib
13
+ import json
14
+ import os
15
+ import threading
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from typing import Any
19
+ from uuid import UUID
20
+
21
+ from loguru import logger
22
+
23
+ from lightfall.devices.base import DeviceBackend
24
+ from lightfall.devices.model import (
25
+ ConnectionType,
26
+ DeviceCategory,
27
+ DeviceConfiguration,
28
+ DeviceInfo,
29
+ DeviceState,
30
+ DeviceStatus,
31
+ MaintenanceRecord,
32
+ )
33
+
34
+ # Mapping from ophyd base class names to DeviceCategory.
35
+ # Checked via MRO introspection — no string matching on user class names.
36
+ # Order matters: first match wins (more specific classes should come first).
37
+ _BASE_CLASS_CATEGORY_MAP: list[tuple[str, str, DeviceCategory]] = [
38
+ # (module, class_name, category)
39
+ # Order matters: first match wins (more specific classes first).
40
+ # Positioner-based classes → Motor (physical read/write)
41
+ ("ophyd", "MotorBundle", DeviceCategory.MOTOR),
42
+ ("ophyd.epics_motor", "EpicsMotor", DeviceCategory.MOTOR),
43
+ ("ophyd.positioner", "PositionerBase", DeviceCategory.MOTOR),
44
+ # Area detectors and signals → Detector (measures something)
45
+ ("ophyd.areadetector.detectors", "DetectorBase", DeviceCategory.DETECTOR),
46
+ ("ophyd.mca", "EpicsMCA", DeviceCategory.DETECTOR),
47
+ ("ophyd.signal", "Signal", DeviceCategory.DETECTOR),
48
+ ]
49
+
50
+ # Fallback: happi functional_group / item type keywords
51
+ _HAPPI_NATIVE_KEYS = {
52
+ "name", "device_class", "active", "args", "kwargs", "type",
53
+ "prefix", "beamline", "documentation",
54
+ }
55
+
56
+ _FUNC_GROUP_CATEGORY_MAP: dict[str, DeviceCategory] = {
57
+ "motor": DeviceCategory.MOTOR,
58
+ "positioner": DeviceCategory.MOTOR,
59
+ "slit": DeviceCategory.MOTOR,
60
+ "detector": DeviceCategory.DETECTOR,
61
+ "areadetector": DeviceCategory.DETECTOR,
62
+ "signal": DeviceCategory.DETECTOR,
63
+ "sensor": DeviceCategory.DETECTOR,
64
+ "diode": DeviceCategory.DETECTOR,
65
+ }
66
+
67
+
68
+ def _resolve_class(device_class: str) -> type | None:
69
+ """Import and return the device class without instantiating it.
70
+
71
+ Args:
72
+ device_class: Dotted import path, e.g. "ophyd.EpicsMotor"
73
+ or "my_pkg.devices.MyDetector".
74
+
75
+ Returns:
76
+ The class object, or None if import fails.
77
+ """
78
+ if not device_class or "." not in device_class:
79
+ return None
80
+
81
+ module_path, _, class_name = device_class.rpartition(".")
82
+ if not module_path or not class_name:
83
+ return None
84
+
85
+ try:
86
+ module = importlib.import_module(module_path)
87
+ return getattr(module, class_name, None)
88
+ except Exception:
89
+ return None
90
+
91
+
92
+ def _guess_category_from_mro(cls: type) -> DeviceCategory | None:
93
+ """Determine device category by inspecting the class MRO.
94
+
95
+ Walks the method resolution order and checks against known ophyd
96
+ base classes. This works for any device class across any plugin
97
+ repo without needing to know specific class names.
98
+ """
99
+ mro_keys = {(c.__module__, c.__name__) for c in cls.__mro__}
100
+ for module, class_name, category in _BASE_CLASS_CATEGORY_MAP:
101
+ if (module, class_name) in mro_keys:
102
+ return category
103
+ return None
104
+
105
+
106
+ def _guess_category(item: Any) -> DeviceCategory:
107
+ """Determine device category from happi item metadata.
108
+
109
+ Strategy (in order):
110
+ 1. Import the device class and inspect its MRO for known ophyd
111
+ base classes (works for any plugin without string matching).
112
+ 2. Fall back to happi functional_group keyword matching.
113
+ """
114
+ device_class = getattr(item, "device_class", "") or ""
115
+
116
+ # Try MRO-based introspection first
117
+ cls = _resolve_class(device_class)
118
+ if cls is not None:
119
+ cat = _guess_category_from_mro(cls)
120
+ if cat is not None:
121
+ return cat
122
+
123
+ # Fallback: check functional_group keywords
124
+ func_group = (getattr(item, "functional_group", "") or "").lower()
125
+ for key, cat in _FUNC_GROUP_CATEGORY_MAP.items():
126
+ if key in func_group:
127
+ return cat
128
+
129
+ return DeviceCategory.CONTROLLER
130
+
131
+
132
+ def _guess_connection_type(item: Any) -> ConnectionType:
133
+ """Guess connection type from happi item."""
134
+ prefix = getattr(item, "prefix", "") or ""
135
+ device_class = getattr(item, "device_class", "") or ""
136
+
137
+ if "epics" in device_class.lower() or prefix:
138
+ return ConnectionType.EPICS
139
+ return ConnectionType.OTHER
140
+
141
+
142
+ class HappiBackend(DeviceBackend):
143
+ """Device backend that reads from a Happi database.
144
+
145
+ Supports JSON file backends (default) and any backend happi supports.
146
+ Devices are loaded from happi and optionally instantiated as ophyd objects.
147
+
148
+ Instantiation modes:
149
+ - "none": Load metadata only, no ophyd devices (fastest startup)
150
+ - "blocking": Instantiate ophyd devices synchronously on connect()
151
+ - "background": Load metadata immediately, instantiate in background threads
152
+
153
+ Example:
154
+ >>> backend = HappiBackend(path="/path/to/happi.json", instantiate="background")
155
+ >>> backend.connect()
156
+ >>> devices = backend.list_devices() # Available immediately
157
+ >>> # Devices connect in background, DeviceConnectionManager emits signals
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ path: str | None = None,
163
+ beamline: str | None = None,
164
+ instantiate: bool | str = False,
165
+ connection_timeout: float | None = None,
166
+ ) -> None:
167
+ """Initialize the Happi backend.
168
+
169
+ Args:
170
+ path: Path to a happi JSON database file. If None, uses
171
+ the HAPPI_BACKEND environment variable / happi defaults.
172
+ beamline: Beamline identifier for device metadata filtering.
173
+ instantiate: Device instantiation mode:
174
+ - False or "none": Metadata only (no ophyd devices)
175
+ - True or "blocking": Synchronous instantiation on connect()
176
+ - "background": Async instantiation via DeviceConnectionManager
177
+ connection_timeout: Timeout for device connections in seconds.
178
+ Only used for "background" mode. If None, uses the
179
+ DeviceConnectionManager's default timeout.
180
+ """
181
+ self._path = path
182
+ self._beamline = beamline
183
+ self._connection_timeout = connection_timeout
184
+
185
+ # Normalize instantiate parameter
186
+ if instantiate is False or instantiate == "none":
187
+ self._instantiate_mode = "none"
188
+ elif instantiate is True or instantiate == "blocking":
189
+ self._instantiate_mode = "blocking"
190
+ elif instantiate == "background":
191
+ self._instantiate_mode = "background"
192
+ else:
193
+ logger.warning(
194
+ "Unknown instantiate mode '{}', defaulting to 'none'",
195
+ instantiate,
196
+ )
197
+ self._instantiate_mode = "none"
198
+ self._instantiate = instantiate
199
+
200
+ self._client: Any = None # happi.Client
201
+ self._devices: dict[UUID, DeviceInfo] = {}
202
+ self._configurations: dict[UUID, list[DeviceConfiguration]] = {}
203
+ self._maintenance: dict[UUID, list[MaintenanceRecord]] = {}
204
+ self._connected = False
205
+
206
+ @property
207
+ def name(self) -> str:
208
+ return "happi"
209
+
210
+ @property
211
+ def is_connected(self) -> bool:
212
+ return self._connected
213
+
214
+ @property
215
+ def path(self) -> str | None:
216
+ return self._path
217
+
218
+ @property
219
+ def is_editable(self) -> bool:
220
+ return True
221
+
222
+ def connect(self) -> bool:
223
+ """Connect to the happi database and load devices."""
224
+ logger.info("HappiBackend.connect() START (instantiate={})", self._instantiate_mode)
225
+ if self._connected:
226
+ return True
227
+
228
+ try:
229
+ import happi
230
+ except ImportError:
231
+ logger.error("happi package not installed. Install with: pip install lightfall[happi]")
232
+ return False
233
+
234
+ try:
235
+ # Auto-init: create the JSON file if it doesn't exist
236
+ if self._path:
237
+ db_path = Path(self._path)
238
+ if not db_path.exists():
239
+ db_path.parent.mkdir(parents=True, exist_ok=True)
240
+ db_path.write_text(json.dumps({}))
241
+ logger.info("Created new happi JSON database at {}", self._path)
242
+ # Toast notification (fire-and-forget)
243
+ try:
244
+ from lightfall.ui.toast import ToastManager
245
+ ToastManager.get_instance().info(
246
+ "Device database",
247
+ f"Created new device database at {self._path}",
248
+ )
249
+ except Exception:
250
+ pass # Notification is best-effort
251
+
252
+ if self._path:
253
+ from happi.backends.json_db import JSONBackend
254
+
255
+ db = JSONBackend(self._path)
256
+ self._client = happi.Client(database=db)
257
+ else:
258
+ # Use default happi config (env vars, etc.)
259
+ self._client = happi.Client.from_config()
260
+
261
+ self._discover_devices()
262
+ self._connected = True
263
+ logger.info(
264
+ "Happi backend connected ({} devices from {}, mode={})",
265
+ len(self._devices),
266
+ self._path or "default config",
267
+ self._instantiate_mode,
268
+ )
269
+
270
+ # Start background connections if in background mode
271
+ if self._instantiate_mode == "background":
272
+ self._start_background_connections()
273
+
274
+ logger.info("HappiBackend.connect() END")
275
+ return True
276
+
277
+ except Exception as e:
278
+ logger.error("Failed to connect Happi backend: {}", e)
279
+ self._client = None
280
+ return False
281
+
282
+ def disconnect(self) -> None:
283
+ self._client = None
284
+ self._devices.clear()
285
+ self._configurations.clear()
286
+ self._maintenance.clear()
287
+ self._connected = False
288
+ logger.info("Happi backend disconnected")
289
+
290
+ def _discover_devices(self) -> None:
291
+ """Load all devices from the happi client."""
292
+ if self._client is None:
293
+ return
294
+
295
+ for result in self._client.search():
296
+ try:
297
+ self._add_device_from_result(result)
298
+ except Exception as e:
299
+ name = getattr(result, "name", "?")
300
+ logger.warning("Failed to load happi device '{}': {}", name, e)
301
+
302
+ def _start_background_connections(self) -> None:
303
+ """Start background connections for all devices with pending happi results."""
304
+ import importlib
305
+
306
+ from lightfall.devices.connection_manager import DeviceConnectionManager
307
+
308
+ manager = DeviceConnectionManager.get_instance()
309
+
310
+ # Connect the manager's signals to update our device cache
311
+ manager.device_connected.connect(self._on_device_connected)
312
+ manager.device_failed.connect(self._on_device_failed)
313
+
314
+ # Collect devices that need connection
315
+ to_connect: list[tuple[DeviceInfo, Any]] = []
316
+ for device in self._devices.values():
317
+ if not device.active:
318
+ continue
319
+ happi_result = device.metadata.pop("_happi_result", None)
320
+ if happi_result is not None:
321
+ to_connect.append((device, happi_result))
322
+
323
+ if to_connect:
324
+ # Pre-import all device classes on the main thread to avoid
325
+ # import lock deadlocks when multiple background threads try
326
+ # to import from the same package simultaneously.
327
+ seen_modules: set[str] = set()
328
+ for device, _happi_result in to_connect:
329
+ device_class = device.device_class or ""
330
+ if "." in device_class:
331
+ module_path = device_class.rsplit(".", 1)[0]
332
+ if module_path not in seen_modules:
333
+ seen_modules.add(module_path)
334
+ try:
335
+ importlib.import_module(module_path)
336
+ logger.debug("Pre-imported device module: {}", module_path)
337
+ except Exception as e:
338
+ logger.warning(
339
+ "Failed to pre-import device module '{}': {}",
340
+ module_path,
341
+ e,
342
+ )
343
+
344
+ logger.info(
345
+ "Starting background connection for {} happi devices",
346
+ len(to_connect),
347
+ )
348
+ manager.connect_all_phased(to_connect, timeout=self._connection_timeout)
349
+
350
+ def _on_device_connected(self, result: Any) -> None:
351
+ """Handle successful device connection from ConnectionManager."""
352
+ from lightfall.devices.connection_manager import ConnectionResult
353
+
354
+ if not isinstance(result, ConnectionResult):
355
+ return
356
+
357
+ device = self._devices.get(result.device_id)
358
+ if device is None:
359
+ return
360
+
361
+ if not device.active:
362
+ device._state = DeviceState(
363
+ device_id=device.id,
364
+ status=DeviceStatus.INACTIVE,
365
+ connected=False,
366
+ )
367
+ logger.debug("Device '{}' is inactive, skipping connection", device.name)
368
+ return
369
+
370
+ # Update the device with the ophyd instance
371
+ device._ophyd_device = result.ophyd_device
372
+ device._state = DeviceState(
373
+ device_id=device.id,
374
+ status=DeviceStatus.ONLINE,
375
+ connected=True,
376
+ )
377
+ logger.debug("Happi device '{}' connected", device.name)
378
+
379
+ def _on_device_failed(self, result: Any) -> None:
380
+ """Handle failed device connection from ConnectionManager."""
381
+ from lightfall.devices.connection_manager import ConnectionResult, ConnectionState
382
+
383
+ if not isinstance(result, ConnectionResult):
384
+ return
385
+
386
+ device = self._devices.get(result.device_id)
387
+ if device is None:
388
+ return
389
+
390
+ # When CA tunnel is active, keep devices in CONNECTING state on
391
+ # first failure — the auto-retry cycle will try again. Only mark
392
+ # as OFFLINE after retries give up (via reconnect_failed_devices).
393
+ ca_tunnel_active = os.environ.get("EPICS_CA_ADDR_LIST", "") != ""
394
+ if ca_tunnel_active and device.name not in self._permanently_failed:
395
+ device._state = DeviceState(
396
+ device_id=device.id,
397
+ status=DeviceStatus.CONNECTING,
398
+ connected=False,
399
+ )
400
+ logger.debug(
401
+ "Happi device '{}' initial connection failed, will retry: {}",
402
+ device.name,
403
+ result.error,
404
+ )
405
+ return
406
+
407
+ # No tunnel or permanently failed — mark offline/error
408
+ if result.state == ConnectionState.TIMEOUT:
409
+ status = DeviceStatus.OFFLINE
410
+ else:
411
+ status = DeviceStatus.ERROR
412
+
413
+ device._state = DeviceState(
414
+ device_id=device.id,
415
+ status=status,
416
+ connected=False,
417
+ )
418
+ logger.debug(
419
+ "Happi device '{}' connection failed: {}",
420
+ device.name,
421
+ result.error,
422
+ )
423
+
424
+ def _add_device_from_result(self, result: Any) -> None:
425
+ """Create DeviceInfo from a happi SearchResult."""
426
+ item = result.item if hasattr(result, "item") else result
427
+
428
+ item_name = getattr(item, "name", str(item))
429
+ device_class = getattr(item, "device_class", "") or ""
430
+ beamline = getattr(item, "beamline", self._beamline) or self._beamline or ""
431
+ location = getattr(item, "location_group", "") or ""
432
+ func_group = getattr(item, "functional_group", "") or ""
433
+
434
+ # Filter by beamline if configured
435
+ if self._beamline and beamline and beamline != self._beamline:
436
+ return
437
+
438
+ category = _guess_category(item)
439
+ connection_type = _guess_connection_type(item)
440
+
441
+ # Build tags
442
+ tags = ["happi"]
443
+ if func_group:
444
+ tags.append(func_group.lower())
445
+
446
+ # Collect all happi metadata
447
+ metadata: dict[str, Any] = {}
448
+ if hasattr(item, "post"):
449
+ # Happi item — extract all fields
450
+ for field in item.info_names:
451
+ try:
452
+ metadata[field] = getattr(item, field, None)
453
+ except Exception:
454
+ pass
455
+ elif isinstance(item, dict):
456
+ metadata = dict(item)
457
+
458
+ # Read Lightfall-specific fields from extraneous or metadata
459
+ extraneous = getattr(item, "extraneous", {}) or {}
460
+ # prefix may be a native happi field OR stored in extraneous (Lightfall write-through)
461
+ prefix = getattr(item, "prefix", "") or extraneous.get("prefix", "") or ""
462
+ display_name = extraneous.get("display_name", "") or metadata.get("display_name", "") or ""
463
+ icon_override = extraneous.get("icon_override", "") or metadata.get("icon_override", "") or ""
464
+ group = extraneous.get("group", "") or metadata.get("group", "") or ""
465
+ active = getattr(item, "active", True)
466
+ # Handle string "True"/"False" from JSON
467
+ if isinstance(active, str):
468
+ active = active.lower() != "false"
469
+
470
+ device_info = DeviceInfo(
471
+ name=item_name,
472
+ description=f"Happi: {device_class}" if device_class else f"Happi device: {item_name}",
473
+ category=category,
474
+ device_class=device_class,
475
+ connection_type=connection_type,
476
+ prefix=prefix,
477
+ beamline=beamline,
478
+ location=location,
479
+ tags=tags,
480
+ metadata=metadata,
481
+ display_name=display_name,
482
+ icon_override=icon_override,
483
+ group=group,
484
+ active=active,
485
+ )
486
+
487
+ # Inactive devices: do NOT instantiate or queue for connection
488
+ if not device_info.active:
489
+ device_info._state = DeviceState(
490
+ device_id=device_info.id,
491
+ status=DeviceStatus.INACTIVE,
492
+ connected=False,
493
+ )
494
+ elif self._instantiate_mode == "blocking":
495
+ # Synchronous instantiation (original behavior)
496
+ try:
497
+ ophyd_device = result.get() if hasattr(result, "get") else None
498
+ if ophyd_device is not None:
499
+ device_info._ophyd_device = ophyd_device
500
+ except Exception as e:
501
+ logger.debug("Could not instantiate '{}': {}", item_name, e)
502
+
503
+ # Set state based on connection result
504
+ device_info._state = DeviceState(
505
+ device_id=device_info.id,
506
+ status=DeviceStatus.ONLINE if device_info._ophyd_device else DeviceStatus.UNKNOWN,
507
+ connected=device_info._ophyd_device is not None,
508
+ )
509
+
510
+ elif self._instantiate_mode == "background":
511
+ # Queue for background connection
512
+ device_info._state = DeviceState(
513
+ device_id=device_info.id,
514
+ status=DeviceStatus.CONNECTING,
515
+ connected=False,
516
+ )
517
+ # Store the happi result for later connection
518
+ device_info.metadata["_happi_result"] = result
519
+
520
+ else:
521
+ # "none" mode — metadata only
522
+ device_info._state = DeviceState(
523
+ device_id=device_info.id,
524
+ status=DeviceStatus.UNKNOWN,
525
+ connected=False,
526
+ )
527
+
528
+ self._devices[device_info.id] = device_info
529
+ self._configurations[device_info.id] = []
530
+ self._maintenance[device_info.id] = []
531
+
532
+ _reconnect_lock = threading.Lock()
533
+ _permanently_failed: set[str] = set() # Device names that failed 3+ times
534
+
535
+ def reconnect_failed_devices(
536
+ self,
537
+ timeout: float = 5.0,
538
+ callback: Any = None,
539
+ ) -> tuple[int, int]:
540
+ """Reconnect devices that failed their initial connection.
541
+
542
+ Goes back to the happi client to re-instantiate ophyd devices.
543
+ This works even after the initial happi_result has been consumed.
544
+
545
+ Uses a lock to prevent concurrent reconnection attempts.
546
+ Tracks devices that consistently fail and skips them.
547
+
548
+ Args:
549
+ timeout: Per-device connection timeout in seconds.
550
+ callback: Optional callable(device_name, success) for progress.
551
+
552
+ Returns:
553
+ Tuple of (connected_count, failed_count).
554
+ """
555
+ if not self._reconnect_lock.acquire(blocking=False):
556
+ logger.debug("Reconnect already in progress, skipping")
557
+ return (0, 0)
558
+
559
+ try:
560
+ return self._do_reconnect(timeout, callback)
561
+ finally:
562
+ self._reconnect_lock.release()
563
+
564
+ def _do_reconnect(
565
+ self, timeout: float, callback: Any
566
+ ) -> tuple[int, int]:
567
+ from concurrent.futures import ThreadPoolExecutor, as_completed
568
+
569
+ if self._client is None:
570
+ logger.warning("Cannot reconnect: happi client not available")
571
+ return (0, 0)
572
+
573
+ # Track per-device failure counts
574
+ if not hasattr(self, "_fail_counts"):
575
+ self._fail_counts: dict[str, int] = {}
576
+
577
+ # Collect devices that need reconnection
578
+ to_reconnect = []
579
+ for device in list(self._devices.values()):
580
+ if not device.active:
581
+ continue
582
+ if device._ophyd_device is not None:
583
+ continue
584
+ if device._state and device._state.connected:
585
+ continue
586
+ if device.name in self._permanently_failed:
587
+ continue
588
+ to_reconnect.append(device)
589
+
590
+ if not to_reconnect:
591
+ return (0, 0)
592
+
593
+ def _connect_one(device: DeviceInfo) -> tuple[DeviceInfo, bool]:
594
+ """Try to connect a single device. Runs in thread pool."""
595
+ try:
596
+ results = self._client.search(name=device.name)
597
+ if not results:
598
+ return (device, False)
599
+ obj = results[0].get()
600
+ obj.wait_for_connection(timeout=timeout)
601
+ if obj.connected:
602
+ device._ophyd_device = obj
603
+ device._state = DeviceState(
604
+ device_id=device.id,
605
+ status=DeviceStatus.ONLINE,
606
+ connected=True,
607
+ )
608
+ return (device, True)
609
+ return (device, False)
610
+ except Exception:
611
+ return (device, False)
612
+
613
+ connected = 0
614
+ failed = 0
615
+
616
+ # Run connections in parallel (max 10 threads to avoid overwhelming)
617
+ with ThreadPoolExecutor(max_workers=10, thread_name_prefix="reconnect") as pool:
618
+ futures = {pool.submit(_connect_one, dev): dev for dev in to_reconnect}
619
+ for future in as_completed(futures):
620
+ device, success = future.result()
621
+ if success:
622
+ connected += 1
623
+ self._fail_counts.pop(device.name, None)
624
+ logger.debug("Reconnected device '{}'", device.name)
625
+ if callback:
626
+ callback(device.name, True)
627
+ else:
628
+ failed += 1
629
+ count = self._fail_counts.get(device.name, 0) + 1
630
+ self._fail_counts[device.name] = count
631
+ if count >= 3:
632
+ self._permanently_failed.add(device.name)
633
+ device._state = DeviceState(
634
+ device_id=device.id,
635
+ status=DeviceStatus.OFFLINE,
636
+ connected=False,
637
+ )
638
+ logger.debug("Device '{}' failed {} times, marking offline", device.name, count)
639
+ if callback:
640
+ callback(device.name, False)
641
+
642
+ logger.info(
643
+ "Device reconnection: {} connected, {} failed, {} permanently skipped",
644
+ connected, failed, len(self._permanently_failed),
645
+ )
646
+ return (connected, failed)
647
+
648
+ def reset_failed_devices(self) -> None:
649
+ """Clear the permanently failed device list, allowing retries."""
650
+ self._permanently_failed.clear()
651
+ if hasattr(self, "_fail_counts"):
652
+ self._fail_counts.clear()
653
+ logger.info("Reset failed device tracking")
654
+
655
+ def reload(self) -> bool:
656
+ """Re-read the happi database to pick up out-of-band edits.
657
+
658
+ Recreates the happi client (the JSON backend caches the
659
+ deserialized payload), then re-discovers devices. Runtime
660
+ state — live ophyd instances, status, and the persistent
661
+ DeviceInfo.id — is preserved for devices whose name is still
662
+ present after the reload, so model lookups and active
663
+ connections survive.
664
+
665
+ Returns:
666
+ True if the reload succeeded.
667
+ """
668
+ if not self._connected:
669
+ return False
670
+
671
+ try:
672
+ import happi as _happi
673
+ from happi.backends.json_db import JSONBackend
674
+ except ImportError:
675
+ return False
676
+
677
+ try:
678
+ if self._path:
679
+ db = JSONBackend(self._path)
680
+ self._client = _happi.Client(database=db)
681
+ else:
682
+ self._client = _happi.Client.from_config()
683
+ except Exception as e:
684
+ logger.error("Failed to reload happi client: {}", e)
685
+ return False
686
+
687
+ # Snapshot existing entries by name so we can carry runtime
688
+ # state forward for devices that still exist.
689
+ old_by_name: dict[str, DeviceInfo] = {
690
+ d.name: d for d in self._devices.values()
691
+ }
692
+
693
+ self._devices.clear()
694
+ self._configurations.clear()
695
+ self._maintenance.clear()
696
+ self._discover_devices()
697
+
698
+ # Re-key new entries with the old UUIDs (and copy runtime state)
699
+ # for names that survived the reload. Anything else is genuinely
700
+ # new and keeps its fresh UUID.
701
+ preserved: dict[UUID, DeviceInfo] = {}
702
+ for new_dev in list(self._devices.values()):
703
+ old = old_by_name.get(new_dev.name)
704
+ if old is not None:
705
+ # Drop the fresh entry's id-keyed empty config/maintenance
706
+ # lists so we don't leak them under the abandoned UUID.
707
+ self._configurations.pop(new_dev.id, None)
708
+ self._maintenance.pop(new_dev.id, None)
709
+
710
+ new_dev.id = old.id
711
+ new_dev._ophyd_device = old._ophyd_device
712
+ new_dev._state = old._state
713
+ if old._ophyd_device is not None:
714
+ # Already live — don't re-queue for background connect.
715
+ new_dev.metadata.pop("_happi_result", None)
716
+ preserved[new_dev.id] = new_dev
717
+ self._configurations.setdefault(new_dev.id, [])
718
+ self._maintenance.setdefault(new_dev.id, [])
719
+
720
+ self._devices = preserved
721
+
722
+ # Reset failure tracking so a previously-broken entry that the
723
+ # user just fixed isn't stuck on the permanent-fail list.
724
+ self._permanently_failed.clear()
725
+ if hasattr(self, "_fail_counts"):
726
+ self._fail_counts.clear()
727
+
728
+ # Queue any newly-introduced (or repaired) devices for connection.
729
+ if self._instantiate_mode == "background":
730
+ self._start_background_connections()
731
+
732
+ logger.info("Reloaded happi backend: {} devices", len(self._devices))
733
+ return True
734
+
735
+ # === Device CRUD ===
736
+
737
+ def get_device(self, device_id: UUID) -> DeviceInfo | None:
738
+ return self._devices.get(device_id)
739
+
740
+ def get_device_by_name(self, name: str) -> DeviceInfo | None:
741
+ for d in self._devices.values():
742
+ if d.name == name:
743
+ return d
744
+ return None
745
+
746
+ def get_device_by_prefix(self, prefix: str) -> DeviceInfo | None:
747
+ for d in self._devices.values():
748
+ if d.prefix == prefix:
749
+ return d
750
+ return None
751
+
752
+ def list_devices(
753
+ self,
754
+ category: DeviceCategory | None = None,
755
+ beamline: str | None = None,
756
+ active_only: bool = True,
757
+ ) -> list[DeviceInfo]:
758
+ result = []
759
+ for d in self._devices.values():
760
+ if active_only and not d.active:
761
+ continue
762
+ if category and d.category != category:
763
+ continue
764
+ if beamline and d.beamline != beamline:
765
+ continue
766
+ result.append(d)
767
+ return result
768
+
769
+ def search_devices(self, query: str) -> list[DeviceInfo]:
770
+ return [d for d in self._devices.values() if d.matches_search(query)]
771
+
772
+ def add_device(self, device: DeviceInfo) -> bool:
773
+ """Add a device to the happi database and persist to JSON.
774
+
775
+ Creates a HappiItem with the device's metadata and stores
776
+ Lightfall-specific fields (display_name, icon_override, group)
777
+ in the item's extraneous dict.
778
+ """
779
+ if self._client is None:
780
+ return False
781
+
782
+ # Reject duplicates
783
+ if self.get_device_by_name(device.name) is not None:
784
+ logger.warning("Device '{}' already exists, cannot add duplicate", device.name)
785
+ return False
786
+
787
+ try:
788
+ import happi
789
+
790
+ # OphydItem (rather than the base HappiItem) seeds the entry
791
+ # with type=OphydItem and the args=["{{prefix}}"] /
792
+ # kwargs={"name": "{{name}}"} defaults required for ophyd
793
+ # instantiation. Without those, the entry loads but fails
794
+ # to construct an ophyd device.
795
+ item = happi.OphydItem(
796
+ name=device.name,
797
+ device_class=device.device_class or "ophyd.Device",
798
+ active=device.active,
799
+ )
800
+ # Set prefix and beamline as native happi attributes when
801
+ # supported (e.g. OphydItem subclasses). Always write through
802
+ # to extraneous so the value persists with HappiItem too.
803
+ for attr in ("prefix", "beamline"):
804
+ value = getattr(device, attr, "") or ""
805
+ try:
806
+ setattr(item, attr, value)
807
+ except Exception:
808
+ pass
809
+ item.extraneous[attr] = value
810
+ # Store Lightfall-specific fields as extraneous metadata
811
+ if device.display_name:
812
+ item.extraneous["display_name"] = device.display_name
813
+ if device.icon_override:
814
+ item.extraneous["icon_override"] = device.icon_override
815
+ if device.group:
816
+ item.extraneous["group"] = device.group
817
+ if device.location:
818
+ item.extraneous["location"] = device.location
819
+ # Sync extra metadata, skipping happi native keys
820
+ for key, value in device.metadata.items():
821
+ if key.startswith("_") or key in _HAPPI_NATIVE_KEYS:
822
+ continue
823
+ item.extraneous[key] = value
824
+
825
+ self._client.add_item(item)
826
+
827
+ # Add to in-memory cache
828
+ self._devices[device.id] = device
829
+ self._configurations[device.id] = []
830
+ self._maintenance[device.id] = []
831
+
832
+ logger.info("Added device '{}' to happi backend", device.name)
833
+ return True
834
+
835
+ except Exception as e:
836
+ logger.error("Failed to add device '{}': {}", device.name, e)
837
+ return False
838
+
839
+ def update_device(self, device: DeviceInfo) -> bool:
840
+ """Update a device in the happi database with write-through to JSON."""
841
+ if device.id not in self._devices:
842
+ return False
843
+ if self._client is None:
844
+ return False
845
+
846
+ try:
847
+ results = self._client.search(name=device.name)
848
+ if not results:
849
+ logger.warning("Device '{}' not found in happi for update", device.name)
850
+ return False
851
+
852
+ item = results[0].item
853
+
854
+ # Update standard happi fields
855
+ item.device_class = device.device_class or "ophyd.Device"
856
+ item.active = device.active
857
+
858
+ # Set prefix and beamline as native happi attributes when
859
+ # supported (e.g. OphydItem subclasses). Always write through
860
+ # to extraneous so the value persists with HappiItem too.
861
+ for attr in ("prefix", "beamline"):
862
+ value = getattr(device, attr, "") or ""
863
+ try:
864
+ setattr(item, attr, value)
865
+ except Exception:
866
+ pass
867
+ item.extraneous[attr] = value
868
+
869
+ # Lightfall-specific fields in extraneous
870
+ item.extraneous["display_name"] = device.display_name or ""
871
+ item.extraneous["icon_override"] = device.icon_override or ""
872
+ item.extraneous["group"] = device.group or ""
873
+ item.extraneous["location"] = device.location or ""
874
+
875
+ # Sync extra metadata (skip internal and happi native keys)
876
+ for key, value in device.metadata.items():
877
+ if key.startswith("_") or key in _HAPPI_NATIVE_KEYS:
878
+ continue
879
+ item.extraneous[key] = value
880
+
881
+ item.save()
882
+
883
+ # Update in-memory cache
884
+ device.modified = datetime.now()
885
+ self._devices[device.id] = device
886
+
887
+ logger.info("Updated device '{}' in happi backend", device.name)
888
+ return True
889
+
890
+ except Exception as e:
891
+ logger.error("Failed to update device '{}': {}", device.name, e)
892
+ return False
893
+
894
+ def remove_device(self, device_id: UUID) -> bool:
895
+ """Remove a device from the happi database and JSON file."""
896
+ if self._client is None:
897
+ return False
898
+
899
+ device = self._devices.get(device_id)
900
+ if device is None:
901
+ return False
902
+
903
+ try:
904
+ results = self._client.search(name=device.name)
905
+ if not results:
906
+ logger.warning("Device '{}' not found in happi for removal", device.name)
907
+ return False
908
+ self._client.remove_item(results[0].item)
909
+
910
+ # Remove from in-memory caches
911
+ del self._devices[device_id]
912
+ self._configurations.pop(device_id, None)
913
+ self._maintenance.pop(device_id, None)
914
+
915
+ logger.info("Removed device '{}' from happi backend", device.name)
916
+ return True
917
+
918
+ except Exception as e:
919
+ logger.error("Failed to remove device '{}': {}", device.name, e)
920
+ return False
921
+
922
+ # === Configuration ===
923
+
924
+ def get_device_configurations(self, device_id: UUID) -> list[DeviceConfiguration]:
925
+ return self._configurations.get(device_id, [])
926
+
927
+ def get_configuration(self, device_id: UUID, config_name: str) -> DeviceConfiguration | None:
928
+ for c in self._configurations.get(device_id, []):
929
+ if c.name == config_name:
930
+ return c
931
+ return None
932
+
933
+ def save_configuration(self, config: DeviceConfiguration) -> bool:
934
+ if config.device_id is None or config.device_id not in self._configurations:
935
+ return False
936
+ configs = self._configurations[config.device_id]
937
+ for i, existing in enumerate(configs):
938
+ if existing.name == config.name:
939
+ configs[i] = config
940
+ return True
941
+ configs.append(config)
942
+ return True
943
+
944
+ def delete_configuration(self, config_id: UUID) -> bool:
945
+ for configs in self._configurations.values():
946
+ for i, c in enumerate(configs):
947
+ if c.id == config_id:
948
+ del configs[i]
949
+ return True
950
+ return False
951
+
952
+ # === Maintenance ===
953
+
954
+ def get_maintenance_history(self, device_id: UUID, limit: int = 100) -> list[MaintenanceRecord]:
955
+ records = self._maintenance.get(device_id, [])
956
+ records.sort(key=lambda r: r.timestamp, reverse=True)
957
+ return records[:limit]
958
+
959
+ def add_maintenance_record(self, record: MaintenanceRecord) -> bool:
960
+ if record.device_id not in self._maintenance:
961
+ self._maintenance[record.device_id] = []
962
+ self._maintenance[record.device_id].append(record)
963
+ return True
964
+
965
+ # === Introspection ===
966
+
967
+ def get_backend_info(self) -> dict[str, Any]:
968
+ # Count devices by connection state
969
+ connected_count = sum(1 for d in self._devices.values() if d._ophyd_device is not None)
970
+ connecting_count = sum(
971
+ 1
972
+ for d in self._devices.values()
973
+ if d._state and d._state.status == DeviceStatus.CONNECTING
974
+ )
975
+
976
+ return {
977
+ "name": self.name,
978
+ "connected": self.is_connected,
979
+ "device_count": len(self._devices),
980
+ "devices_connected": connected_count,
981
+ "devices_connecting": connecting_count,
982
+ "path": self._path,
983
+ "beamline": self._beamline,
984
+ "instantiate_mode": self._instantiate_mode,
985
+ "connection_timeout": self._connection_timeout,
986
+ }