-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.py
1407 lines (1113 loc) · 48.5 KB
/
controller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2021-01-19
# @Filename: archon.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
from __future__ import annotations
import asyncio
import configparser
import io
import os
import re
import warnings
from collections.abc import AsyncIterator
from typing import Any, Callable, Iterable, Literal, Optional, cast, overload
import numpy
from clu.device import Device
from archon import config as lib_config
from archon import log
from archon.controller.command import ArchonCommand, ArchonCommandStatus
from archon.controller.maskbits import ArchonPower, ControllerStatus, ModType
from archon.exceptions import (
ArchonControllerError,
ArchonControllerWarning,
ArchonUserWarning,
)
from . import MAX_COMMAND_ID, MAX_CONFIG_LINES
__all__ = ["ArchonController"]
class ArchonController(Device):
"""Talks to an Archon controller over TCP/IP.
Parameters
----------
name
A name identifying this controller.
host
The hostname of the Archon.
port
The port on which the Archon listens to incoming connections.
Defaults to 4242.
config
Configuration data. Otherwise uses default configuration.
"""
__running_commands: dict[int, ArchonCommand] = {}
_id_pool = set(range(MAX_COMMAND_ID))
def __init__(
self,
name: str,
host: str,
port: int = 4242,
config: dict | None = None,
):
Device.__init__(self, host, port)
self.name = name
self._status: ControllerStatus = ControllerStatus.UNKNOWN
self.__status_event = asyncio.Event()
self._binary_reply: Optional[bytearray] = None
self.auto_flush: bool | None = None
self.parameters: dict[str, int] = {}
self.current_window: dict[str, int] = {}
self.default_window: dict[str, int] = {}
self.config = config or lib_config
self.acf_file: str | None = None
self.acf_config: configparser.ConfigParser | None = None
# TODO: asyncio recommends using asyncio.create_task directly, but that
# call get_running_loop() which fails in iPython.
self._job = asyncio.get_event_loop().create_task(self.__track_commands())
async def start(self, reset: bool = True, read_acf: bool = True):
"""Starts the controller connection. If ``reset=True``, resets the status."""
await super().start()
log.debug(f"Controller {self.name} connected at {self.host}.")
if read_acf:
log.debug(f"Retrieving ACF data from controller {self.name}.")
config_parser, _ = await self.read_config()
self.acf_config = config_parser
self._parse_params()
if reset:
try:
await self._set_default_window_params()
await self.reset()
except ArchonControllerError as err:
warnings.warn(f"Failed resetting controller: {err}", ArchonUserWarning)
return self
@property
def status(self) -> ControllerStatus:
"""Returns the status of the controller as a `.ControllerStatus` enum type."""
return self._status
def update_status(
self,
bits: ControllerStatus | list[ControllerStatus],
mode="on",
notify=True,
):
"""Updates the status bitmask, allowing to turn on, off, or toggle a bit."""
if not isinstance(bits, (list, tuple)):
bits = [bits]
# Check that we don't get IDLE and ACTIVE at the same time
all_bits = ControllerStatus(0)
for bit in bits:
all_bits |= bit
if (ControllerStatus.ACTIVE & all_bits) and (ControllerStatus.IDLE & all_bits):
raise ValueError("Cannot set IDLE and ACTIVE bits at the same time.")
status = self.status
for bit in bits:
if mode == "on":
status |= bit
elif mode == "off":
status &= ~bit
elif mode == "toggle":
status ^= bit
else:
raise ValueError(f"Invalid mode '{mode}'.")
# Make sure that we don't have IDLE and ACTIVE states at the same time.
if ControllerStatus.IDLE in bits:
status &= ~ControllerStatus.ACTIVE
if status & ControllerStatus.ACTIVE:
status &= ~ControllerStatus.IDLE
else:
status |= ControllerStatus.IDLE
# Handle incompatible power bits.
if ControllerStatus.POWERBAD in bits:
status &= ~(ControllerStatus.POWERON | ControllerStatus.POWEROFF)
elif ControllerStatus.POWERON in bits or ControllerStatus.POWEROFF in bits:
status &= ~ControllerStatus.POWERBAD
if ControllerStatus.POWERON in bits:
status &= ~ControllerStatus.POWEROFF
else:
status &= ~ControllerStatus.POWERON
# Remove UNKNOWN bit if any other status has been set.
if status != ControllerStatus.UNKNOWN:
status &= ~ControllerStatus.UNKNOWN
self._status = status
if notify:
self.__status_event.set()
async def yield_status(self) -> AsyncIterator[ControllerStatus]:
"""Asynchronous generator yield the status of the controller."""
yield self.status # Yield the status on subscription to the generator.
while True:
prev_status = self._status
await self.__status_event.wait()
if self.status != prev_status:
yield self.status
self.__status_event.clear()
def send_command(
self,
command_string: str,
command_id: Optional[int] = None,
**kwargs,
) -> ArchonCommand:
"""Sends a command to the Archon.
Parameters
----------
command_string
The command to send to the Archon. Will be converted to uppercase.
command_id
The command id to associate with this message. If not provided, a
sequential, autogenerated one will be used.
kwargs
Other keyword arguments to pass to `.ArchonCommand`.
"""
command_id = command_id or self._get_id()
if command_id > MAX_COMMAND_ID or command_id < 0:
raise ArchonControllerError(
f"Command ID must be in the range [0, {MAX_COMMAND_ID:d}]."
)
command = ArchonCommand(
command_string,
command_id,
controller=self,
**kwargs,
)
self.__running_commands[command_id] = command
self.write(command.raw)
log.debug(f"{self.name} -> {command.raw}")
return command
async def send_many(
self,
cmd_strs: Iterable[str],
max_chunk=100,
timeout: Optional[float] = None,
) -> tuple[list[ArchonCommand], list[ArchonCommand]]:
"""Sends many commands and waits until they are all done.
If any command fails or times out, cancels any future command. Returns a list
of done commands and a list failed commands (empty if all the commands
have succeeded). Note that ``done+pending`` can be fewer than the length
of ``cmd_strs``.
The order in which the commands are sent and done is not guaranteed. If that's
important, you should use `.send_command`.
Parameters
----------
cmd_strs
List of command strings to send. The command ids are assigned automatically
from available IDs in the pool.
max_chunk
Maximum number of commands to send at once. After sending, waits until all
the commands in the chunk are done. This does not guarantee that
``max_chunk`` of commands will be running at once, that depends on the
available command ids in the pool.
timeout
Timeout for each single command.
"""
# Copy the strings so that we can pop them. Also reverse it because
# we'll be popping items and we want to conserve the order.
cmd_strs = list(cmd_strs)[::-1]
done: list[ArchonCommand] = []
while len(cmd_strs) > 0:
pending: list[ArchonCommand] = []
if len(cmd_strs) < max_chunk:
max_chunk = len(cmd_strs)
if len(self._id_pool) >= max_chunk:
cmd_ids = (self._get_id() for __ in range(max_chunk))
else:
cmd_ids = (self._get_id() for __ in range(len(self._id_pool)))
for cmd_id in cmd_ids:
cmd_str = cmd_strs.pop()
cmd = self.send_command(cmd_str, command_id=cmd_id, timeout=timeout)
pending.append(cmd)
done_cmds: list[ArchonCommand] = await asyncio.gather(*pending)
if all([cmd.succeeded() for cmd in done_cmds]):
done += done_cmds
for cmd in done_cmds:
self._id_pool.add(cmd.command_id)
else:
failed: list[ArchonCommand] = []
for cmd in done_cmds:
if cmd.succeeded():
done.append(cmd)
else:
failed.append(cmd)
return done, failed
return (done, [])
async def send_and_wait(
self,
command_string: str,
raise_error: bool = True,
**kwargs,
):
"""Sends a command to the controller and waits for it to complete.
Parameters
----------
command_string
The command to send to the Archon. Will be converted to uppercase.
raise_error
Whether to raise an error if the command fails. If `False`, a
warning will be issued.
kwargs
Other arguments to be sent to `.send_command`.
"""
command_string = command_string.upper()
command = await self.send_command(command_string, **kwargs)
if not command.succeeded():
if raise_error:
self.update_status(ControllerStatus.ERROR)
raise ArchonControllerError(f"Failed running {command_string}.")
else:
warnings.warn(f"Failed running {command_string}.", ArchonUserWarning)
async def process_message(self, line: bytes) -> None:
"""Processes a message from the Archon and associates it with its command."""
match = re.match(b"^[<|?]([0-9A-F]{2})", line)
if match is None:
warnings.warn(
f"Received invalid reply {line.decode()}",
ArchonControllerWarning,
)
return
command_id = int(match[1], 16)
if command_id not in self.__running_commands:
warnings.warn(
f"Cannot find running command for {line}",
ArchonControllerWarning,
)
return
self.__running_commands[command_id].process_reply(line)
async def stop(self):
"""Stops the client and cancels the command tracker."""
self._job.cancel()
await super().stop()
async def get_system(self) -> dict[str, Any]:
"""Returns a dictionary with the output of the ``SYSTEM`` command."""
cmd = await self.send_command("SYSTEM", timeout=5)
if not cmd.succeeded():
error = cmd.status == ArchonCommandStatus.TIMEDOUT
raise ArchonControllerError(
f"Command STATUS finished with status {cmd.status.name!r}",
set_error_status=error,
)
keywords = str(cmd.replies[0].reply).split()
system = {}
for key, value in map(lambda k: k.split("="), keywords):
system[key.lower()] = value
if match := re.match(r"^MOD([0-9]{1,2})_TYPE", key, re.IGNORECASE):
name_key = f"mod{match.groups()[0]}_name"
system[name_key] = ModType(int(value)).name
return system
async def get_device_status(self, update_power_bits: bool = True) -> dict[str, Any]:
"""Returns a dictionary with the output of the ``STATUS`` command."""
def check_int(s):
if s[0] in ("-", "+"):
return s[1:].isdigit()
return s.isdigit()
cmd = await self.send_command("STATUS", timeout=5)
if not cmd.succeeded():
error = cmd.status == ArchonCommandStatus.TIMEDOUT
raise ArchonControllerError(
f"Command STATUS finished with status {cmd.status.name!r}",
set_error_status=error,
)
keywords = str(cmd.replies[0].reply).split()
status = {
key.lower(): int(value) if check_int(value) else float(value)
for (key, value) in map(lambda k: k.split("="), keywords)
}
if update_power_bits:
await self.power()
return status
async def get_frame(self) -> dict[str, int]:
"""Returns the frame information.
All the returned values in the dictionary are integers in decimal
representation.
"""
cmd = await self.send_command("FRAME", timeout=5)
if not cmd.succeeded():
raise ArchonControllerError(
f"Command FRAME failed with status {cmd.status.name!r}"
)
keywords = str(cmd.replies[0].reply).split()
frame = {
key.lower(): int(value) if "TIME" not in key else int(value, 16)
for (key, value) in map(lambda k: k.split("="), keywords)
}
return frame
async def read_config(
self,
save: str | bool = False,
) -> tuple[configparser.ConfigParser, list[str]]:
"""Reads the configuration from the controller.
Parameters
----------
save
Save the configuration to a file. If ``save=True``, the configuration will
be saved to ``~/archon_<controller_name>.acf``, or set ``save`` to the path
of the file to save.
"""
key_value_re = re.compile("^(.+?)=(.*)$")
def parse_line(line):
match = key_value_re.match(line)
assert match
k, v = match.groups()
# It seems the GUI replaces / with \ even if that doesn't seem
# necessary in the INI format.
k = k.replace("/", "\\")
if ";" in v or "=" in v or "," in v:
v = f'"{v}"'
return k, v
await self.send_command("POLLOFF")
cmd_strs = [f"RCONFIG{n_line:04X}" for n_line in range(MAX_CONFIG_LINES)]
done, failed = await self.send_many(cmd_strs, max_chunk=100, timeout=0.5)
await self.send_command("POLLON")
if len(failed) > 0:
ff = failed[0]
status = ff.status.name
raise ArchonControllerError(
f"An RCONFIG command returned with code {status!r}"
)
if any([len(cmd.replies) != 1 for cmd in done]):
raise ArchonControllerError("Some commands did not get any reply.")
lines = [str(cmd.replies[0]) for cmd in done]
# Trim possible empty lines at the end.
config_lines = "\n".join(lines).strip().splitlines()
# The GUI ACF file includes the system information, so we get it.
system = await self.get_system()
c = configparser.ConfigParser()
c.optionxform = str # type: ignore Make it case-sensitive
c.add_section("SYSTEM")
for sk, sv in system.items():
if "_name" in sk.lower():
continue
sl = f"{sk.upper()}={sv}"
k, v = parse_line(sl)
c.set("SYSTEM", k, v)
c.add_section("CONFIG")
for cl in config_lines:
k, v = parse_line(cl)
c.set("CONFIG", k, v)
if save is not False and save is not None:
if isinstance(save, str):
path = save
else:
path = os.path.expanduser(f"~/archon_{self.name}.acf")
with open(path, "w") as f:
c.write(f, space_around_delimiters=False)
return (c, config_lines)
async def write_config(
self,
input: str | os.PathLike[str],
applyall: bool = False,
applymods: list[str] = [],
poweron: bool = False,
timeout: float | None = None,
overrides: dict = {},
notifier: Optional[Callable[[str], None]] = None,
):
"""Writes a configuration file to the contoller.
Parameters
----------
input
The path to the configuration file to load. It must be in INI format with
a section called ``[CONFIG]``. It can also be a string containing the
configuration itself.
applyall
Whether to run ``APPLYALL`` after successfully sending the configuration.
applymods
A list of apply commands to send to modules (e.g.,
``['LOADTIMING', 'APPLYMOD2']``).
poweron
Whether to run ``POWERON`` after successfully sending the configuration.
Requires ``applyall=True``.
timeout
The amount of time to wait for each command to succeed. If `None`, reads
the value from the configuration entry for
``timeouts.write_config_timeout``.
overrides
A dictionary with configuration lines to be overridden. Must be a mapping
of keywords to replace, including the module name (e.g.,
``MOD11/HEATERAP``), to the new values.
notifier
A callback that receives a message with the current operation being
performed. Useful when `.write_config` is called by the actor to report
progress to the users.
"""
ACS = ArchonCommandStatus
notifier = notifier or (lambda x: None)
notifier("Reading configuration file")
timeout = timeout or self.config["timeouts"]["write_config_timeout"]
delay: float = self.config["timeouts"]["write_config_delay"]
cp = configparser.ConfigParser()
input = str(input)
if os.path.exists(input):
cp.read(input)
else:
cp.read_string(input)
if not cp.has_section("CONFIG"):
raise ArchonControllerError(
"The config file does not have a CONFIG section."
)
# Undo the INI format: revert \ to / and remove quotes around values.
aconfig = cp["CONFIG"]
lines = []
for key in aconfig:
lines.append(key.upper().replace("\\", "/") + "=" + aconfig[key].strip('"'))
notifier("Clearing previous configuration")
await self.send_and_wait("CLEARCONFIG", timeout=timeout)
notifier("Sending configuration lines")
# Stop the controller from polling internally to speed up network response
# time. This command is not in the official documentation.
await self.send_command("POLLOFF")
cmd_strs = [f"WCONFIG{n_line:04X}{line}" for n_line, line in enumerate(lines)]
for line in cmd_strs:
cmd = await self.send_command(line, timeout=timeout)
if cmd.status == ACS.FAILED or cmd.status == ACS.TIMEDOUT:
self.update_status(ControllerStatus.ERROR)
await self.send_command("POLLON")
raise ArchonControllerError(
f"Failed sending line {cmd.raw!r} ({cmd.status.name})"
)
await asyncio.sleep(delay)
notifier("Sucessfully sent config lines")
self.acf_config = cp
self.acf_file = input if os.path.exists(input) else None
# Write overrides. Do not apply since we optionall do an APPLYALL afterwards.
if overrides and len(overrides) > 0:
notifier("Writing configuration overrides.")
for keyword, value in overrides.items():
await self.write_line(keyword, value, apply=False)
# Restore polling
await self.send_command("POLLON")
for mod in applymods:
notifier(f"Sending {mod.upper()}")
await self.send_and_wait(mod.upper(), timeout=5)
if applyall:
notifier("Sending APPLYALL")
await self.send_and_wait("APPLYALL", timeout=5)
# Reset objects that depend on the configuration file.
self._parse_params()
await self._set_default_window_params()
if poweron:
notifier("Sending POWERON")
await self.power(True)
await self.reset()
return
async def write_line(
self,
keyword: str,
value: int | float | str,
mod: Optional[str] = None,
apply: bool | str = True,
):
"""Write a single line to the controller, replacing the current configuration.
Parameters
----------
keyword
The config keyword to replace. If ``mod=None``, must include the module
name (e.g., ``MOD11/HEATERAP``); otherwise the module is added from
``mod``. Modules and module keywords can be separated by slashes or
backlashes.
value
The value of the keyword.
mod
The name of the keyword module, e.g., ``MOD11``.
apply
Whether to re-apply the configuration for the module. If ``apply``
is a string, defines the command to be used to apply the new setting,
e.g., ``APPLYCDS``.
"""
if not self.acf_config:
raise ArchonControllerError("The controller ACF configuration is unknown.")
keyword = keyword.upper().replace("/", "\\")
if mod != "" and mod is not None:
mod = mod.upper()
if not keyword.startswith(mod):
keyword = mod + "\\" + keyword
else:
mod_re = re.match(r"(MOD[0-9]+)\\", keyword)
if mod_re:
mod = mod_re.group(1)
current_keywords = [k.upper() for k in list(self.acf_config["CONFIG"])]
if keyword not in current_keywords:
raise ArchonControllerError(f"Invalid keyword {keyword}")
n_line = current_keywords.index(keyword)
if isinstance(value, (int, float)):
value_str = str(value)
elif isinstance(value, str):
if any(quotable_char in value for quotable_char in [",", " ", "="]):
value_str = '"' + value + '"'
else:
value_str = value
# For WCONFIG we need to use MODX/KEYWORD.
keyword_wconfig = keyword.replace("\\", "/")
line = f"{keyword_wconfig}={value_str}"
cmd = await self.send_command(f"WCONFIG{n_line:04X}{line}")
if cmd.status == ArchonCommandStatus.FAILED:
raise ArchonControllerError(
f"Failed sending line {cmd.raw!r} ({cmd.status.name})"
)
self.acf_config["CONFIG"][keyword] = value_str
if apply:
if isinstance(apply, str):
apply_cmd_str = apply.upper()
else:
if mod is None:
raise ArchonControllerError("Apply can only be used with modules.")
modn = mod[3:]
apply_cmd_str = f"APPLYMOD{modn}"
cmd_apply = await self.send_command(apply_cmd_str)
if cmd_apply.status == ArchonCommandStatus.FAILED:
raise ArchonControllerError(f"Failed applying changes to {mod}.")
log.info(f"{self.name}: {keyword}={value_str}")
async def power(self, mode: bool | None = None):
"""Handles power to the CCD(s). Sets the power status bit.
Parameters
----------
mode
If `None`, returns `True` if the array is currently powered,
`False` otherwise. If `True`, powers n the array; if `False`
powers if off.
Returns
-------
state : `.ArchonPower`
The power state as an `.ArchonPower` flag.
"""
if mode is not None:
cmd_str = "POWERON" if mode is True else "POWEROFF"
cmd = await self.send_command(cmd_str, timeout=10)
if not cmd.succeeded():
self.update_status([ControllerStatus.ERROR, ControllerStatus.POWERBAD])
raise ArchonControllerError(
f"Failed sending POWERON ({cmd.status.name})"
)
await asyncio.sleep(1)
status = await self.get_device_status(update_power_bits=False)
power_status = ArchonPower(status["power"])
if (
power_status not in [ArchonPower.ON, ArchonPower.OFF]
or status["powergood"] == 0
):
if power_status == ArchonPower.INTERMEDIATE:
warnings.warn("Power in INTERMEDIATE state.", ArchonUserWarning)
self.update_status(ControllerStatus.POWERBAD)
else:
if power_status == ArchonPower.ON:
self.update_status(ControllerStatus.POWERON)
elif power_status == ArchonPower.OFF:
self.update_status(ControllerStatus.POWEROFF)
return power_status
async def set_autoflush(self, mode: bool):
"""Enables or disables autoflushing."""
await self.set_param("AutoFlush", int(mode))
log.info(f"{self.name}: autoflush is {'on' if mode else 'off'}.")
self.auto_flush = mode
async def reset(
self,
autoflush: bool = True,
release_timing: bool = True,
reset_timing: bool = False,
update_status: bool = True,
):
"""Resets timing and discards current exposures."""
self._parse_params()
log.info(f"{self.name}: resetting controller.")
await self.send_command("HOLDTIMING")
await self.set_autoflush(autoflush)
await self.set_param("Exposures", 0)
await self.set_param("ReadOut", 0)
await self.set_param("AbortExposure", 0)
await self.set_param("DoFlush", 0)
await self.set_param("WaitCount", 0, silent=True)
# Reset parameters to their default values.
if "default_parameters" in self.config["archon"]:
default_parameters = self.config["archon"]["default_parameters"]
for param in default_parameters:
await self.set_param(param, default_parameters[param])
timing_commands: list[str] = []
if reset_timing:
release_timing = True
timing_commands.append("RESETTIMING")
if release_timing:
log.info(f"{self.name}: restarting timing .")
timing_commands.append("RELEASETIMING")
for cmd_str in timing_commands:
cmd = await self.send_command(cmd_str, timeout=1)
if not cmd.succeeded():
self.update_status(ControllerStatus.ERROR)
raise ArchonControllerError(
f"Failed sending {cmd_str} ({cmd.status.name})"
)
if update_status:
self._status = ControllerStatus.IDLE
await self.power() # Sets power bit.
def _parse_params(self):
"""Reads the ACF file and constructs a dictionary of parameters."""
if not self.acf_config:
raise ArchonControllerError("ACF file not loaded. Cannot parse parameters.")
# Dump the ACF ConfigParser object into a dummy file and read it as a string.
f = io.StringIO()
self.acf_config.write(f)
f.seek(0)
data = f.read()
matches = re.findall(
r'PARAMETER[0-9]+\s*=\s*"([A-Z]+)\s*=\s*([0-9]+)"',
data,
re.IGNORECASE,
)
self.parameters = {k.upper(): int(v) for k, v in dict(matches).items()}
async def _set_default_window_params(self, reset: bool = True):
"""Sets the default window parameters.
This is assumed to be called only after the default ACF has been loaded
and before any calls to `.write_line` or `.set_param`. Resets the window.
"""
self.default_window = {
"lines": int(self.parameters.get("LINES", -1)),
"pixels": int(self.parameters.get("PIXELS", -1)),
"preskiplines": int(self.parameters.get("PRESKIPLINES", 0)),
"postskiplines": int(self.parameters.get("POSTSKIPLINES", 0)),
"preskippixels": int(self.parameters.get("PRESKIPPIXELS", 0)),
"postskippixels": int(self.parameters.get("POSTSKIPPIXELS", 0)),
"overscanpixels": int(self.parameters.get("OVERSCANPIXELS", 0)),
"overscanlines": int(self.parameters.get("OVERSCANLINES", 0)),
"hbin": int(self.parameters.get("HORIZONTALBINNING", 1)),
"vbin": int(self.parameters.get("VERTICALBINNING", 1)),
}
log.info(f"{self.name}: default window: {self.default_window}")
self.current_window = self.default_window.copy()
log.info(f"{self.name}: current window: {self.current_window}")
if reset:
await self.reset_window()
async def set_param(
self, param: str, value: int, force: bool = False, silent: bool = False
) -> ArchonCommand | None:
"""Sets the parameter ``param`` to value ``value`` calling ``FASTLOADPARAM``."""
# First we check if the parameter actually exists.
if len(self.parameters) == 0:
if self.acf_config is None:
raise ArchonControllerError("ACF not loaded. Cannot modify parameters.")
param = param.upper()
if param not in self.parameters and force is False:
if not silent:
warnings.warn(
f"Trying to set unknown parameter {param}.",
ArchonUserWarning,
)
return
cmd = await self.send_command(f"FASTLOADPARAM {param} {value}")
if not cmd.succeeded():
raise ArchonControllerError(
f"Failed setting parameter {param!r} ({cmd.status.name})."
)
log.debug(f"{self.name}: {param}={value}")
self.parameters[param] = value
return cmd
async def reset_window(self):
"""Resets the exposure window."""
await self.set_window(**self.default_window)
async def set_window(
self,
lines: int | None = None,
pixels: int | None = None,
preskiplines: int | None = None,
postskiplines: int | None = None,
preskippixels: int | None = None,
postskippixels: int | None = None,
overscanlines: int | None = None,
overscanpixels: int | None = None,
hbin: int | None = None,
vbin: int | None = None,
):
"""Sets the CCD window."""
if lines is None:
lines = self.current_window["lines"]
if pixels is None:
pixels = self.current_window["pixels"]
if preskiplines is None:
preskiplines = self.current_window["preskiplines"]
if postskiplines is None:
postskiplines = self.current_window["postskiplines"]
if preskippixels is None:
preskippixels = self.current_window["preskippixels"]
if postskippixels is None:
postskippixels = self.current_window["postskippixels"]
if overscanlines is None:
overscanlines = self.current_window["overscanlines"]
if overscanpixels is None:
overscanpixels = self.current_window["overscanpixels"]
if vbin is None:
vbin = self.current_window["vbin"]
if hbin is None:
hbin = self.current_window["hbin"]
if lines >= 0:
await self.set_param("Lines", lines)
else:
warnings.warn("Lines value unknown. Did not set.", ArchonUserWarning)
if pixels >= 0:
await self.set_param("Pixels", pixels)
else:
warnings.warn("Pixels value unknown. Did not set.", ArchonUserWarning)
await self.set_param("Pixels", pixels)
await self.set_param("PreSkipLines", preskiplines)
await self.set_param("PostSkipLines", postskiplines)
await self.set_param("PreSkipPixels", preskippixels)
await self.set_param("PostSkipPixels", postskippixels)
await self.set_param("VerticalBinning", vbin)
await self.set_param("HorizontalBinning", hbin)
linecount = (lines + overscanlines) // vbin
pixelcount = (pixels + overscanpixels) // hbin
await self.write_line("LINECOUNT", linecount, apply=False)
await self.write_line("PIXELCOUNT", pixelcount, apply="APPLYCDS")
self.current_window = {
"lines": lines,
"pixels": pixels,
"preskiplines": preskiplines,
"postskiplines": postskiplines,
"preskippixels": preskippixels,
"postskippixels": postskippixels,
"overscanpixels": overscanpixels,
"overscanlines": overscanlines,
"hbin": hbin,
"vbin": vbin,
}
log.info(f"{self.name}: current window: {self.current_window}")
return self.current_window
async def expose(
self,
exposure_time: float = 1,
readout: bool = True,
) -> asyncio.Task:
"""Integrates the CCD for ``exposure_time`` seconds.
Returns immediately once the exposure has begun. If ``readout=False``, does
not trigger a readout immediately after the integration finishes. The returned
`~asyncio.Task` waits until the integration is done and, if ``readout``, checks
that the readout has started.
"""
log.info(f"{self.name}: exposing with exposure time {exposure_time}.")
CS = ControllerStatus
if not (CS.IDLE & self.status):
raise ArchonControllerError("The controller is not idle.")
if CS.READOUT_PENDING & self.status:
raise ArchonControllerError(
"Controller has a readout pending. Read the device or flush."
)