etho-python 0.23.0__py3-none-any.whl → 1.2__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.
- etho/app.py +235 -242
- etho/cli.py +72 -19
- etho/client.py +74 -204
- etho/res_app.py +225 -0
- etho/resumable.py +283 -0
- etho/services/BLTZeroService.py +45 -19
- etho/services/DAQZeroService.py +103 -20
- etho/services/DLPZeroService.py +46 -19
- etho/services/GCMZeroService.py +57 -16
- etho/services/GOVZeroService.py +60 -0
- etho/services/NICounterZeroService.py +57 -14
- etho/services/{NITriggerZeroService.py → ScanImageTriggerZeroService.py} +55 -26
- etho/services/TemplateZeroService.py +46 -20
- etho/services/ZeroService.py +11 -6
- etho/services/__init__.py +52 -0
- etho/services/callbacks/_trace.py +3 -98
- etho/services/dlp/dlp_runners.py +3 -15
- etho/services/resumable.py +476 -0
- etho/utils/sound.py +63 -99
- etho_python-1.2.dist-info/METADATA +148 -0
- {etho_python-0.23.0.dist-info → etho_python-1.2.dist-info}/RECORD +24 -21
- etho_python-1.2.dist-info/licenses/LICENSE +21 -0
- etho/services/ANAZeroService.py +0 -123
- etho_python-0.23.0.dist-info/METADATA +0 -229
- {etho_python-0.23.0.dist-info → etho_python-1.2.dist-info}/WHEEL +0 -0
- {etho_python-0.23.0.dist-info → etho_python-1.2.dist-info}/entry_points.txt +0 -0
etho/cli.py
CHANGED
|
@@ -36,6 +36,52 @@ def run(
|
|
|
36
36
|
debug=debug,
|
|
37
37
|
preview=preview,
|
|
38
38
|
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def res_run(
|
|
42
|
+
protocolfile: str,
|
|
43
|
+
playlistfile: Optional[str] = None,
|
|
44
|
+
*,
|
|
45
|
+
save_prefix: Optional[str] = None,
|
|
46
|
+
show_progress: bool = True,
|
|
47
|
+
debug: bool = False,
|
|
48
|
+
preview: bool = False,
|
|
49
|
+
):
|
|
50
|
+
"""Starts a resumable DAQ/GCM experiment from the CLI."""
|
|
51
|
+
from . import resumable
|
|
52
|
+
|
|
53
|
+
return resumable.run(
|
|
54
|
+
protocolfile=protocolfile,
|
|
55
|
+
playlistfile=playlistfile,
|
|
56
|
+
save_prefix=save_prefix,
|
|
57
|
+
show_progress=show_progress,
|
|
58
|
+
debug=debug,
|
|
59
|
+
preview=preview,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def res_gui(protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
|
|
64
|
+
"""Opens the resumable DAQ/GCM graphical user interface."""
|
|
65
|
+
from . import res_app
|
|
66
|
+
|
|
67
|
+
return res_app.main(protocol_folder=protocol_folder, playlist_folder=playlist_folder)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def govee(duration: float = 10.0):
|
|
71
|
+
"""Lists nearby Govee H5075 sensors and their protocol addresses/readings."""
|
|
72
|
+
import asyncio
|
|
73
|
+
|
|
74
|
+
from .services.GOVZeroService import discover_h5075_sensors
|
|
75
|
+
|
|
76
|
+
print(f"Scanning for Govee sensors for {duration:g} seconds...", flush=True)
|
|
77
|
+
sensors = asyncio.run(discover_h5075_sensors(duration))
|
|
78
|
+
if not sensors:
|
|
79
|
+
print("No Govee H5075 sensors found.")
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
print(f"{'Address (use as GOV.address)':<38} {'Name':<16} {'Temperature':>11} {'Humidity':>9}")
|
|
83
|
+
for address, name, measurement in sensors:
|
|
84
|
+
print(f"{address:<38} {(name or '-'):<16} {measurement.temperature_c:>10.1f}°C {measurement.humidity:>8.1f}%")
|
|
39
85
|
|
|
40
86
|
|
|
41
87
|
def version(*, debug: bool = False):
|
|
@@ -179,15 +225,13 @@ def init():
|
|
|
179
225
|
yaml.dump(protocol, f, Dumper=yaml.SafeDumper)
|
|
180
226
|
|
|
181
227
|
# generate test playlist
|
|
182
|
-
playlist = {
|
|
183
|
-
"stimFileName": {0: "SIN_100_0_1000"},
|
|
184
|
-
"silencePre": {0: 10000},
|
|
185
|
-
"silencePost": {0: 9000},
|
|
186
|
-
"
|
|
187
|
-
"
|
|
188
|
-
|
|
189
|
-
"MODE": {0: None},
|
|
190
|
-
}
|
|
228
|
+
playlist = {
|
|
229
|
+
"stimFileName": {0: "SIN_100_0_1000"},
|
|
230
|
+
"silencePre": {0: 10000},
|
|
231
|
+
"silencePost": {0: 9000},
|
|
232
|
+
"intensity": {0: 0.0},
|
|
233
|
+
"freq": {0: 100},
|
|
234
|
+
}
|
|
191
235
|
path_playlist = home / "ethoconfig/playlists/0_silence.txt"
|
|
192
236
|
logging.info(f" playlist {str(path_playlist)}.")
|
|
193
237
|
pd.DataFrame.from_dict(playlist).to_csv(path_playlist, sep="\t", index=False)
|
|
@@ -198,18 +242,27 @@ def main():
|
|
|
198
242
|
subcommands = {
|
|
199
243
|
"version": version,
|
|
200
244
|
"init": init,
|
|
245
|
+
"govee": govee,
|
|
201
246
|
}
|
|
202
247
|
|
|
203
248
|
if client is not None:
|
|
204
249
|
subcommands.update({"run": run})
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
250
|
+
subcommands["res-run"] = res_run
|
|
251
|
+
try:
|
|
252
|
+
from . import app
|
|
253
|
+
|
|
254
|
+
subcommands["gui"] = app.main
|
|
209
255
|
except (ImportError, ModuleNotFoundError):
|
|
210
|
-
logging.exception("No GUI avalaible.")
|
|
211
|
-
# fall back to function that displays helpful instructions
|
|
212
|
-
subcommands["gui"] = no_gui
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
256
|
+
logging.exception("No GUI avalaible.")
|
|
257
|
+
# fall back to function that displays helpful instructions
|
|
258
|
+
subcommands["gui"] = no_gui
|
|
259
|
+
try:
|
|
260
|
+
from . import res_app
|
|
261
|
+
|
|
262
|
+
subcommands["res-gui"] = res_app.main
|
|
263
|
+
except (ImportError, ModuleNotFoundError):
|
|
264
|
+
logging.exception("No resumable GUI avalaible.")
|
|
265
|
+
subcommands["res-gui"] = no_gui
|
|
266
|
+
|
|
267
|
+
logging.basicConfig(level=logging.INFO, force=True)
|
|
268
|
+
defopt.run(subcommands, show_defaults=False)
|
etho/client.py
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import time
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import rich
|
|
7
|
-
import threading
|
|
1
|
+
import time
|
|
2
|
+
import logging
|
|
3
|
+
from rich.progress import Progress
|
|
4
|
+
import rich
|
|
5
|
+
import threading
|
|
8
6
|
import _thread as thread
|
|
9
7
|
import queue
|
|
10
8
|
from typing import Optional, Union, Dict, Any
|
|
@@ -13,13 +11,8 @@ import psutil
|
|
|
13
11
|
from .utils.tui import rich_information
|
|
14
12
|
|
|
15
13
|
from . import config
|
|
16
|
-
from .
|
|
17
|
-
from .utils.
|
|
18
|
-
|
|
19
|
-
from .services.GOVZeroService import GOV
|
|
20
|
-
from .services.DAQZeroService import DAQ
|
|
21
|
-
from .services.GCMZeroService import GCM
|
|
22
|
-
from .services.NICounterZeroService import NIC
|
|
14
|
+
from . import services as service_module
|
|
15
|
+
from .utils.config import defaultify, readconfig
|
|
23
16
|
|
|
24
17
|
|
|
25
18
|
def timed(fn, s, *args, **kwargs):
|
|
@@ -59,6 +52,71 @@ def _reject_remote_host_blocks(prot: Dict[str, Any]) -> None:
|
|
|
59
52
|
raise ValueError(f"Remote service hosts are no longer supported. Remove the 'host' block from: {services}.")
|
|
60
53
|
|
|
61
54
|
|
|
55
|
+
def _setup_services(prot, defaults, playlistfile, save_prefix, preview, new_console):
|
|
56
|
+
services = {}
|
|
57
|
+
service_classes = {}
|
|
58
|
+
service_counts = {}
|
|
59
|
+
|
|
60
|
+
for service_name in prot["use_services"]:
|
|
61
|
+
service_class = service_module.service_class_for(service_name)
|
|
62
|
+
service_type = service_class.SERVICE_NAME
|
|
63
|
+
service_index = service_counts.get(service_type, 0)
|
|
64
|
+
service_counts[service_type] = service_index + 1
|
|
65
|
+
|
|
66
|
+
service = service_class.setup_client(
|
|
67
|
+
service_name,
|
|
68
|
+
service_index,
|
|
69
|
+
prot,
|
|
70
|
+
defaults,
|
|
71
|
+
playlistfile,
|
|
72
|
+
save_prefix,
|
|
73
|
+
preview,
|
|
74
|
+
new_console,
|
|
75
|
+
)
|
|
76
|
+
if service is None:
|
|
77
|
+
continue
|
|
78
|
+
|
|
79
|
+
services[service_name] = service
|
|
80
|
+
service_classes[service_name] = service_class
|
|
81
|
+
|
|
82
|
+
return services, service_classes
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _start_services(services, service_classes):
|
|
86
|
+
logging.info("Starting services")
|
|
87
|
+
|
|
88
|
+
start_groups = {service_name: getattr(service_classes[service_name], "CLIENT_START_GROUP", "pre") for service_name in services}
|
|
89
|
+
started_groups = set()
|
|
90
|
+
time_last_prereq_started = time.time()
|
|
91
|
+
|
|
92
|
+
def start_group(group):
|
|
93
|
+
nonlocal time_last_prereq_started
|
|
94
|
+
started_groups.add(group)
|
|
95
|
+
for service_name, service in services.items():
|
|
96
|
+
if start_groups[service_name] != group:
|
|
97
|
+
continue
|
|
98
|
+
logging.info(f" {service_name}.")
|
|
99
|
+
service.start()
|
|
100
|
+
if group in {"pre", "trigger"}:
|
|
101
|
+
time_last_prereq_started = time.time()
|
|
102
|
+
|
|
103
|
+
start_group("pre")
|
|
104
|
+
time.sleep(0.5)
|
|
105
|
+
start_group("trigger")
|
|
106
|
+
|
|
107
|
+
if "daq" in start_groups.values():
|
|
108
|
+
wait_remaining = 5 - (time.time() - time_last_prereq_started)
|
|
109
|
+
if wait_remaining > 0:
|
|
110
|
+
time.sleep(wait_remaining)
|
|
111
|
+
start_group("daq")
|
|
112
|
+
|
|
113
|
+
for group in start_groups.values():
|
|
114
|
+
if group not in started_groups:
|
|
115
|
+
start_group(group)
|
|
116
|
+
|
|
117
|
+
logging.info("All services started.")
|
|
118
|
+
|
|
119
|
+
|
|
62
120
|
def client(
|
|
63
121
|
protocolfile: Optional[str],
|
|
64
122
|
playlistfile: Optional[str] = None,
|
|
@@ -112,201 +170,13 @@ def client(
|
|
|
112
170
|
|
|
113
171
|
new_console = debug
|
|
114
172
|
|
|
115
|
-
services =
|
|
116
|
-
if "GOV" in prot["use_services"] and not preview:
|
|
117
|
-
this = defaults.copy()
|
|
118
|
-
|
|
119
|
-
if prot["GOV"].get("port") is None:
|
|
120
|
-
prot["GOV"]["port"] = GOV.SERVICE_PORT
|
|
121
|
-
|
|
122
|
-
interval = prot["GOV"].get("interval")
|
|
123
|
-
if interval is None:
|
|
124
|
-
interval = 60
|
|
125
|
-
|
|
126
|
-
gov = GOV.make(
|
|
127
|
-
this["serializer"],
|
|
128
|
-
this["host"],
|
|
129
|
-
this["python_exe"],
|
|
130
|
-
port=prot["GOV"]["port"],
|
|
131
|
-
)
|
|
132
|
-
gov.setup(prot["GOV"]["address"], interval, prot["maxduration"] + 10)
|
|
133
|
-
gov.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}_gov.log")
|
|
134
|
-
services["GOV"] = gov
|
|
135
|
-
|
|
136
|
-
gcm_keys = [key for key in prot["use_services"] if "GCM" in key]
|
|
137
|
-
for gcm_cnt, gcm_key in enumerate(gcm_keys):
|
|
138
|
-
# if gcm_key in prot["use_services"] and gcm_key in prot:
|
|
139
|
-
this = defaults.copy()
|
|
140
|
-
this.update(prot[gcm_key])
|
|
141
|
-
|
|
142
|
-
if "port" not in prot[gcm_key]:
|
|
143
|
-
prot[gcm_key]["port"] = GCM.SERVICE_PORT + gcm_cnt
|
|
144
|
-
gcm = GCM.make(
|
|
145
|
-
this["serializer"],
|
|
146
|
-
this["host"],
|
|
147
|
-
this["python_exe"],
|
|
148
|
-
new_console=new_console,
|
|
149
|
-
port=prot[gcm_key]["port"],
|
|
150
|
-
)
|
|
151
|
-
|
|
152
|
-
cam_params = undefaultify(prot[gcm_key])
|
|
153
|
-
if not preview:
|
|
154
|
-
maxduration = prot["maxduration"] + 10
|
|
155
|
-
else:
|
|
156
|
-
maxduration = 1_000_000
|
|
157
|
-
|
|
158
|
-
if preview:
|
|
159
|
-
cam_params["callbacks"] = {"disp_fast": None}
|
|
160
|
-
|
|
161
|
-
save_suffix = f"_{gcm_cnt + 1}" if gcm_cnt > 0 else ""
|
|
162
|
-
gcm.setup(
|
|
163
|
-
f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}",
|
|
164
|
-
maxduration,
|
|
165
|
-
cam_params,
|
|
166
|
-
)
|
|
167
|
-
|
|
168
|
-
if not preview:
|
|
169
|
-
gcm.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}_gcm.log")
|
|
170
|
-
services[gcm_key] = gcm
|
|
171
|
-
|
|
172
|
-
daq_keys = [key for key in prot["use_services"] if "DAQ" in key]
|
|
173
|
-
daq_keys = [] if preview else daq_keys
|
|
174
|
-
for daq_cnt, daq_key in enumerate(daq_keys):
|
|
175
|
-
this = defaults.copy()
|
|
176
|
-
this.update(prot[daq_key])
|
|
177
|
-
|
|
178
|
-
if "device" not in prot[daq_key]:
|
|
179
|
-
prot[daq_key]["device"] = "Dev1"
|
|
180
|
-
|
|
181
|
-
if "port" not in prot[daq_key]:
|
|
182
|
-
prot[daq_key]["port"] = DAQ.SERVICE_PORT + daq_cnt
|
|
183
|
-
|
|
184
|
-
if this["host"] in config["ATTENUATION"]: # use node specific attenuation data
|
|
185
|
-
attenuation = config["ATTENUATION"][this["host"]]
|
|
186
|
-
logging.info(f"Using attenuation data specific to {this['host']}.")
|
|
187
|
-
else:
|
|
188
|
-
attenuation = config["ATTENUATION"]
|
|
189
|
-
|
|
190
|
-
# Load/generate all stimuli specified in playlist
|
|
191
|
-
fs = prot[daq_key]["samplingrate"]
|
|
192
|
-
playlist = parse_table(playlistfile)
|
|
193
|
-
sounds = load_sounds(
|
|
194
|
-
playlist,
|
|
195
|
-
fs,
|
|
196
|
-
attenuation=attenuation,
|
|
197
|
-
LEDamp=prot[daq_key]["ledamp"],
|
|
198
|
-
stimfolder=config["stimfolder"],
|
|
199
|
-
)
|
|
200
|
-
sounds = [sound.astype(np.float64) for sound in sounds]
|
|
201
|
-
|
|
202
|
-
# Generate stimulus sequence (shuffle, loop playlist)
|
|
203
|
-
playlist_items, totallen = build_playlist(sounds, prot["maxduration"], fs, shuffle=prot[daq_key]["shuffle"])
|
|
204
|
-
if prot["maxduration"] == -1:
|
|
205
|
-
logging.info(f"Setting maxduration from playlist to {totallen}.")
|
|
206
|
-
prot["maxduration"] = totallen
|
|
207
|
-
playlist_items = cycle(playlist_items) # iter(playlist_items)
|
|
208
|
-
else:
|
|
209
|
-
playlist_items = cycle(playlist_items)
|
|
210
|
-
|
|
211
|
-
# split analog and digital outputs
|
|
212
|
-
# TODO: catch errors if channel numbers are inconsistent - sounds[ii].shape[-1] should be nb_analog+nb_digital
|
|
213
|
-
if prot[daq_key]["digital_chans_out"] is not None:
|
|
214
|
-
nb_digital_chans_out = len(prot[daq_key]["digital_chans_out"])
|
|
215
|
-
digital_data = [snd[:, -nb_digital_chans_out:].astype(np.uint8) for snd in sounds]
|
|
216
|
-
analog_data = [snd[:, :-nb_digital_chans_out] for snd in sounds] # remove digital traces from stimset
|
|
217
|
-
else:
|
|
218
|
-
digital_data = None
|
|
219
|
-
analog_data = sounds
|
|
220
|
-
|
|
221
|
-
daq = DAQ.make(
|
|
222
|
-
this["serializer"],
|
|
223
|
-
this["host"],
|
|
224
|
-
this["python_exe"],
|
|
225
|
-
new_console=new_console,
|
|
226
|
-
port=prot[daq_key]["port"],
|
|
227
|
-
)
|
|
228
|
-
save_suffix = f"_{daq_cnt + 1}" if daq_cnt > 0 else ""
|
|
229
|
-
daq.setup(
|
|
230
|
-
f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}",
|
|
231
|
-
playlist_items,
|
|
232
|
-
playlist,
|
|
233
|
-
prot["maxduration"],
|
|
234
|
-
fs,
|
|
235
|
-
dev_name=prot[daq_key]["device"],
|
|
236
|
-
clock_source=prot[daq_key]["clock_source"],
|
|
237
|
-
nb_inputsamples_per_cycle=prot[daq_key]["nb_inputsamples_per_cycle"],
|
|
238
|
-
analog_chans_in=prot[daq_key]["analog_chans_in"],
|
|
239
|
-
# analog_chans_in_limits=None,
|
|
240
|
-
# analog_chans_in_terminals=None,
|
|
241
|
-
analog_chans_out=prot[daq_key]["analog_chans_out"],
|
|
242
|
-
# analog_chans_out_limits=None,
|
|
243
|
-
analog_data_out=analog_data,
|
|
244
|
-
digital_chans_out=prot[daq_key]["digital_chans_out"],
|
|
245
|
-
digital_data_out=digital_data,
|
|
246
|
-
metadata={
|
|
247
|
-
"analog_chans_in_info": prot[daq_key]["analog_chans_in_info"],
|
|
248
|
-
"analog_chans_out_info": prot[daq_key]["analog_chans_out_info"],
|
|
249
|
-
"digitial_chans_out_info": prot[daq_key]["digitial_chans_out_info"],
|
|
250
|
-
},
|
|
251
|
-
params=undefaultify(prot[daq_key]),
|
|
252
|
-
)
|
|
253
|
-
daq.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}_daq.log")
|
|
254
|
-
services[daq_key] = daq
|
|
255
|
-
|
|
256
|
-
if "NIC" in prot["use_services"]:
|
|
257
|
-
this = defaults.copy()
|
|
258
|
-
this.update(prot["NIC"])
|
|
259
|
-
|
|
260
|
-
nic = NIC.make(
|
|
261
|
-
this["serializer"],
|
|
262
|
-
this["host"],
|
|
263
|
-
this["python_exe"],
|
|
264
|
-
new_console=new_console,
|
|
265
|
-
port=prot["NIC"]["port"],
|
|
266
|
-
)
|
|
267
|
-
|
|
268
|
-
nic_params = undefaultify(prot["NIC"])
|
|
269
|
-
nic.setup(
|
|
270
|
-
nic_params["output_channel"],
|
|
271
|
-
prot["maxduration"] + 10,
|
|
272
|
-
nic_params["frequency"],
|
|
273
|
-
nic_params["duty_cycle"],
|
|
274
|
-
nic_params,
|
|
275
|
-
)
|
|
276
|
-
nic.init_local_logger(f"{this['savefolder']}/{save_prefix}/{save_prefix}{save_suffix}_daq.log")
|
|
173
|
+
services, service_classes = _setup_services(prot, defaults, playlistfile, save_prefix, preview, new_console)
|
|
277
174
|
|
|
278
175
|
# display config info
|
|
279
176
|
for key, s in services.items():
|
|
280
177
|
rich_information(s.information(), prefix=key)
|
|
281
178
|
|
|
282
|
-
|
|
283
|
-
# First, start video services - this will start acquisition or, if external triggering is enabled, arm the cameras to wait for the triggers
|
|
284
|
-
time_last_cam_started = time.time() + 5 # in case no cam was initialized
|
|
285
|
-
for service_name, service in services.items():
|
|
286
|
-
if "GCM" in service_name or "GOV" in service_name:
|
|
287
|
-
logging.info(f" {service_name}.")
|
|
288
|
-
service.start()
|
|
289
|
-
time_last_cam_started = time.time()
|
|
290
|
-
time.sleep(0.5)
|
|
291
|
-
|
|
292
|
-
# start the counter task for triggering frames
|
|
293
|
-
if "NIC" in prot["use_services"]:
|
|
294
|
-
logging.info(" NI Counter service.")
|
|
295
|
-
nic.start()
|
|
296
|
-
time_last_cam_started = time.time()
|
|
297
|
-
|
|
298
|
-
# Wait 5 seconds for cams to run
|
|
299
|
-
if daq_keys:
|
|
300
|
-
while time.time() - time_last_cam_started < 5:
|
|
301
|
-
time.sleep(0.1)
|
|
302
|
-
|
|
303
|
-
# Start DAQ services
|
|
304
|
-
for service_name, service in services.items():
|
|
305
|
-
if "DAQ" in service_name:
|
|
306
|
-
logging.info(f" {service_name}.")
|
|
307
|
-
service.start()
|
|
308
|
-
|
|
309
|
-
logging.info("All services started.")
|
|
179
|
+
_start_services(services, service_classes)
|
|
310
180
|
|
|
311
181
|
if monitor or show_progress:
|
|
312
182
|
total = 0
|
etho/res_app.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import sys
|
|
3
|
+
import threading
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
from qtpy.QtCore import QObject, Signal
|
|
7
|
+
from qtpy.QtWidgets import QApplication, QLabel, QMessageBox, QPushButton, QSizePolicy
|
|
8
|
+
|
|
9
|
+
from .app import MainWindow as EthoMainWindow
|
|
10
|
+
from .app import _system_icon
|
|
11
|
+
from .resumable import ResumableExperimentRunner
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
CONTROL_COLUMN_WIDTH = 145
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class WorkerSignals(QObject):
|
|
19
|
+
finished = Signal(str)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MainWindow(EthoMainWindow):
|
|
23
|
+
def __init__(self, protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
|
|
24
|
+
super().__init__(protocol_folder, playlist_folder)
|
|
25
|
+
self.setWindowTitle("etho resumable control")
|
|
26
|
+
self.runner = None
|
|
27
|
+
self.worker = None
|
|
28
|
+
self.progress_thread = None
|
|
29
|
+
self.progress_stop_event = None
|
|
30
|
+
self.run_active = False
|
|
31
|
+
self.signals = WorkerSignals()
|
|
32
|
+
self.signals.finished.connect(self.on_worker_finished)
|
|
33
|
+
try:
|
|
34
|
+
self.run_timer.timeout.disconnect(self.sync_run_state)
|
|
35
|
+
except (TypeError, RuntimeError):
|
|
36
|
+
pass
|
|
37
|
+
self.run_timer.stop()
|
|
38
|
+
|
|
39
|
+
buttons = self.layout.itemAtPosition(0, 0).layout()
|
|
40
|
+
self.button["Initialize hardware"] = QPushButton("Initialize hardware")
|
|
41
|
+
self.button["Initialize hardware"].clicked.connect(self.initialize_hardware)
|
|
42
|
+
self.button["Shutdown hardware"] = QPushButton("Shutdown hardware")
|
|
43
|
+
self.button["Shutdown hardware"].clicked.connect(self.shutdown_hardware)
|
|
44
|
+
self.status_label = QLabel("Select a protocol and initialize hardware.")
|
|
45
|
+
self.status_label.setWordWrap(True)
|
|
46
|
+
self.status_label.setFixedWidth(CONTROL_COLUMN_WIDTH)
|
|
47
|
+
self.status_label.setMinimumHeight(72)
|
|
48
|
+
self.status_label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
|
|
49
|
+
|
|
50
|
+
buttons.insertWidget(1, self.button["Initialize hardware"])
|
|
51
|
+
buttons.insertWidget(2, self.button["Shutdown hardware"])
|
|
52
|
+
buttons.insertSpacing(3, 12)
|
|
53
|
+
buttons.insertSpacing(6, 8)
|
|
54
|
+
buttons.insertWidget(buttons.count() - 1, self.status_label)
|
|
55
|
+
self.layout.setColumnMinimumWidth(0, CONTROL_COLUMN_WIDTH)
|
|
56
|
+
self.layout.setColumnStretch(0, 0)
|
|
57
|
+
for button in self.button.values():
|
|
58
|
+
if hasattr(button, "setFixedWidth"):
|
|
59
|
+
button.setFixedWidth(CONTROL_COLUMN_WIDTH)
|
|
60
|
+
self.set_resumable_buttons("idle")
|
|
61
|
+
|
|
62
|
+
def refresh_lists(self, init: bool = False):
|
|
63
|
+
super().refresh_lists(init)
|
|
64
|
+
if self.playlists_view.selected_string is None:
|
|
65
|
+
self.playlists_view.selected_string = str(self.playlists_view.model()._data.iloc[0, 0])
|
|
66
|
+
if self.protocols_view.selected_string is None:
|
|
67
|
+
self.protocols_view.selected_string = str(self.protocols_view.model()._data.iloc[0, 0])
|
|
68
|
+
|
|
69
|
+
def selected_playlist(self):
|
|
70
|
+
if self.playlists_view.selected_string is None:
|
|
71
|
+
return None
|
|
72
|
+
return (self.playlist_folder / self.playlists_view.selected_string).as_posix()
|
|
73
|
+
|
|
74
|
+
def run_background(self, message, target):
|
|
75
|
+
if self.worker is not None and self.worker.is_alive():
|
|
76
|
+
return
|
|
77
|
+
self.status_label.setText(message)
|
|
78
|
+
self.set_resumable_buttons("busy")
|
|
79
|
+
|
|
80
|
+
def wrapped():
|
|
81
|
+
try:
|
|
82
|
+
status = target()
|
|
83
|
+
except Exception as e:
|
|
84
|
+
logger.exception("Resumable GUI action failed.")
|
|
85
|
+
self.run_active = False
|
|
86
|
+
status = f"Error: {e}"
|
|
87
|
+
self.signals.finished.emit(status)
|
|
88
|
+
|
|
89
|
+
self.worker = threading.Thread(target=wrapped, daemon=True)
|
|
90
|
+
self.worker.start()
|
|
91
|
+
|
|
92
|
+
def on_worker_finished(self, status):
|
|
93
|
+
self.worker = None
|
|
94
|
+
self.status_label.setText(status)
|
|
95
|
+
if not self.run_active:
|
|
96
|
+
self.run_timer.stop()
|
|
97
|
+
elif self.progress_thread is None or not self.progress_thread.is_alive():
|
|
98
|
+
self.start_progress_monitor()
|
|
99
|
+
self.set_resumable_buttons("ready" if self.runner else "idle")
|
|
100
|
+
|
|
101
|
+
def initialize_hardware(self):
|
|
102
|
+
if self.runner is not None:
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
def work():
|
|
106
|
+
logging.getLogger().setLevel(logging.DEBUG if self.button["Debug"].isChecked() else logging.INFO)
|
|
107
|
+
runner = ResumableExperimentRunner(protocol=self.current_protocol)
|
|
108
|
+
runner.setup_hardware()
|
|
109
|
+
self.runner = runner
|
|
110
|
+
services = ", ".join(runner.services)
|
|
111
|
+
return f"Hardware {services} initialized. Ready to run an experiment"
|
|
112
|
+
|
|
113
|
+
self.run_background("Initializing hardware...", work)
|
|
114
|
+
|
|
115
|
+
def shutdown_hardware(self):
|
|
116
|
+
if self.runner is None:
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
def work():
|
|
120
|
+
self.runner.close()
|
|
121
|
+
self.runner = None
|
|
122
|
+
self.run_active = False
|
|
123
|
+
if self.progress_stop_event is not None:
|
|
124
|
+
self.progress_stop_event.set()
|
|
125
|
+
return "Hardware shut down."
|
|
126
|
+
|
|
127
|
+
self.run_background("Shutting down hardware...", work)
|
|
128
|
+
|
|
129
|
+
def start(self, preview: bool = False):
|
|
130
|
+
if self.runner is None:
|
|
131
|
+
QMessageBox.warning(self, "Hardware not initialized", "Initialize hardware first.")
|
|
132
|
+
return
|
|
133
|
+
playlist = self.selected_playlist()
|
|
134
|
+
if playlist is None:
|
|
135
|
+
QMessageBox.warning(self, "Missing playlist", "Select a playlist first.")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
def work():
|
|
139
|
+
logging.getLogger().setLevel(logging.DEBUG if self.button["Debug"].isChecked() else logging.INFO)
|
|
140
|
+
if self.progress_stop_event is not None:
|
|
141
|
+
self.progress_stop_event.set()
|
|
142
|
+
if self.progress_thread is not None and self.progress_thread.is_alive():
|
|
143
|
+
self.progress_thread.join(timeout=0.2)
|
|
144
|
+
self.runner.stop_run()
|
|
145
|
+
self.progress_stop_event = threading.Event()
|
|
146
|
+
self.runner.prepare_playlist_run(playlist, preview=preview)
|
|
147
|
+
self.runner.start()
|
|
148
|
+
self.run_active = True
|
|
149
|
+
return "Camera preview running." if preview else "Experiment running."
|
|
150
|
+
|
|
151
|
+
self.run_background("Starting experiment...", work)
|
|
152
|
+
|
|
153
|
+
def request_stop(self):
|
|
154
|
+
if self.runner is None:
|
|
155
|
+
return
|
|
156
|
+
|
|
157
|
+
def work():
|
|
158
|
+
if self.progress_stop_event is not None:
|
|
159
|
+
self.progress_stop_event.set()
|
|
160
|
+
self.runner.stop_run()
|
|
161
|
+
self.run_active = False
|
|
162
|
+
return "Experiment stopped."
|
|
163
|
+
|
|
164
|
+
self.run_background("Stopping experiment...", work)
|
|
165
|
+
|
|
166
|
+
def camera_preview(self):
|
|
167
|
+
self.start(preview=True)
|
|
168
|
+
|
|
169
|
+
def start_progress_monitor(self):
|
|
170
|
+
if self.runner is None or self.progress_stop_event is None:
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
def monitor():
|
|
174
|
+
try:
|
|
175
|
+
self.runner.monitor_progress(
|
|
176
|
+
show_progress=self.button["Progress"].isChecked(),
|
|
177
|
+
stop_event=self.progress_stop_event,
|
|
178
|
+
)
|
|
179
|
+
finally:
|
|
180
|
+
if self.run_active and self.progress_stop_event is not None and not self.progress_stop_event.is_set():
|
|
181
|
+
self.runner.stop_run()
|
|
182
|
+
self.run_active = False
|
|
183
|
+
self.signals.finished.emit("Experiment finished.")
|
|
184
|
+
|
|
185
|
+
self.progress_thread = threading.Thread(target=monitor, daemon=True)
|
|
186
|
+
self.progress_thread.start()
|
|
187
|
+
|
|
188
|
+
def set_resumable_buttons(self, state):
|
|
189
|
+
busy = state == "busy"
|
|
190
|
+
ready = self.runner is not None
|
|
191
|
+
running = ready and self.run_active
|
|
192
|
+
self.button["Refresh lists"].setEnabled(not busy and not ready)
|
|
193
|
+
self.button["Initialize hardware"].setEnabled(not busy and not ready)
|
|
194
|
+
self.button["Shutdown hardware"].setEnabled(not busy and ready)
|
|
195
|
+
self.button["Start"].setEnabled(not busy and ready)
|
|
196
|
+
self.button["Stop"].setEnabled(not busy and running)
|
|
197
|
+
self.button["Camera_preview"].setEnabled(not busy and ready)
|
|
198
|
+
self.button["Debug"].setEnabled(not busy)
|
|
199
|
+
self.button["Progress"].setEnabled(not busy)
|
|
200
|
+
self.button["Exit"].setEnabled(not busy)
|
|
201
|
+
self.protocols_view.setEnabled(not busy and not ready)
|
|
202
|
+
self.protocol_view.setEnabled(not busy and not ready)
|
|
203
|
+
self.playlists_view.setEnabled(not busy)
|
|
204
|
+
self.playlist_view.setEnabled(not busy)
|
|
205
|
+
|
|
206
|
+
def closeEvent(self, event):
|
|
207
|
+
if self.progress_stop_event is not None:
|
|
208
|
+
self.progress_stop_event.set()
|
|
209
|
+
if self.runner is not None:
|
|
210
|
+
self.runner.close()
|
|
211
|
+
self.runner = None
|
|
212
|
+
self.run_active = False
|
|
213
|
+
event.accept()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def main(protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
|
|
217
|
+
app = QApplication(sys.argv)
|
|
218
|
+
icon = _system_icon(app)
|
|
219
|
+
app.setWindowIcon(icon)
|
|
220
|
+
|
|
221
|
+
window = MainWindow(protocol_folder, playlist_folder)
|
|
222
|
+
window.setWindowIcon(icon)
|
|
223
|
+
window.show()
|
|
224
|
+
|
|
225
|
+
sys.exit(app.exec_())
|