Debian Codegraph @

pymeasure/experiment/listeners.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26 from logging import StreamHandler, FileHandler
27
28 from ..log import QueueListener
29 from ..thread import StoppableThread
30
31 log = logging.getLogger(__name__)
32 log.addHandler(logging.NullHandler())
33
34 try:
35 import zmq
36 import cloudpickle
37 except ImportError:
38 zmq = None
39 cloudpickle = None
40 log.warning("ZMQ and cloudpickle are required for TCP communication")
41
42
43 class Monitor(QueueListener):
44 def __init__(self, results, queue):
45 console = StreamHandler()
46 console.setFormatter(results.formatter)
47
48 super().__init__(queue, console)
49
50
51 class Listener(StoppableThread):
52 """Base class for Threads that need to listen for messages on
53 a ZMQ TCP port and can be stopped by a thread-safe method call
54 """
55
56 def __init__(self, port, topic='', timeout=0.01):
57 """ Constructs the Listener object with a subscriber port
58 over which to listen for messages
59
60 :param port: TCP port to listen on
61 :param topic: Topic to listen on
62 :param timeout: Timeout in seconds to recheck stop flag
63 """
64 super().__init__()
65
66 self.port = port
67 self.topic = topic
68 self.context = zmq.Context()
69 log.debug(f"{self.__class__.__name__} has ZMQ Context: {self.context!r}")
70 self.subscriber = self.context.socket(zmq.SUB)
71 self.subscriber.setsockopt(zmq.SUBSCRIBE, topic.encode())
72 self.subscriber.connect('tcp://localhost:%d' % port)
73 log.info("%s connected to '%s' topic on tcp://localhost:%d" % (
74 self.__class__.__name__, topic, port))
75
76 self.poller = zmq.Poller()
77 self.poller.register(self.subscriber, zmq.POLLIN)
78 self.timeout = timeout
79
80 def receive(self, flags=0):
81 topic, record = self.subscriber.recv_serialized(
82 deserialize=lambda msg: (msg[0].decode(), cloudpickle.loads(msg[1])),
83 flags=flags
84 )
85 return topic, record
86
87 def message_waiting(self):
88 """Check if we have a message, wait at most until timeout."""
89 return self.poller.poll(self.timeout * 1000) # poll timeout is in ms
90
91 def __repr__(self):
92 return "<{}(port={},topic={},should_stop={})>".format(
93 self.__class__.__name__, self.port, self.topic, self.should_stop())
94
95
96 class Recorder(QueueListener):
97 """ Recorder loads the initial Results for a filepath and
98 appends data by listening for it over a queue. The queue
99 ensures that no data is lost between the Recorder and Worker.
100 """
101
102 def __init__(self, results, queue, **kwargs):
103 """ Constructs a Recorder to record the Procedure data into
104 the file path, by waiting for data on the subscription port
105 """
106 handlers = []
107 for filename in results.data_filenames:
108 fh = FileHandler(filename=filename, **kwargs)
109 fh.setFormatter(results.formatter)
110 fh.setLevel(logging.NOTSET)
111 handlers.append(fh)
112
113 super().__init__(queue, *handlers)
114
115 def stop(self):
116 for handler in self.handlers:
117 handler.close()
118
119 super().stop()