Exemplo n.º 1
0
def maintcp():
  app = QApplication(sys.argv)
  loop = QEventLoop(app)
  asyncio.set_event_loop(loop)
  form = MyApp()
  form.show()

  with loop:
    coro = asyncio.start_server(form.handle_echo, '', 5000, loop=loop)
    loop.run_until_complete(coro)
    try:
      loop.run_forever()
    except Exception as ex:
      print("maintcp error: ",str(ex))
Exemplo n.º 2
0
class App(Observation):
    def __init__(self, subject):
        Observation.__init__(self, subject)
        self.subject = subject
        self.loop = None
        self.backend = None

        self.app = QApplication(sys.argv)
        self.app.setApplicationName(ApplicationInfo.name)
        self.app.setApplicationDisplayName(ApplicationInfo.name)

        Fonts.initDb()

        self.main = Main(subject)

        self._init_responders()

    def document_new_responder(self, e):
        self.subject = Subject()
        self._init_responders()

        self.main.close()
        self.main.deleteLater()
        self.main = Main(self.subject)
        self.backend.delete()
        self.backend = BackendRouter(self.loop, self.subject)

        self.main.show()

    def _init_responders(self):
        self.add_responder(events.view.main.FileNew,
                           self.document_new_responder)

    def run(self):
        self.loop = QEventLoop(self.app)
        self.backend = BackendRouter(self.loop, self.subject)
        asyncio.set_event_loop(self.loop)
        self.main.show()

        with self.loop:
            code = self.loop.run_forever()
            pending = asyncio.Task.all_tasks()
            self.notify(events.app.Quit())
            try:
                self.loop.run_until_complete(
                    asyncio.wait_for(asyncio.gather(*pending), 10))
            except asyncio.futures.TimeoutError as e:
                print(e)
            sys.exit(code)
Exemplo n.º 3
0
    def run(self):
        app = self.app

        app.setQuitOnLastWindowClosed(False)

        # Create the icon
        icon = QIcon(self.img_icon)

        # Create the tray
        tray = QSystemTrayIcon()
        tray.setIcon(icon)
        tray.setVisible(True)

        # Create the menu
        menu = QMenu()
        self.open_site_link = open_site = QAction("Open")
        open_site.triggered.connect(self.open_site)

        menu.addAction(open_site)

        # Add a Quit option to the menu.
        quit = QAction("Quit")
        quit.triggered.connect(app.quit)
        menu.addAction(quit)

        # Add the menu to the tray
        tray.setContextMenu(menu)

        loop = QEventLoop(self.app)
        asyncio.set_event_loop(loop)

        web_app = web.Application()

        cors = aiohttp_cors.setup(web_app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                )
        })
        cors.add(web_app.router.add_get('/', self.web_get_root))
        cors.add(web_app.router.add_get('/inc-link/', self.web_get_inc_link))

        return loop.run_until_complete(web._run_app(web_app, port=8766, host='127.0.0.1'))
Exemplo n.º 4
0
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)

progress = QProgressBar()
progress.setRange(0, 99)
progress.show()


async def master():
    await first_50()
    with QThreadExecutor(1) as exec:
        await loop.run_in_executor(exec, last_50)


async def first_50():
    for i in range(50):
        progress.setValue(i)
        await asyncio.sleep(.1)


def last_50():
    for i in range(50, 100):
        loop.call_soon_threadsafe(progress.setValue, i)
        time.sleep(.1)


with loop:
    loop.run_until_complete(master())
Exemplo n.º 5
0
class WavemeterChannelMonitor(WavemeterClient):
    """
    Connects to a :class:`WavemeterServer` to monitor a channel wavelength, temperature or pressure. There are three
    available GUI elements: a stripchart plot, a scalable number display, and an interferogram plot.

    :param host: the address at which the :class:`WavemeterServer` publisher is running
    :param channel: wavemeter channel (can be either <n>, '<n>', 'ch<n>', 'T' or 'p')
    :param port: port of the publisher
    :param rpc_host: host of the wavemeter server (only needed for interferograms, default = same as publisher)
    :param rpc_port: port of the wavemeter server rpc target (only needed for interferograms)
    :param rpc_target: target name for rpcs (only needed for interferograms)
    :param title: the window title (generated from the server details by default)
    :param window_width: initial width of the window in pixels
    :param window_x: initial x position of the window in pixels
    :param window_y: initial y position of the window in pixels
    :param enable_stripchart: show the stripchart
    :param stripchart_height: initial stripchart height in pixels
    :param stripchart_num_points: number of data points displayed in the stripchart
    :param plot_freq: True for frequency plot, False for wavelength plot
    :param plot_offset: y offset of the plot (unit is MHz for frequencies and nm for wavelengths)
    :param plot_pen: pen specification for the plot trace (see pyqtgraph documentation)
    :param plot_symbol: symbol specification for the plot points
    :param plot_bgr: bgr color of the plot
    :param enable_lcd: show the current value (wavelength or frequency) as a scalable number
    :param lcd_height: lcd height in pixels
    :param lcd_ndigits: number of digits in the lcd
    :param lcd_freq: start with the number display showing the frequency (default is wavelength)
    :param enable_interferograms: display the interferograms
    :param interferogram_update_interval: number of values after which to update the interferograms
    :param show_interferogram_update_control: show the spinbox to adjust interferogram update rate
    :param if0_pen: pen specification for the 1st interferogram
    :param if1_pen: pen specification for the 2nd interferogram
    :param interferogram_bgr: bgr color of the interferogram plot
    :param interferogram_height: initial height of the interferogram plot in pixels
    :param interferogram_exposure_control: enable control of wavemeter exposure times
    """

    def __init__(self, host: str = "::1", channel: str = "ch1",
                 port: int = 3281, rpc_host: str = "", rpc_port: int = 3280, rpc_target="wavemeter_server",
                 title: str = None, window_width: int = 611, window_x: int = 0, window_y: int = 0,
                 enable_stripchart: bool = True, stripchart_height: int = 350, stripchart_num_points: int = 100,
                 plot_freq: bool = True, plot_offset: float = 0., plot_pen: Any = pyqtgraph.mkPen(color="k", width=3),
                 plot_symbol: Any = None, plot_bgr: str = "w", enable_lcd: bool = True, lcd_height: int = 160,
                 lcd_ndigits: int = 10, lcd_freq: bool = False, enable_interferograms: bool = False,
                 interferogram_update_interval: int = 1, show_interferogram_update_control: bool = False,
                 if0_pen: Any = pyqtgraph.mkPen(color="g", width=1),
                 if1_pen: Any = pyqtgraph.mkPen(color="b", width=1), interferogram_bgr: str = "w",
                 interferogram_height: int = 150, interferogram_exposure_control: bool = False):

        # user interface components
        self._enable_stripchart = enable_stripchart
        self._enable_lcd = enable_lcd
        self._enable_interferograms = enable_interferograms

        self.lcd_ndigits = lcd_ndigits

        self.stripchart_pen = plot_pen
        self.stripchart_symbol = plot_symbol
        self.stripchart_bgr = plot_bgr

        self._app = QApplication(sys.argv)
        self._loop = QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

        self.plot_freq = plot_freq
        self.plot_offset = plot_offset

        self.lcd_freq = lcd_freq

        try:  # accept integer (or string lacking the "ch" prefix) as channel argument
            self.channel = "ch{}".format(int(channel))
        except ValueError:
            self.channel = channel

        self.not_a_wavelength = (self.channel in ["T", "p"])  # disable frequency conversion options for T and p
        if self.not_a_wavelength:
            self.plot_freq = False
            self.lcd_freq = False
            self._enable_interferograms = False

        self.title = title if title is not None else "{} monitor ({}:{})".format(channel, host, port)

        if self._enable_interferograms and not self.not_a_wavelength:
            channel_id = int(self.channel[2:])
            self.interferograms = InterferogramWidget(rpc_host=rpc_host, rpc_port=rpc_port, rpc_target=rpc_target,
                                                      channel_id=channel_id, if0_pen=if0_pen, if1_pen=if1_pen,
                                                      bgr_color=interferogram_bgr,
                                                      update_interval=interferogram_update_interval,
                                                      show_interval_spinbox=show_interferogram_update_control,
                                                      show_exposure_ctrl=interferogram_exposure_control)

        self._build_ui(window_width, window_x, window_y, stripchart_height, stripchart_num_points, lcd_height,
                       interferogram_height)

        super().__init__(self.channel, host, port, self._loop)

    def _build_ui(self, window_width, window_x, window_y, stripchart_height, stripchart_num_points, lcd_height,
                  interferogram_height):
        self.window = QWidget()
        self.window.setWindowTitle(self.title)
        window_height = stripchart_height * self._enable_stripchart \
            + lcd_height * self._enable_lcd \
            + interferogram_height * self._enable_interferograms
        self.window.resize(window_width, window_height)
        self.window.move(window_x, window_y)

        # The layout only contains one element (the splitter), but it is needed to rescale widgets as window is rescaled
        self.v_layout = QVBoxLayout()
        self.v_splitter = QSplitter(Qt.Vertical)
        self.v_layout.addWidget(self.v_splitter)

        self.window.setLayout(self.v_layout)
        self.v_layout.addWidget(self.v_splitter)

        splitter_sizes = []
        if self._enable_stripchart:
            self._build_stripchart(stripchart_num_points)
            splitter_sizes.append(stripchart_height)
        if self._enable_lcd:
            self._build_lcd()
            splitter_sizes.append(lcd_height)
        if self._enable_interferograms:
            self.v_splitter.addWidget(self.interferograms)
            splitter_sizes.append(interferogram_height)

        self.v_splitter.setSizes(splitter_sizes)

    def _build_stripchart(self, num_points):
        plot_title = ""
        if self.plot_freq:
            plot_y_label = "frequency (MHz)"
            if self.plot_offset != 0:
                plot_title = "offset: {:11} THz".format(self.plot_offset * 1e-6)
        else:
            if self.channel == "T":
                plot_y_label = "temperature (degrees C)"
                if self.plot_offset != 0:
                    plot_title = "offset: {:5} degrees C".format(self.plot_offset)
            elif self.channel == "p":
                plot_y_label = "pressure (mbar)"
                if self.plot_offset != 0:
                    plot_title = "offset: {:6} mbar".format(self.plot_offset)
            else:
                plot_y_label = "vac. wavelength (nm)"
                if self.plot_offset != 0:
                    plot_title = "offset: {:10} nm".format(self.plot_offset)

        self.stripchart = Stripchart(num_points=num_points, xvalues=True, offset=self.plot_offset,
                                     plot_title=plot_title, plot_pen=self.stripchart_pen,
                                     plot_symbol=self.stripchart_symbol, plot_bgr=self.stripchart_bgr,
                                     x_label="wavemeter time stamp (s)", y_label=plot_y_label, y_grid=True)
        clear_button = QPushButton("&Clear")
        clear_button.clicked.connect(self.stripchart.clear_data)

        layout = QVBoxLayout()
        layout.addWidget(self.stripchart)
        layout.addWidget(clear_button)
        widget = QWidget()
        widget.setLayout(layout)
        self.v_splitter.addWidget(widget)

    def _add_stripchart_point(self):
        if self.value < 0:  # ignore error codes
            return
        if self.plot_freq:  # plot frequency in MHz
            self.stripchart.add_point(self.timestamp * 1e-3, 299792456e3 / self.value)
        else:  # plot wavelength in nm
            self.stripchart.add_point(self.timestamp * 1e-3, self.value)

    def _build_lcd(self):
        layout = QVBoxLayout()
        self.lcd = QLCDNumber()
        self.lcd.setSmallDecimalPoint(True)
        self.lcd.setDigitCount(self.lcd_ndigits)
        freq_checkbox = QCheckBox("Display frequency")
        freq_checkbox.setChecked(self.lcd_freq)

        def switch_wl_freq():
            self.lcd_freq = freq_checkbox.isChecked()
            self._update_lcd()

        freq_checkbox.clicked.connect(switch_wl_freq)
        layout.addWidget(self.lcd)
        if not self.not_a_wavelength:
            layout.addWidget(freq_checkbox)
        widget = QWidget()
        widget.setLayout(layout)
        self.v_splitter.addWidget(widget)

    def _update_lcd(self):
        if self.value > 0:
            value = 299792456e-3 / self.value if self.lcd_freq else self.value
            # next line is to keep number of decimals constant (i.e. display trailing zeros)
            self.lcd.display("{{:.0{}f}}".format(self.lcd_ndigits-len(str(int(value)))).format(value))
        elif self.value == -2:  # bad signal
            self.lcd.display("b")
        elif self.value == -3:  # underexposed
            self.lcd.display("u")
        elif self.value == -4:  # overexposed
            self.lcd.display("o")
        else:
            self.lcd.display(self.value)

    def _init_callback(self):
        if self._enable_lcd:
            self._update_lcd()
        if self._enable_interferograms:
            self.interferograms.update_data()

    def _new_value_callback(self):
        if self._enable_stripchart:
            self._add_stripchart_point()
        if self._enable_lcd:
            self._update_lcd()
        if self._enable_interferograms:
            self.interferograms.update_data()

    def run(self):
        self.window.show()
        self._loop.run_forever()
        if self._subscriber is not None:
            self._loop.run_until_complete(self._subscriber.close())
Exemplo n.º 6
0
class Application(QtApplication):
    """ Add asyncio support . Seems like a complete hack compared to twisted
    but whatever.

    """

    loop = Instance(QEventLoop)
    queue = Instance(Queue, ())
    running = Bool()

    def __init__(self):
        super().__init__()
        self.loop = QEventLoop(self._qapp)
        asyncio.set_event_loop(self.loop)
        for name in ('asyncqt._unix._Selector',
                     'asyncqt._QEventLoop',
                     'asyncqt._SimpleTimer'):
            log = logging.getLogger(name)
            log.setLevel(logging.WARN)

    def start(self):
        """ Run using the event loop

        """
        log.info("Application starting")
        self.running = True
        with self.loop:
            try:
                self.loop.run_until_complete(self.main())
            except RuntimeError as e:
                if 'loop stopped' not in str(e):
                    raise

    async def main(self):
        """ Run any async deferred calls in the main ui loop.

        """
        while self.running:
            try:
                task = self.queue.get(block=False)
                await task
            except Empty:
                self.process_events()
                await asyncio.sleep(0.1)
            except Exception as e:
                if 'cannot enter context' in str(e):
                    # HACK: Something is jacked up
                    await asyncio.sleep(0.1)
                    continue
                log.exception(e)

    def process_events(self):
        """ Let the the app process events during long-running cpu intensive
        tasks.

        """
        self._qapp.processEvents()

    def deferred_call(self, callback, *args, **kwargs):
        """ Invoke a callable on the next cycle of the main event loop
        thread.

        Parameters
        ----------
        callback : callable
            The callable object to execute at some point in the future.

        args, kwargs
            Any additional positional and keyword arguments to pass to
            the callback.

        """
        if asyncio.iscoroutinefunction(callback) or kwargs.pop('async_', None):
            task = asyncio.create_task(callback(*args, **kwargs))
            return self.add_task(task)
        return super().deferred_call(callback, *args, **kwargs)

    def timed_call(self, ms, callback, *args, **kwargs):
        """ Invoke a callable on the main event loop thread at a
        specified time in the future.

        Parameters
        ----------
        ms : int
            The time to delay, in milliseconds, before executing the
            callable.

        callback : callable
            The callable object to execute at some point in the future.

        args, kwargs
            Any additional positional and keyword arguments to pass to
            the callback.

        """
        if asyncio.iscoroutinefunction(callback) or kwargs.pop('async_', None):
            task = asyncio.create_task(callback(*args, **kwargs))
            return super().timed_call(ms, self.add_task, task)
        return super().timed_call(ms, callback, *args, **kwargs)

    def add_task(self, task):
        """ Put a task into the queue

        """
        self.queue.put(task)
Exemplo n.º 7
0
class WavemeterRemote:
    """
    Simple remote control for a :class:`WavemeterServer`, providing controls to start and stop the measurement,
    calibrate, control autocalibration and displaying the timestamp of the latest successful calibration as well as
    the autocalibration countdown.

    :param host: the address at which the :class:`WavemeterServer` RPC server and Publisher are running
    :param rpc_target: name of the RPC target
    :param rpc_port: port of the RPC server
    :param notifier_port: port of the publisher (notifier "status", containing the calibration timestamp and countdown)
    :param title: the window title (generated from the RPC target name by default)
    :param window_x: initial x position of the window in pixels
    :param window_y: initial y position of the window in pixels
    :param cal_channel: startup entry for the calibration channel
    :param cal_wl: startup entry for the calibration wavelength (in nm)
    :param cal_threshold: startup entry for the autocalibration threshold (in nm)
    :param cal_interval: startup entry for the autocalibration interval (in s)
    :param cal_retry_interval: startup entry for the autocalibration retry interval (in s)
    :param start_autocal: set to start autocalibration on startup
    """
    def __init__(self,
                 host: str = "::1",
                 rpc_target: str = "wavemeter_server",
                 rpc_port: int = 3280,
                 notifier_port: int = 3281,
                 title: str = None,
                 window_x: int = 0,
                 window_y: int = 0,
                 cal_channel: int = 1,
                 cal_wl: float = 633.,
                 cal_threshold: float = 0.00005,
                 cal_interval: int = 600,
                 cal_retry_interval: int = 10,
                 start_autocal: bool = False):

        self._app = QApplication(sys.argv)
        self._loop = QEventLoop(self._app)
        asyncio.set_event_loop(self._loop)

        self.wm_status_dict = {
            "autocal_countdown": 0,
            "calibration_timestamp": -1
        }

        self._subscriber = Subscriber("status", self._subscriber_init_cb,
                                      self._subscriber_mod_cb)
        logger.info(
            "Connecting to publisher at {}:{}, notifier name: status".format(
                host, notifier_port))
        self._loop.run_until_complete(
            self._subscriber.connect(host, notifier_port))

        logger.info(
            "Connecting to RPC server at {}:{}, target name: {}".format(
                host, rpc_port, rpc_target))
        self._rpc_client = BestEffortClient(host, rpc_port, rpc_target)
        self._loop.create_task(self.keepalive_loop())

        self.title = title if title is not None else "Wavemeter remote control ({} at {})".format(
            rpc_target, host)

        self._ui_input_elements = dict(
        )  # stores all input elements, used on function calls to retrieve their values
        self._build_ui(window_x, window_y, cal_channel, cal_wl, cal_threshold,
                       cal_interval, cal_retry_interval)

        if start_autocal and self._rpc_client is not None:
            self._rpc_client.start_autocalibration(cal_channel, cal_wl,
                                                   cal_threshold, cal_interval,
                                                   cal_retry_interval)

    def _build_ui(self, window_x, window_y, cal_channel, cal_wl, cal_threshold,
                  cal_interval, cal_retry_interval):
        self.window = QWidget()
        self.window.setWindowTitle(self.title)

        self.window.move(window_x, window_y)

        self.v_layout = QVBoxLayout()

        self.window.setLayout(self.v_layout)

        indicator_font = QFont()
        indicator_font.setPointSize(18)
        self.calibration_timestamp_display = QLabel()
        self.calibration_timestamp_display.setFont(indicator_font)
        self.calibration_countdown_display = QLabel()
        self.calibration_countdown_display.setFont(indicator_font)

        startstop_gb = QGroupBox("Measurement")
        startstop_gb_layout = QHBoxLayout()
        startstop_gb.setLayout(startstop_gb_layout)

        start_button = QPushButton("&Start measurement")

        def start():
            if self._rpc_client is not None:
                logger.info("sending RPC start_measurement()")
                self._rpc_client.start_measurement()

        start_button.clicked.connect(start)
        startstop_gb_layout.addWidget(start_button)

        stop_button = QPushButton("S&top measurement")

        def stop():
            if self._rpc_client is not None:
                logger.info("sending RPC stop_measurement()")
                self._rpc_client.stop_measurement()

        stop_button.clicked.connect(stop)
        startstop_gb_layout.addWidget(stop_button)

        self.v_layout.addWidget(startstop_gb)

        cal_gb = QGroupBox("Calibration")
        cal_gb_outer_layout = QVBoxLayout()
        cal_gb_outer_layout.addWidget(self.calibration_timestamp_display)
        cal_gb_outer_layout.addWidget(self.calibration_countdown_display)
        cal_gb_layout = QHBoxLayout()
        cal_gb_outer_layout.addLayout(cal_gb_layout)
        cal_gb.setLayout(cal_gb_outer_layout)

        calibrate_gb = QGroupBox("Calibrate")
        calibrate_gb_layout = QFormLayout()
        calibrate_gb.setLayout(calibrate_gb_layout)

        calibrate_button = QPushButton("&Calibrate")

        def calibrate():
            ch = int(self._ui_input_elements["cal_channel"].value())
            wl = self._ui_input_elements["cal_wl"].value()
            if self._rpc_client is not None:
                logger.info(
                    "sending RPC calibrate(channel={}, wavelength={})".format(
                        ch, wl))
                self._rpc_client.calibrate(ch, wl)

        calibrate_button.clicked.connect(calibrate)

        calibrate_gb_layout.addRow("", calibrate_button)

        self._ui_input_elements.update({"cal_channel": QDoubleSpinBox()})
        self._ui_input_elements["cal_channel"].setRange(1, 100)
        self._ui_input_elements["cal_channel"].setSingleStep(1)
        self._ui_input_elements["cal_channel"].setDecimals(0)
        self._ui_input_elements["cal_channel"].setValue(cal_channel)
        calibrate_gb_layout.addRow("Channel",
                                   self._ui_input_elements["cal_channel"])

        self._ui_input_elements.update({"cal_wl": QDoubleSpinBox()})
        self._ui_input_elements["cal_wl"].setRange(1., 10000.)
        self._ui_input_elements["cal_wl"].setSingleStep(1e-10)
        self._ui_input_elements["cal_wl"].setDecimals(10)
        self._ui_input_elements["cal_wl"].setSuffix(" nm")
        self._ui_input_elements["cal_wl"].setValue(cal_wl)
        calibrate_gb_layout.addRow("Wavelength",
                                   self._ui_input_elements["cal_wl"])

        cal_gb_layout.addWidget(calibrate_gb)

        autocalibration_gb = QGroupBox("Autocalibration")
        autocalibration_gb_layout = QFormLayout()
        autocalibration_gb.setLayout(autocalibration_gb_layout)

        start_autocalibration_button = QPushButton("Start &autocalibration")

        def start_autocalibration():
            ch = int(self._ui_input_elements["autocal_channel"].value())
            wl = self._ui_input_elements["autocal_wl"].value()
            thr = self._ui_input_elements["autocal_threshold"].value()
            interval = int(self._ui_input_elements["autocal_interval"].value())
            retry_interval = int(
                self._ui_input_elements["autocal_retry_interval"].value())
            if self._rpc_client is not None:
                logger.info(
                    "sending RPC start_autocalibration(channel={}, wavelength={}, threshold={}, "
                    "interval={}, retry_interval={})".format(
                        ch, wl, thr, interval, retry_interval))
                self._rpc_client.start_autocalibration(ch, wl, thr, interval,
                                                       retry_interval)

        start_autocalibration_button.clicked.connect(start_autocalibration)

        autocalibration_gb_layout.addRow("", start_autocalibration_button)

        self._ui_input_elements.update({"autocal_channel": QDoubleSpinBox()})
        self._ui_input_elements["autocal_channel"].setRange(1, 100)
        self._ui_input_elements["autocal_channel"].setSingleStep(1)
        self._ui_input_elements["autocal_channel"].setDecimals(0)
        self._ui_input_elements["autocal_channel"].setValue(cal_channel)
        autocalibration_gb_layout.addRow(
            "Channel", self._ui_input_elements["autocal_channel"])

        self._ui_input_elements.update({"autocal_wl": QDoubleSpinBox()})
        self._ui_input_elements["autocal_wl"].setRange(1., 10000.)
        self._ui_input_elements["autocal_wl"].setSingleStep(1e-10)
        self._ui_input_elements["autocal_wl"].setDecimals(10)
        self._ui_input_elements["autocal_wl"].setSuffix(" nm")
        self._ui_input_elements["autocal_wl"].setValue(cal_wl)
        autocalibration_gb_layout.addRow("Wavelength",
                                         self._ui_input_elements["autocal_wl"])

        self._ui_input_elements.update({"autocal_threshold": QDoubleSpinBox()})
        self._ui_input_elements["autocal_threshold"].setRange(1e-10, 10000.)
        self._ui_input_elements["autocal_threshold"].setSingleStep(1e-10)
        self._ui_input_elements["autocal_threshold"].setDecimals(10)
        self._ui_input_elements["autocal_threshold"].setSuffix(" nm")
        self._ui_input_elements["autocal_threshold"].setValue(cal_threshold)
        autocalibration_gb_layout.addRow(
            "Threshold", self._ui_input_elements["autocal_threshold"])

        self._ui_input_elements.update({"autocal_interval": QDoubleSpinBox()})
        self._ui_input_elements["autocal_interval"].setRange(1, 100000)
        self._ui_input_elements["autocal_interval"].setSingleStep(1)
        self._ui_input_elements["autocal_interval"].setDecimals(0)
        self._ui_input_elements["autocal_interval"].setSuffix(" s")
        self._ui_input_elements["autocal_interval"].setValue(cal_interval)
        autocalibration_gb_layout.addRow(
            "Interval", self._ui_input_elements["autocal_interval"])

        self._ui_input_elements.update(
            {"autocal_retry_interval": QDoubleSpinBox()})
        self._ui_input_elements["autocal_retry_interval"].setRange(1, 100000)
        self._ui_input_elements["autocal_retry_interval"].setSingleStep(1)
        self._ui_input_elements["autocal_retry_interval"].setDecimals(0)
        self._ui_input_elements["autocal_retry_interval"].setSuffix(" s")
        self._ui_input_elements["autocal_retry_interval"].setValue(
            cal_retry_interval)
        autocalibration_gb_layout.addRow(
            "Retry interval",
            self._ui_input_elements["autocal_retry_interval"])

        stop_autocalibration_button = QPushButton("St&op autocalibration")

        def stop_autocalibration():
            if self._rpc_client is not None:
                logger.info("sending RPC stop_autocalibration()")
                self._rpc_client.stop_autocalibration()

        stop_autocalibration_button.clicked.connect(stop_autocalibration)

        autocalibration_gb_layout.addRow("", stop_autocalibration_button)

        cal_gb_layout.addWidget(autocalibration_gb)

        self.v_layout.addWidget(cal_gb)

        exposure_gb = QGroupBox("Exposure")
        exposure_gb_layout = QHBoxLayout()
        exposure_gb.setLayout(exposure_gb_layout)

        control_form = QFormLayout()
        self._ui_input_elements.update({"exp_channel": QDoubleSpinBox()})
        self._ui_input_elements["exp_channel"].setRange(1, 100)
        self._ui_input_elements["exp_channel"].setSingleStep(1)
        self._ui_input_elements["exp_channel"].setDecimals(0)
        self._ui_input_elements["exp_channel"].setValue(1)
        control_form.addRow("Channel", self._ui_input_elements["exp_channel"])

        self._ui_input_elements.update({"exp_time1": QDoubleSpinBox()})
        self._ui_input_elements["exp_time1"].setRange(1, 2000)
        self._ui_input_elements["exp_time1"].setSingleStep(1)
        self._ui_input_elements["exp_time1"].setDecimals(0)
        self._ui_input_elements["exp_time1"].setSuffix(" ms")
        self._ui_input_elements["exp_time1"].setValue(1)
        control_form.addRow("Time 1", self._ui_input_elements["exp_time1"])

        self._ui_input_elements.update({"exp_time2": QDoubleSpinBox()})
        self._ui_input_elements["exp_time2"].setRange(0, 2000)
        self._ui_input_elements["exp_time2"].setSingleStep(1)
        self._ui_input_elements["exp_time2"].setDecimals(0)
        self._ui_input_elements["exp_time2"].setSuffix(" ms")
        self._ui_input_elements["exp_time2"].setValue(1)
        control_form.addRow("Time 2", self._ui_input_elements["exp_time2"])

        self._ui_input_elements.update({"exp_auto": QCheckBox()})
        control_form.addRow("Auto adjust", self._ui_input_elements["exp_auto"])

        exposure_gb_layout.addLayout(control_form)

        exposure_button_layout = QVBoxLayout()

        exposure_get_button = QPushButton("&Get")

        def exposure_get():
            channel = int(self._ui_input_elements["exp_channel"].value())
            if self._rpc_client is not None:
                logger.info(
                    "sending RPC get_exposure_time({}, 1)".format(channel))
                time1 = self._rpc_client.get_exposure_time(channel, 1)
                logger.info(
                    "sending RPC get_exposure_time({}, 2)".format(channel))
                time2 = self._rpc_client.get_exposure_time(channel, 2)
                logger.info(
                    "sending RPC get_exposure_auto_adjust({})".format(channel))
                auto = self._rpc_client.get_exposure_auto_adjust(channel)
                self._ui_input_elements["exp_time1"].setValue(time1)
                self._ui_input_elements["exp_time2"].setValue(time2)
                self._ui_input_elements["exp_auto"].setChecked(auto)

        exposure_get_button.clicked.connect(exposure_get)

        exposure_button_layout.addWidget(exposure_get_button)

        exposure_set_button = QPushButton("S&et")

        def exposure_set():
            channel = int(self._ui_input_elements["exp_channel"].value())
            time1 = int(self._ui_input_elements["exp_time1"].value())
            time2 = int(self._ui_input_elements["exp_time2"].value())
            auto = bool(self._ui_input_elements["exp_auto"].isChecked())
            if self._rpc_client is not None:
                logger.info("sending RPC set_exposure_time({}, 1, {})".format(
                    channel, time1))
                self._rpc_client.set_exposure_time(channel, 1, time1)
                logger.info("sending RPC set_exposure_time({}, 2, {})".format(
                    channel, time2))
                self._rpc_client.set_exposure_time(channel, 2, time2)
                logger.info(
                    "sending RPC set_exposure_auto_adjust({}, {})".format(
                        channel, auto))
                self._rpc_client.set_exposure_auto_adjust(channel, auto)

        exposure_set_button.clicked.connect(exposure_set)

        exposure_button_layout.addWidget(exposure_set_button)

        exposure_gb_layout.addLayout(exposure_button_layout)

        self.v_layout.addWidget(exposure_gb)

    def _update_cal_timestamp(self):
        self.calibration_timestamp_display.setText(
            "Last successful"
            " calibration:\n{}".format(
                time.asctime(
                    time.localtime(
                        self.wm_status_dict["calibration_timestamp"]))))

    def _update_cal_countdown(self):
        self.calibration_countdown_display.setText(
            "Next autocalibration attempt in {:.0f} s".format(
                self.wm_status_dict["autocal_countdown"]))

    def _subscriber_init_cb(self, data):
        self.wm_status_dict = data
        self._update_cal_timestamp()
        self._update_cal_countdown()
        return data

    def _subscriber_mod_cb(self, mod):
        try:
            if mod["key"] == "calibration_timestamp":
                self._update_cal_timestamp()
            elif mod["key"] == "autocal_countdown":
                self._update_cal_countdown()
        except KeyError:
            pass

    keepalive_interval = 3600.  # ping RPC server after this interval to keep the connection alive

    async def keepalive_loop(self):
        """Keep the RPC connection alive"""
        while True:
            logger.info("Pinging the RPC server to keep the connection alive")
            self._rpc_client.ping()
            await asyncio.sleep(self.keepalive_interval)

    def run(self):
        self.window.show()
        self._loop.run_forever()
        if self._subscriber is not None:
            self._loop.run_until_complete(self._subscriber.close())
        if self._rpc_client is not None:
            self._rpc_client.close_rpc()
            self.sensor_shelves[sensor_states.shelf] = sensor_shelf_widget

            self.render_view()

        await self.client.subscribe(self.subject, cb=callback_)

        future = asyncio.Future()
        await asyncio.gather(future)

    def close(self) -> None:
        self.client.close()


if __name__ == '__main__':
    if (sys.version_info[0], sys.version_info[1]) < (3, 7):
        raise Exception("Required Python 3.7+")

    app = QApplication(sys.argv)
    loop = QEventLoop(app)

    asyncio.set_event_loop(loop)

    wgt = SensorSubscriberWidget()
    wgt.show()

    try:
        with loop:
            sys.exit(loop.run_until_complete(wgt.receive()))
    except (Exception, SystemExit, KeyboardInterrupt):
        wgt.close()