Esempio n. 1
0
def get_qs_client(expname):
    """
    Create a `happi.Client` from the experiment questionnaire.

    Connects to the questionnaire webservice via the ``happi`` ``QSBackend``
    using ``psdm_qs_cli`` to collect well-defined devices.

    There are two possible methods of authentication to the
    ``QuestionnaireClient``, ``Kerberos`` and ``WS-Auth``. The first is simpler
    but is not possible for all users, we therefore search for a configuration
    file named ``web.cfg``, either hidden in the current directory or the users
    home directory. This should contain the username and password needed to
    authenticate into the ``QuestionnaireClient``. The format of this
    configuration file is the standard ``.ini`` structure and should define the
    username and password like:

    .. code:: ini

        [DEFAULT]
        user = MY_USERNAME
        pw = MY_PASSWORD

    Parameters
    ----------
    expname: ``str``
        The experiment's name from the elog

    Returns
    -------
    qs_client: `happi.Client`
        Mapping from questionnaire ``python name`` to loaded object.
    """
    # Determine which method of authentication we are going to use.
    # Search for a configuration file, either in the current directory
    # or hidden in the users home directory. If not found, attempt to
    # launch the client via Kerberos
    cfg = ConfigParser()
    cfgs = cfg.read([
        'qs.cfg', '.qs.cfg',
        os.path.expanduser('~/.qs.cfg'), 'web.cfg', '.web.cfg',
        os.path.expanduser('~/.web.cfg')
    ])
    # Ws-auth
    if cfgs:
        user = cfg.get('DEFAULT', 'user', fallback=None)
        try:
            pw = cfg.get('DEFAULT', 'pw')
        except NoOptionError as exc:
            raise ValueError("Must specify password as 'pw' in "
                             "configuration file") from exc
        qs_client = happi.Client(
            database=QSBackend(expname, use_kerberos=False, user=user, pw=pw))
    # Kerberos
    else:
        qs_client = happi.Client(
            database=QSBackend(expname, use_kerberos=True))
    return qs_client
Esempio n. 2
0
 def __init__(self, happi_json, system_json):
     #Load happi client
     self.client = happi.Client(database=JSONBackend(happi_json))
     #Load system information
     self.live_systems = simplejson.load(open(system_json, 'r'))
     #Create cache of previously loaded devices
     self.cache = {}
Esempio n. 3
0
 def add_device(obj, device):
     # Needs metadata
     if not hasattr(device, 'md'):
         logger.error(
             "Device %r has no stored metadata. "
             "Unable to load in TyphonConsole", device)
         return
     # Create a temporary file
     name = hashlib.md5(str(localtime()).encode('utf-8')).hexdigest()
     name = os.path.join(tempfile.gettempdir(), name)
     try:
         # Dump the device in the tempfile
         client = happi.Client(path=name, initialize=True)
         client.add_device(device.md)
         # Create a valid Python identifier
         python_name = make_identifier(device.md.name)
         # Create the script to load the device
         load_script = (
             f'import happi; '
             f'from happi.loader import from_container; '
             f'client = happi.Client(path="{name}"); '
             f'md = client.find_device(name="{device.md.name}"); '
             f'{python_name} = from_container(md)')
         # Execute the script
         obj.kernel.kernel_client.execute(load_script, silent=True)
     except Exception:
         logger.exception("Unable to add device %r to TyphonConsole.",
                          device.md.name)
         # Cleanup after ourselves
         if os.path.exists(name):
             os.remove(name)
Esempio n. 4
0
def test_add_then_load():
    item = yaqc_bluesky.happi_containers.YAQItem(name="test", port=39424)
    with tempfile.NamedTemporaryFile() as f:
        backend = happi.backends.backend(f.name)
        happi_client = happi.Client(database=backend)
        happi_client.add_device(item)
        output = happi_client.load_device(name="test")
Esempio n. 5
0
def main():
    #Parse command line
    fclass = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(epilog=description,
                                     formatter_class=fclass)

    #Arguments
    parser.add_argument('name', help='Name of Device')

    parser.add_argument('-e',
                        '--embedded',
                        dest='embedded',
                        help='Choice to use embedded screen',
                        default=False,
                        action='store_true')

    parser.add_argument('-b',
                        '--block',
                        dest='block',
                        help='Block the main thread while '
                        'the screen is open',
                        default=False,
                        action='store_true')

    parser.add_argument('-d',
                        '--dir',
                        dest='dir',
                        help='Directory to launch screen from',
                        default=None)

    #Parse arguments
    args = parser.parse_args()
    client = happi.Client()

    try:
        device = client.load_device(name=args.name)

    except happi.errors.SearchError:
        print('Unable to locate any device with '
              'name {} in the database.'
              ''.format(args.name))
        return

    #Create string of macros based on template
    env = Environment().from_string(device.macros)
    macros = env.render(**device.post())

    #Gather screen path
    if args.embedded:
        screen = device.embedded_screen
    else:
        screen = device.main_screen

    #Launch screen
    launch(screen, wait=args.block, wd=args.dir, macros=macros)
Esempio n. 6
0
def get_happi_objs(db, hutch):
    """
    Get the relevant devices for ``hutch`` from ``db``.

    This depends on a JSON ``happi`` database stored somewhere in the file
    system and handles setting up the ``happi.Client`` and querying the data
    base for devices.

    Parameters
    ----------
    db: ``str``
        Path to database

    hutch: ``str``
        Name of hutch

    Returns
    -------
    objs: ``dict``
        A mapping from device name to device
    """
    # Load the happi Client
    client = happi.Client(path=db)
    containers = list()
    # Find upstream devices based on lightpath configuration
    beamline_conf = beamlines.get(hutch.upper())
    # Something strange is happening if there are no upstream devices
    if not beamline_conf:
        logger.warning("Unable to find lightpath for %s", hutch.upper())
        beamline_conf = {}
    # Add the complete hutch beamline
    beamline_conf[hutch.upper()] = {}
    # Base beamline
    for beamline, conf in beamline_conf.items():
        # Assume we want hutch devices that are active and in the bounds
        # determined by the beamline configuration
        reqs = dict(beamline=beamline,
                    active=True,
                    start=conf.get('start', 0),
                    end=conf.get('end', None))
        results = client.search_range(key='z', **reqs)
        blc = [res.device for res in results]
        # Add the beamline containers to the complete list
        if blc:
            containers.extend(blc)
        else:
            logger.warning("No devices found in database for %s",
                           beamline.upper())
    # Instantiate the devices needed
    dev_namespace = load_devices(*containers, pprint=False)
    return dev_namespace.__dict__
Esempio n. 7
0
def lcls_client():
    # Reset the configuration database
    lightpath.controller.beamlines = {
        'MEC': {
            'HXR': {}
        },
        'CXI': {
            'HXR': {}
        },
        'XCS': {
            'HXR': {}
        }
    }
    db = os.path.join(os.path.dirname(__file__), 'path.json')

    return happi.Client(path=db)
Esempio n. 8
0
def get_lightpath(db, hutch):
    """
    Create a lightpath from relevant ``happi`` objects.

    Parameters
    ----------
    db: ``str``
        Path to database

    hutch: ``str``
        Name of hutch

    Returns
    -------
    path: ``lightpath.BeamPath``
        Object that provides a convenient way to visualize all the devices
        that may block the beam on the way to the interaction point.
    """
    # Load the happi Client
    client = happi.Client(path=db)
    # Allow the lightpath module to create a path
    lc = lightpath.LightController(client, endstations=[hutch.upper()])
    # Return the BeamPath object created by the LightController
    return lc.beamlines[hutch.upper()]
Esempio n. 9
0
        super(HappiDeviceExplorer, self).__init__(parent=parent)

        self.filter_label = QtWidgets.QLabel("&Filter")
        self.filter_edit = QtWidgets.QLineEdit()
        self.filter_label.setBuddy(self.filter_edit)

        def set_filter(text):
            self.view.proxy_model.setFilterRegExp(text)

        self.filter_edit.textEdited.connect(set_filter)

        self.view = happi.qt.model.HappiDeviceListView(self)

        self.setLayout(QtWidgets.QGridLayout())
        self.layout().addWidget(self.filter_label, 1, 0)
        self.layout().addWidget(self.filter_edit, 1, 1)
        self.layout().addWidget(self.view, 3, 0, 1, 2)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    file_path = pathlib.Path(__file__).resolve()
    db_path = file_path.parent.parent / "db.json"
    cli = happi.Client(path=db_path)
    w = HappiDeviceExplorer()
    w.view.client = cli
    w.view.search(beamline="DEMO_BEAMLINE")
    w.show()

    app.exec_()
Esempio n. 10
0
from bluesky.callbacks.best_effort import BestEffortCallback
from bluesky.callbacks.zmq import Publisher as zmqPublisher
from bluesky_kafka import Publisher as kafkaPublisher

from bluesky_adaptive.per_start import adaptive_plan

from bluesky_queueserver.plan import configure_plan

import databroker
import happi
import happi.loader

ip = IPython.get_ipython()

hclient = happi.Client(path='/usr/local/share/happi/test_db.json')
db = databroker.catalog['MAD']

RE = RunEngine()
bec = BestEffortCallback()

zmq_publisher = zmqPublisher("127.0.0.1:4567")
kafka_publisher = kafkaPublisher(
    topic="mad.bluesky.documents",
    bootstrap_servers="127.0.0.1:9092",
    key="kafka-unit-test-key",
    # work with a single broker
    producer_config={
        "acks": 1,
        "enable.idempotence": False,
        "request.timeout.ms": 5000,
Esempio n. 11
0
    def trigger(self):
        super().trigger()

        uid = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S.%f")
        sim = Simulate(self._sirepo_sim_address)
        data = sim.auth('srw', self._sim_id)

        # all simulated componets
        # sim_fee_m1h = sim.find_element(data['models']['beamline'], 'title', 'fee_m1h')
        # sim_fee_m2h = sim.find_element(data['models']['beamline'], 'title', 'fee_m2h')
        # sim_hx2_slits = sim.find_element(data['models']['beamline'], 'title', 'hx2_slits')
        sim_um6_slits = sim.find_element(data['models']['beamline'], 'title',
                                         'um6_slits')
        # sim_xrt_m1h = sim.find_element(data['models']['beamline'], 'title', 'xrt_m1h')
        # sim_xrt_m2h = sim.find_element(data['models']['beamline'], 'title', 'xrt_m2h')
        # sim_hdx_dg2_slits = sim.find_element(data['models']['beamline'], 'title', 'hxd_dg2_slits')

        # reading current value of motors
        x = self._x_motor.read()[self._x_field]['value']
        y = self._y_motor.read()[self._y_field]['value']
        # set value of motor to change x and y position of slit at each scan
        sim_um6_slits['horizontalOffset'] = x
        sim_um6_slits['verticalOffset'] = y

        # setting values of devices in beamline according to current beamline value
        client = happi.Client(path='./happi_db.json')
        # all devices from happi database
        # fee_m1h = client.find_device(name = 'fee_m1h')
        # fee_m2h = client.find_device(name = 'fee_m2h')
        # hx2_slits = client.find_device(name = 'hx2_slits')
        um6_slits = client.find_device(name="um6_slits")
        # xrt_m1h = client.find_device(name = 'xrt_m1h')
        # xrt_m2h = client.find_device(name = 'xrt_m2h')
        # hxd_dg2_slits = client.find_device(name = 'hxd_dg2_slits')
        # getting value from these devices and set to simulated ones
        # sim_fee_m1h['position'] = fee_m1h.z
        # sim_fee_m2h['position'] = fee_m2h.z
        # sim_hx2_slits['position'] = hx2_slits.z
        sim_um6_slits['position'] = um6_slits.z
        # sim_xrt_m1h['position'] = xrt_m1h.z
        # sim_xrt_m2h['position'] = xrt_m2h.z
        # sim_hdx_dg2_slits['position'] = hxd_dg2_slits.z

        watch = sim.find_element(data['models']['beamline'], 'title',
                                 'Watchpoint')
        data['report'] = 'watchpointReport{}'.format(watch['id'])
        sim.run_simulation()

        data_file_path = os.path.abspath('.') + '/data/%s.txt' % uid

        dec = sim.get_datafile().decode('UTF-8')
        datafile = open(data_file_path, "w+")
        datafile.write(dec)
        datafile.close()
        data_dict = extract_simulation_data(data_file_path)

        self.maxim.put(np.amax(data_dict['data']))

        hf5 = h5py.File(self._image_file, 'a')
        hf5.create_dataset(uid, data=data_dict['data'])
        if 'x_range' in hf5 or 'y_range' in hf5:
            pass
        else:
            hf5['x_range'] = data_dict['x_range']
            hf5['y_range'] = data_dict['y_range']

        hf5.close()
        return NullStatus()
Esempio n. 12
0
import happi

client = happi.Client(path=r"C:\Users\gaire01\Downloads\codes\happi_db.json")
x1 = client.find_device(name='xrt_m1h')
print(x1.z)