mosca 2.0.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.
- mosca/__init__.py +11 -0
- mosca/common/__init__.py +9 -0
- mosca/common/enums.py +79 -0
- mosca/common/logger.py +139 -0
- mosca/common/threads.py +199 -0
- mosca/common/utils.py +70 -0
- mosca/control/__init__.py +4 -0
- mosca/control/buffer.py +526 -0
- mosca/control/controller.py +278 -0
- mosca/control/datahandler.py +261 -0
- mosca/control/detectors.py +116 -0
- mosca/control/mosca.py +693 -0
- mosca/control/spectra.py +36 -0
- mosca/control/stats.py +43 -0
- mosca/control/tasks/__init__.py +3 -0
- mosca/control/tasks/background.py +118 -0
- mosca/control/tasks/rois.py +466 -0
- mosca/control/tasks/saving.py +391 -0
- mosca/control/tasks/spectrasums.py +185 -0
- mosca/control/tasks/task.py +201 -0
- mosca/control/tasks/taskmanager.py +133 -0
- mosca/devices/__init__.py +28 -0
- mosca/devices/hamamatsu/__init__.py +0 -0
- mosca/devices/hamamatsu/hamamatsu.py +88 -0
- mosca/devices/hamamatsu/hamamatsuhw.py +1298 -0
- mosca/devices/oceanoptics/__init__.py +0 -0
- mosca/devices/oceanoptics/oceanoptics.py +59 -0
- mosca/devices/oceanoptics/oceanopticshw.py +379 -0
- mosca/devices/simulation/__init__.py +0 -0
- mosca/devices/simulation/dante/__init__.py +1 -0
- mosca/devices/simulation/dante/simdante.py +33 -0
- mosca/devices/simulation/dante/simdantehw.py +506 -0
- mosca/devices/simulation/dummy/__init__.py +1 -0
- mosca/devices/simulation/dummy/dummy.py +299 -0
- mosca/devices/simulation/generator.py +607 -0
- mosca/devices/simulation/xia/__init__.py +1 -0
- mosca/devices/simulation/xia/iniparser.py +99 -0
- mosca/devices/simulation/xia/simfalconx.py +26 -0
- mosca/devices/simulation/xia/simfalconxhw.py +599 -0
- mosca/devices/xglab/__init__.py +0 -0
- mosca/devices/xglab/dante.py +126 -0
- mosca/devices/xglab/dantehw.py +1178 -0
- mosca/devices/xia/__init__.py +0 -0
- mosca/devices/xia/falconx.py +232 -0
- mosca/devices/xia/handel/__init__.py +14 -0
- mosca/devices/xia/handel/_cffi.py +62 -0
- mosca/devices/xia/handel/error.py +272 -0
- mosca/devices/xia/handel/handel_inc/handel_constants.h +127 -0
- mosca/devices/xia/handel/handel_inc/handel_errors.h +254 -0
- mosca/devices/xia/handel/handel_inc/handel_generic.h +66 -0
- mosca/devices/xia/handel/interface.py +1025 -0
- mosca/devices/xia/handel/mapping.py +107 -0
- mosca/devices/xia/handel/parser.py +62 -0
- mosca/devices/xia/handel/stats.py +85 -0
- mosca/devices/xia/mercury.py +160 -0
- mosca/devices/xia/utils.py +47 -0
- mosca/devices/xia/xia.py +575 -0
- mosca/devices/xia/xiads.py +161 -0
- mosca/mosca.py +0 -0
- mosca/tango/__init__.py +2 -0
- mosca/tango/controller.py +80 -0
- mosca/tango/main.py +163 -0
- mosca/tango/mosca.py +513 -0
- mosca/tango/moscav1.py +408 -0
- mosca/tango/shared.py +23 -0
- mosca/tango/tasks/__init__.py +0 -0
- mosca/tango/tasks/background.py +55 -0
- mosca/tango/utils.py +109 -0
- mosca-2.0.2.dist-info/METADATA +32 -0
- mosca-2.0.2.dist-info/RECORD +73 -0
- mosca-2.0.2.dist-info/WHEEL +4 -0
- mosca-2.0.2.dist-info/entry_points.txt +2 -0
- mosca-2.0.2.dist-info/licenses/LICENSE +166 -0
mosca/__init__.py
ADDED
mosca/common/__init__.py
ADDED
mosca/common/enums.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
logger = logging.getLogger(__name__)
|
|
3
|
+
|
|
4
|
+
import enum
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def to_enum(value, enum_class):
|
|
8
|
+
"""
|
|
9
|
+
Takes a value and checks that it is a value
|
|
10
|
+
defined in Enum enum.
|
|
11
|
+
value: str or value defined in Enum enum
|
|
12
|
+
enum_class: Enum
|
|
13
|
+
"""
|
|
14
|
+
if value is None:
|
|
15
|
+
raise ValueError(f"None is not a valid {enum_class.__name__} value.")
|
|
16
|
+
if isinstance(value, enum_class):
|
|
17
|
+
return value
|
|
18
|
+
if isinstance(value, enum.Enum):
|
|
19
|
+
raise TypeError(
|
|
20
|
+
f"Expected a {enum_class.__name__} member, int, or str, "
|
|
21
|
+
f"got a {type(value).__name__} member ({value!r})."
|
|
22
|
+
)
|
|
23
|
+
try:
|
|
24
|
+
return enum_class[value]
|
|
25
|
+
except KeyError:
|
|
26
|
+
if isinstance(value, str):
|
|
27
|
+
try:
|
|
28
|
+
return enum_class[value.upper()]
|
|
29
|
+
except KeyError:
|
|
30
|
+
pass
|
|
31
|
+
try:
|
|
32
|
+
value = int(value)
|
|
33
|
+
except ValueError:
|
|
34
|
+
pass
|
|
35
|
+
return enum_class(value)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class TriggerMode(enum.IntEnum):
|
|
39
|
+
# must use zero to make it compatible with tango TypeEnum
|
|
40
|
+
UNKNOWN = 0
|
|
41
|
+
FREERUN = enum.auto()
|
|
42
|
+
#TODO: rename to int_trig_timer? int_trig_multi (a la p201)?
|
|
43
|
+
INT_TRIG_READOUT = enum.auto()
|
|
44
|
+
GATE = enum.auto()
|
|
45
|
+
EXT_TRIG = enum.auto()
|
|
46
|
+
#TODO: rename to ext_trig_timer? ext_trig_multi (a la p201)?
|
|
47
|
+
EXT_TRIG_READOUT = enum.auto()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Status(enum.IntEnum):
|
|
51
|
+
UNKNOWN = 0
|
|
52
|
+
UNINITIALIZED = enum.auto()
|
|
53
|
+
INITIALIZING = enum.auto()
|
|
54
|
+
READY = enum.auto()
|
|
55
|
+
PREPARED = enum.auto()
|
|
56
|
+
RUNNING = enum.auto()
|
|
57
|
+
FAULT = enum.auto()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class GateMode(enum.IntEnum):
|
|
61
|
+
UNKNOWN = 0
|
|
62
|
+
IGNORE = 1
|
|
63
|
+
HIGH = 2
|
|
64
|
+
LOW = 3
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class AcquisitionModes(enum.IntEnum):
|
|
68
|
+
NONE = 0
|
|
69
|
+
SINGLE = enum.auto()
|
|
70
|
+
CONCATENATION = enum.auto()
|
|
71
|
+
ACCUMULATION = enum.auto()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class DiscardMode(enum.IntEnum):
|
|
75
|
+
NONE = 0
|
|
76
|
+
# disabling until this is proven necessary...
|
|
77
|
+
# ODD = enum.auto()
|
|
78
|
+
# EVEN = enum.auto()
|
|
79
|
+
FIRST = enum.auto()
|
mosca/common/logger.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Logger.
|
|
3
|
+
"""
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import enum
|
|
8
|
+
import logging
|
|
9
|
+
from logging.handlers import RotatingFileHandler
|
|
10
|
+
|
|
11
|
+
if sys.platform.startswith("win"):
|
|
12
|
+
os.system("color")
|
|
13
|
+
logging.basicConfig()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
LOG_FORMAT = (
|
|
17
|
+
"[%(asctime)s.%(msecs)03d] "
|
|
18
|
+
"%(levelname)-8s "
|
|
19
|
+
"[%(name)s] "
|
|
20
|
+
"%(message)s (%(filename)s:%(lineno)d)"
|
|
21
|
+
)
|
|
22
|
+
HDR_LEN = 26
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
ASC_TIME = "%Y-%m-%d %H:%M:%S"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class COLORS(enum.Enum):
|
|
29
|
+
GREY = "\x1b[38;21m"
|
|
30
|
+
BLUE = "\x1b[38;5;39m"
|
|
31
|
+
YELLOW = "\x1b[38;5;226m"
|
|
32
|
+
GREEN = "\x1b[32m"
|
|
33
|
+
RED = "\x1b[38;5;196m"
|
|
34
|
+
BOLD_RED = "\x1b[31;1m"
|
|
35
|
+
RESET = "\x1b[0m"
|
|
36
|
+
NONE = ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
FORMATS = {
|
|
40
|
+
logging.DEBUG: COLORS.BLUE,# + LOG_FORMAT + RESET,
|
|
41
|
+
logging.INFO: COLORS.GREEN,# + LOG_FORMAT + RESET,
|
|
42
|
+
logging.WARNING: COLORS.YELLOW,# + LOG_FORMAT + RESET,
|
|
43
|
+
logging.ERROR: COLORS.RED,# + LOG_FORMAT + RESET,
|
|
44
|
+
logging.CRITICAL: COLORS.BOLD_RED# + LOG_FORMAT + RESET,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class MultilineFormatter(logging.Formatter):
|
|
49
|
+
def format(self, record: logging.LogRecord):
|
|
50
|
+
msg = super().format(record)
|
|
51
|
+
if "\n" in msg:
|
|
52
|
+
fmt_len = 0
|
|
53
|
+
try:
|
|
54
|
+
fmt_len = len(repr(FORMATS[record.levelno].value)) + 3
|
|
55
|
+
# + 3 because of the "\x1" in front of the format
|
|
56
|
+
except KeyError:
|
|
57
|
+
pass
|
|
58
|
+
idx = HDR_LEN + fmt_len
|
|
59
|
+
idx += msg[idx:].index("]") + 3
|
|
60
|
+
# + 1 to get past the "]""
|
|
61
|
+
# + 2 for the extra blanks after the timestamp
|
|
62
|
+
split = msg[idx:].splitlines()
|
|
63
|
+
blank = "\n" + (idx - fmt_len + 7) * " "
|
|
64
|
+
# why 7? no idea
|
|
65
|
+
# TODO: figure that out
|
|
66
|
+
msg = msg[:idx] + blank.join(split[:-1]) + split[-1]
|
|
67
|
+
return msg
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class MoscaColorFormatter(logging.Formatter):
|
|
71
|
+
"""
|
|
72
|
+
Color formatter
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(self):
|
|
76
|
+
super().__init__()
|
|
77
|
+
self._color_formatters = {
|
|
78
|
+
level: MultilineFormatter(fmt.value + LOG_FORMAT + COLORS.RESET.value, ASC_TIME)
|
|
79
|
+
for level, fmt in FORMATS.items()
|
|
80
|
+
}
|
|
81
|
+
self._default = MultilineFormatter(LOG_FORMAT, ASC_TIME)
|
|
82
|
+
|
|
83
|
+
def format(self, record):
|
|
84
|
+
formatter = self._color_formatters.get(record.levelno, self._default)
|
|
85
|
+
return formatter.format(record)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
MOSCA_LOGGER = logging.getLogger("mosca")
|
|
89
|
+
handler = logging.StreamHandler()
|
|
90
|
+
handler.setFormatter(MoscaColorFormatter())
|
|
91
|
+
MOSCA_LOGGER.propagate = False
|
|
92
|
+
MOSCA_LOGGER.setLevel("INFO")
|
|
93
|
+
MOSCA_LOGGER.addHandler(handler)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class MoscaFileHandler(RotatingFileHandler):
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def mosca_disable_log_file():
|
|
101
|
+
file_hdlrs = [
|
|
102
|
+
hdlr for hdlr in MOSCA_LOGGER.handlers if isinstance(hdlr, (MoscaFileHandler,))
|
|
103
|
+
]
|
|
104
|
+
for hdlr in file_hdlrs:
|
|
105
|
+
MOSCA_LOGGER.removeHandler(hdlr)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def mosca_enable_log_file(filename, *args, **kwargs):
|
|
109
|
+
mosca_disable_log_file()
|
|
110
|
+
hdlr = MoscaFileHandler(filename, *args, **kwargs)
|
|
111
|
+
hdlr.setFormatter(logging.Formatter(LOG_FORMAT))
|
|
112
|
+
MOSCA_LOGGER.addHandler(hdlr)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_logger(name):
|
|
116
|
+
"""
|
|
117
|
+
Return the mosca logger with the given name.
|
|
118
|
+
If <logfile> file name is provided then logs will be written to the given file.
|
|
119
|
+
"""
|
|
120
|
+
split_name = name.split(".")
|
|
121
|
+
if split_name[0] != "mosca":
|
|
122
|
+
split_name = ["mosca"] + split_name
|
|
123
|
+
name = ".".join(split_name)
|
|
124
|
+
return logging.getLogger(name)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def mosca_logger_names(rx_pattern=None):
|
|
128
|
+
logger_names = [name for name in logging.root.manager.loggerDict if name.startswith("mosca")]
|
|
129
|
+
if rx_pattern:
|
|
130
|
+
rx = re.compile(rx_pattern)
|
|
131
|
+
logger_names = [name for name in logger_names if rx.match(name)]
|
|
132
|
+
return logger_names
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def set_mosca_log_level(rx_patten=None, level=logging.ERROR):
|
|
136
|
+
logger_names = mosca_logger_names(rx_pattern=rx_patten)
|
|
137
|
+
if logger_names:
|
|
138
|
+
for logger_name in logger_names:
|
|
139
|
+
logging.getLogger(logger_name).setLevel(level)
|
mosca/common/threads.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
logger = logging.getLogger(__name__)
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
import typing
|
|
6
|
+
import queue
|
|
7
|
+
import threading
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
USE_GEVENT = None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def RLock(*args, **kwargs):
|
|
15
|
+
if USE_GEVENT:
|
|
16
|
+
raise NotImplementedError
|
|
17
|
+
else:
|
|
18
|
+
return threading.RLock(*args, **kwargs)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def Lock(*args, **kwargs):
|
|
22
|
+
if USE_GEVENT:
|
|
23
|
+
raise NotImplementedError
|
|
24
|
+
else:
|
|
25
|
+
return threading.Lock(*args, **kwargs)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def Event(*args, **kwargs):
|
|
29
|
+
if USE_GEVENT:
|
|
30
|
+
raise NotImplementedError
|
|
31
|
+
else:
|
|
32
|
+
return threading.Event(*args, **kwargs)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def Queue(*args, **kwargs):
|
|
36
|
+
if USE_GEVENT:
|
|
37
|
+
raise NotImplementedError
|
|
38
|
+
else:
|
|
39
|
+
return queue.Queue(*args, **kwargs)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def run(target, *args, **kwargs):
|
|
43
|
+
if USE_GEVENT:
|
|
44
|
+
raise NotImplementedError
|
|
45
|
+
else:
|
|
46
|
+
thread = threading.Thread(target=target, args=args, kwargs=kwargs)
|
|
47
|
+
thread.daemon=True
|
|
48
|
+
thread.start()
|
|
49
|
+
return thread
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def sleep(time_s):
|
|
53
|
+
if USE_GEVENT:
|
|
54
|
+
raise NotImplementedError
|
|
55
|
+
else:
|
|
56
|
+
return time.sleep(time_s)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Timeout:
|
|
60
|
+
timeout = property(lambda self: self._timeout)
|
|
61
|
+
|
|
62
|
+
def __init__(self, timeout):
|
|
63
|
+
self._t0 = None
|
|
64
|
+
self._timeout = timeout
|
|
65
|
+
|
|
66
|
+
def __bool__(self):
|
|
67
|
+
if self._t0 is None:
|
|
68
|
+
self._t0 = time.perf_counter()
|
|
69
|
+
return time.perf_counter() - self._t0 < self._timeout
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@contextmanager
|
|
73
|
+
def get_lock(lock, timeout=-1):
|
|
74
|
+
held = lock.acquire(timeout=timeout)
|
|
75
|
+
if not held:
|
|
76
|
+
raise TimeoutError(f"Could not acquire lock within {timeout}s.")
|
|
77
|
+
try:
|
|
78
|
+
yield held
|
|
79
|
+
finally:
|
|
80
|
+
lock.release()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class AsyncTask:
|
|
84
|
+
stop_set = property(lambda self: self._stop_event.is_set())
|
|
85
|
+
start_lock = property(lambda self: self._start_lock)
|
|
86
|
+
queue = property(lambda self: self._queue)
|
|
87
|
+
|
|
88
|
+
def __init__(self, *args, run_func=None, prepare_func=None, cleanup_func=None, use_gevent=USE_GEVENT, rlock=True, start=True, **kwargs):
|
|
89
|
+
super().__init__()
|
|
90
|
+
|
|
91
|
+
self._thread = None
|
|
92
|
+
self._use_gevent = use_gevent
|
|
93
|
+
if use_gevent:
|
|
94
|
+
raise NotImplementedError
|
|
95
|
+
else:
|
|
96
|
+
if rlock:
|
|
97
|
+
self._lock = threading.RLock()
|
|
98
|
+
else:
|
|
99
|
+
self._lock = threading.Lock()
|
|
100
|
+
self._start_lock = threading.Lock()
|
|
101
|
+
self._start_event = threading.Event()
|
|
102
|
+
self._stop_event = threading.Event()
|
|
103
|
+
self._queue = queue.Queue()
|
|
104
|
+
self._sleep = time.sleep
|
|
105
|
+
|
|
106
|
+
self._prepare_fn = prepare_func
|
|
107
|
+
self._run_fn = run_func
|
|
108
|
+
self._cleanup_fn = cleanup_func
|
|
109
|
+
|
|
110
|
+
if start:
|
|
111
|
+
self(*args, **kwargs)
|
|
112
|
+
|
|
113
|
+
def ready(self):
|
|
114
|
+
if self._thread is None:
|
|
115
|
+
return True
|
|
116
|
+
if self._use_gevent:
|
|
117
|
+
raise NotImplementedError
|
|
118
|
+
else:
|
|
119
|
+
return not self._thread.is_alive()
|
|
120
|
+
|
|
121
|
+
def put(self, data):
|
|
122
|
+
self._queue.put(data)
|
|
123
|
+
|
|
124
|
+
def get(self, timeout=None):
|
|
125
|
+
return self._queue.get(timeout=timeout)
|
|
126
|
+
|
|
127
|
+
def _thread_run(self, *args, **kwargs):
|
|
128
|
+
if self._use_gevent:
|
|
129
|
+
raise NotImplementedError
|
|
130
|
+
else:
|
|
131
|
+
thread = threading.Thread(target=self._run_target, args=args, kwargs=kwargs)
|
|
132
|
+
thread.start()
|
|
133
|
+
return thread
|
|
134
|
+
|
|
135
|
+
def __call__(self, *args, **kwargs):
|
|
136
|
+
with get_lock(self._start_lock):
|
|
137
|
+
self._start_event.clear()
|
|
138
|
+
self._stop_event.clear()
|
|
139
|
+
self._thread = self._thread_run(*args, **kwargs)
|
|
140
|
+
self._start_event.wait()
|
|
141
|
+
|
|
142
|
+
def stop(self, wait=True):
|
|
143
|
+
self._stop_event.set()
|
|
144
|
+
if wait:
|
|
145
|
+
self.join()
|
|
146
|
+
|
|
147
|
+
def join(self):
|
|
148
|
+
# briefly acquiring _start_lock ensures that a concurrent, in-flight
|
|
149
|
+
# __call__() has finished assigning self._thread before we read it
|
|
150
|
+
with get_lock(self._start_lock):
|
|
151
|
+
thread = self._thread
|
|
152
|
+
if thread:
|
|
153
|
+
thread.join()
|
|
154
|
+
|
|
155
|
+
def _run_target(self, *args, **kwargs):
|
|
156
|
+
try:
|
|
157
|
+
try:
|
|
158
|
+
if self._prepare_fn:
|
|
159
|
+
self._prepare_fn(self, *args, **kwargs)
|
|
160
|
+
else:
|
|
161
|
+
self._prepare(*args, **kwargs)
|
|
162
|
+
except Exception as ex:
|
|
163
|
+
logger.exception(ex)
|
|
164
|
+
self._start_event.set()
|
|
165
|
+
raise
|
|
166
|
+
self._start_event.set()
|
|
167
|
+
try:
|
|
168
|
+
if self._run_fn:
|
|
169
|
+
self._run_fn(self, *args, **kwargs)
|
|
170
|
+
else:
|
|
171
|
+
self._run(*args, **kwargs)
|
|
172
|
+
except Exception as ex:
|
|
173
|
+
logger.exception(ex)
|
|
174
|
+
raise
|
|
175
|
+
finally:
|
|
176
|
+
self._cleanup(*args, **kwargs)
|
|
177
|
+
|
|
178
|
+
def _wait_stop(self, timeout):
|
|
179
|
+
# TODO: set it public
|
|
180
|
+
return self._stop_event.wait(timeout)
|
|
181
|
+
|
|
182
|
+
def _cleanup(self, *args, **kwargs):
|
|
183
|
+
if self._cleanup_fn:
|
|
184
|
+
self._cleanup_fn(self, *args, **kwargs)
|
|
185
|
+
if self._use_gevent:
|
|
186
|
+
import gevent
|
|
187
|
+
gevent.get_hub().destroy(True)
|
|
188
|
+
|
|
189
|
+
def wait_started(self):
|
|
190
|
+
self._start_event.wait()
|
|
191
|
+
|
|
192
|
+
def sleep(self, time_s):
|
|
193
|
+
self._sleep(time_s)
|
|
194
|
+
|
|
195
|
+
def _prepare(self, *args, **kwargs):
|
|
196
|
+
pass
|
|
197
|
+
|
|
198
|
+
def _run(self, *args, **kwargs):
|
|
199
|
+
pass
|
mosca/common/utils.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from weakref import WeakMethod
|
|
3
|
+
import logging
|
|
4
|
+
logger = logging.getLogger(__name__)
|
|
5
|
+
|
|
6
|
+
from .threads import Lock
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# TODO: allow multiple callback
|
|
11
|
+
|
|
12
|
+
class Callback:
|
|
13
|
+
blocked = property(lambda self: self._blocked)
|
|
14
|
+
|
|
15
|
+
def __init__(self, callback=None, blocked=False):
|
|
16
|
+
self._cb = None
|
|
17
|
+
self._blocked = blocked
|
|
18
|
+
self.register(callback)
|
|
19
|
+
|
|
20
|
+
def register(self, callback):
|
|
21
|
+
if callback is None:
|
|
22
|
+
self._cb = None
|
|
23
|
+
elif inspect.ismethod(callback):
|
|
24
|
+
# WeakMethod only supports bound methods; avoid keeping
|
|
25
|
+
# the owning object alive artificially.
|
|
26
|
+
self._cb = WeakMethod(callback)
|
|
27
|
+
else:
|
|
28
|
+
# plain function/lambda/functools.partial/etc: no natural
|
|
29
|
+
# "owner" to weakly reference, so keep a normal reference.
|
|
30
|
+
self._cb = lambda callback=callback: callback
|
|
31
|
+
|
|
32
|
+
@blocked.setter
|
|
33
|
+
def blocked(self, blocked: bool):
|
|
34
|
+
self._blocked = blocked
|
|
35
|
+
|
|
36
|
+
def __call__(self):
|
|
37
|
+
if not self._blocked:
|
|
38
|
+
cb = self._cb and self._cb()
|
|
39
|
+
if cb:
|
|
40
|
+
cb()
|
|
41
|
+
elif self._cb is not None:
|
|
42
|
+
logger.debug("Callback target has been garbage collected, skipping call.")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Blocker:
|
|
46
|
+
def __init__(self, func):
|
|
47
|
+
self.func = func
|
|
48
|
+
self._refcount = 0
|
|
49
|
+
self._lock = Lock()
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def blocked(self):
|
|
53
|
+
return self._refcount > 0
|
|
54
|
+
|
|
55
|
+
def __enter__(self):
|
|
56
|
+
with self._lock:
|
|
57
|
+
self._refcount += 1
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
def __exit__(self, type, value, traceback):
|
|
61
|
+
with self._lock:
|
|
62
|
+
self._refcount -= 1
|
|
63
|
+
refcount = self._refcount
|
|
64
|
+
if type is not None:
|
|
65
|
+
logger.debug("Call to func %s skipped due to exception.", self.func)
|
|
66
|
+
return
|
|
67
|
+
if refcount == 0:
|
|
68
|
+
self.func()
|
|
69
|
+
else:
|
|
70
|
+
logger.debug("Call to func %s delayed.", self.func)
|