示例#1
0
def test_multi_device_access():
    devices_info = (
        {
            "class": Device1,
            "devices": [{
                "name": "test/device1/1"
            }]
        },
        {
            "class": Device2,
            "devices": [{
                "name": "test/device2/2"
            }]
        },
    )

    with MultiDeviceTestContext(devices_info) as context:
        device_access1 = context.get_device_access("test/device1/1")
        device_access2 = context.get_device_access("test/device2/2")
        server_access = context.get_server_access()
        assert "test/device1/1" in device_access1
        assert "test/device2/2" in device_access2
        assert context.server_name in server_access
        proxy1 = tango.DeviceProxy(device_access1)
        proxy2 = tango.DeviceProxy(device_access2)
        proxy_server = tango.DeviceProxy(server_access)
        assert proxy1.attr1 == 100
        assert proxy2.attr2 == 200
        assert proxy_server.State() == tango.DevState.ON
示例#2
0
 def init_device(self):
     Device.init_device(self)
     self._logger = logging.getLogger(str(self))
     logging.basicConfig(level=logging.INFO)
     self._logger.setLevel(logging.DEBUG)
     try:
         self._nanoBpmProxy = tango.get_device_proxy(
             self.NanoBPM,
             green_mode=GreenMode.Gevent,
             wait=True,
             timeout=True)
         if self.XController is not None:
             self._xcontrolProxy = tango.DeviceProxy(self.XController)
         if self.YController is not None:
             self._ycontrolProxy = tango.DeviceProxy(self.YController)
         self._event = gevent.event.Event()
         self._servoId = None
         self._xcoord = 0
         self._ycoord = 0
         self._xmovePerPixel = 1.0
         self._ymovePerPixel = 1.0
         self._xcentre = 640
         self._ycentre = 512
         self._minimumXMove = 1.0
         self._minimumYMove = 1.0
         self._maximumXMove = 100.0
         self._maximumYMove = 100.0
         if self._nanoBpmProxy is not None:
             self._centreId = self._nanoBpmProxy.subscribe_event(
                 "Centre", tango.EventType.CHANGE_EVENT, self)
         self.set_state(tango.DevState.ON)
     except:
         self.set_state(tango.DevState.FAULT)
示例#3
0
    def __init__(self):

        motor_x_path = 'p02/motor/elab.01'  # x_motor
        motor_y_path = 'p02/motor/elab.02'  # y_motor
        gripper_path = 'p02/register/elab.out08'  # io_register
        self.backlash_mm = 3  # backlash
        self.amount = 5  # number of beamstops

        self.gripper = tango.DeviceProxy(gripper_path)
        self.motor_x = tango.DeviceProxy(motor_x_path)
        self.motor_y = tango.DeviceProxy(motor_y_path)
示例#4
0
 def __init__(self):
     #
     print(APPLICATION_NAME + ' version ' + APPLICATION_VERSION +
           ' started')
     #
     # timer device
     try:
         self.timer_device = tango.DeviceProxy('binp/nbi/timing')
         self.adc_device = tango.DeviceProxy('binp/nbi/adc0')
     except:
         self.timer_device = None
         self.adc_device = None
示例#5
0
    def init_device(self):
        SKABaseDevice.init_device(self)
        # PROTECTED REGION ID(TmCspSubarrayLeafNodeTest.init_device) ENABLED START #
        self.set_state(DevState.INIT)

        self._config_ID = ""
        self._doppler_phase_correction = [0.0, 0.0, 0.0, 0.0]
        self._jones_matrix = {}  # this is interpreted as a JSON object
        self._delay_model = {}  # this is interpreted as a JSON object
        self._beam_weights = {}  # this is interpreted as a JSON object
        self._vis_destination_address = {}  # this is interpreted as a JSON object
        self._received_output_links = False

        # these properties do not exist anymore and are not used anywhere in this file so they have been commented out
        # self._proxy_cbf_controller = tango.DeviceProxy(self.CbfControllerAddress)
        # self._proxy_cbf_controller = tango.DeviceProxy(
        #    self._proxy_cbf_controller.get_property("CspMidCbf")["CspMidCbf"][0]
        # )

        # decoupling mif-cbf-mcs from csp-mid-lmc so that it can be tested  standalone
        # TmCspSubarrayLeafNodeTest device subscribes directly to the CbfSubarray 
        # outputLinksDistribution attribute to received the outputlinks.
        self._proxy_cbf_subarray = tango.DeviceProxy(self.CbfSubarrayAddress)
        self._proxy_cbf_subarray.subscribe_event(
            "outputLinksDistribution",
            tango.EventType.CHANGE_EVENT,
            self.__output_links_event_callback,
            stateless=True
        )

        self.set_state(DevState.STANDBY)
示例#6
0
 def __init__(self, *shutter_devs):
     super().__init__()
     self.device_list = [tango.DeviceProxy(name) for name in shutter_devs]
     self.status_list = [
         True,
     ] * len(shutter_devs)
     self.stopped = False
示例#7
0
    def __init__(self, device, *args, **kwargs):
        # find out if using a serial port (e.g. /dev/ttyACM0) or a tango device
        serial_class = None
        try:
            self.serial = tango.DeviceProxy(device)
            serial_class = self.serial.info().dev_class
        except:  # not a tango device
            pass
        if serial_class is None:
            import serial
            self.serial = serial.Serial(device, *args, **kwargs)
            serial_class = 'serial'
        if serial_class not in self.KNOWN_SERIALS:
            raise ('Unknown serial. Valid ones are: %s' % self.KNOWN_SERIALS)

        # initialize serial device if necessary
        if serial_class == self.KNOWN_SERIALS[0]:  # serial port
            self._comm = self._communicate_raw
        elif serial_class == self.KNOWN_SERIALS[1]:  # Serial tango dev
            self.serial.command_inout('DevSerFlush', 2)
            self._comm = self._communicate_raw_Serial
        else:  # PySerial tango dev
            if self.serial.State() != tango.DevState.ON:
                self.serial.command_inout('Open')
            self.serial.command_inout('FlushInput')
            self.serial.command_inout('FlushOutput')
            self._comm = self._communicate_raw_PySerial
示例#8
0
    def run(self):
        """ worker thread
        """
        if hasattr(tango.ApiUtil, 'cleanup'):
            tango.ApiUtil.cleanup()
        self.__proxy = tango.DeviceProxy(self.__device)

        stime = time.time()
        etime = stime
        ids = []
        while etime - stime < self.__period:
            try:
                id_ = self.__proxy.subscribe_event(
                    self.__attribute, tango.EventType.CHANGE_EVENT, cb_tango)
                ids.append(id_)
            except Exception:
                self.__errors += 1
            else:
                self.__counter += 1
            etime = time.time()
        for id_ in ids:
            self.__proxy.unsubscribe_event(id_)
        self.__qresult.put(
            utils.Result(self.__wid, self.__counter, etime - stime,
                         self.__errors))
示例#9
0
def get_db_data(db, patterns=None, class_properties=False, **options):
    # dump TANGO database into JSON. Optionally filter which things to include
    # (currently only "positive" filters are possible; you can say which
    # servers/classes/devices to include, but you can't exclude selectively)
    # By default, dserver devices aren't included!

    dbproxy = tango.DeviceProxy(db.dev_name())
    data = SetterDict()

    if not patterns:
        # the user did not specify a pattern, so we will dump *everything*
        servers = get_servers_with_filters(dbproxy, **options)
        data.servers.update(servers)
        if class_properties:
            classes = get_classes_properties(dbproxy)
            data.classes.update(classes)
    else:
        # go through all patterns and fill in the data
        for pattern in patterns:
            prefix, pattern = pattern.split(":")
            kwargs = {prefix: pattern}
            kwargs.update(options)
            servers = get_servers_with_filters(dbproxy, **kwargs)
            data.servers.update(servers)
            if class_properties:
                classes = get_classes_properties(dbproxy, server=pattern)
                data.classes.update(classes)
    return data.to_dict()
示例#10
0
def calendarclock(request):
    """Creates and returns a TANGO DeviceTestContext object.

    Parameters
    ----------
    request: _pytest.fixtures.SubRequest
        A request object gives access to the requesting test context.
    """
    if request is not None:
        logging.info(str(request))
    properties = {}
    true_context = request.config.getoption("--true-context")
    if not true_context:
        tc = DeviceTestContext(CalendarClockDevice,
                               properties=properties,
                               process=True)
        tc.start()
        yield tc.device
        tc.stop()
    else:
        database = tango.Database()
        instance_list = database.get_device_exported_for_class(
            "CalendarClockDevice")
        for instance in instance_list.value_string:
            yield tango.DeviceProxy(instance)
            break
 def __init__(self, inst, props, *args, **kwargs):
     CounterTimerController.__init__(self, inst, props, *args, **kwargs)
     self.amptekPX5 = tango.DeviceProxy(self.deviceName)
     self.amptekPX5.set_timeout_millis(7000)
     self.acqTime = 0
     self.sta = State.On
     self.acq = False
     self.timeout = 0  # not need for now
示例#12
0
 def __init__(self,
              shutter_list,
              avoid_injections=True,
              respect_countdown=True):
     try:
         self.shutter_checker = TangoShutterChecker(*shutter_list)
         self.shutter_checker.start()
         self.injection_device = tango.DeviceProxy(
             'g-v-csproxy-0:10000/R3-319S2/DIA/DCCT-01')
         self.countdown_device = tango.DeviceProxy(
             'g-v-csproxy-0:10000/g/ctl/machinestatus')
         self.disabled = False
         self.avoid_injections = avoid_injections
         self.respect_countdown = respect_countdown
     except Exception as e:
         print('Failed to initialize scheduler:')
         print(e)
示例#13
0
def set_stow_mode(az):
    az['initial_az'] = resource(DISH).get("achievedPointing")[1]
    dish_proxy = tango.DeviceProxy(DISH)
    LOGGER.info(f"{DISH} initial azimuth: {az['initial_az']}")
    LOGGER.info(
        f"{DISH} initial elevation: {resource(DISH).get('achievedPointing')[2]}"
    )
    dish_proxy.setstowmode()
    LOGGER.info(f"{DISH} requested dishMode: STOW")
示例#14
0
def andrew_dev():
    """Create DeviceProxy for tests"""
    database = tango.Database()
    instance_list = database.get_device_exported_for_class('AndrewDev')
    for instance in instance_list.value_string:
        try:
            return tango.DeviceProxy(instance)
        except tango.DevFailed:
            continue
    pytest.fail('failed to create proxy')
示例#15
0
文件: ald.py 项目: cmft/sardana-lastm
 def run(self):
     ctrl_name = self.getEnv("ALDTGCtrl")
     ctrl = self.getController(ctrl_name)
     axes = ctrl.getUsedAxes()
     ctrl_proxy = ctrl.getDeviceProxy()
     raspi_name = ctrl_proxy.get_property("device")["device"][0]
     raspi_proxy = tango.DeviceProxy(raspi_name)
     for axis in axes:
         self.output("Setting PIN %d to output" % axis)
         raspi_proxy.write_attribute("pin%d_output" % axis, True)
 def set_tango_log_level(self, level=None):
     self.util = tango.Util.instance(self)
     self.dserver = self.util.get_dserver_device()
     self.dserver_name = self.dserver.get_name()
     self.dserver_proxy = tango.DeviceProxy(self.dserver_name)
     if level is None:
         level = TANGO_LOG_LEVELS[self.read_log_level()]
     elif isinstance(level, str):
         level = TANGO_LOG_LEVELS[level.upper()]
     self.dserver_proxy.command_inout('SetLoggingLevel',
                                      [[level], [self.get_name()]])
def test_sdp_master():
    master = tango.DeviceProxy('sip_sdp/elt/master')
    # print(master.get_attribute_list())
    assert master.version == __version__
    assert master.state() == tango.DevState.STANDBY
    assert master.current_sdp_state == 'unknown'
    assert master.target_sdp_state == 'unknown'
    print(master.resource_availability)
    print(type(master.resource_availability[0]))
    # assert 'nodes_free' in master.resource_availability
    assert master.health_check >= 0
示例#18
0
def event_receiver(request):
    """Create DeviceProxy for tests"""
    true_context = request.config.getoption("--true-context")
    if not true_context:
        with DeviceTestContext(EventReceiver, process=True) as proxy:
            yield proxy
    else:
        database = tango.Database()
        instance_list = database.get_device_exported_for_class("EventReceiver")
        for instance in instance_list.value_string:
            yield tango.DeviceProxy(instance)
            break
示例#19
0
 def activate(self):
     if not self.active:
         try:
             self.db = tango.Database()
             self.devProxy = tango.DeviceProxy(self.get_name())
             self.active = True
             LOGGER.log(logging.DEBUG, "ADC %s activated" % self.get_name())
         except:
             self.active = False
             self.timeout = time.time() + 10000
             LOGGER.log(logging.ERROR, "ADC %s activation error" % self.get_name())
     return self.active
    def __enter__(self):
        if self.__starter is not None:
            self.__starter.DevStart(self.__name)
        else:
            self.__stdout = open(os.devnull, 'w')
            self.__proc = subprocess.Popen(
                self.__name.split('/'),
                stdout=self.__stdout,
                stderr=self.__stdout,
                shell=False)

        return tango.DeviceProxy("dserver/" + self.__name.lower())
示例#21
0
def power_supply(request):
    """Create DeviceProxy for tests"""
    true_context = request.config.getoption("--true-context")
    if not true_context:
        with DeviceTestContext(PowerSupply) as proxy:
            yield proxy
    else:
        database = tango.Database()
        instance_list = database.get_device_exported_for_class("PowerSupply")
        for instance in instance_list.value_string:
            yield tango.DeviceProxy(instance)
            break
 def __init__(self, inst, props, *args, **kwargs):
     CounterTimerController.__init__(self, inst, props, *args, **kwargs)
     self.amptekPX5 = tango.DeviceProxy(self.deviceName)
     self.amptekPX5.SetTextConfiguration(["MCAC=%d" % 4096])
     self.amptekPX5.set_timeout_millis(7000)
     self.acqTime = 0
     self.sta = State.On
     self.acqStartTime = None
     self.spectrum = None
     self.icr = None
     self.tcr = None
     self.scas = {}
示例#23
0
 async def init_device(self):
     #self.lock = asyncio.Lock()
     self.lock = threading.Lock()
     self.task = None
     self.error_count = 0
     self.values = [float('NaN')] * 6
     self.time = time.time() - self.READING_VALID_TIME - 1.0
     self.timeval = tango.TimeVal.now()
     self.set_state(DevState.INIT)
     Device.init_device(self)
     self.last_level = logging.INFO
     # get device proxy
     self.dp = tango.DeviceProxy(self.get_name())
     # get all defined device properties
     self.proplist = self.dp.get_property_list('*')
     self.properties = self.dp.get_property(self.proplist)
     # read port and addr properties
     self.prt = self.get_device_property('port', 'COM1')
     self.addr = self.get_device_property('addr', 6)
     # config logger
     #self.logger = logging.getLogger(__name__)
     self.logger = logging.getLogger('%s:%s' %(self.prt, self.addr))
     self.logger.propagate = False
     self.logger.setLevel(logging.DEBUG)
     self.f_str = '%(asctime)s,%(msecs)3d %(levelname)-7s [%(process)d:%(thread)d] %(filename)s ' \
             '%(funcName)s(%(lineno)s) ' + ('%s:%s' %(self.prt, self.addr)) + ' - %(message)s'
     log_formatter = logging.Formatter(self.f_str, datefmt='%H:%M:%S')
     console_handler = logging.StreamHandler()
     console_handler.setFormatter(log_formatter)
     if not self.logger.hasHandlers():
         self.logger.addHandler(console_handler)
     # create TDKLambda device
     self.tdk = AsyncTDKLambda(self.prt, self.addr, logger=self.logger)
     await self.tdk.init()
     # check if device OK
     if self.tdk.initialized():
         # add device to list
         Async_TDKLambda_Server.devices.append(self)
         # set state to running
         self.set_state(DevState.RUNNING)
         # set maximal values for set voltage and current
         self.programmed_current.set_max_value(self.tdk.max_current)
         self.programmed_voltage.set_max_value(self.tdk.max_voltage)
         await self.read_all()
         msg = '%s:%d TDKLambda %s created successfully' % (self.tdk.port, self.tdk.addr, self.tdk.id)
         self.logger.info(msg)
         self.info_stream(msg)
     else:
         self.set_state(DevState.FAULT)
         msg = '%s:%d TDKLambda device created with errors' % (self.tdk.port, self.tdk.addr)
         self.logger.error(msg)
         self.error_stream(msg)
示例#24
0
 def guessPath(self):
     """
     As a beamline convenience, sees if there's an SDM path available
     to start with.
     """
     try:
         import tango, os
         dev = tango.DeviceProxy('b303a/ctl/sdm-01')
         path = dev.path
         if os.path.exists(path):
             self.ui.filenameBox.setText(path)
     except Exception as e:
         print("couldn't find path from tango - but that's ok")
def _benchmark(options):

    total_num_of_dev = 0

    db = tango.Database()
    starter = _make_starter_proxy(db)

    _remove_all_devices(db, options.device_name_base)

    try:
        starter.DevStop(options.device_server)
    except Exception:
        pass

    for (i, num_of_dev) in enumerate(options.number_of_devices):

        delta_num_of_dev = max(0, num_of_dev - total_num_of_dev)

        min_dev_idx = total_num_of_dev
        max_dev_idx = total_num_of_dev + delta_num_of_dev
        dev_idx = range(min_dev_idx, max_dev_idx)

        devices = (options.device_name_base + str(i) for i in dev_idx)

        _declare_devices(db, devices, options.device_class,
                         options.device_server)

        with ServerProcessManager(
                options.device_server,
                starter if options.with_starter else None) as admin:

            startup_time = 0
            errors = 0

            if options.ping_last:
                last_dev_name = options.device_name_base + str(max_dev_idx - 1)
                dev_to_ping = tango.DeviceProxy(last_dev_name)
            else:
                dev_to_ping = admin

            try:
                startup_time = _ping_device(dev_to_ping, timeout=2 * 60)
            except Exception:
                errors = 1

            total_num_of_dev += delta_num_of_dev

            record = [i, total_num_of_dev, startup_time, errors]
            yield record

    _remove_all_devices(db, options.device_name_base)
示例#26
0
 def __get_capability_proxies(self):
     # for now, assume that given addresses are valid
     if self.CorrelationAddress:
         self._proxy_correlation = tango.DeviceProxy(
             self.CorrelationAddress)
     if self.PSSAddress:
         self._proxy_pss = tango.DeviceProxy(self.PSSAddress)
     if self.PSTAddress:
         self._proxy_pst = tango.DeviceProxy(self.PSTAddress)
     if self.VLBIAddress:
         self._proxy_vlbi = tango.DeviceProxy(self.VLBIAddress)
     if self.FspCorrSubarray:
         self._proxy_fsp_corr_subarray = [
             *map(tango.DeviceProxy, list(self.FspCorrSubarray))
         ]
     if self.FspPssSubarray:
         self._proxy_fsp_pss_subarray = [
             *map(tango.DeviceProxy, list(self.FspPssSubarray))
         ]
     if self.FspPstSubarray:
         self._proxy_fsp_pst_subarray = [
             *map(tango.DeviceProxy, list(self.FspPstSubarray))
         ]
示例#27
0
 def activate(self):
     if self.active:
         return True
     try:
         self.db = tango.Database()
         self.devProxy = tango.DeviceProxy(self.dev)
         self.time = time.time()
         self.active = True
         LOGGER.log(logging.DEBUG, "Device %s activated" % self.dev)
     except:
         self.active = False
         self.time = time.time()
         LOGGER.log(logging.ERROR, "Device %s activation error" % self.dev)
         print_exception_info()
     return self.active
    def init_device(self):
        SKASubarray.init_device(self)
        # self.set_change_event("adminMode", True, True)
        # self.set_archive_event("adminMode", True, True)
        # self.set_change_event("obsState", True, True)
        # self.set_archive_event("obsState", True, True)
        # PROTECTED REGION ID(FspPstSubarray.init_device) ENABLED START #
        self.set_state(tango.DevState.INIT)

        #get relevant IDs
        self._subarray_id = self.SubID
        self._fsp_id = self.FspID

        # initialize attribute values
        self._timing_beams = []
        self._timing_beam_id = []
        self._receptors = []
        self._output_enable = 0

        # device proxy for easy reference to CBF Controller
        self._proxy_cbf_controller = tango.DeviceProxy(
            self.CbfControllerAddress)

        self._controller_max_capabilities = dict(
            pair.split(":")
            for pair in self._proxy_cbf_controller.get_property(
                "MaxCapabilities")["MaxCapabilities"])
        self._count_vcc = int(self._controller_max_capabilities["VCC"])
        self._fqdn_vcc = list(self.VCC)[:self._count_vcc]
        self._proxies_vcc = [*map(tango.DeviceProxy, self._fqdn_vcc)]

        # device proxy for easy reference to CBF Subarray
        self._proxy_cbf_subarray = tango.DeviceProxy(self.CbfSubarrayAddress)

        self._update_obs_state(ObsState.IDLE)
        self.set_state(tango.DevState.OFF)
示例#29
0
    def _fetch_tango_proxies(self, zmx_slot):
        """
        Creates tango device proxies based on zmx motor slot.

        param: zmx_slot <int>
            number of the zmx slot. use numbers >16 for second crate
            on hzgpp05vme0:10000 (DMM)
        """

        # set correct server prefix for vme0 second crate
        if (self._tango_host == 'hzgpp05vme0:10000' and zmx_slot in range(17, 33)):
            self._server_prefixes['hzgpp05vme0:10000']['zmx'] = '/p05/ZMX/multi.'
            self._server_prefixes['hzgpp05vme0:10000']['oms'] = '/p05/motor/multi.'
        # Get Tango device proxy
        zmx_device_name = (self._tango_host
                           + self._server_prefixes[self._tango_host]['zmx']
                           + '{:02d}'.format(zmx_slot))
        zmx_device = tango.DeviceProxy(zmx_device_name)
        oms_device_name = (self._tango_host
                           + self._server_prefixes[self._tango_host]['oms']
                           + '{:02d}'.format(zmx_slot))
        oms_device = tango.DeviceProxy(oms_device_name)
        return {'zmx':{'device_name': zmx_device_name, 'device': zmx_device},
                'oms':{'device_name': oms_device_name, 'device': oms_device}}
示例#30
0
def _benchmark(options):

    try:
        proxy = tango.DeviceProxy(options.device)
        proxy.set_timeout_millis(2 * 60 * 1000)
        proxy.command_inout("ClearDynamicAttributes")
    except Exception as e:
        sys.stderr.write("{}\n".format(e))
        return

    total_num_of_attr = 0

    for (i, num_of_attr) in enumerate(options.number_of_attributes):
        delta_num_of_attr = max(0, num_of_attr - total_num_of_attr)

        args = [delta_num_of_attr, options.spectrum_size]

        min_attr_idx = total_num_of_attr
        max_attr_idx = total_num_of_attr + delta_num_of_attr

        errors = 0
        memory = 0

        try:
            res = proxy.command_inout("CreateDynamicAttributes", args)
            assert res == max_attr_idx, "Failed to create attributes"

            for n in range(min_attr_idx, max_attr_idx):
                proxy.write_attribute(
                    "BenchmarkDynamicSpectrumAttribute_{}".format(n), [])
        except Exception:
            errors += 1

        try:
            memory = proxy.command_inout("GetMemoryUsage")
        except Exception:
            pass

        total_num_of_attr += delta_num_of_attr

        record = [i, total_num_of_attr, memory, errors]
        yield record

    try:
        proxy.command_inout("ClearDynamicAttributes")
    except Exception as e:
        sys.stderr.write("{}\n".format(e))
        return