thzdaq-api 0.0.6b3__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.
- thzdaq_api/__init__.py +1 -0
- thzdaq_api/analysis.py +62 -0
- thzdaq_api/approvals.py +87 -0
- thzdaq_api/assistant/agents.md +202 -0
- thzdaq_api/assistant/assistant.md +23 -0
- thzdaq_api/assistant/hints.md +15 -0
- thzdaq_api/atomic.py +79 -0
- thzdaq_api/catalog.py +131 -0
- thzdaq_api/console.py +70 -0
- thzdaq_api/custom.py +326 -0
- thzdaq_api/daemon.py +183 -0
- thzdaq_api/data.py +55 -0
- thzdaq_api/declare.py +193 -0
- thzdaq_api/declaring.py +125 -0
- thzdaq_api/devices.py +307 -0
- thzdaq_api/errors.py +47 -0
- thzdaq_api/events.py +224 -0
- thzdaq_api/examples/hot_cold.py +67 -0
- thzdaq_api/examples/hot_cold_grid.py +74 -0
- thzdaq_api/examples/iv_analysis.py +34 -0
- thzdaq_api/examples/map.py +42 -0
- thzdaq_api/examples/monitor.py +35 -0
- thzdaq_api/examples/raw_instrument.py +37 -0
- thzdaq_api/examples/sweep.py +38 -0
- thzdaq_api/examples.py +79 -0
- thzdaq_api/guides.py +61 -0
- thzdaq_api/host.py +494 -0
- thzdaq_api/interpreters.py +422 -0
- thzdaq_api/kernel.py +137 -0
- thzdaq_api/lab.py +562 -0
- thzdaq_api/lanes.py +170 -0
- thzdaq_api/leases.py +29 -0
- thzdaq_api/lock.py +65 -0
- thzdaq_api/measurement_file.py +459 -0
- thzdaq_api/measurements.py +433 -0
- thzdaq_api/operation.py +52 -0
- thzdaq_api/origins.py +86 -0
- thzdaq_api/present.py +376 -0
- thzdaq_api/procedures.py +124 -0
- thzdaq_api/raw.py +272 -0
- thzdaq_api/remote.py +267 -0
- thzdaq_api/rights.py +81 -0
- thzdaq_api/script.py +382 -0
- thzdaq_api/scripts.py +133 -0
- thzdaq_api/sessions.py +176 -0
- thzdaq_api/station.py +192 -0
- thzdaq_api/terminal.py +66 -0
- thzdaq_api/tools.py +275 -0
- thzdaq_api/transport.py +93 -0
- thzdaq_api/ui.py +152 -0
- thzdaq_api/windows.py +192 -0
- thzdaq_api/wire.py +35 -0
- thzdaq_api/workspace.py +239 -0
- thzdaq_api-0.0.6b3.dist-info/METADATA +30 -0
- thzdaq_api-0.0.6b3.dist-info/RECORD +57 -0
- thzdaq_api-0.0.6b3.dist-info/WHEEL +4 -0
- thzdaq_api-0.0.6b3.dist-info/licenses/LICENSE +21 -0
thzdaq_api/station.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""The bench's profile, the drivers a profile can use, the shared connections.
|
|
2
|
+
|
|
3
|
+
The profile travels as its YAML file holds it (version 2): instruments by id,
|
|
4
|
+
each with its driver, title, connection and the devices configured on it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, Iterable, Optional, Tuple, Union
|
|
8
|
+
|
|
9
|
+
import msgspec
|
|
10
|
+
|
|
11
|
+
from thzdaq_api.measurements import ParameterInfo
|
|
12
|
+
from thzdaq_api.operation import Operation, Rights
|
|
13
|
+
|
|
14
|
+
ConnectionKey = Tuple[Union[str, int, float, None], ...]
|
|
15
|
+
|
|
16
|
+
# Keys of the profile as it travels (StationProfile.profile)
|
|
17
|
+
INSTRUMENTS = "instruments"
|
|
18
|
+
DEVICES = "devices"
|
|
19
|
+
SETTINGS = "settings"
|
|
20
|
+
METADATA = "metadata"
|
|
21
|
+
DRIVER = "driver"
|
|
22
|
+
TITLE = "title"
|
|
23
|
+
CONNECTION = "connection"
|
|
24
|
+
SIMULATE = "simulate"
|
|
25
|
+
KIND = "kind" # of a device (sis_bias), and of a connection (socket)
|
|
26
|
+
CHANNEL = "channel"
|
|
27
|
+
SAFETY = "safety"
|
|
28
|
+
LIMITS = "limits"
|
|
29
|
+
SAFE_STATE = "safe_state"
|
|
30
|
+
HARDWARE_PROTECTION = "hardware_protection"
|
|
31
|
+
|
|
32
|
+
# DriverInfo.type of the drivers that only reach an instrument (generic.scpi):
|
|
33
|
+
# without a driver of its own it takes raw commands only
|
|
34
|
+
GENERIC = "generic"
|
|
35
|
+
|
|
36
|
+
# What declare_instrument did to the profile
|
|
37
|
+
ADDED = "added"
|
|
38
|
+
UPDATED = "updated"
|
|
39
|
+
KEPT = "kept" # the profile has it as declared: nothing changed
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class StationProfile(msgspec.Struct, frozen=True):
|
|
43
|
+
"""The profile as its YAML file holds it (version 2: instruments with their
|
|
44
|
+
devices), where it is kept, and whether the bench runs on simulators."""
|
|
45
|
+
|
|
46
|
+
name: str
|
|
47
|
+
path: Optional[str]
|
|
48
|
+
simulate: bool
|
|
49
|
+
profile: Dict[str, Any]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class DeviceKindInfo(msgspec.Struct, frozen=True):
|
|
53
|
+
"""A device a user can configure on an instrument (a SIS bias on a block)."""
|
|
54
|
+
|
|
55
|
+
key: str
|
|
56
|
+
title: str
|
|
57
|
+
settings: Tuple[ParameterInfo, ...] = ()
|
|
58
|
+
needs_channel: bool = False
|
|
59
|
+
channels: Tuple[str, ...] = () # the channels it may take
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class DriverInfo(msgspec.Struct, frozen=True):
|
|
63
|
+
key: str # what a profile names as driver
|
|
64
|
+
title: str
|
|
65
|
+
type: str # what device it is: instrument ids start with it
|
|
66
|
+
capabilities: Tuple[str, ...]
|
|
67
|
+
simulated: bool = False # a simulator of its own, no hardware
|
|
68
|
+
kinds: Tuple[DeviceKindInfo, ...] = ()
|
|
69
|
+
channels: Tuple[str, ...] = () # fixed channels: outputs of a supply
|
|
70
|
+
connection: Optional[Dict[str, Any]] = None # the recommended one
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ConnectionKindInfo(msgspec.Struct, frozen=True):
|
|
74
|
+
"""A way to reach an instrument (a TCP socket, a Prologix GPIB adapter): the
|
|
75
|
+
fields of a connection it uses, in form order, and their defaults."""
|
|
76
|
+
|
|
77
|
+
key: str
|
|
78
|
+
title: str
|
|
79
|
+
fields: Tuple[str, ...]
|
|
80
|
+
defaults: Dict[str, Any] = {}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ConnectionInfo(msgspec.Struct, frozen=True):
|
|
84
|
+
"""A connection several instruments may share (a Prologix, a socket)."""
|
|
85
|
+
|
|
86
|
+
key: ConnectionKey
|
|
87
|
+
label: str
|
|
88
|
+
instruments: Tuple[str, ...]
|
|
89
|
+
open: bool
|
|
90
|
+
broken: bool
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class GetStation(Operation[StationProfile]):
|
|
94
|
+
"""The profile of the bench: its instruments, their connections and the
|
|
95
|
+
devices configured on them."""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class LoadStation(Operation[StationProfile]):
|
|
99
|
+
"""Work with another profile: a YAML file, or a profile of the program by
|
|
100
|
+
its name (lab: stations/lab.yaml). Refused while measurements run."""
|
|
101
|
+
|
|
102
|
+
rights = Rights.STATION
|
|
103
|
+
path: str
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class NewStation(Operation[StationProfile]):
|
|
107
|
+
"""Start an empty profile in a new file (a path, or a name of the
|
|
108
|
+
program's stations/) and work with it. Refused while measurements run."""
|
|
109
|
+
|
|
110
|
+
rights = Rights.STATION
|
|
111
|
+
path: str
|
|
112
|
+
title: str
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class UpdateStation(Operation[StationProfile]):
|
|
116
|
+
"""Replace the profile with an edited one (as get_station gives it); it is
|
|
117
|
+
checked, saved and applied: only instruments whose setup changed reopen."""
|
|
118
|
+
|
|
119
|
+
rights = Rights.STATION
|
|
120
|
+
profile: Dict[str, Any]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class DeclareInstrument(Operation[str]):
|
|
124
|
+
"""An instrument a script declares (instrument(...) of thzdaq), put into
|
|
125
|
+
the profile: added when the profile has no instrument of that id, its
|
|
126
|
+
driver and connection changed when they differ; nothing changes and
|
|
127
|
+
nobody is asked when the profile has it as declared. A person allows a
|
|
128
|
+
change, agents and their scripts never change the profile; no instrument
|
|
129
|
+
is removed this way. connection: one line (tcp://169.254.0.50:5025,
|
|
130
|
+
prologix://169.254.156.103/19, serial://COM3) or its fields as the
|
|
131
|
+
profile holds them. Returns added, updated or kept."""
|
|
132
|
+
|
|
133
|
+
rights = Rights.STATION
|
|
134
|
+
instrument: str
|
|
135
|
+
driver: str
|
|
136
|
+
connection: Union[str, Dict[str, Any]]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class ListDrivers(Operation[Tuple[DriverInfo, ...]]):
|
|
140
|
+
"""Drivers a profile can name, with the devices each lets a user configure
|
|
141
|
+
and the connection it recommends."""
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ListConnectionKinds(Operation[Tuple[ConnectionKindInfo, ...]]):
|
|
145
|
+
"""The kinds of connections an instrument of the profile may use, with the
|
|
146
|
+
fields each one takes."""
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class ConnectInstrument(Operation[str]):
|
|
150
|
+
"""Open an instrument and ask who it is: returns its identity, or "opened"
|
|
151
|
+
when it cannot tell."""
|
|
152
|
+
|
|
153
|
+
instrument: str
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class GetSisCalibration(Operation[Dict[str, Any]]):
|
|
157
|
+
"""The calibration coefficients of a SIS bias as the profile keeps them, or
|
|
158
|
+
the defaults of its channel. A coefficient is a number or an arithmetic
|
|
159
|
+
expression ("5.47e-9 / 5")."""
|
|
160
|
+
|
|
161
|
+
ref: str
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class SetSisCalibration(Operation[StationProfile]):
|
|
165
|
+
"""Keep the calibration coefficients of a SIS bias in the profile; they are
|
|
166
|
+
checked first. The device's write_calibration action stores them in the
|
|
167
|
+
block."""
|
|
168
|
+
|
|
169
|
+
rights = Rights.STATION
|
|
170
|
+
ref: str
|
|
171
|
+
coefficients: Dict[str, Any]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class ListConnections(Operation[Tuple[ConnectionInfo, ...]]):
|
|
175
|
+
"""Connections the profile's instruments share, and their state."""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class ResetConnection(Operation[bool]):
|
|
179
|
+
"""Break and reopen a connection that hangs (its instruments reconnect on
|
|
180
|
+
their next command). Returns whether it was open."""
|
|
181
|
+
|
|
182
|
+
rights = Rights.SET
|
|
183
|
+
key: ConnectionKey
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def free_id(taken: Iterable[str], prefix: str) -> str:
|
|
187
|
+
"""The first id like power_supply_3 that is not taken."""
|
|
188
|
+
used = set(taken)
|
|
189
|
+
number = 1
|
|
190
|
+
while f"{prefix}_{number}" in used:
|
|
191
|
+
number += 1
|
|
192
|
+
return f"{prefix}_{number}"
|
thzdaq_api/terminal.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""A person at this terminal: whether one is there, and a line they type that
|
|
2
|
+
is given up when what it answers is answered elsewhere (in a window).
|
|
3
|
+
|
|
4
|
+
A script started by a person in their terminal asks there, as a window does,
|
|
5
|
+
what its start needs allowed; in an agent's shell nobody types, so only a
|
|
6
|
+
window answers.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
from thzdaq_api.origins import agent_shell
|
|
14
|
+
|
|
15
|
+
LOOK_S = 0.1 # how often an unanswered line looks whether it is still needed
|
|
16
|
+
ALLOW = "allow? [y/N] " # asked of the person here about what waits for one
|
|
17
|
+
YES = ("y", "yes")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def yes(typed: str) -> bool:
|
|
21
|
+
"""A typed answer is yes; anything else (Enter too) is no."""
|
|
22
|
+
return typed.strip().lower() in YES
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def person_here() -> bool:
|
|
26
|
+
"""A person types into this terminal: one is attached, no agent drives it."""
|
|
27
|
+
return sys.stdin.isatty() and not agent_shell()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def line(prompt: str, gone: threading.Event) -> Optional[str]:
|
|
31
|
+
"""The line typed after prompt; None once gone is set first."""
|
|
32
|
+
sys.stderr.write(prompt)
|
|
33
|
+
sys.stderr.flush()
|
|
34
|
+
typed = _windows_line(gone) if sys.platform == "win32" else _posix_line(gone)
|
|
35
|
+
if typed is None:
|
|
36
|
+
sys.stderr.write("\n")
|
|
37
|
+
return typed
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _posix_line(gone: threading.Event) -> Optional[str]:
|
|
41
|
+
import select
|
|
42
|
+
|
|
43
|
+
while not gone.is_set():
|
|
44
|
+
# A terminal is readable once a whole line is typed (Enter)
|
|
45
|
+
if select.select([sys.stdin], [], [], LOOK_S)[0]:
|
|
46
|
+
return sys.stdin.readline().strip()
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _windows_line(gone: threading.Event) -> Optional[str]:
|
|
51
|
+
import msvcrt
|
|
52
|
+
|
|
53
|
+
typed = []
|
|
54
|
+
while not gone.is_set():
|
|
55
|
+
if not msvcrt.kbhit():
|
|
56
|
+
gone.wait(LOOK_S)
|
|
57
|
+
continue
|
|
58
|
+
char = msvcrt.getwche()
|
|
59
|
+
if char in "\r\n":
|
|
60
|
+
sys.stderr.write("\n")
|
|
61
|
+
return "".join(typed).strip()
|
|
62
|
+
if char == "\b":
|
|
63
|
+
typed = typed[:-1]
|
|
64
|
+
else:
|
|
65
|
+
typed.append(char)
|
|
66
|
+
return None
|
thzdaq_api/tools.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""The tools of agents and of the assistant in the window: operations of the
|
|
2
|
+
catalog, each with its name, its docstring and the JSON schema of its arguments
|
|
3
|
+
(thzdaq_api.catalog), and the short text it answers with (present.py). The MCP
|
|
4
|
+
server (thzdaq-mcp) hands them to an agent, the assistant to its model: both
|
|
5
|
+
get the same set.
|
|
6
|
+
|
|
7
|
+
The set is chosen: an agent looks at the bench, sets and calls with a person's
|
|
8
|
+
consent, asks an instrument a raw query with a person's consent, runs
|
|
9
|
+
measurements and follows them, reads, checks and (with a person's consent)
|
|
10
|
+
writes the bench's own measurements, asks the person, and shows the person
|
|
11
|
+
where things are in the window (opens, fills a form, highlights). It does not edit the profile,
|
|
12
|
+
answer for a person, write raw commands or stop the daemon (those are a
|
|
13
|
+
person's, and the daemon would refuse them anyway), nor take what it cannot
|
|
14
|
+
use (polls, streams of records).
|
|
15
|
+
|
|
16
|
+
A tool is called in a thread of its own and waits as its operation does (for a
|
|
17
|
+
person, for a measurement); a client that must not wait runs it apart.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import threading
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import (
|
|
23
|
+
Any,
|
|
24
|
+
Callable,
|
|
25
|
+
Dict,
|
|
26
|
+
List,
|
|
27
|
+
Mapping,
|
|
28
|
+
Optional,
|
|
29
|
+
Tuple,
|
|
30
|
+
Type,
|
|
31
|
+
TypeVar,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
import msgspec
|
|
35
|
+
|
|
36
|
+
from thzdaq_api import (
|
|
37
|
+
approvals,
|
|
38
|
+
catalog,
|
|
39
|
+
custom,
|
|
40
|
+
daemon,
|
|
41
|
+
devices,
|
|
42
|
+
measurements,
|
|
43
|
+
present,
|
|
44
|
+
station,
|
|
45
|
+
ui,
|
|
46
|
+
wire,
|
|
47
|
+
)
|
|
48
|
+
from thzdaq_api.events import Event, MeasurementProgress
|
|
49
|
+
from thzdaq_api.lab import Lab
|
|
50
|
+
from thzdaq_api.measurement_file import RUNNING
|
|
51
|
+
from thzdaq_api.operation import Operation, Rights
|
|
52
|
+
|
|
53
|
+
R = TypeVar("R")
|
|
54
|
+
|
|
55
|
+
# How a tool tells how far it is: (done, total, message); called in the
|
|
56
|
+
# thread of the events
|
|
57
|
+
Progress = Callable[[float, Optional[float], Optional[str]], None]
|
|
58
|
+
Listener = Callable[[Event], None] # runs in the thread of the events
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Reach:
|
|
62
|
+
"""The bench as an agent reaches it: its calls, and its events heard
|
|
63
|
+
through one subscription by every tool that listens. While it lives the
|
|
64
|
+
daemon lists the agent among its clients (the kind its lab listens as)
|
|
65
|
+
and stays while the agent works."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, lab: Lab):
|
|
68
|
+
self.lab = lab
|
|
69
|
+
self._listeners: List[Listener] = []
|
|
70
|
+
self._lock = threading.Lock()
|
|
71
|
+
self._stop = lab.subscribe(self._heard)
|
|
72
|
+
|
|
73
|
+
def _heard(self, event: Event) -> None:
|
|
74
|
+
with self._lock:
|
|
75
|
+
listeners = list(self._listeners)
|
|
76
|
+
for listener in listeners:
|
|
77
|
+
listener(event)
|
|
78
|
+
|
|
79
|
+
def listen(self, listener: Listener) -> Callable[[], None]:
|
|
80
|
+
"""Hear the events from now on; returns what stops it."""
|
|
81
|
+
with self._lock:
|
|
82
|
+
self._listeners.append(listener)
|
|
83
|
+
|
|
84
|
+
def stop() -> None:
|
|
85
|
+
with self._lock:
|
|
86
|
+
self._listeners.remove(listener)
|
|
87
|
+
|
|
88
|
+
return stop
|
|
89
|
+
|
|
90
|
+
def call(self, operation: Operation[R]) -> R:
|
|
91
|
+
return self.lab.call(operation)
|
|
92
|
+
|
|
93
|
+
def close(self) -> None:
|
|
94
|
+
self._stop()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Tool:
|
|
98
|
+
"""An operation as a tool: called with its arguments, answered in text."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, operation: Type[Operation]):
|
|
101
|
+
self.operation = operation
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def name(self) -> str:
|
|
105
|
+
return self.operation.name
|
|
106
|
+
|
|
107
|
+
def description(self) -> str:
|
|
108
|
+
return catalog.description(self.operation)
|
|
109
|
+
|
|
110
|
+
def schema(self) -> Dict[str, Any]:
|
|
111
|
+
return catalog.tool_schema(self.operation)
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def reads(self) -> bool:
|
|
115
|
+
"""It changes nothing."""
|
|
116
|
+
return self.operation.rights is Rights.READ
|
|
117
|
+
|
|
118
|
+
def arguments(self, given: Mapping[str, Any]) -> Operation:
|
|
119
|
+
"""The arguments as a model or an agent gave them, checked; LabError
|
|
120
|
+
INVALID_ARGUMENTS says what is wrong."""
|
|
121
|
+
return wire.decode_arguments(self.name, wire.encode(dict(given)))
|
|
122
|
+
|
|
123
|
+
def call(self, reach: Reach, args: Operation, progress: Optional[Progress]) -> str:
|
|
124
|
+
raise NotImplementedError
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Plain(Tool):
|
|
128
|
+
"""Called once, its result told by text()."""
|
|
129
|
+
|
|
130
|
+
def __init__(self, operation: Type[Operation], text: Callable[..., str]):
|
|
131
|
+
super().__init__(operation)
|
|
132
|
+
self.text = text
|
|
133
|
+
|
|
134
|
+
def call(self, reach, args, progress):
|
|
135
|
+
return self.text(reach.call(args))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class Values(Tool):
|
|
139
|
+
"""A read or a set, answered with the units of the device's quantities."""
|
|
140
|
+
|
|
141
|
+
def call(self, reach, args, progress):
|
|
142
|
+
result = reach.call(args)
|
|
143
|
+
described = reach.call(devices.DescribeDevice(ref=result.ref))
|
|
144
|
+
found = (
|
|
145
|
+
result.values
|
|
146
|
+
if isinstance(result, devices.Reading)
|
|
147
|
+
else {result.key: result.value}
|
|
148
|
+
)
|
|
149
|
+
return present.values(result.ref, found, described)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Procedure(Tool):
|
|
153
|
+
"""A procedure with the devices of the bench that suit each slot."""
|
|
154
|
+
|
|
155
|
+
def call(self, reach, args, progress):
|
|
156
|
+
info = reach.call(args)
|
|
157
|
+
return present.procedure(info, reach.call(devices.ListDevices()))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Start(Plain):
|
|
161
|
+
"""A start goes to the agent's workspace unless it names another: the file
|
|
162
|
+
lands in its data/, next to the agent's work (with none, in the
|
|
163
|
+
program's). workspace() is asked at each start: a window's may change."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, workspace: Callable[[], Optional[Path]]):
|
|
166
|
+
super().__init__(measurements.StartMeasurement, present.run)
|
|
167
|
+
self.workspace = workspace
|
|
168
|
+
|
|
169
|
+
def call(self, reach, args, progress):
|
|
170
|
+
folder = self.workspace()
|
|
171
|
+
if args.workspace is None and folder is not None:
|
|
172
|
+
args = msgspec.structs.replace(args, workspace=str(folder))
|
|
173
|
+
return super().call(reach, args, progress)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class Wait(Tool):
|
|
177
|
+
"""Waits for a measurement to end; tells its progress meanwhile when asked
|
|
178
|
+
to, and answers with the summary of what it holds once it ended."""
|
|
179
|
+
|
|
180
|
+
def call(self, reach, args, progress):
|
|
181
|
+
now = reach.call(msgspec.structs.replace(args, timeout=0.0))
|
|
182
|
+
if now.status == RUNNING:
|
|
183
|
+
if progress is None:
|
|
184
|
+
now = reach.call(args)
|
|
185
|
+
else:
|
|
186
|
+
progress(now.done, now.total, None)
|
|
187
|
+
now = self._following(reach, args, progress)
|
|
188
|
+
if now.status == RUNNING:
|
|
189
|
+
return present.run(now)
|
|
190
|
+
return present.summary(reach.call(measurements.SummarizeMeasurement(id=now.id)))
|
|
191
|
+
|
|
192
|
+
@staticmethod
|
|
193
|
+
def _following(
|
|
194
|
+
reach: Reach, args: measurements.WaitMeasurement, progress: Progress
|
|
195
|
+
) -> measurements.RunInfo:
|
|
196
|
+
def heard(event: Event) -> None:
|
|
197
|
+
body = event.body
|
|
198
|
+
if isinstance(body, MeasurementProgress) and body.id == args.id:
|
|
199
|
+
progress(body.done, body.total, None)
|
|
200
|
+
|
|
201
|
+
stop = reach.listen(heard)
|
|
202
|
+
try:
|
|
203
|
+
return reach.call(args)
|
|
204
|
+
finally:
|
|
205
|
+
stop()
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class Shown(Tool):
|
|
209
|
+
"""Asks a window of the person (thzdaq_api.ui). The assistant of a window
|
|
210
|
+
always asks its own (window() gives its id) and its model sees no window
|
|
211
|
+
to choose; an agent beside the window asks the one it names, else the
|
|
212
|
+
one the person was at last. text(args, result) tells what was done."""
|
|
213
|
+
|
|
214
|
+
def __init__(
|
|
215
|
+
self,
|
|
216
|
+
operation: Type[Operation],
|
|
217
|
+
text: Callable[[Operation, Any], str],
|
|
218
|
+
window: Callable[[], Optional[str]],
|
|
219
|
+
):
|
|
220
|
+
super().__init__(operation)
|
|
221
|
+
self.text = text
|
|
222
|
+
self.window = window
|
|
223
|
+
|
|
224
|
+
def schema(self):
|
|
225
|
+
found = super().schema()
|
|
226
|
+
if self.window() is not None:
|
|
227
|
+
properties = dict(found["properties"])
|
|
228
|
+
properties.pop("window")
|
|
229
|
+
found = {**found, "properties": properties}
|
|
230
|
+
return found
|
|
231
|
+
|
|
232
|
+
def call(self, reach, args, progress):
|
|
233
|
+
own = self.window()
|
|
234
|
+
if own is not None:
|
|
235
|
+
args = msgspec.structs.replace(args, window=own)
|
|
236
|
+
return self.text(args, reach.call(args))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def tools(
|
|
240
|
+
workspace: Callable[[], Optional[Path]],
|
|
241
|
+
window: Callable[[], Optional[str]] = lambda: None,
|
|
242
|
+
) -> Tuple[Tool, ...]:
|
|
243
|
+
"""The tools; a measurement goes to workspace() unless named, what is
|
|
244
|
+
shown in a window to window() when it gives one (the assistant's own)."""
|
|
245
|
+
return (
|
|
246
|
+
Plain(devices.ListDevices, present.devices),
|
|
247
|
+
Plain(devices.DescribeDevice, present.description),
|
|
248
|
+
Values(devices.ReadDevice),
|
|
249
|
+
Values(devices.SetQuantity),
|
|
250
|
+
Plain(devices.CallAction, present.action_result),
|
|
251
|
+
Plain(devices.RawCommand, present.raw),
|
|
252
|
+
Plain(station.ListConnections, present.connections),
|
|
253
|
+
Plain(measurements.ListProcedures, present.procedures),
|
|
254
|
+
Procedure(measurements.DescribeProcedure),
|
|
255
|
+
Start(workspace),
|
|
256
|
+
Wait(measurements.WaitMeasurement),
|
|
257
|
+
Plain(measurements.SummarizeMeasurement, present.summary),
|
|
258
|
+
Plain(measurements.CancelMeasurement, present.run),
|
|
259
|
+
Plain(measurements.ListRuns, present.runs),
|
|
260
|
+
Plain(custom.ListCustom, present.library),
|
|
261
|
+
Plain(custom.ReadCustom, present.custom_text),
|
|
262
|
+
Plain(custom.CheckCustom, present.check),
|
|
263
|
+
Plain(custom.WriteCustom, present.check),
|
|
264
|
+
Plain(approvals.AskUser, present.answer),
|
|
265
|
+
Plain(approvals.WaitAnswer, present.answer),
|
|
266
|
+
Shown(ui.UiState, lambda args, found: present.window(found), window),
|
|
267
|
+
Shown(ui.UiOpen, lambda args, _: present.opened(args.place), window),
|
|
268
|
+
Shown(ui.UiFillMeasurement, lambda args, found: present.form(found), window),
|
|
269
|
+
Shown(ui.UiHighlight, lambda args, _: present.highlighted(args.anchor), window),
|
|
270
|
+
Plain(daemon.GetDaemonStatus, present.status),
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def by_name(found: Tuple[Tool, ...]) -> Dict[str, Tool]:
|
|
275
|
+
return {tool.name: tool for tool in found}
|
thzdaq_api/transport.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""HTTP between a client and the daemon: one request, and the frames of the
|
|
2
|
+
event stream (server-sent events). Only 127.0.0.1, only with the token."""
|
|
3
|
+
|
|
4
|
+
import http.client
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Dict, Iterator, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from thzdaq_api.errors import ErrorCode, LabError
|
|
9
|
+
|
|
10
|
+
LOCALHOST = "127.0.0.1"
|
|
11
|
+
# Headers of the contract
|
|
12
|
+
TOKEN = "Authorization"
|
|
13
|
+
ORIGIN = "X-Thzdaq-Origin" # who calls: gui, cli, mcp:<name>, assistant
|
|
14
|
+
CLIENT = "X-Thzdaq-Client" # what kind of client listens
|
|
15
|
+
PID = "X-Thzdaq-Pid"
|
|
16
|
+
WINDOW = "X-Thzdaq-Window" # the id of the main window a client is (thzdaq_api.ui)
|
|
17
|
+
SEQ = "X-Thzdaq-Seq" # the last event when an operation ended
|
|
18
|
+
LAST_EVENT = "Last-Event-ID"
|
|
19
|
+
|
|
20
|
+
HEALTH = "/health"
|
|
21
|
+
STATUS = "/status"
|
|
22
|
+
EVENTS = "/events"
|
|
23
|
+
OPERATIONS = "/ops/"
|
|
24
|
+
HEARTBEAT = "heartbeat" # the event type of the stream's heartbeats
|
|
25
|
+
JSON = "application/json" # operations, answers and failures
|
|
26
|
+
HEARTBEAT_S = 2.0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def bearer(token: str) -> str:
|
|
30
|
+
return f"Bearer {token}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def request(
|
|
34
|
+
port: int,
|
|
35
|
+
token: str,
|
|
36
|
+
method: str,
|
|
37
|
+
path: str,
|
|
38
|
+
body: Optional[bytes] = None,
|
|
39
|
+
headers: Optional[Dict[str, str]] = None,
|
|
40
|
+
timeout: Optional[float] = None,
|
|
41
|
+
) -> Tuple[int, Dict[str, str], bytes]:
|
|
42
|
+
"""(status, headers, body); LabError UNREACHABLE when nothing answers."""
|
|
43
|
+
connection = http.client.HTTPConnection(LOCALHOST, port, timeout=timeout)
|
|
44
|
+
try:
|
|
45
|
+
sent = {TOKEN: bearer(token), "Content-Type": JSON, **(headers or {})}
|
|
46
|
+
connection.request(method, path, body, sent)
|
|
47
|
+
response = connection.getresponse()
|
|
48
|
+
return response.status, dict(response.getheaders()), response.read()
|
|
49
|
+
except OSError as e:
|
|
50
|
+
raise LabError(
|
|
51
|
+
ErrorCode.UNREACHABLE,
|
|
52
|
+
f"The daemon on port {port} does not answer: {e}",
|
|
53
|
+
"is it running? connect_or_start() starts it",
|
|
54
|
+
) from None
|
|
55
|
+
finally:
|
|
56
|
+
connection.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Frame:
|
|
61
|
+
"""One message of the event stream."""
|
|
62
|
+
|
|
63
|
+
event: str = ""
|
|
64
|
+
data: str = ""
|
|
65
|
+
id: Optional[str] = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def frames(lines: Iterator[bytes]) -> Iterator[Frame]:
|
|
69
|
+
"""Frames of an event stream from its lines; comments (": ping") are skipped."""
|
|
70
|
+
frame = Frame()
|
|
71
|
+
for raw in lines:
|
|
72
|
+
line = raw.decode("utf-8").rstrip("\r\n")
|
|
73
|
+
if not line:
|
|
74
|
+
if frame.event or frame.data:
|
|
75
|
+
yield frame
|
|
76
|
+
frame = Frame()
|
|
77
|
+
elif line.startswith(":"):
|
|
78
|
+
continue
|
|
79
|
+
else:
|
|
80
|
+
field, _, value = line.partition(":")
|
|
81
|
+
value = value[1:] if value.startswith(" ") else value
|
|
82
|
+
if field == "event":
|
|
83
|
+
frame.event = value
|
|
84
|
+
elif field == "data":
|
|
85
|
+
frame.data = f"{frame.data}\n{value}" if frame.data else value
|
|
86
|
+
elif field == "id":
|
|
87
|
+
frame.id = value
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def frame(event: str, data: bytes, id: Optional[int] = None) -> bytes:
|
|
91
|
+
"""A frame as the daemon writes it; data is one line of JSON."""
|
|
92
|
+
head = f"id: {id}\n" if id is not None else ""
|
|
93
|
+
return f"{head}event: {event}\ndata: ".encode() + data + b"\n\n"
|