Source code for nxsblisswriter.NXSWriterService

#!/usr/bin/env python
#   This file is part of nexdatas - Tango Server for NeXus data writer
#
#    Copyright (C) 2026 DESY, Jan Kotanski <jkotan@mail.desy.de>
#
#    nexdatas is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    nexdatas is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with nexdatas.  If not, see <http://www.gnu.org/licenses/>.
#

""" Provides the access to a database with NDTS configuration files """

import weakref
import time
import threading

from blissdata.redis_engine.store import DataStore
from blissdata.redis_engine.scan import ScanState
from blissdata.redis_engine.exceptions import EndOfStream
from blissdata.redis_engine.exceptions import NoScanAvailable

from .NXSFile import create_nexus_file
from .StreamSet import StreamSet


[docs] class NXSWriterService: def __init__(self, redis_url, session, next_scan_timeout, default_nexus_path="/scan{serialno}:NXentry/" "instrument:NXinstrument/collection", point_sleep_time=0.01, vmaps_shape_plugins=None, vds_plugins=None, server=None): """ constructor :param redis_url: blissdata redis url :type redis_url: :obj:`str` :param session: blissdata session name :type session: :obj:`str` :param next_scan_timeout: timeout between the scans in seconds :type next_scan_timeout: :obj:`int` :param default_nexus_path: default nexus path :type default_nexus_path: :obj:`str` :param point_sleep_time: sleep time between write point calls :type point_sleep_time: :obj:`float` :param vmaps_shape_plugins: vmaps_shape plugins :type vmaps_shape_plugins: :obj:`list` <:obj:`str`> :param vds_plugins: vds plugins :type vds_plugins: :obj:`list` <:obj:`str`> :param server: NXSConfigServer instance :type server: :class:`tango.LatestDeviceImpl` """ #: (:class:`StreamSet` or :class:`tango.LatestDeviceImpl`) stream set self._streams = StreamSet(weakref.ref(server) if server else None) #: (:obj:`bool`) service running flag self.__running = False #: (:obj:`bool`) service error flag self.__error = False #: (:obj:`int`) scan timeout in seconds self.__next_scan_timeout = next_scan_timeout #: (:obj:`str`) default nexus path self.__default_nexus_path = default_nexus_path #: (:obj:`str`) session name self.__session = session #: (:obj:`float`) sleep time between write point calls self.__point_sleep_time = point_sleep_time #: (:obj:`list` <:obj:`str`>) vmaps shape plugins self.__vmaps_shape_plugins = vmaps_shape_plugins or [] #: (:obj:`list` <:obj:`str`>) vds plugins self.__vds_plugins = vds_plugins or ["lima", "asapo_stream"] #: (:class:`blissdata.redis_engine.store.DataStore`) datastore self.__datastore = DataStore(redis_url) #: (:obj:`list`<:obj:`str`>) error list self.__errors = [] #: (:class:`threading.Lock`) threading lock self.__error_lock = threading.Lock() #: (:obj:`dict`<:obj:`str`, :class:`ScanWriter`>) scan writers self.__sws = {}
[docs] def start(self): """ start writer service """ self.__running = True self.__error = False timestamp = None self.__errors = [] while self.__running: try: try: timestamp, key = self.__datastore.get_next_scan( since=timestamp, timeout=self.__next_scan_timeout ) except NoScanAvailable: continue scan = self.__datastore.load_scan(key) if self.__session in ["__all__", scan.session]: self.join_scans() sw = ScanWriter( scan, self._streams, self.__next_scan_timeout, self.__default_nexus_path, self.__point_sleep_time, self.__vmaps_shape_plugins, self.__vds_plugins, ) self.__sws[key] = sw sw.start() # self.write_scan(scan) except Exception as e: self.__error = True with self.__error_lock: self.__errors.append(str(e))
[docs] def join_scans(self, stop=False): """ join scans which are stopped :param stop: stop all scans flag :type stop: :obj:`bool` """ for key in list(self.__sws.keys()): sw = self.__sws.pop(key) if stop: sw.running = False if not sw.running: if sw.error: with self.__error_lock: self.__errors.extend(sw.errors[:]) sw.join()
[docs] def get_status(self): """ get writer service status """ if self.__error: status = "is FAILED" else: status = "is RUNNING" if self.__running else "is STOPPED" return "NXSBlissWriter %s" % status
[docs] def stop(self): """ stop writer service """ self.__running = False self.joint_scans(stop=True)
[docs] def errors(self): """ list of errors """ errors = [] with self.__error_lock: errors = self.__errors[:] return errors
[docs] class ScanWriter(threading.Thread): def __init__(self, scan, streams, next_scan_timeout, default_nexus_path="/scan{serialno}:NXentry/" "instrument:NXinstrument/collection", point_sleep_time=0.01, vmaps_shape_plugins=None, vds_plugins=None): """ constructor :param scan: blissdata redis url :type scan: :class:`Scan` :param streams: tango streams :type streams: :class:`StreamSet` or :class:`tango.LatestDeviceImpl` :param next_scan_timeout: timeout between the scans in seconds :type next_scan_timeout: :obj:`int` :param default_nexus_path: default nexus path :type default_nexus_path: :obj:`str` :param point_sleep_time: sleep time between write point calls :type point_sleep_time: :obj:`float` :param vmaps_shape_plugins: vmaps_shape plugins :type vmaps_shape_plugins: :obj:`list` <:obj:`str`> :param vds_plugins: vds plugins :type vds_plugins: :obj:`list` <:obj:`str`> """ threading.Thread.__init__(self) #: (:class:`Scan`) blissdata scan self._scan = scan #: (:class:`StreamSet` or :class:`tango.LatestDeviceImpl`) stream set self._streams = streams #: (:obj:`bool`) service running flag self.running = True #: (:obj:`bool`) service error flag self.error = False #: (:obj:`int`) scan timeout in seconds self.__next_scan_timeout = next_scan_timeout #: (:obj:`str`) default nexus path self.__default_nexus_path = default_nexus_path #: (:obj:`float`) sleep time between write point calls self.__point_sleep_time = point_sleep_time #: (:obj:`list` <:obj:`str`>) vmaps shape plugins self.__vmaps_shape_plugins = vmaps_shape_plugins or [] #: (:obj:`list` <:obj:`str`>) vds plugins self.__vds_plugins = vds_plugins or ["lima", "asapo_stream"] #: (:obj:`list`<:obj:`str`>) error list self.errors = [] #: (:class:`threading.Lock`) threading lock self.error_lock = threading.Lock()
[docs] def run(self): """ write scan data """ self.running = True try: while self._scan.state < ScanState.PREPARED and self.running: time.sleep(self.__point_sleep_time) self._scan.update() self._streams.info( "NXSWriterService::write_scan CREATE FILE: %s" % self._scan.number) nxsfl = create_nexus_file( self._scan, self._streams, self.__default_nexus_path, self.__vmaps_shape_plugins, self.__vds_plugins ) if nxsfl is None: return self._streams.info( "NXSWriterService::write_scan INIT: %s" % self._scan.number) nxsfl.write_init_snapshot() nxsfl.prepareChannels() # while scan.state < ScanState.STOPPED: while self.running: try: self._scan.update(block=False) self._streams.debug( "NXSWriterService::write_scan SCAN POINT: %s" % self._scan.number) nxsfl.write_scan_points() time.sleep(self.__point_sleep_time) except EndOfStream: break except Exception: break counter = 0 while self._scan.state < ScanState.CLOSED and self.running: counter += 1 time.sleep(self.__point_sleep_time) self._scan.update(timeout=self.__next_scan_timeout) if counter > 30: self._streams.error( "NXSWriterService::write_scan scan.info not CLOSED: %s" % self._scan.number) self.running = False self._streams.debug( "NXSWriterService::update VDS: %s" % self._scan.number) nxsfl.updateVDS() self._streams.info( "NXSWriterService::write_scan FINAL: %s" % self._scan.number) nxsfl.write_final_snapshot() except Exception as e: self.error = True with self.error_lock: self.errors.append(str(e)) self._streams.error("NXSWriterService::error %s" % str(e)) finally: try: nxsfl.close() except Exception as e: with self.error_lock: self.errors.append(str(e)) self._streams.error("NXSWriterService::error %s" % str(e)) self.running = False
[docs] def main(): """ main function """ import argparse parser = argparse.ArgumentParser( description="Start a Tango server for saving data from blisdata" "in NeXus file" ) parser.add_argument( "--redis-url", "-u", type=str, dest="redis_url", default="redis://localhost:6380", help="Blissdata redis url ('redis://localhost:6380' by default)", ) parser.add_argument( "--session", "-s", type=str, dest="session", default="", help="Blissdata session name ('' by default)", ) parser.add_argument( "--scan-timeout", "-t", type=int, dest="scan_timeout", default=0, help="Scan timeout (0 by default)", ) args = parser.parse_args() NXSWriterService(args.redis_url, args.session, args.scan_timeout).start()
if __name__ == "__main__": main()