Example #1
0
class TuringMachine(Device):

    blank_symbol = device_property(dtype=str, default_value=" ")
    initial_state = device_property(dtype=str, default_value="init")

    def init_device(self):
        Device.init_device(self)
        self.__tape = {}
        self.__head = 0
        self.__state = self.initial_state
        self.__final_states = []
        self.__transition_function = None
        self.set_state(DevState.RUNNING)

    @attribute(dtype=(str,))
    def final_states(self):
        return self.__final_states

    @final_states.write
    def final_states(self, final_states):
        self.__final_states = final_states

    @attribute(dtype=str)
    def transition_function(self):
        return self.__transition_function

    @transition_function.write
    def transition_function(self, func_str):
        self.__transition_function = tf = {}
        for k, v in json.loads(func_str).items():
            tf[tuple(str(k).split(","))] = map(str, v)
        print(tf)

    @attribute(dtype=str)
    def tape(self):
        s, keys = "", self.__tape.keys()
        min_used, max_used = min(keys), max(keys)
        for i in range(min_used, max_used):
            s += self.__tape.get(i, self.__blank_symbol)
        return s

    @command
    def step(self):
        char_under_head = self.__tape.get(self.__head, self.blank_symbol)
        x = self.__state, char_under_head
        if x in self.__transition_function:
            y = self.__transition_function[x]
            self.__tape[self.__head] = y[1]
            if y[2] == "R":
                self.__head += 1
            elif y[2] == "L":
                self.__head -= 1
            self.__state = y[0]
        print(self.__state)

    def dev_state(self):
        if self.__state in self.__final_states:
            return DevState.ON
        else:
            return DevState.RUNNING
Example #2
0
class PowerSupply(Device):
    __metaclass__ = DeviceMeta
    #attribute voltage only read
    voltage = attribute(label="Voltage",
                        dtype=float,
                        display_level=DispLevel.OPERATOR,
                        access=AttrWriteType.READ,
                        unit="V",
                        format="8.4f",
                        doc="the power supply voltage")
    #attribute current read and write both
    current = attribute(label="Current",
                        dtype=float,
                        display_level=DispLevel.EXPERT,
                        access=AttrWriteType.READ_WRITE,
                        unit="A",
                        format="8.4f",
                        min_value=0.0,
                        max_value=8.5,
                        min_alarm=0.1,
                        max_alarm=8.4,
                        min_warning=0.5,
                        max_warning=8.0,
                        fget="get_current",
                        fset="set_current",
                        doc="the power supply current")

    host = device_property(dtype=str)
    port = device_property(dtype=int, default_value=9788)

    def init_device(self):
        Device.init_device(self)
        self.__current = 0.0
        self.set_state(DevState.STANDBY)

    def read_voltage(self):
        self.info_stream("read_voltage(%s, %d)", self.host, self.port)
        return 9.99, time.time(), AttrQuality.ATTR_WARNING

    def get_current(self):
        return self.__current

    def set_current(self, current):
        # should set the power supply current
        self.__current = current

    @command
    def TurnOn(self):
        self.set_state(DevState.ON)

    @command
    def TurnOff(self):
        # turn off the actual power supply here
        self.set_state(DevState.OFF)
Example #3
0
class TangoEspARS(Device):
    __metaclass__ = DeviceMeta

    host = device_property(dtype=str, doc="Host name or IP of the esp8266")
    port = device_property(dtype=int, doc="socket port", default_value=23)

    def init_device(self):
        Device.init_device(self)
        self.esp_device = TemperatureSensors(self.host, self.port)

        # create dynamic attributes
        attr_prop = UserDefaultAttrProp()
        for i in range(self.esp_device.nr_sensors):
            attr_name = 'T%d' % (i+1)
            attr_unit = 'C'
            attr_prop.set_display_unit(attr_unit)
            attr_prop.set_standard_unit(attr_unit)
            attr_prop.set_unit(attr_unit)
            #attr_prop.set_event_rel_change(0.01)
            attr = Attr(attr_name, PyTango.DevDouble)
            attr.set_default_properties(attr_prop)
            
            attr = self.add_attribute(attr, r_meth=self.read_attrs)
            self.poll_attribute(attr_name, 200)
            self.set_change_event(attr_name, False)

    def read_attrs(self, attr):
    
        value = getattr(self.esp_device, attr.get_name())
        attr.set_value(value)

    def always_executed_hook(self):
        state, status = self.esp_device.state
        if state == 'OK':
            self.set_state(DevState.ON)
            self.set_status("The PLC is ready to fill the IO Chambers")
        elif state == 'ALARM':
            self.set_state(DevState.ALARM)
            self.set_status(status)

    @attribute(label="Finding", dtype=bool)
    def finding(self):
        return self.esp_device.finding

    @command
    def StartSearch(self):
        self.esp_device.finding = True

    @command
    def StopSearch(self):
        self.esp_device.finding = False
class FileLogger(Device):
    __metaclass__ = DeviceMeta



    log_path = device_property(dtype=str, default_value="/tmp")

    def __init__(self, cl, name):
        super(FileLogger, self).__init__(cl, name)
        print self.log_path



    @command(dtype_in='DevVarStringArray', dtype_out=None)
    def log(self, details):
        # import ipdb; ipdb.set_trace()
        source_device =  details[2]
        message = details[3]
        timestamp = str(datetime.datetime.fromtimestamp(float(details[0]) / 1000))
        logger = logger_dict.get(source_device)
        if not logger:
            logger = logging.getLogger(source_device)
            logger.setLevel(logging.INFO)

            # Add the log message handler to the logger
            handler = logging.handlers.RotatingFileHandler(
                self.log_path+ "/"+source_device.replace("/", "_"), maxBytes=3000000, backupCount=5)

            logger.addHandler(handler)
            logger_dict[source_device] = logger

        logger.info("{}]\t{}".format(timestamp,message))
    def update_class(self, key, dct):
        """Create properties, attribute and read method.

        Also register useful informations in the property dictionary.
        """
        # Parent method
        logical_attribute.update_class(self, key, dct)
        proxy.update_class(self, key, dct)
        # Create device property
        doc = "Attribute of '{0}' forwarded as {1}.".format(self.device, key)
        if self.prop:
            dct[self.prop] = device_property(dtype=str, doc=doc,
                                             default_value=self.attr)
        # Read-only
        if not self.writable:
            return
        # Custom write
        if dct.get("is_" + key + "_allowed") or \
           set(self.kwargs) & set(["fwrite", "fset"]):
            return

        # Write method
        def write(device, value):
            proxy_name = device._device_dict[key]
            device_proxy = device._proxy_dict[proxy_name]
            proxy_attr = device._attribute_dict[key]
            device_proxy.write_attribute(proxy_attr, value)
        dct[key] = dct[key].setter(write)
class SKATelState(SKABaseDevice):
    """
    A generic base device for Telescope State for SKA.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(SKATelState.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  SKATelState.class_variable

    # -----------------
    # Device Properties
    # -----------------

    TelStateConfigFile = device_property(dtype='str', )

    # ----------
    # Attributes
    # ----------

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        SKABaseDevice.init_device(self)
        # PROTECTED REGION ID(SKATelState.init_device) ENABLED START #
        # PROTECTED REGION END #    //  SKATelState.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(SKATelState.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKATelState.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(SKATelState.delete_device) ENABLED START #
        pass
Example #7
0
class Rack(SKABaseDevice):
    """
    Ref (Reference Elt) Rack device
    """
    __metaclass__ = DeviceMeta

    # -----------------
    # Device Properties
    # -----------------

    pdus = device_property(dtype=('str', ), mandatory=True)

    switches = device_property(dtype=('str', ), mandatory=True)

    servers = device_property(dtype=('str', ), mandatory=True)

    # ----------
    # Attributes
    # ----------

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        SKABaseDevice.init_device(self)

    def always_executed_hook(self):
        pass

    def delete_device(self):
        pass

    # ------------------
    # Attributes methods
    # ------------------

    # --------
    # Commands
    # --------

    @command()
    @DebugIt()
    def Reset(self):
        pass
Example #8
0
class EventsTest(Device):
    """
    Switches beetwen valid and invalid attribute`s values.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(EventsTest.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  EventsTest.class_variable

    # -----------------
    # Device Properties
    # -----------------

    DeviceName = device_property(dtype='str', )

    # ----------
    # Attributes
    # ----------

    Max = attribute(dtype='double', )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(EventsTest.init_device) ENABLED START #
        self.set_state(DevState.ON)
        self.proxy = AttributeProxy(self.DeviceName)
        # PROTECTED REGION END #    //  EventsTest.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(EventsTest.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  EventsTest.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(EventsTest.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  EventsTest.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_Max(self):
        # PROTECTED REGION ID(EventsTest.Attribute1_read) ENABLED START #
        value = self.proxy.read().value
        maximums = []
        for row in value:
            maximums.append(max(row))
        value = max(maximums)
        attr_quality = AttrQuality.ATTR_ALARM
        self.push_change_event("Max", float(value), time(), attr_quality)
        self.push_archive_event("Max", float(value), time(), attr_quality)
        return float(value), time(), attr_quality
Example #9
0
class PhaseshifterDS(Device):
    __metaclass__ = DeviceMeta

    phase = attribute(label="Phase",
                      dtype=float,
                      access=pt.AttrWriteType.READ_WRITE,
                      unit="deg",
                      format="3.2f",
                      min_value=0.0,
                      max_value=720.0,
                      fget="get_phase",
                      fset="set_phase",
                      doc="RF phase",
                      memorized=True,
                      hw_memorized=True)

    dac_ds_name = device_property(
        dtype=str, doc="Name of the underlying AD5370 DAC device server")
    phase_volt_cal = device_property(dtype=float,
                                     doc="Calibration factor in degrees/volt",
                                     default_value=36.0)
    dac_channel = device_property(dtype=int,
                                  doc="Channel connected to the phase shifter",
                                  default_value=39)

    def init_device(self):
        self.debug_stream("In init_device:")
        Device.init_device(self)
        self.phase_val = 0.0
        self.dac_dev = pt.DeviceProxy(self.dac_ds_name)
        self.set_state(pt.DevState.ON)

    def get_phase(self):
        self.debug_stream("In get_phase:")
        return self.phase_val, time.time(), pt.AttrQuality.ATTR_VALID

    def set_phase(self, new_phase):
        self.debug_stream("In set_phase: New phase " + str(new_phase))
        self.phase_val = new_phase
        self.dac_dev.write_attribute(
            "".join(("channel", str(self.dac_channel))),
            new_phase / self.phase_volt_cal)
def update_docs(dct):
    """Update the documentation for device properties."""
    # Get attributes
    attrs_dct = {}
    for attr, value in dct["_class_dict"]["devices"].items():
        if isinstance(value, proxy_attribute):
            attrs_dct.setdefault(value.device, []).append(attr)
    # Generate doc
    for device, attrs in attrs_dct.items():
        doc = 's ' + ', '.join(attrs[:-1]) + ' and ' if attrs[:-1] else ' '
        doc = 'Proxy device for attribute{0}.'.format(doc + attrs[-1])
        dct[device] = device_property(dtype=str, doc=doc)
Example #11
0
class SKAPowerSupplyGroup(SKABaseDevice):
    """
    Description
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(SKAPowerSupplyGroup.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  SKAPowerSupplyGroup.class_variable

    # -----------------
    # Device Properties
    # -----------------

    PowerSupplyGroup = device_property(dtype='str', mandatory=True)

    # ----------
    # Attributes
    # ----------

    PowerSupplyList = attribute(
        dtype=('str', ),
        max_dim_x=2048,
    )

    Current = attribute(
        dtype=('double', ),
        max_dim_x=128,
    )

    Voltage = attribute(
        dtype=('double', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=128,
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        SKABaseDevice.init_device(self)
        # PROTECTED REGION ID(SKAPowerSupplyGroup.init_device) ENABLED START #
        self.tg = tango.Group('power supplies')
        self.setpoints = [0.0]
        # name of the group for the Power Supplies
        self.tg.add(self.PowerSupplyGroup)
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.always_executed_hook) ENABLED START #
        print(self.PowerSupplyGroup)
        print(self.tg.get_device_list())
        r = self.tg.read_attribute('State')
        states = {}
        try:
            for b in r:
                name = b.dev_name()
                value = b.get_data(
                ).value if not b.has_failed() else DevState.FAULT
                states[name] = value
            self.set_status('\n'.join('%s: %s' % t for t in states.items()))
            stateset = list(set(states.values()))
            if not stateset:
                self.set_state(DevState.INIT)
            elif DevState.FAULT in stateset:
                self.set_state(DevState.FAULT)
            elif DevState.ALARM in stateset:
                self.set_state(DevState.ALARM)
            elif len(stateset) != 1:
                self.set_state(DevState.UNKNOWN)
            else:
                self.set_state(stateset[0])
        except:
            self.logger.error(traceback.format_exc())
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_PowerSupplyList(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.PowerSupplyList_read) ENABLED START #
        devs = list(self.tg.get_device_list())
        if not len(devs):
            self.set_state(DevState.FAULT)
            raise Exception('No Power Supplies running?')
        return list(sorted(devs))
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.PowerSupplyList_read

    def read_Current(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.Current_read) ENABLED START #
        r = self.tg.read_attribute('Current')
        currents = {}
        try:
            for b in r:
                name = b.dev_name()
                value = b.get_data().value if not b.has_failed() else math.nan
                currents[name] = value
        except:
            self.logger.error(traceback.format_exc())
        return list(v for k, v in sorted(currents.items()))
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.Current_read

    def read_Voltage(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.Voltage_read) ENABLED START #
        r = self.tg.read_attribute('Voltage')
        voltages = {}
        try:
            for b in r:
                name = b.dev_name()
                value = b.get_data().value if not b.has_failed() else math.nan
                if value != self.setpoints[0]:
                    self.set_state(DevState.FAULT)
                voltages[name] = value
        except:
            self.logger.error(traceback.format_exc())
        return list(v for k, v in sorted(voltages.items()))

        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.Voltage_read

    def write_Voltage(self, value):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.Voltage_write) ENABLED START #
        r = self.tg.write_attribute('Voltage', value)
        self.setpoints = value
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.Voltage_write

    # --------
    # Commands
    # --------

    @command()
    @DebugIt()
    def On(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.On) ENABLED START #
        self.tg.command_inout('On')
        # PROTECTED REGION END #    //  SKAPowerSupplyGroup.On

    @command()
    @DebugIt()
    def Off(self):
        # PROTECTED REGION ID(SKAPowerSupplyGroup.Off) ENABLED START #
        self.tg.command_inout('Off')
Example #12
0
class CryoCon32(Device):
    """
    Minimalistic driver for the Cryocon32 controller used in our Mossbauer transmission setup.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(CryoCon32.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  CryoCon32.class_variable

    # -----------------
    # Device Properties
    # -----------------

    SerialPort = device_property(dtype='str', default_value="/dev/ttyS0")

    SerialSpeed = device_property(dtype='uint16', default_value=9600)

    # ----------
    # Attributes
    # ----------

    TemperatureA = attribute(
        dtype='double',
        unit="K",
        standard_unit="K",
        display_unit="K",
        format="%4.1f",
        max_value=1000.0,
        min_value=0.0,
    )

    SetPoint = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        label="SetPoint",
        unit="K",
        standard_unit="K",
        display_unit="K",
        format="%4.1f",
        max_value=1000.0,
        min_value=0.0,
    )

    TemperatureB = attribute(
        dtype='double',
        unit="K",
    )

    HeaterLevel = attribute(
        dtype='DevEnum',
        access=AttrWriteType.READ_WRITE,
        enum_labels=[
            "LOW",
            "MID",
            "HIGH",
        ],
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(CryoCon32.init_device) ENABLED START #
        try:
            self.ser = serial.Serial(self.SerialPort,
                                     self.SerialSpeed,
                                     bytesize=8,
                                     parity="N",
                                     stopbits=1,
                                     timeout=0.5)
            self.ser.write("*IDN?\n")
            idn = self.ser.readline()
            if (idn[0:16] != "Cryocon Model 32"):
                self.set_status("Not a CryoCon32 on serial port")
                self.debug_stream("Not a CryoCon32 on serial port")
                return
            self.ser.write("INPUT A:UNITS K\n")
            self.ser.write("LOOP 1:TYPE PID\n")
            self.ser.write("CONTROL?\n")
            mode = self.ser.readline()
            if mode[0:3] == "OFF":
                self.set_state(PyTango.DevState.OFF)
            else:
                self.set_state(PyTango.DevState.ON)
        except:
            self.set_state(PyTango.DevState.FAULT)
            self.set_status("Can't connect to CryoCon32")
            self.debug_stream("Can't connect to CryoCon32")
            return
        self.set_status("Connected to CryoCon32")
        self.debug_stream("Connected to CryoCon32")
        # PROTECTED REGION END #    //  CryoCon32.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(CryoCon32.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  CryoCon32.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(CryoCon32.delete_device) ENABLED START #
        self.ser.close()
        # PROTECTED REGION END #    //  CryoCon32.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_TemperatureA(self):
        # PROTECTED REGION ID(CryoCon32.TemperatureA_read) ENABLED START #
        self.ser.write("INPUT? A\n")
        temperature = float(self.ser.readline())
        return (temperature)
        # PROTECTED REGION END #    //  CryoCon32.TemperatureA_read

    def read_SetPoint(self):
        # PROTECTED REGION ID(CryoCon32.SetPoint_read) ENABLED START #
        self.ser.write("LOOP 1:SETPT?\n")
        temperature = float(self.ser.readline()
                            [:-2])  # Remove \n and units (assume we are in K!)
        return (temperature)
        # PROTECTED REGION END #    //  CryoCon32.SetPoint_read

    def write_SetPoint(self, value):
        # PROTECTED REGION ID(CryoCon32.SetPoint_write) ENABLED START #
        self.ser.write("LOOP 1:SETPT %f \n" % (value))
        # PROTECTED REGION END #    //  CryoCon32.SetPoint_write

    def read_TemperatureB(self):
        # PROTECTED REGION ID(CryoCon32.TemperatureB_read) ENABLED START #
        self.ser.write("INPUT? B\n")
        temperature = float(self.ser.readline())
        return (temperature)
        # PROTECTED REGION END #    //  CryoCon32.TemperatureB_read

    def read_HeaterLevel(self):
        # PROTECTED REGION ID(CryoCon32.HeaterLevel_read) ENABLED START #
        self.ser.write("LOOP 1:RANGE?\n")
        res = self.ser.readline()
        if (res[:-1] == "LOW"):
            return 0
        elif (res[:-1] == "MID"):
            return 1
        else:
            return 2
        # PROTECTED REGION END #    //  CryoCon32.HeaterLevel_read

    def write_HeaterLevel(self, value):
        # PROTECTED REGION ID(CryoCon32.HeaterLevel_write) ENABLED START #
        if (value == 0):
            self.ser.write("LOOP 1:RANGE LOW\n")
        elif (value == 1):
            self.ser.write("LOOP 1:RANGE MID\n")
        elif (value == 2):
            self.ser.write("LOOP 1:RANGE HI\n")
        return
        # PROTECTED REGION END #    //  CryoCon32.HeaterLevel_write

    # --------
    # Commands
    # --------

    @command()
    @DebugIt()
    def On(self):
        # PROTECTED REGION ID(CryoCon32.On) ENABLED START #
        self.ser.write("CONTROL ON\n")
        self.set_state(PyTango.DevState.ON)
        pass
        # PROTECTED REGION END #    //  CryoCon32.On

    @command()
    @DebugIt()
    def Off(self):
        # PROTECTED REGION ID(CryoCon32.Off) ENABLED START #
        self.ser.write("STOP\n")
        self.set_state(PyTango.DevState.OFF)
        pass
        # PROTECTED REGION END #    //  CryoCon32.Off

    @command(
        dtype_in='str', )
    @DebugIt()
    def SendCmd(self, argin):
        # PROTECTED REGION ID(CryoCon32.SendCmd) ENABLED START #
        self.ser.write(argin + "\n")
        return ""
        # PROTECTED REGION END #    //  CryoCon32.SendCmd

    @command(
        dtype_in='str',
        dtype_out='str',
    )
    @DebugIt()
    def SendQuery(self, argin):
        # PROTECTED REGION ID(CryoCon32.SendQuery) ENABLED START #
        self.ser.write(argin + "\n")
        return self.ser.readline()
Example #13
0
class TangoTest(Device):
    """
    A device to test generic clients. It offers a \``echo\`` like command for
    each TANGO data type (i.e. each command returns an exact copy of <argin>).
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(TangoTest.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  TangoTest.class_variable
    # ----------------
    # Class Properties
    # ----------------

    # -----------------
    # Device Properties
    # -----------------

    Mthreaded_impl = device_property(dtype='int16', )
    Sleep_period = device_property(dtype='int', )
    UShort_image_ro_size = device_property(dtype='int', default_value=251)
    # ----------
    # Attributes
    # ----------

    ampli = attribute(
        dtype='double',
        access=AttrWriteType.WRITE,
    )
    boolean_scalar = attribute(
        dtype='bool',
        access=AttrWriteType.READ_WRITE,
        label="boolean_scalar",
        doc="A boolean scalar attribute",
    )
    double_scalar = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
    )
    double_scalar_rww = attribute(
        dtype='double',
        access=AttrWriteType.READ_WITH_WRITE,
    )
    double_scalar_w = attribute(
        dtype='double',
        access=AttrWriteType.WRITE,
    )
    float_scalar = attribute(
        dtype='float',
        access=AttrWriteType.READ_WRITE,
        label="float_scalar",
        doc="A float attribute",
    )
    long64_scalar = attribute(
        dtype='int64',
        access=AttrWriteType.READ_WRITE,
    )
    long_scalar = attribute(
        dtype='int',
        access=AttrWriteType.READ_WRITE,
    )
    long_scalar_rww = attribute(
        dtype='int',
        access=AttrWriteType.READ_WITH_WRITE,
    )
    long_scalar_w = attribute(
        dtype='int',
        access=AttrWriteType.WRITE,
    )
    no_value = attribute(dtype='int', )
    short_scalar = attribute(
        dtype='int16',
        access=AttrWriteType.READ_WRITE,
    )
    short_scalar_ro = attribute(dtype='int16', )
    short_scalar_rww = attribute(
        dtype='int16',
        access=AttrWriteType.READ_WITH_WRITE,
    )
    short_scalar_w = attribute(
        dtype='int16',
        access=AttrWriteType.WRITE,
    )
    string_scalar = attribute(
        dtype='str',
        access=AttrWriteType.READ_WRITE,
    )
    throw_exception = attribute(dtype='int', )
    uchar_scalar = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
        label="uchar_scalar",
    )
    ulong64_scalar = attribute(
        dtype='uint64',
        access=AttrWriteType.READ_WRITE,
    )
    ushort_scalar = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        label="ushort_scalar",
    )
    ulong_scalar = attribute(
        dtype='uint',
        access=AttrWriteType.READ_WRITE,
    )
    boolean_spectrum = attribute(
        dtype=('bool', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
        label="boolean_spectrum",
    )
    boolean_spectrum_ro = attribute(
        dtype=('bool', ),
        max_dim_x=4096,
    )
    double_spectrum = attribute(
        dtype=('double', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
    )
    double_spectrum_ro = attribute(
        dtype=('double', ),
        max_dim_x=4096,
    )
    float_spectrum = attribute(
        dtype=('float', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
        label="float_spectrum",
        doc="A float spectrum attribute",
    )
    float_spectrum_ro = attribute(
        dtype=('float', ),
        max_dim_x=4096,
    )
    long64_spectrum_ro = attribute(
        dtype=('int64', ),
        max_dim_x=4096,
    )
    long_spectrum = attribute(
        dtype=('int', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
    )
    long_spectrum_ro = attribute(
        dtype=('int', ),
        max_dim_x=4096,
    )
    short_spectrum = attribute(
        dtype=('int16', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
    )
    short_spectrum_ro = attribute(
        dtype=('int16', ),
        max_dim_x=4096,
    )
    string_spectrum = attribute(
        dtype=('str', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=256,
    )
    string_spectrum_ro = attribute(
        dtype=('str', ),
        max_dim_x=256,
    )
    uchar_spectrum = attribute(
        dtype=('char', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
        label="uchar_spectrum",
        max_value=255,
        min_value=0,
        doc="An unsigned char spectrum attribute",
    )
    uchar_spectrum_ro = attribute(
        dtype=('char', ),
        max_dim_x=4096,
    )
    ulong64_spectrum_ro = attribute(
        dtype=('uint64', ),
        max_dim_x=4096,
    )
    ulong_spectrum_ro = attribute(
        dtype=('uint', ),
        max_dim_x=4096,
    )
    ushort_spectrum = attribute(
        dtype=('uint16', ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=4096,
        label="ushort_spectrum",
        doc="An unsigned short spectrum attribute",
    )
    ushort_spectrum_ro = attribute(
        dtype=('uint16', ),
        max_dim_x=4096,
    )
    wave = attribute(
        dtype=('double', ),
        max_dim_x=4096,
    )
    boolean_image = attribute(
        dtype=(('bool', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    boolean_image_ro = attribute(
        dtype=(('bool', ), ),
        max_dim_x=251,
        max_dim_y=251,
        label="boolean_image",
    )
    double_image = attribute(
        dtype=(('double', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    double_image_ro = attribute(
        dtype=(('double', ), ),
        max_dim_x=251,
        max_dim_y=251,
    )
    float_image = attribute(
        dtype=(('float', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    float_image_ro = attribute(
        dtype=(('float', ), ),
        max_dim_x=251,
        max_dim_y=251,
        label="float_image",
        max_value=255,
        min_value=0,
        doc="A float image attribute",
    )
    long64_image_ro = attribute(
        dtype=(('int64', ), ),
        max_dim_x=251,
        max_dim_y=251,
    )
    long_image = attribute(
        dtype=(('int', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    long_image_ro = attribute(
        dtype=(('int', ), ),
        max_dim_x=251,
        max_dim_y=251,
    )
    short_image = attribute(
        dtype=(('int16', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    short_image_ro = attribute(
        dtype=(('int16', ), ),
        max_dim_x=251,
        max_dim_y=251,
    )
    string_image = attribute(
        dtype=(('str', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=256,
        max_dim_y=256,
    )
    string_image_ro = attribute(
        dtype=(('str', ), ),
        max_dim_x=256,
        max_dim_y=256,
    )
    uchar_image = attribute(
        dtype=(('char', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    uchar_image_ro = attribute(
        dtype=(('char', ), ),
        max_dim_x=251,
        max_dim_y=251,
        label="uchar_image",
        max_value=255,
        min_value=0,
        doc="An unsigned char image attribute",
    )
    ulong64_image_ro = attribute(
        dtype=(('uint64', ), ),
        max_dim_x=251,
        max_dim_y=251,
    )
    ulong_image_ro = attribute(
        dtype=(('uint', ), ),
        max_dim_x=251,
        max_dim_y=251,
    )
    ushort_image = attribute(
        dtype=(('uint16', ), ),
        access=AttrWriteType.READ_WRITE,
        max_dim_x=251,
        max_dim_y=251,
    )
    ushort_image_ro = attribute(
        dtype=(('uint16', ), ),
        max_dim_x=8192,
        max_dim_y=8192,
        label="ushort_image_ro",
        max_value=255,
        min_value=0,
        doc="An unsigned short image attribute",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(TangoTest.init_device) ENABLED START #
        # PROTECTED REGION END #    //  TangoTest.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(TangoTest.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(TangoTest.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def write_ampli(self, value):
        # PROTECTED REGION ID(TangoTest.ampli_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.ampli_write

    def read_boolean_scalar(self):
        # PROTECTED REGION ID(TangoTest.boolean_scalar_read) ENABLED START #
        return False
        # PROTECTED REGION END #    //  TangoTest.boolean_scalar_read

    def write_boolean_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.boolean_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.boolean_scalar_write

    def read_double_scalar(self):
        # PROTECTED REGION ID(TangoTest.double_scalar_read) ENABLED START #
        return 0.0
        # PROTECTED REGION END #    //  TangoTest.double_scalar_read

    def write_double_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.double_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.double_scalar_write

    def read_double_scalar_rww(self):
        # PROTECTED REGION ID(TangoTest.double_scalar_rww_read) ENABLED START #
        return 0.0
        # PROTECTED REGION END #    //  TangoTest.double_scalar_rww_read

    def write_double_scalar_rww(self, value):
        # PROTECTED REGION ID(TangoTest.double_scalar_rww_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.double_scalar_rww_write

    def write_double_scalar_w(self, value):
        # PROTECTED REGION ID(TangoTest.double_scalar_w_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.double_scalar_w_write

    def read_float_scalar(self):
        # PROTECTED REGION ID(TangoTest.float_scalar_read) ENABLED START #
        return 0.0
        # PROTECTED REGION END #    //  TangoTest.float_scalar_read

    def write_float_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.float_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.float_scalar_write

    def read_long64_scalar(self):
        # PROTECTED REGION ID(TangoTest.long64_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.long64_scalar_read

    def write_long64_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.long64_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.long64_scalar_write

    def read_long_scalar(self):
        # PROTECTED REGION ID(TangoTest.long_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.long_scalar_read

    def write_long_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.long_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.long_scalar_write

    def read_long_scalar_rww(self):
        # PROTECTED REGION ID(TangoTest.long_scalar_rww_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.long_scalar_rww_read

    def write_long_scalar_rww(self, value):
        # PROTECTED REGION ID(TangoTest.long_scalar_rww_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.long_scalar_rww_write

    def write_long_scalar_w(self, value):
        # PROTECTED REGION ID(TangoTest.long_scalar_w_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.long_scalar_w_write

    def read_no_value(self):
        # PROTECTED REGION ID(TangoTest.no_value_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.no_value_read

    def read_short_scalar(self):
        # PROTECTED REGION ID(TangoTest.short_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.short_scalar_read

    def write_short_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.short_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.short_scalar_write

    def read_short_scalar_ro(self):
        # PROTECTED REGION ID(TangoTest.short_scalar_ro_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.short_scalar_ro_read

    def read_short_scalar_rww(self):
        # PROTECTED REGION ID(TangoTest.short_scalar_rww_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.short_scalar_rww_read

    def write_short_scalar_rww(self, value):
        # PROTECTED REGION ID(TangoTest.short_scalar_rww_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.short_scalar_rww_write

    def write_short_scalar_w(self, value):
        # PROTECTED REGION ID(TangoTest.short_scalar_w_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.short_scalar_w_write

    def read_string_scalar(self):
        # PROTECTED REGION ID(TangoTest.string_scalar_read) ENABLED START #
        return ''
        # PROTECTED REGION END #    //  TangoTest.string_scalar_read

    def write_string_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.string_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.string_scalar_write

    def read_throw_exception(self):
        # PROTECTED REGION ID(TangoTest.throw_exception_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.throw_exception_read

    def read_uchar_scalar(self):
        # PROTECTED REGION ID(TangoTest.uchar_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.uchar_scalar_read

    def write_uchar_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.uchar_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.uchar_scalar_write

    def read_ulong64_scalar(self):
        # PROTECTED REGION ID(TangoTest.ulong64_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.ulong64_scalar_read

    def write_ulong64_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.ulong64_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.ulong64_scalar_write

    def read_ushort_scalar(self):
        # PROTECTED REGION ID(TangoTest.ushort_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.ushort_scalar_read

    def write_ushort_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.ushort_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.ushort_scalar_write

    def read_ulong_scalar(self):
        # PROTECTED REGION ID(TangoTest.ulong_scalar_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.ulong_scalar_read

    def write_ulong_scalar(self, value):
        # PROTECTED REGION ID(TangoTest.ulong_scalar_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.ulong_scalar_write

    def read_boolean_spectrum(self):
        # PROTECTED REGION ID(TangoTest.boolean_spectrum_read) ENABLED START #
        return [False]
        # PROTECTED REGION END #    //  TangoTest.boolean_spectrum_read

    def write_boolean_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.boolean_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.boolean_spectrum_write

    def read_boolean_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.boolean_spectrum_ro_read) ENABLED START #
        return [False]
        # PROTECTED REGION END #    //  TangoTest.boolean_spectrum_ro_read

    def read_double_spectrum(self):
        # PROTECTED REGION ID(TangoTest.double_spectrum_read) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.double_spectrum_read

    def write_double_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.double_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.double_spectrum_write

    def read_double_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.double_spectrum_ro_read) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.double_spectrum_ro_read

    def read_float_spectrum(self):
        # PROTECTED REGION ID(TangoTest.float_spectrum_read) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.float_spectrum_read

    def write_float_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.float_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.float_spectrum_write

    def read_float_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.float_spectrum_ro_read) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.float_spectrum_ro_read

    def read_long64_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.long64_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.long64_spectrum_ro_read

    def read_long_spectrum(self):
        # PROTECTED REGION ID(TangoTest.long_spectrum_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.long_spectrum_read

    def write_long_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.long_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.long_spectrum_write

    def read_long_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.long_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.long_spectrum_ro_read

    def read_short_spectrum(self):
        # PROTECTED REGION ID(TangoTest.short_spectrum_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.short_spectrum_read

    def write_short_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.short_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.short_spectrum_write

    def read_short_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.short_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.short_spectrum_ro_read

    def read_string_spectrum(self):
        # PROTECTED REGION ID(TangoTest.string_spectrum_read) ENABLED START #
        return ['']
        # PROTECTED REGION END #    //  TangoTest.string_spectrum_read

    def write_string_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.string_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.string_spectrum_write

    def read_string_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.string_spectrum_ro_read) ENABLED START #
        return ['']
        # PROTECTED REGION END #    //  TangoTest.string_spectrum_ro_read

    def read_uchar_spectrum(self):
        # PROTECTED REGION ID(TangoTest.uchar_spectrum_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.uchar_spectrum_read

    def write_uchar_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.uchar_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.uchar_spectrum_write

    def read_uchar_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.uchar_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.uchar_spectrum_ro_read

    def read_ulong64_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.ulong64_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.ulong64_spectrum_ro_read

    def read_ulong_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.ulong_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.ulong_spectrum_ro_read

    def read_ushort_spectrum(self):
        # PROTECTED REGION ID(TangoTest.ushort_spectrum_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.ushort_spectrum_read

    def write_ushort_spectrum(self, value):
        # PROTECTED REGION ID(TangoTest.ushort_spectrum_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.ushort_spectrum_write

    def read_ushort_spectrum_ro(self):
        # PROTECTED REGION ID(TangoTest.ushort_spectrum_ro_read) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.ushort_spectrum_ro_read

    def read_wave(self):
        # PROTECTED REGION ID(TangoTest.wave_read) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.wave_read

    def read_boolean_image(self):
        # PROTECTED REGION ID(TangoTest.boolean_image_read) ENABLED START #
        return [[False]]
        # PROTECTED REGION END #    //  TangoTest.boolean_image_read

    def write_boolean_image(self, value):
        # PROTECTED REGION ID(TangoTest.boolean_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.boolean_image_write

    def read_boolean_image_ro(self):
        # PROTECTED REGION ID(TangoTest.boolean_image_ro_read) ENABLED START #
        return [[False]]
        # PROTECTED REGION END #    //  TangoTest.boolean_image_ro_read

    def read_double_image(self):
        # PROTECTED REGION ID(TangoTest.double_image_read) ENABLED START #
        return [[0.0]]
        # PROTECTED REGION END #    //  TangoTest.double_image_read

    def write_double_image(self, value):
        # PROTECTED REGION ID(TangoTest.double_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.double_image_write

    def read_double_image_ro(self):
        # PROTECTED REGION ID(TangoTest.double_image_ro_read) ENABLED START #
        return [[0.0]]
        # PROTECTED REGION END #    //  TangoTest.double_image_ro_read

    def read_float_image(self):
        # PROTECTED REGION ID(TangoTest.float_image_read) ENABLED START #
        return [[0.0]]
        # PROTECTED REGION END #    //  TangoTest.float_image_read

    def write_float_image(self, value):
        # PROTECTED REGION ID(TangoTest.float_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.float_image_write

    def read_float_image_ro(self):
        # PROTECTED REGION ID(TangoTest.float_image_ro_read) ENABLED START #
        return [[0.0]]
        # PROTECTED REGION END #    //  TangoTest.float_image_ro_read

    def read_long64_image_ro(self):
        # PROTECTED REGION ID(TangoTest.long64_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.long64_image_ro_read

    def read_long_image(self):
        # PROTECTED REGION ID(TangoTest.long_image_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.long_image_read

    def write_long_image(self, value):
        # PROTECTED REGION ID(TangoTest.long_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.long_image_write

    def read_long_image_ro(self):
        # PROTECTED REGION ID(TangoTest.long_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.long_image_ro_read

    def read_short_image(self):
        # PROTECTED REGION ID(TangoTest.short_image_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.short_image_read

    def write_short_image(self, value):
        # PROTECTED REGION ID(TangoTest.short_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.short_image_write

    def read_short_image_ro(self):
        # PROTECTED REGION ID(TangoTest.short_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.short_image_ro_read

    def read_string_image(self):
        # PROTECTED REGION ID(TangoTest.string_image_read) ENABLED START #
        return [['']]
        # PROTECTED REGION END #    //  TangoTest.string_image_read

    def write_string_image(self, value):
        # PROTECTED REGION ID(TangoTest.string_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.string_image_write

    def read_string_image_ro(self):
        # PROTECTED REGION ID(TangoTest.string_image_ro_read) ENABLED START #
        return [['']]
        # PROTECTED REGION END #    //  TangoTest.string_image_ro_read

    def read_uchar_image(self):
        # PROTECTED REGION ID(TangoTest.uchar_image_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.uchar_image_read

    def write_uchar_image(self, value):
        # PROTECTED REGION ID(TangoTest.uchar_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.uchar_image_write

    def read_uchar_image_ro(self):
        # PROTECTED REGION ID(TangoTest.uchar_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.uchar_image_ro_read

    def read_ulong64_image_ro(self):
        # PROTECTED REGION ID(TangoTest.ulong64_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.ulong64_image_ro_read

    def read_ulong_image_ro(self):
        # PROTECTED REGION ID(TangoTest.ulong_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.ulong_image_ro_read

    def read_ushort_image(self):
        # PROTECTED REGION ID(TangoTest.ushort_image_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.ushort_image_read

    def write_ushort_image(self, value):
        # PROTECTED REGION ID(TangoTest.ushort_image_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.ushort_image_write

    def read_ushort_image_ro(self):
        # PROTECTED REGION ID(TangoTest.ushort_image_ro_read) ENABLED START #
        return [[0]]
        # PROTECTED REGION END #    //  TangoTest.ushort_image_ro_read

    # --------
    # Commands
    # --------

    @command
    @DebugIt()
    def CrashFromDevelopperThread(self):
        # PROTECTED REGION ID(TangoTest.CrashFromDevelopperThread) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.CrashFromDevelopperThread

    @command
    @DebugIt()
    def CrashFromOmniThread(self):
        # PROTECTED REGION ID(TangoTest.CrashFromOmniThread) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.CrashFromOmniThread

    @command(dtype_in='bool',
             doc_in="Any boolean value",
             dtype_out='bool',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevBoolean(self, argin):
        # PROTECTED REGION ID(TangoTest.DevBoolean) ENABLED START #
        return False
        # PROTECTED REGION END #    //  TangoTest.DevBoolean

    @command(dtype_in='double',
             doc_in="Any DevDouble value",
             dtype_out='double',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevDouble(self, argin):
        # PROTECTED REGION ID(TangoTest.DevDouble) ENABLED START #
        return 0.0
        # PROTECTED REGION END #    //  TangoTest.DevDouble

    @command(dtype_in='float',
             doc_in="Any DevFloat value",
             dtype_out='float',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevFloat(self, argin):
        # PROTECTED REGION ID(TangoTest.DevFloat) ENABLED START #
        return 0.0
        # PROTECTED REGION END #    //  TangoTest.DevFloat

    @command(dtype_in='int',
             doc_in="Any DevLong value",
             dtype_out='int',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevLong(self, argin):
        # PROTECTED REGION ID(TangoTest.DevLong) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.DevLong

    @command(dtype_in='int64',
             doc_in="Any DevLong64 value",
             dtype_out='int64',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevLong64(self, argin):
        # PROTECTED REGION ID(TangoTest.DevLong64) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.DevLong64

    @command(dtype_in='int16',
             doc_in="Any DevShort value",
             dtype_out='int16',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevShort(self, argin):
        # PROTECTED REGION ID(TangoTest.DevShort) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.DevShort

    @command(dtype_in='str', doc_in="-", dtype_out='str', doc_out="-")
    @DebugIt()
    def DevString(self, argin):
        # PROTECTED REGION ID(TangoTest.DevString) ENABLED START #
        return ""
        # PROTECTED REGION END #    //  TangoTest.DevString

    @command(dtype_in='uint',
             doc_in="Any DevULong",
             dtype_out='uint',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevULong(self, argin):
        # PROTECTED REGION ID(TangoTest.DevULong) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.DevULong

    @command(dtype_in='uint64',
             doc_in="Any DevULong64 value",
             dtype_out='uint64',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevULong64(self, argin):
        # PROTECTED REGION ID(TangoTest.DevULong64) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.DevULong64

    @command(dtype_in='uint16',
             doc_in="Any DevUShort value",
             dtype_out='uint16',
             doc_out="Echo of the argin value")
    @DebugIt()
    def DevUShort(self, argin):
        # PROTECTED REGION ID(TangoTest.DevUShort) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  TangoTest.DevUShort

    @command(dtype_in=('char', ),
             doc_in="-",
             dtype_out=('char', ),
             doc_out="-")
    @DebugIt()
    def DevVarCharArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarCharArray) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarCharArray

    @command(dtype_in=('double', ),
             doc_in="-",
             dtype_out=('double', ),
             doc_out="-")
    @DebugIt()
    def DevVarDoubleArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarDoubleArray) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.DevVarDoubleArray

    @command(dtype_in='DevVarDoubleStringArray',
             doc_in="-",
             dtype_out='DevVarDoubleStringArray',
             doc_out="-")
    @DebugIt()
    def DevVarDoubleStringArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarDoubleStringArray) ENABLED START #
        return [[0.0], [""]]
        # PROTECTED REGION END #    //  TangoTest.DevVarDoubleStringArray

    @command(dtype_in=('float', ),
             doc_in="-",
             dtype_out=('float', ),
             doc_out="-")
    @DebugIt()
    def DevVarFloatArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarFloatArray) ENABLED START #
        return [0.0]
        # PROTECTED REGION END #    //  TangoTest.DevVarFloatArray

    @command(
        dtype_in=('int64', ),
        dtype_out=('int64', ),
    )
    @DebugIt()
    def DevVarLong64Array(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarLong64Array) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarLong64Array

    @command(dtype_in=('int', ), doc_in="-", dtype_out=('int', ), doc_out="-")
    @DebugIt()
    def DevVarLongArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarLongArray) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarLongArray

    @command(dtype_in='DevVarLongStringArray',
             doc_in="-",
             dtype_out='DevVarLongStringArray',
             doc_out="-")
    @DebugIt()
    def DevVarLongStringArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarLongStringArray) ENABLED START #
        return [[0], [""]]
        # PROTECTED REGION END #    //  TangoTest.DevVarLongStringArray

    @command(dtype_in=('int16', ),
             doc_in="-",
             dtype_out=('int16', ),
             doc_out="-")
    @DebugIt()
    def DevVarShortArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarShortArray) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarShortArray

    @command(dtype_in=('str', ), doc_in="-", dtype_out=('str', ), doc_out="-")
    @DebugIt()
    def DevVarStringArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarStringArray) ENABLED START #
        return [""]
        # PROTECTED REGION END #    //  TangoTest.DevVarStringArray

    @command(
        dtype_in=('uint64'),
        dtype_out=('uint64'),
    )
    @DebugIt()
    def DevVarULong64Array(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarULong64Array) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarULong64Array

    @command(dtype_in=('uint', ),
             doc_in="-",
             dtype_out=('uint', ),
             doc_out="-")
    @DebugIt()
    def DevVarULongArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarULongArray) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarULongArray

    @command(dtype_in=('uint16', ),
             doc_in="-",
             dtype_out=('uint16', ),
             doc_out="-")
    @DebugIt()
    def DevVarUShortArray(self, argin):
        # PROTECTED REGION ID(TangoTest.DevVarUShortArray) ENABLED START #
        return [0]
        # PROTECTED REGION END #    //  TangoTest.DevVarUShortArray

    @command
    @DebugIt()
    def DevVoid(self):
        # PROTECTED REGION ID(TangoTest.DevVoid) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.DevVoid

    @command
    @DebugIt()
    def DumpExecutionState(self):
        # PROTECTED REGION ID(TangoTest.DumpExecutionState) ENABLED START #
        pass
        # PROTECTED REGION END #    //  TangoTest.DumpExecutionState

    @command
    @DebugIt()
    def SwitchStates(self):
        # PROTECTED REGION ID(TangoTest.SwitchStates) ENABLED START #
        pass
Example #14
0
class Keithley2100(Device):
    """
    Server for Keithley DVMM 61/2 digits
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(Keithley2100.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  Keithley2100.class_variable

    # -----------------
    # Device Properties
    # -----------------

    idProduct = device_property(
        dtype='uint', default_value=8448
    )

    idVendor = device_property(
        dtype='uint', default_value=1510
    )

    # ----------
    # Attributes
    # ----------

    Field = attribute(
        dtype='double',
        unit="T",
        format="%5.4f",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(Keithley2100.init_device) ENABLED START #
        #instr=usbtmc.Instrument(idVendor,idProduct)
        self.instr=usbtmc.Instrument(0x05e6,0x2100)
        self.set_status("Connected to DVMM Keithley 2100")
        self.debug_stream("Connected to DVMM Keithley 2100")
        self.set_state(PyTango.DevState.ON)
        # PROTECTED REGION END #    //  Keithley2100.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(Keithley2100.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  Keithley2100.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(Keithley2100.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  Keithley2100.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_Field(self):
        # PROTECTED REGION ID(Keithley2100.Field_read) ENABLED START #
        return float(self.instr.ask("MEAS:VOLT:DC?"))*10.0
        # PROTECTED REGION END #    //  Keithley2100.Field_read


    # --------
    # Commands
    # --------

    @command(
    dtype_in='str', 
    dtype_out='str', 
    )
    @DebugIt()
    def sendCommand(self, argin):
        # PROTECTED REGION ID(Keithley2100.sendCommand) ENABLED START #
        return self.instr.ask(argin)
class SecondOrderImpulseResponse(Device):
    """
    This is a sample DS for simulating a impulse response of a second-order intertial object.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(SecondOrderImpulseResponse.class_variable) ENABLED START #
    amplification = 1.0
    time_constant_1 = 1.0
    time_constant_2 = 1.0
    output = [0.0]
    # PROTECTED REGION END #    //  SecondOrderImpulseResponse.class_variable
    # ----------------
    # Class Properties
    # ----------------

    # -----------------
    # Device Properties
    # -----------------

    TimeRange = device_property(dtype='str', )

    # ----------
    # Attributes
    # ----------

    TimeConstant_1 = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
    )

    Amplification = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
    )

    TimeConstant_2 = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
    )

    Output = attribute(
        dtype=('double', ),
        max_dim_x=10000,
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(SecondOrderImpulseResponse.init_device) ENABLED START #
        self.set_state(DevState.ON)
        self.set_status("Second Order working!")
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_TimeConstant_1(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.TimeConstant_1_read) ENABLED START #
        return self.time_constant_1
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.TimeConstant_1_read

    def write_TimeConstant_1(self, value):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.TimeConstant_1_write) ENABLED START #
        self.time_constant_1 = value
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.TimeConstant_1_write

    def read_Amplification(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.Amplification_read) ENABLED START #
        return self.amplification
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.Amplification_read

    def write_Amplification(self, value):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.Amplification_write) ENABLED START #
        self.amplification = value
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.Amplification_write

    def read_TimeConstant_2(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.TimeConstant_2_read) ENABLED START #
        return self.time_constant_2
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.TimeConstant_2_read

    def write_TimeConstant_2(self, value):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.TimeConstant_2_write) ENABLED START #
        self.time_constant_2 = value
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.TimeConstant_2_write

    def read_Output(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.Output_read) ENABLED START #
        return self.output
        # PROTECTED REGION END #    //  SecondOrderImpulseResponse.Output_read

    # --------
    # Commands
    # --------

    @command
    @DebugIt()
    def CalculateResponse(self):
        # PROTECTED REGION ID(SecondOrderImpulseResponse.CalculateResponse) ENABLED START #
        try:
            h_times = arange(0.0, float(self.TimeRange), 1)
            sys = signal.lti(self.amplification,
                             [1, self.time_constant_1, self.time_constant_2])
            impulse_response = sys.impulse(T=h_times)[1]
            self.output = impulse_response
        except Exception as e:
            self.set_state(DevState.FAULT)
            self.set_status("Exception caught in CalculateResponse:\n%s" % e)
Example #16
0
class V4L2Camera(Device):
    """
    A simple driver to obtain frames from a V4L2 Camera.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(V4L2Camera.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  V4L2Camera.class_variable

    # -----------------
    # Device Properties
    # -----------------

    CaptureDevice = device_property(dtype='str', default_value="/dev/video0")

    # ----------
    # Attributes
    # ----------

    width = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
    )

    Height = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
    )

    View = attribute(
        dtype=(('float', ), ),
        max_dim_x=640,
        max_dim_y=480,
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(V4L2Camera.init_device) ENABLED START #
        self.video_capture = cv2.VideoCapture(0)
        if not self.video_capture.isOpened():
            self.set_status("Cannnot connect to camera")
            self.debug_stream("Cannot connet to camera")
            self.set_state(PyTango.DevState.FAULT)
        self.set_status("Connected to camera")
        self.set_state(PyTango.DevState.ON)
        self.video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        # PROTECTED REGION END #    //  V4L2Camera.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(V4L2Camera.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  V4L2Camera.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(V4L2Camera.delete_device) ENABLED START #
        video_capture.release()
        # PROTECTED REGION END #    //  V4L2Camera.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_width(self):
        # PROTECTED REGION ID(V4L2Camera.width_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  V4L2Camera.width_read

    def write_width(self, value):
        # PROTECTED REGION ID(V4L2Camera.width_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  V4L2Camera.width_write

    def read_Height(self):
        # PROTECTED REGION ID(V4L2Camera.Height_read) ENABLED START #
        return 0
        # PROTECTED REGION END #    //  V4L2Camera.Height_read

    def write_Height(self, value):
        # PROTECTED REGION ID(V4L2Camera.Height_write) ENABLED START #
        pass
        # PROTECTED REGION END #    //  V4L2Camera.Height_write

    def read_View(self):
        # PROTECTED REGION ID(V4L2Camera.View_read) ENABLED START #
        ret, frame = self.video_capture.read()
        #img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        return gray
Example #17
0
class SKASubarray(SKAObsDevice):
    """
    SubArray handling device
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(SKASubarray.class_variable) ENABLED START #
    def _is_command_allowed(self, command_name):
        """Determine whether the command specified by the command_name parameter should
        be allowed to execute or not.

        Parameters
        ----------
        command_name: str
            The name of the command which is to be executed.

        Returns
        -------
        True or False: boolean
            A True is returned when the device is in the allowed states and modes to
            execute the command. Returns False if the command name is not in the list of
            commands with rules specified for them.

        Raises
        ------
        PyTango.DevFailed: If the device is not in the allowed states and/modes to
            execute the command.
        """
        dp = DeviceProxy(self.get_name())

        obstate_labels = list(dp.attribute_query('obsState').enum_labels)
        obs_idle = obstate_labels.index('IDLE')
        obs_ready = obstate_labels.index('READY')

        admin_labels = list(dp.attribute_query('adminMode').enum_labels)
        admin_online = admin_labels.index('ON-LINE')
        admin_maintenance = admin_labels.index('MAINTENANCE')
        admin_offline = admin_labels.index('OFF-LINE')
        admin_not_fitted = admin_labels.index('NOT-FITTED')
        current_admin_mode = self.read_adminMode()

        if command_name in ["ReleaseResources", "AssignResources"]:
            if current_admin_mode in [admin_offline, admin_not_fitted]:
                Except.throw_exception("Command failed!", "Subarray adminMode is"
                                       " 'OFF-LINE' or 'NOT-FITTED'.",
                                       command_name, ErrSeverity.ERR)

            if self.read_obsState() == obs_idle:
                if current_admin_mode in [admin_online, admin_maintenance]:
                    return True
                else:
                    Except.throw_exception("Command failed!", "Subarray adminMode not"
                                           "'ON-LINE' or not in 'MAINTENANCE'.",
                                           command_name, ErrSeverity.ERR)

            else:
                Except.throw_exception("Command failed!", "Subarray obsState not 'IDLE'.",
                                       command_name, ErrSeverity.ERR)

        elif command_name in ['ConfigureCapability', 'DeconfigureCapability',
                              'DeconfigureAllCapabilities']:
            if self.get_state() == DevState.ON and self.read_adminMode() == admin_online:
                if self.read_obsState() in [obs_idle, obs_ready]:
                    return True
                else:
                    Except.throw_exception(
                        "Command failed!", "Subarray obsState not 'IDLE' or 'READY'.",
                        command_name, ErrSeverity.ERR)
            else:
                Except.throw_exception(
                    "Command failed!", "Subarray State not 'ON' and/or adminMode not"
                    " 'ON-LINE'.", command_name, ErrSeverity.ERR)

        return False


    def _validate_capability_types(self, command_name, capability_types):
        """Check the validity of the input parameter passed on to the command specified
        by the command_name parameter.

        Parameters
        ----------
        command_name: str
            The name of the command which is to be executed.
        capability_types: list
            A list strings representing capability types.

        Raises
        ------
        PyTango.DevFailed: If any of the capabilities requested are not valid.
        """
        invalid_capabilities = list(
            set(capability_types) - set(self._configured_capabilities))

        if invalid_capabilities:
            Except.throw_exception(
                "Command failed!", "Invalid capability types requested {}".format(
                    invalid_capabilities), command_name, ErrSeverity.ERR)


    def _validate_input_sizes(self, command_name, argin):
        """Check the validity of the input parameters passed on to the command specified
        by the command_name parameter.

        Parameters
        ----------
        command_name: str
            The name of the command which is to be executed.
        argin: PyTango.DevVarLongStringArray
            A tuple of two lists representing [number of instances][capability types]

        Raises
        ------
        PyTango.DevFailed: If the two lists are not equal in length.
        """
        capabilities_instances, capability_types = argin
        if len(capabilities_instances) != len(capability_types):
            Except.throw_exception("Command failed!", "Argin value lists size mismatch.",
                                   command_name, ErrSeverity.ERR)


    def is_AssignResources_allowed(self):
        return self._is_command_allowed("AssignResources")


    def is_ReleaseResources_allowed(self):
        return self._is_command_allowed("ReleaseResources")


    def is_ReleaseAllResources_allowed(self):
        return self._is_command_allowed("ReleaseResources")


    def is_ConfigureCapability_allowed(self):
        return self._is_command_allowed('ConfigureCapability')


    def is_DeconfigureCapability_allowed(self):
        return self._is_command_allowed('DeconfigureCapability')


    def is_DeconfigureAllCapabilities_allowed(self):
        return self._is_command_allowed('DeconfigureAllCapabilities')
    # PROTECTED REGION END #    //  SKASubarray.class_variable

    # -----------------
    # Device Properties
    # -----------------

    CapabilityTypes = device_property(
        dtype=('str',),
    )







    SubID = device_property(
        dtype='str',
    )

    # ----------
    # Attributes
    # ----------

    activationTime = attribute(
        dtype='double',
        unit="s",
        standard_unit="s",
        display_unit="s",
        doc="Time of activation in seconds since Unix epoch.",
    )















    assignedResources = attribute(
        dtype=('str',),
        max_dim_x=100,
        doc="The list of resources assigned to the subarray.",
    )

    configuredCapabilities = attribute(
        dtype=('str',),
        max_dim_x=10,
        doc="A list of capability types with no. of instances in use on this subarray; e.g.\nCorrelators:512, PssBeams:4, PstBeams:4, VlbiBeams:0.",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        SKAObsDevice.init_device(self)
        # PROTECTED REGION ID(SKASubarray.init_device) ENABLED START #

        # Initialize attribute values.
        self._activation_time = 0.0
        self._assigned_resources = [""]
        # self._configured_capabilities is gonna be kept as a dictionary internally. The
        # keys and value will represent the capability type name and the number of
        # instances, respectively.
        try:
            self._configured_capabilities = dict.fromkeys(self.CapabilityTypes, 0)
        except TypeError:
            # Might need to have the device property be mandatory in the database.
            self._configured_capabilities = {}

        # When Subarray in not in use it reports:
        self.set_state(DevState.DISABLE)

        # PROTECTED REGION END #    //  SKASubarray.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(SKASubarray.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(SKASubarray.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_activationTime(self):
        # PROTECTED REGION ID(SKASubarray.activationTime_read) ENABLED START #
        return self._activation_time
        # PROTECTED REGION END #    //  SKASubarray.activationTime_read

    def read_assignedResources(self):
        # PROTECTED REGION ID(SKASubarray.assignedResources_read) ENABLED START #
        return self._assigned_resources
        # PROTECTED REGION END #    //  SKASubarray.assignedResources_read

    def read_configuredCapabilities(self):
        # PROTECTED REGION ID(SKASubarray.configuredCapabilities_read) ENABLED START #
        configured_capabilities = []
        for capability_type, capability_instances in (
                self._configured_capabilities.items()):
            configured_capabilities.append(
                "{}:{}".format(capability_type, capability_instances))
        return sorted(configured_capabilities)
        # PROTECTED REGION END #    //  SKASubarray.configuredCapabilities_read


    # --------
    # Commands
    # --------

    @command(
    )
    @DebugIt()
    def Abort(self):
        # PROTECTED REGION ID(SKASubarray.Abort) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.Abort

    @command(
    dtype_in='DevVarLongStringArray', 
    doc_in="[Number of instances to add][Capability types]", 
    )
    @DebugIt()
    def ConfigureCapability(self, argin):
        # PROTECTED REGION ID(SKASubarray.ConfigureCapability) ENABLED START #
        command_name = 'ConfigureCapability'
        dp = DeviceProxy(self.get_name())
        obstate_labels = list(dp.attribute_query('obsState').enum_labels)
        obs_configuring = obstate_labels.index('CONFIGURING')

        capabilities_instances, capability_types = argin
        self._validate_capability_types(command_name, capability_types)
        self._validate_input_sizes(command_name, argin)

        # Set obsState to 'CONFIGURING'.
        self._obs_state = obs_configuring

        # Perform the configuration.
        for capability_instances, capability_type in izip(
                capabilities_instances, capability_types):
            self._configured_capabilities[capability_type] += capability_instances

        # Change the obsState to 'READY'.
        obs_ready = obstate_labels.index('READY')
        self._obs_state = obs_ready
        # PROTECTED REGION END #    //  SKASubarray.ConfigureCapability

    @command(
    dtype_in='str', 
    doc_in="Capability type", 
    )
    @DebugIt()
    def DeconfigureAllCapabilities(self, argin):
        # PROTECTED REGION ID(SKASubarray.DeconfigureAllCapabilities) ENABLED START #i
        self._validate_capability_types('DeconfigureAllCapabilities', [argin])
        self._configured_capabilities[argin] = 0
        # PROTECTED REGION END #    //  SKASubarray.DeconfigureAllCapabilities

    @command(
    dtype_in='DevVarLongStringArray', 
    doc_in="[Number of instances to remove][Capability types]", 
    )
    @DebugIt()
    def DeconfigureCapability(self, argin):
        # PROTECTED REGION ID(SKASubarray.DeconfigureCapability) ENABLED START #
        command_name = 'DeconfigureCapability'
        capabilities_instances, capability_types = argin

        self._validate_capability_types(command_name, capability_types)
        self._validate_input_sizes(command_name, argin)


        # Perform the deconfiguration
        for capability_instances, capability_type in izip(
                capabilities_instances, capability_types):
            if self._configured_capabilities[capability_type] < int(capability_instances):
                self._configured_capabilities[capability_type] = 0
            else:
                self._configured_capabilities[capability_type] -= (
                    int(capability_instances))
        # PROTECTED REGION END #    //  SKASubarray.DeconfigureCapability

    @command(
    dtype_in=('str',), 
    doc_in="List of Resources to add to subarray.", 
    dtype_out=('str',), 
    doc_out="A list of Resources added to the subarray.", 
    )
    @DebugIt()
    def AssignResources(self, argin):
        # PROTECTED REGION ID(SKASubarray.AssignResources) ENABLED START #
        argout = []
        resources = self._assigned_resources[:]
        for resource in argin:
            if resource not in resources:
                self._assigned_resources.append(resource)
            argout.append(resource)
        return argout

    @command(
    dtype_in=('str',),
    doc_in="List of resources to remove from the subarray.",
    dtype_out=('str',),
    doc_out="List of resources removed from the subarray.",
    )
    @DebugIt()
    def ReleaseResources(self, argin):
        # PROTECTED REGION ID(SKASubarray.ReleaseResources) ENABLED START #
        argout = []
        # Release resources...
        resources = self._assigned_resources[:]
        for resource in argin:
            if resource in resources:
                self._assigned_resources.remove(resource)
            argout.append(resource)
        return argout
        # PROTECTED REGION END #    //  SKASubarray.ReleaseResources

    @command(
    )
    @DebugIt()
    def EndSB(self):
        # PROTECTED REGION ID(SKASubarray.EndSB) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.EndSB

    @command(
    )
    @DebugIt()
    def EndScan(self):
        # PROTECTED REGION ID(SKASubarray.EndScan) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.EndScan

    @command(
    )
    @DebugIt()
    def Pause(self):
        # PROTECTED REGION ID(SKASubarray.Pause) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.Pause

    @command(
    dtype_out=('str',), 
    doc_out="List of resources removed from the subarray.", 
    )
    @DebugIt()
    def ReleaseAllResources(self):
        # PROTECTED REGION ID(SKASubarray.ReleaseAllResources) ENABLED START #
        resources = self._assigned_resources[:]
        released_resources = self.ReleaseResources(resources)
        return released_resources
        # PROTECTED REGION END #    //  SKASubarray.ReleaseAllResources

    @command(
    dtype_in=('str',), 
    doc_in="List of resources to remove from the subarray.", 
    dtype_out=('str',), 
    doc_out="List of resources removed from the subarray.", 
    )
    @DebugIt()
    def ReleaseResources(self, argin):
        # PROTECTED REGION ID(SKASubarray.ReleaseResources) ENABLED START #
        return [""]
        # PROTECTED REGION END #    //  SKASubarray.ReleaseResources

    @command(
    )
    @DebugIt()
    def Resume(self):
        # PROTECTED REGION ID(SKASubarray.Resume) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKASubarray.Resume

    @command(
    dtype_in=('str',), 
    )
    @DebugIt()
    def Scan(self, argin):
        # PROTECTED REGION ID(SKASubarray.Scan) ENABLED START #
        pass
Example #18
0
class SpectrometerCameraDS(Device):
    __metaclass__ = DeviceMeta

    exposuretime = attribute(
        label='ExposureTime',
        dtype=float,
        access=tango.AttrWriteType.READ_WRITE,
        unit="us",
        format="%8.1f",
        min_value=0.0,
        max_value=1e7,
        fget="get_exposuretime",
        fset="set_exposuretime",
        doc="Camera exposure time in us",
        memorized=True,
    )

    gain = attribute(
        label='Gain',
        dtype=float,
        access=tango.AttrWriteType.READ_WRITE,
        unit="dB",
        format="%3.2f",
        min_value=0.0,
        max_value=1e2,
        fget="get_gain",
        fset="set_gain",
        doc="Camera gain in dB",
        memorized=True,
    )

    wavelengthvector = attribute(
        label='WavelengthVector',
        dtype=[np.double],
        access=tango.AttrWriteType.READ,
        max_dim_x=16384,
        display_level=tango.DispLevel.OPERATOR,
        unit="m",
        format="%5.2e",
        fget="get_wavelengthvector",
        doc="Wavelength vector",
    )

    spectrum = attribute(
        label='Spectrum',
        dtype=[np.double],
        access=tango.AttrWriteType.READ,
        max_dim_x=16384,
        display_level=tango.DispLevel.OPERATOR,
        unit="a.u.",
        format="%5.2f",
        fget="get_spectrum",
        doc="Spectrum",
    )

    width = attribute(
        label='Spectrum width FWHM',
        dtype=np.double,
        access=tango.AttrWriteType.READ,
        display_level=tango.DispLevel.OPERATOR,
        unit="m",
        format="%5.2e",
        fget="get_width",
        doc=
        "FWHM for the peak in spectrum. Basic thresholding and peak detection is used.",
    )

    peak = attribute(
        label='Spectrum peak',
        dtype=np.double,
        access=tango.AttrWriteType.READ,
        display_level=tango.DispLevel.OPERATOR,
        unit="m",
        format="%5.2e",
        fget="get_peak",
        doc=
        "Wavelength for the peak in spectrum. Basic thresholding and peak detection is used.",
    )

    sat_lvl = attribute(
        label='Saturation level',
        dtype=np.double,
        access=tango.AttrWriteType.READ,
        display_level=tango.DispLevel.OPERATOR,
        unit="relative",
        format="%2.2e",
        fget="get_satlvl",
        doc=
        "Relative amount of pixels that are saturated. This should be zero.",
    )

    camera_name = device_property(
        dtype=str,
        doc="Tango name of the camera device",
        default_value="gunlaser/cameras/spectrometer_camera")

    watchdog_timeout = device_property(
        dtype=float,
        doc="Timeout for the watchdog resetting the hardware in s",
        default_value="2.0")

    dispersion = device_property(
        dtype=float,
        doc="Dispersion of the spectrometer in nm/px. "
        "Positive if wavelength increases to the right",
        default_value="0.056")

    central_wavelength = device_property(
        dtype=float,
        doc="Wavelength of the central pixel of the ROI in nm",
        default_value="2.0")

    roi = device_property(
        dtype=[int],
        doc="Pixel coordinates for the ROI: [left, top, width, height]",
        default_value=[0, 0, 100, 100])

    saturation_level = device_property(
        dtype=int,
        doc="Saturation pixel value, used for estimating overexposure",
        default_value=65536)

    def __init__(self, klass, name):
        self.wavelengthvector_data = np.array([])
        self.max_value = 1.0
        self.controller = None  # type: SpectrometerCameraController
        self.state_dispatcher = None  # type: StateDispatcher
        self.db = None
        Device.__init__(self, klass, name)

    def init_device(self):
        self.debug_stream("In init_device:")
        Device.init_device(self)
        self.db = tango.Database()
        self.set_state(tango.DevState.UNKNOWN)
        try:
            if self.state_dispatcher is not None:
                self.state_dispatcher.stop()
        except Exception as e:
            self.error_info("Error stopping state dispatcher: {0}".format(e))
        try:
            self.controller = SpectrometerCameraController(self.camera_name)
            self.controller.add_state_notifier(self.change_state)
        except Exception as e:
            self.error_stream(
                "Error creating camera controller: {0}".format(e))
            return
        self.setup_params()
        self.setup_spectrometer()

        self.state_dispatcher = StateDispatcher(self.controller)
        self.state_dispatcher.start()

        self.debug_stream("init_device finished")

    def setup_params(self):
        params = dict()
        params["imageoffsetx"] = self.roi[0]
        params["imageoffsety"] = self.roi[1]
        params["imagewidth"] = self.roi[2]
        params["imageheight"] = self.roi[3]
        params["triggermode"] = "Off"
        self.controller.setup_params = params

    def setup_spectrometer(self):
        self.info_stream("Entering setup_camera")
        self.wavelengthvector_data = (self.central_wavelength + np.arange(
            -self.roi[2] / 2, self.roi[2] / 2) * self.dispersion) * 1e-9
        self.max_value = self.saturation_level
        wavelength_attr = tango.DeviceAttribute()
        wavelength_attr.name = "wavelengths"
        wavelength_attr.quality = tango.AttrQuality.ATTR_VALID
        wavelength_attr.value = self.wavelengthvector_data
        # wavelength_attr.data_format = tango.AttrDataFormat.SPECTRUM
        wavelength_attr.time = tango.time_val.TimeVal(time.time())
        max_value_attr = tango.DeviceAttribute()
        max_value_attr.name = "max_value"
        max_value_attr.quality = tango.AttrQuality.ATTR_VALID
        max_value_attr.value = self.max_value
        # max_value_attr.data_format = tango.AttrDataFormat.SCALAR
        max_value_attr.time = tango.time_val.TimeVal(time.time())
        with self.controller.state_lock:
            self.controller.camera_result["wavelengths"] = wavelength_attr
            self.controller.camera_result["max_value"] = max_value_attr

    def change_state(self, new_state, new_status=None):
        self.info_stream("Change state: {0}, status {1}".format(
            new_state, new_status))
        # Map new_state string to tango state
        if new_state in ["running"]:
            tango_state = tango.DevState.RUNNING
        elif new_state in ["on"]:
            tango_state = tango.DevState.ON
        elif new_state in ["device_connect", "setup_attributes"]:
            tango_state = tango.DevState.INIT
        elif new_state in ["fault"]:
            tango_state = tango.DevState.FAULT
        else:
            tango_state = tango.DevState.UNKNOWN

        # Set memorized attributes when entering init from unknown state:
        if self.get_state(
        ) is tango.DevState.INIT and new_state is not tango.DevState.UNKNOWN:
            self.debug_stream("Set memorized attributes")
            try:
                data = self.db.get_device_attribute_property(
                    self.get_name(), "gain")
                self.debug_stream(
                    "Database returned data for \"gain\": {0}".format(
                        data["gain"]))
            except TypeError as e:
                self.warn_stream("Gain not found in database. {0}".format(e))
            try:
                new_value = float(data["gain"]["__value"][0])
                self.debug_stream("{0}".format(new_value))
                self.controller.write_attribute("gain", "camera", new_value)
            except (KeyError, TypeError, IndexError, ValueError):
                pass
            try:
                data = self.db.get_device_attribute_property(
                    self.get_name(), "exposuretime")
                self.debug_stream(
                    "Database returned data for \"exposuretime\": {0}".format(
                        data["exposuretime"]))
            except TypeError as e:
                self.warn_stream(
                    "Exposuretime not found in database. {0}".format(e))
            try:
                new_value = float(data["exposuretime"]["__value"][0])
                self.controller.write_attribute("exposuretime", "camera",
                                                new_value)
            except (KeyError, TypeError, IndexError, ValueError):
                pass

        if tango_state != self.get_state():
            self.debug_stream("Change state from {0} to {1}".format(
                self.get_state(), new_state))
            self.set_state(tango_state)
        if new_status is not None:
            self.debug_stream("Setting status {0}".format(new_status))
            self.set_status(new_status)

    def get_spectrum(self):
        attr = self.controller.get_attribute("spectrum")
        try:
            self.debug_stream("get_spectrum: {0}".format(attr.value.shape))
        except Exception as e:
            self.warn_stream("Could not format attribute: {0}".format(e))
        return attr.value, attr.time.totime(), attr.quality

    def get_wavelengthvector(self):
        self.debug_stream("get_wavelengthvector: size {0}".format(
            self.wavelengthvector_data.shape))
        attr = self.controller.get_attribute("wavelengths")
        return attr.value, attr.time.totime(), attr.quality

    def get_exposuretime(self):
        attr = self.controller.get_attribute("exposuretime")
        try:
            self.debug_stream("get_exposuretime: {0}".format(attr))
        except Exception as e:
            self.warn_stream("Could not format attribute: {0}".format(e))
        return attr.value, attr.time.totime(), attr.quality

    def set_exposuretime(self, new_exposuretime):
        self.debug_stream(
            "In set_exposuretime: New value {0}".format(new_exposuretime))
        # self.controller.write_attribute("exposuretime", "camera", new_exposuretime)
        try:
            old_exposure = self.controller.get_attribute("exposuretime").value
        except AttributeError:
            old_exposure = 0.0
        tol = np.abs(new_exposuretime - old_exposure) * 0.1
        self.controller.check_attribute("exposuretime",
                                        "camera",
                                        new_exposuretime,
                                        tolerance=tol,
                                        write=True)

    def get_gain(self):
        attr = self.controller.get_attribute("gain")
        return attr.value, attr.time.totime(), attr.quality

    def set_gain(self, new_gain):
        self.debug_stream("In set_gain: New value {0}".format(new_gain))
        self.controller.write_attribute("gain", "camera", new_gain)
        self.controller.read_attribute("gain", "camera")

    def get_width(self):
        attr = self.controller.get_attribute("width")
        return attr.value, attr.time.totime(), attr.quality

    def get_peak(self):
        attr = self.controller.get_attribute("peak")
        return attr.value, attr.time.totime(), attr.quality

    def get_satlvl(self):
        attr = self.controller.get_attribute("satlvl")
        return attr.value, attr.time.totime(), attr.quality

    @command(doc_in="Start spectrometer.")
    def start(self):
        """Start spectrometer camera"""
        self.info_stream("Starting spectrometer")
        self.state_dispatcher.send_command("start")

    @command(doc_in="Stop spectrometer.")
    def stop(self):
        """Stop spectrometer camera"""
        self.info_stream("Stopping spectrometer")
        self.state_dispatcher.send_command("stop")
class SKACapability(SKAObsDevice):
    """
    Subarray handling device
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(SKACapability.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  SKACapability.class_variable

    # -----------------
    # Device Properties
    # -----------------

    CapType = device_property(dtype='str', )

    CapID = device_property(dtype='str', )

    subID = device_property(dtype='str', )

    # ----------
    # Attributes
    # ----------

    activationTime = attribute(
        dtype='double',
        unit="s",
        standard_unit="s",
        display_unit="s",
        doc="Time of activation in seconds since Unix epoch.",
    )

    configuredInstances = attribute(
        dtype='uint16',
        doc=
        "Number of instances of this Capability Type currently in use on this subarray.",
    )

    usedComponents = attribute(
        dtype=('str', ),
        max_dim_x=100,
        doc=
        "A list of components with no. of instances in use on this Capability.",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        SKAObsDevice.init_device(self)
        # PROTECTED REGION ID(SKACapability.init_device) ENABLED START #
        self._activation_time = 0.0
        self._configured_instances = 0
        self._used_components = [""]
        # PROTECTED REGION END #    //  SKACapability.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(SKACapability.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKACapability.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(SKACapability.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SKACapability.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_activationTime(self):
        # PROTECTED REGION ID(SKACapability.activationTime_read) ENABLED START #
        return self._activation_time
        # PROTECTED REGION END #    //  SKACapability.activationTime_read

    def read_configuredInstances(self):
        # PROTECTED REGION ID(SKACapability.configuredInstances_read) ENABLED START #
        return self._configured_instances
        # PROTECTED REGION END #    //  SKACapability.configuredInstances_read

    def read_usedComponents(self):
        # PROTECTED REGION ID(SKACapability.usedComponents_read) ENABLED START #
        return self._used_components
        # PROTECTED REGION END #    //  SKACapability.usedComponents_read

    # --------
    # Commands
    # --------

    @command(
        dtype_in='uint16',
        doc_in="The number of instances to configure for this Capability.",
    )
    @DebugIt()
    def ConfigureInstances(self, argin):
        # PROTECTED REGION ID(SKACapability.ConfigureInstances) ENABLED START #
        self._configured_instances = argin
Example #20
0
class TangoTestDeviceServerBase(Device):
    __metaclass__ = DeviceMeta

    instances = weakref.WeakValueDictionary()

    model_key = device_property(
        dtype=str,
        doc=
        "Simulator model key, usually the TANGO name of the simulated device.")

    def __init__(self, dev_class, name):
        super(TangoTestDeviceServerBase, self).__init__(dev_class, name)

        self.model = None
        self._attribute_name = ''
        self.model_quantity = None
        self._pause_active = False
        self.sim_device_attributes = None
        self.init_device()

    def init_device(self):
        super(TangoTestDeviceServerBase, self).init_device()
        name = self.get_name()
        self.instances[name] = self

        try:
            self.model = model.model_registry[self.model_key]
        except KeyError:
            raise RuntimeError(
                'Could not find model with device name or key '
                '{}. Set the "model_key" device property to the '
                'correct value.'.format(self.model_key))
        self.sim_device_attributes = self.model.sim_quantities.keys()
        self.set_state(DevState.ON)

    def initialize_dynamic_attributes(self):
        """The device method that sets up attributes during run time"""
        # Get attributes to control the device model quantities
        # from class variables of the quantities included in the device model.
        models = set(
            [quant.__class__ for quant in self.model.sim_quantities.values()])
        control_attributes = []

        for cls in models:
            control_attributes += [attr for attr in cls.adjustable_attributes]

        # Add a list of float attributes from the list of Guassian variables
        for attribute_name in control_attributes:
            model.MODULE_LOGGER.info(
                "Added weather {} attribute control".format(attribute_name))
            attr_props = UserDefaultAttrProp()
            attr = Attr(attribute_name, DevDouble, AttrWriteType.READ_WRITE)
            attr.set_default_properties(attr_props)
            self.add_attribute(attr, self.read_attributes,
                               self.write_attributes)

    # Static attributes of the device
    @attribute(dtype=bool)
    def pause_active(self):
        return self._pause_active

    @pause_active.write
    def pause_active(self, is_active):
        self._pause_active = is_active
        setattr(self.model, 'paused', is_active)

    def read_attributes(self, attr):
        """Method reading an attribute value

        Parameters
        ----------
        attr : PyTango.DevAttr
            The attribute to read from.

        """
        name = attr.get_name()
        self.info_stream("Reading attribute %s", name)
        attr.set_value(getattr(self.model_quantity, name))

    def write_attributes(self, attr):
        """Method writing an attribute value

        Parameters
        ----------
        attr : PyTango.DevAttr
            The attribute to write to.

        """
        name = attr.get_name()
        data = attr.get_write_value()
        self.info_stream("Writing attribute {} with value: {}".format(
            name, data))

        if name == 'last_val':
            self.model_quantity.set_val(data, self.model.time_func())
        else:
            setattr(self.model_quantity, name, data)
Example #21
0
class ElmitecLEEM2k(Device):
    """
    Device server for accessing the settings of the LEEM2000 program from Elmitec.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(ElmitecLEEM2k.class_variable) ENABLED START #
    ElmitecLEEM2kConnected = False

    def TCPBlockingReceive(self):
        Bytereceived = '0'
        szData = ''
        while ord(Bytereceived) != 0:
            ReceivedLength = 0
            while ReceivedLength == 0:
                Bytereceived = self.s.recv(1)
                #print 'Bytereceived=',Bytereceived,'ord(Bytereceived)=',ord(Bytereceived)
                ReceivedLength = len(Bytereceived)
            if ord(Bytereceived) != 0:
                szData = szData + Bytereceived
        return szData

    def connect(self):
        if self.ElmitecLEEM2kConnected:
            return
        else:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                #self.s.connect((self.IP, self.Port))
                self.s.connect(("leem.labo", 5566))
            except:
                self.ElmitecLEEM2kConnected = False
                self.set_state(PyTango.DevState.FAULT)
                self.set_status("Can't connect to ElmitecLEEM2k")
                self.debug_stream("Can't connect to ElmitecLEEM2k")
                return
            #Start string communication
            TCPString = 'asc'
            self.s.send(TCPString)
            data = self.TCPBlockingReceive()
            self.ElmitecLEEM2kConnected = True
            self.set_state(PyTango.DevState.ON)
            self.set_status("Connected to ElmitecLEEM2k")
            self.debug_stream("Connected to ElmitecLEEM2k")

    def disconnect(self):
        if self.ElmitecLEEM2kConnected:
            self.s.send('clo')
            self.s.close()
            self.ElmitecLEEM2kConnected = False
            self.debug_stream("Disconnected!")

    # PROTECTED REGION END #    //  ElmitecLEEM2k.class_variable

    # -----------------
    # Device Properties
    # -----------------

    IP = device_property(dtype='str', )

    Port = device_property(dtype='uint16', )

    # ----------
    # Attributes
    # ----------

    Objective = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        standard_unit="mA",
    )

    Preset = attribute(
        dtype='str',
        access=AttrWriteType.READ_WRITE,
    )

    StartVoltage = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        standard_unit="V",
    )

    TransferLens = attribute(
        dtype='double',
        standard_unit="mA",
    )

    FieldLens = attribute(
        dtype='double',
        standard_unit="mA",
    )

    IntermLens = attribute(
        dtype='double',
        standard_unit="mA",
    )

    P1Lens = attribute(
        dtype='double',
        standard_unit="mA",
    )

    P2Lens = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        standard_unit="mA",
    )

    SampleTemperature = attribute(
        dtype='double',
        standard_unit="ºC",
    )

    ChannelPlateVoltage = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        standard_unit="kV",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(ElmitecLEEM2k.init_device) ENABLED START #
        self.connect()
        # PROTECTED REGION END #    //  ElmitecLEEM2k.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  ElmitecLEEM2k.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.delete_device) ENABLED START #
        self.disconnect()
        self.set_state(PyTango.DevState.OFF)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_Objective(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.Objective_read) ENABLED START #
        self.s.send("val 11")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.Objective_read

    def write_Objective(self, value):
        # PROTECTED REGION ID(ElmitecLEEM2k.Objective_write) ENABLED START #
        self.s.send("val 11 " + str(value))
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.Objective_write

    def read_Preset(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.Preset_read) ENABLED START #
        self.s.send("prl")
        data = self.TCPBlockingReceive()
        return data
        # PROTECTED REGION END #    //  ElmitecLEEM2k.Preset_read

    def write_Preset(self, value):
        # PROTECTED REGION ID(ElmitecLEEM2k.Preset_write) ENABLED START #
        #self.s.send("sep "+str(value))
        #data = self.TCPBlockingReceive()
        #return data
        pass
        # PROTECTED REGION END #    //  ElmitecLEEM2k.Preset_write

    def read_StartVoltage(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.StartVoltage_read) ENABLED START #
        self.s.send("val 38")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.StartVoltage_read

    def write_StartVoltage(self, value):
        # PROTECTED REGION ID(ElmitecLEEM2k.StartVoltage_write) ENABLED START #
        self.s.send("val 38 " + str(value))
        data = self.TCPBlockingReceive()
        # PROTECTED REGION END #    //  ElmitecLEEM2k.StartVoltage_write

    def read_TransferLens(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.TransferLens_read) ENABLED START #
        self.s.send("val 14")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.TransferLens_read

    def read_FieldLens(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.FieldLens_read) ENABLED START #
        self.s.send("val 19")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.FieldLens_read

    def read_IntermLens(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.IntermLens_read) ENABLED START #
        self.s.send("val 21")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.IntermLens_read

    def read_P1Lens(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.P1Lens_read) ENABLED START #
        self.s.send("val 24")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.P1Lens_read

    def read_P2Lens(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.P2Lens_read) ENABLED START #
        self.s.send("val 27")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.P2Lens_read

    def write_P2Lens(self, value):
        # PROTECTED REGION ID(ElmitecLEEM2k.P2Lens_write) ENABLED START #
        self.s.send("val 27 " + str(value))
        data = self.TCPBlockingReceive()
        # PROTECTED REGION END #    //  ElmitecLEEM2k.P2Lens_write

    def read_SampleTemperature(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.SampleTemperature_read) ENABLED START #
        self.s.send("val 39")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.SampleTemperature_read

    def read_ChannelPlateVoltage(self):
        # PROTECTED REGION ID(ElmitecLEEM2k.ChannelPlateVoltage_read) ENABLED START #
        self.s.send("val 105")
        data = self.TCPBlockingReceive()
        return float(data)
        # PROTECTED REGION END #    //  ElmitecLEEM2k.ChannelPlateVoltage_read

    def write_ChannelPlateVoltage(self, value):
        # PROTECTED REGION ID(ElmitecLEEM2k.ChannelPlateVoltage_write) ENABLED START #
        #self.s.send("val 105 "+str(value))
        #data = self.TCPBlockingReceive()
        pass
        # PROTECTED REGION END #    //  ElmitecLEEM2k.ChannelPlateVoltage_write

    # --------
    # Commands
    # --------

    @command(
        dtype_in='str',
        dtype_out='str',
        display_level=DispLevel.EXPERT,
    )
    @DebugIt()
    def sendCommand(self, argin):
        # PROTECTED REGION ID(ElmitecLEEM2k.sendCommand) ENABLED START #
        self.s.send(argin)
        data = self.TCPBlockingReceive()
        return data
Example #22
0
class HuttingerPFGDC(Device):
    """
    Driver for the Huttinger DC generators, such as the PFG-DC1500, a 1500W 1KV power supply for magnetron sputtering growth.
    """
    __metaclass__ = DeviceMeta

    # PROTECTED REGION ID(HuttingerPFGDC.class_variable) ENABLED START #

    def sendcommand(self, address, command, data):
        # Asume command is an string in hexadecimal, say C4
        # address is 0 for generator, 1 for matchbox
        cmd = struct.pack(">BBH", address, int(command, 16), data)
        cmd_string = cmd + self.crc_code(cmd)
        self.ser.write(cmd_string)
        return (self.ser.read(5))

    def parse_response(self, resp):
        (address, cmd, data, crc) = struct.unpack(">BBHB", resp)
        cmd = ord(resp[1])
        if (cmd == 21):
            command = "NACK"
        elif (cmd == 6):
            command = "ACK"
        else:
            command = "%x" % ord(resp[1])
        return (address, command, data)

    def byte_hex(self, a):
        return ("%02x" % ord(a))

    def crc_code(self, a):
        result = 0
        for i in range(0, len(a)):
            result = result ^ ord(a[i])
        return (struct.pack(">B", result))

    # PROTECTED REGION END #    //  HuttingerPFGDC.class_variable

    # -----------------
    # Device Properties
    # -----------------

    SerialPort = device_property(dtype='str', mandatory=True)

    # ----------
    # Attributes
    # ----------

    NominalPower = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        label="Nominal Power",
        unit="W",
        standard_unit="W",
        display_unit="W",
        max_value=150,
        min_value=0,
    )

    NominalVoltage = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        label="Nominal Voltage",
        unit="V",
        standard_unit="V",
        display_unit="V",
        format="%d",
        max_value=1000,
        min_value=0,
    )

    NominalCurrent = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        label="Nominal Current",
        unit="A",
        standard_unit="A",
        display_unit="A",
        format="%4.2f",
        max_value=3.5,
        min_value=0,
    )

    InitialPower = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        label="Initial Power",
        unit="W",
        standard_unit="W",
        display_unit="W",
        max_value=1500,
        min_value=0,
    )

    InitialVoltage = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        label="Initial Voltage",
        unit="V",
        standard_unit="V",
        display_unit="V",
        max_value=1000,
        min_value=0,
    )

    InitialCurrent = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        label="Initial Current",
        unit="A",
        standard_unit="A",
        display_unit="A",
        format="%4.2f",
    )

    VoltageRange = attribute(
        dtype='uint16',
        label="Voltage Range",
        max_value=4,
        min_value=1,
        doc="(1=375V, 2=500V, 3=750V, 4=1000V)",
    )

    ArcDetection = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
        display_level=DispLevel.EXPERT,
        label="ArcDetection",
    )

    RampTime = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        label="RampTime",
        unit="s",
        standard_unit="s",
        display_unit="s",
        format="%4.1f",
        max_value=3200.0,
        min_value=0.0,
        doc="(1=power, 2=voltage, 3=current)",
    )

    ArcDetectionLevel = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
        display_level=DispLevel.EXPERT,
        label="Level",
        max_value=3,
        min_value=1,
    )

    ArcDetectionPause = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
        display_level=DispLevel.EXPERT,
        label="ArcDetectionPause",
        max_value=3,
        min_value=1,
    )

    RampType = attribute(
        dtype='char',
        access=AttrWriteType.READ_WRITE,
        label="RampType",
        max_value=3,
        min_value=1,
        doc="(1=power, 2=voltage, 3=current)",
    )

    Power = attribute(
        dtype='double',
        label="Power",
        unit="W",
        standard_unit="W",
        display_unit="W",
    )

    Voltage = attribute(
        dtype='double',
        label="Voltage",
        unit="V",
        standard_unit="V",
        display_unit="V",
    )

    Current = attribute(
        dtype='double',
        label="Current",
        unit="A",
        standard_unit="A",
        display_unit="A",
    )

    Arcs = attribute(
        dtype='double',
        display_level=DispLevel.EXPERT,
        label="Arcs",
    )

    OperationMode = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        display_level=DispLevel.EXPERT,
        label="OperationMode",
        max_value=2,
        min_value=0,
        doc="(0=OFF;1=On;\n2=On+Ramp)",
    )

    Control = attribute(
        dtype='uint16',
        access=AttrWriteType.READ_WRITE,
        display_level=DispLevel.EXPERT,
        max_value=5,
        min_value=1,
        doc="(1=LOCAL, 2=REALTIME,\n3=REMOTE, 4=RS232,\n5=RS485)",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(HuttingerPFGDC.init_device) ENABLED START #
        self.ser = serial.Serial(self.SerialPort,
                                 baudrate=9600,
                                 bytesize=8,
                                 parity="N",
                                 stopbits=1,
                                 timeout=0.5)
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4E", 4))
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4F", 0))
        self.set_state(PyTango.DevState.OFF)
        if (command != "ACK"):
            self.set_state(PyTango.DevState.FAULT)
        # PROTECTED REGION END #    //  HuttingerPFGDC.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(HuttingerPFGDC.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  HuttingerPFGDC.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(HuttingerPFGDC.delete_device) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4F", 0))
        self.ser.close()
        # PROTECTED REGION END #    //  HuttingerPFGDC.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_NominalPower(self):
        # PROTECTED REGION ID(HuttingerPFGDC.NominalPower_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C1", 0))
        return data * 10
        # PROTECTED REGION END #    //  HuttingerPFGDC.NominalPower_read

    def write_NominalPower(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.NominalPower_write) ENABLED START #
        (address, command, data) = self.parse_response(
            self.sendcommand(0, "41", int(value / 10.0)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.NominalPower_write

    def read_NominalVoltage(self):
        # PROTECTED REGION ID(HuttingerPFGDC.NominalVoltage_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C2", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.NominalVoltage_read

    def write_NominalVoltage(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.NominalVoltage_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "42", int(value)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.NominalVoltage_write

    def read_NominalCurrent(self):
        # PROTECTED REGION ID(HuttingerPFGDC.NominalCurrent_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C3", 4))
        return data / 100.0
        # PROTECTED REGION END #    //  HuttingerPFGDC.NominalCurrent_read

    def write_NominalCurrent(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.NominalCurrent_write) ENABLED START #
        (address, command, data) = self.parse_response(
            self.sendcommand(0, "43", int(value * 100.0)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.NominalCurrent_write

    def read_InitialPower(self):
        # PROTECTED REGION ID(HuttingerPFGDC.InitialPower_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C4", 4))
        return data * 10
        # PROTECTED REGION END #    //  HuttingerPFGDC.InitialPower_read

    def write_InitialPower(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.InitialPower_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "44",
                                                      int(value / 10)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.InitialPower_write

    def read_InitialVoltage(self):
        # PROTECTED REGION ID(HuttingerPFGDC.InitialVoltage_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C5", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.InitialVoltage_read

    def write_InitialVoltage(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.InitialVoltage_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "45", int(value)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.InitialVoltage_write

    def read_InitialCurrent(self):
        # PROTECTED REGION ID(HuttingerPFGDC.InitialCurrent_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C6", 4))
        return data / 100.0
        # PROTECTED REGION END #    //  HuttingerPFGDC.InitialCurrent_read

    def write_InitialCurrent(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.InitialCurrent_write) ENABLED START #
        (address, command, data) = self.parse_response(
            self.sendcommand(0, "46", int(value * 100)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.InitialCurrent_write

    def read_VoltageRange(self):
        # PROTECTED REGION ID(HuttingerPFGDC.VoltageRange_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C8", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.VoltageRange_read

    def read_ArcDetection(self):
        # PROTECTED REGION ID(HuttingerPFGDC.ArcDetection_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "C9", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.ArcDetection_read

    def write_ArcDetection(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.ArcDetection_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "49", value))
        # PROTECTED REGION END #    //  HuttingerPFGDC.ArcDetection_write

    def read_RampTime(self):
        # PROTECTED REGION ID(HuttingerPFGDC.RampTime_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "CA", 0))
        return data / 10.0
        # PROTECTED REGION END #    //  HuttingerPFGDC.RampTime_read

    def write_RampTime(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.RampTime_write) ENABLED START #
        (address, command, data) = self.parse_response(
            self.sendcommand(0, "4A", int(value * 10.0)))
        # PROTECTED REGION END #    //  HuttingerPFGDC.RampTime_write

    def read_ArcDetectionLevel(self):
        # PROTECTED REGION ID(HuttingerPFGDC.ArcDetectionLevel_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "CB", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.ArcDetectionLevel_read

    def write_ArcDetectionLevel(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.ArcDetectionLevel_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4B", value))
        # PROTECTED REGION END #    //  HuttingerPFGDC.ArcDetectionLevel_write

    def read_ArcDetectionPause(self):
        # PROTECTED REGION ID(HuttingerPFGDC.ArcDetectionPause_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "CC", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.ArcDetectionPause_read

    def write_ArcDetectionPause(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.ArcDetectionPause_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4C", value))
        # PROTECTED REGION END #    //  HuttingerPFGDC.ArcDetectionPause_write

    def read_RampType(self):
        # PROTECTED REGION ID(HuttingerPFGDC.RampType_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "CD", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.RampType_read

    def write_RampType(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.RampType_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4D", value))
        # PROTECTED REGION END #    //  HuttingerPFGDC.RampType_write

    def read_Power(self):
        # PROTECTED REGION ID(HuttingerPFGDC.Power_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "D1", 4))
        return data * 10.0
        # PROTECTED REGION END #    //  HuttingerPFGDC.Power_read

    def read_Voltage(self):
        # PROTECTED REGION ID(HuttingerPFGDC.Voltage_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "D2", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.Voltage_read

    def read_Current(self):
        # PROTECTED REGION ID(HuttingerPFGDC.Current_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "D3", 4))
        return data / 100.0
        # PROTECTED REGION END #    //  HuttingerPFGDC.Current_read

    def read_Arcs(self):
        # PROTECTED REGION ID(HuttingerPFGDC.Arcs_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "D9", 4))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.Arcs_read

    def read_OperationMode(self):
        # PROTECTED REGION ID(HuttingerPFGDC.OperationMode_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "CF", 0))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.OperationMode_read

    def write_OperationMode(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.OperationMode_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4F", value))
        # PROTECTED REGION END #    //  HuttingerPFGDC.OperationMode_write

    def read_Control(self):
        # PROTECTED REGION ID(HuttingerPFGDC.Control_read) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "CE", 0))
        return data
        # PROTECTED REGION END #    //  HuttingerPFGDC.Control_read

    def write_Control(self, value):
        # PROTECTED REGION ID(HuttingerPFGDC.Control_write) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4E", value))
        # PROTECTED REGION END #    //  HuttingerPFGDC.Control_write

    # --------
    # Commands
    # --------

    @command()
    @DebugIt()
    def On(self):
        # PROTECTED REGION ID(HuttingerPFGDC.On) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4F", 2))
        self.set_state(PyTango.DevState.ON)
        # PROTECTED REGION END #    //  HuttingerPFGDC.On

    @command()
    @DebugIt()
    def Off(self):
        # PROTECTED REGION ID(HuttingerPFGDC.Off) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4F", 0))
        self.set_state(PyTango.DevState.OFF)
        # PROTECTED REGION END #    //  HuttingerPFGDC.Off

    @command(
        dtype_in=('str', ),
        dtype_out=('str', ),
        display_level=DispLevel.EXPERT,
    )
    @DebugIt()
    def SendCmd(self, argin):
        # PROTECTED REGION ID(HuttingerPFGDC.SendCmd) ENABLED START #
        (address, command, data) = self.parse_response(
            self.sendcommand(0, argin[0], int(argin[1])))
        return ([command + " %d" % data])
        # PROTECTED REGION END #    //  HuttingerPFGDC.SendCmd

    @command()
    @DebugIt()
    def reset_arc_counter(self):
        # PROTECTED REGION ID(HuttingerPFGDC.reset_arc_counter) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "59", 0))
        # PROTECTED REGION END #    //  HuttingerPFGDC.reset_arc_counter

    @command(
        display_level=DispLevel.EXPERT, )
    @DebugIt()
    def On_with_ramp(self):
        # PROTECTED REGION ID(HuttingerPFGDC.On_with_ramp) ENABLED START #
        (address, command,
         data) = self.parse_response(self.sendcommand(0, "4F", 1))
        self.set_state(PyTango.DevState.ON)
class VarianMultiGauge(Device):
    """
    Simple devicer server for the Varian Multigauge controller. Asumes it has a hot cathode gauge.
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(VarianMultiGauge.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  VarianMultiGauge.class_variable

    # -----------------
    # Device Properties
    # -----------------

    SerialPort = device_property(
        dtype='str',
    )

    Speed = device_property(
        dtype='uint16',
    )

    # ----------
    # Attributes
    # ----------

    Pressure_IG1 = attribute(
        dtype='double',
        unit="mbar",
        format="%.1e",
    )

    Pressure_IG2 = attribute(
        dtype='double',
        unit="mbar",
        format="%.1e",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(VarianMultiGauge.init_device) ENABLED START #
        try:
            self.ser=serial.Serial(self.SerialPort,baudrate=self.Speed,bytesize=8,parity="N",stopbits=1,timeout=1)
            self.ser.write("#0011\r") # Set units to mbar
            self.ser.inWaiting()
            resp=self.ser.readline()
            self.ser.write("#0032I1\r") # Check emission on IC1
            self.ser.inWaiting()
            resp=self.ser.readline()
        except:
            self.set_state(PyTango.DevState.FAULT)
            self.set_status("Can't connect to Varian MultiGauge")
            self.debug_stream("Can't connect to Varian MultiGauge")
            return
        self.set_status("Connected to Varian MultiGauge")
        self.debug_stream("Connected to Varian MultiGauge")
        
        if (resp==">01\r"): # Only check first gauge to set device status
            self.set_state(PyTango.DevState.ON)
        else:
            self.set_state(PyTango.DevState.OFF)
        # PROTECTED REGION END #    //  VarianMultiGauge.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(VarianMultiGauge.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  VarianMultiGauge.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(VarianMultiGauge.delete_device) ENABLED START #
        self.ser.close()
        # PROTECTED REGION END #    //  VarianMultiGauge.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_Pressure_IG1(self):
        # PROTECTED REGION ID(VarianMultiGauge.Pressure_IG1_read) ENABLED START #
        self.ser.write("#0002I1\r")
        self.ser.inWaiting()
        a=self.ser.readline()
        return(float(a[1:]))
        # PROTECTED REGION END #    //  VarianMultiGauge.Pressure_IG1_read

    def read_Pressure_IG2(self):
        # PROTECTED REGION ID(VarianMultiGauge.Pressure_IG2_read) ENABLED START #
        self.ser.write("#0002I2\r")
        self.ser.inWaiting()
        a=self.ser.readline()
        return(float(a[1:]))
        # PROTECTED REGION END #    //  VarianMultiGauge.Pressure_IG2_read


    # --------
    # Commands
    # --------

    @command(
    dtype_in='str', 
    dtype_out='str', 
    display_level=DispLevel.EXPERT,
    )
    @DebugIt()
    def SendCommand(self, argin):
        # PROTECTED REGION ID(VarianMultiGauge.SendCommand) ENABLED START #
        self.ser.write(argin+"\r")
        self.ser.inWaiting()
        res=self.ser.readline()
        return(res)
class MVC3GaugeControllerTango(Device, metaclass=DeviceMeta):

    serial_address = device_property(dtype=int,  # store address in decimal (can be 1 - 126)
                                     default_value=1,
                                     doc="this is the devices serial address in decimal. Connection on this device is "
                                         "not done by asking for the serial number (not supported by device) but by "
                                         "asking for the RS485 Serial Address (can also be set/requested in the here "
                                         "used RS232 mode). These were manually set with SSA (e.g. 'RSA46\r' sets this "
                                         "to hex value 46 which is 70 in decimal) command and are labeled on the case "
                                         "of each device. IMPORTANT: after setting the serial address the device must "
                                         "be switched to RS485 and can then be switched back to RS232 immediately. "
                                         "Otherwise the address will reset on next device restart")

    pressure_decimal_places = device_property(dtype=int,
                                              default_value=2,
                                              doc="number of displayed decimal places on pressure readings")

    def init_device(self):
        sys.stdout = StoreStdOut()
        self.get_device_properties()  # otherwise self.serial will be None
        self.mvc3 = MVC3GaugeController(self.serial_address)
        self.set_state(DevState.OFF)
        self.connect()  # try to auto connect on server start. can also be done manually

    def delete_device(self):
        self.mvc3.disconnect()
        print('device deleted')

    @attribute(dtype=str)
    def server_message(self):
        return sys.stdout.read_stored_message()

    @command
    def connect(self):
        self.get_device_properties()
        self.set_state(DevState.INIT)
        if self.mvc3.connect():
            self.set_state(DevState.ON)
        else:
            self.set_state(DevState.FAULT)

    cmd_connect = attribute(access=AttrWriteType.WRITE)

    def write_cmd_connect(self, _):
        self.connect()

    @command
    def disconnect(self):
        self.mvc3.disconnect()
        self.set_state(DevState.OFF)

    cmd_disconnect = attribute(access=AttrWriteType.WRITE)

    def write_cmd_disconnect(self, _):
        self.disconnect()

    cmd_reconnect = attribute(access=AttrWriteType.WRITE)

    def write_cmd_reconnect(self, _):
        self.disconnect()
        self.connect()

    @attribute(dtype=str, #unit='mBar',
               access=AttrWriteType.READ)
    def P1(self):
        """writes out errors and info too"""
        try:
            pressure = self.mvc3.read_pressure(1, decimal_places=self.pressure_decimal_places)
            if self.get_state() == DevState.FAULT:
                self.set_state(DevState.ON)
            return pressure
        # yes, general exception catching is not good but cs studio otherwise hides this completely (even worse)
        except Exception as e:
            self.set_state(DevState.FAULT)
            return "ERROR: %s" % e

    @attribute(dtype=str, unit='mBar', access=AttrWriteType.READ)
    def P2(self):
        """writes out errors and info too"""
        try:
            pressure = self.mvc3.read_pressure(2, decimal_places=self.pressure_decimal_places)
            if self.get_state() == DevState.FAULT:
                self.set_state(DevState.ON)
            return pressure
        # yes, general exception catching is not good but cs studio otherwise hides this completely (even worse)
        except Exception as e:
            self.set_state(DevState.FAULT)
            return "ERROR: %s" % e

    @attribute(dtype=str, unit='mBar', access=AttrWriteType.READ)
    def P3(self):
        """writes out errors and info too"""
        try:
            pressure = self.mvc3.read_pressure(3, decimal_places=self.pressure_decimal_places)
            if self.get_state() == DevState.FAULT:
                self.set_state(DevState.ON)
            return pressure
        # yes, general exception catching is not good but cs studio otherwise hides this completely (even worse)
        except Exception as e:
            self.set_state(DevState.FAULT)
            return "ERROR: %s" % e
 def update_class(self, key, dct):
     """Register proxy and create device property."""
     if not self.device:
         self.device = key
     dct["_class_dict"]["devices"][key] = self
     dct[self.device] = device_property(dtype=str, doc="Proxy device.")
class RaspberryButton(Device, metaclass=DeviceMeta):
    """
    Simple interface to turn on and off a GPIO pin in a Raspberry PI.
    """
    #__metaclass__ = DeviceMeta
    # PROTECTED REGION ID(RaspberryButton.class_variable) ENABLED START #
    # PROTECTED REGION END #    //  RaspberryButton.class_variable

    # -----------------
    # Device Properties
    # -----------------

    Pin = device_property(dtype='uint16', )

    TrueHigh = device_property(dtype='bool', )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(RaspberryButton.init_device) ENABLED START #
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.Pin, GPIO.OUT)
        if (self.TrueHigh == True):
            GPIO.output(self.Pin, 0)
        else:
            GPIO.output(self.Pin, 1)
        self.set_state(PyTango.DevState.OFF)
        # PROTECTED REGION END #    //  RaspberryButton.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(RaspberryButton.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  RaspberryButton.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(RaspberryButton.delete_device) ENABLED START #
        GPIO.cleanup()
        # PROTECTED REGION END #    //  RaspberryButton.delete_device

    # --------
    # Commands
    # --------

    @command()
    @DebugIt()
    def On(self):
        # PROTECTED REGION ID(RaspberryButton.On) ENABLED START #
        if (self.TrueHigh == True):
            GPIO.output(self.Pin, 1)
        else:
            GPIO.output(self.Pin, 0)
        self.set_state(PyTango.DevState.ON)
        # PROTECTED REGION END #    //  RaspberryButton.On

    @command()
    @DebugIt()
    def Off(self):
        # PROTECTED REGION ID(RaspberryButton.Off) ENABLED START #
        if (self.TrueHigh == True):
            GPIO.output(self.Pin, 0)
        else:
            GPIO.output(self.Pin, 1)
        self.set_state(PyTango.DevState.OFF)
    def update_class(self, key, dct):
        """Create the command, methods and device properties."""
        # Register
        proxy.update_class(self, key, dct)
        dct["_class_dict"]["commands"][key] = self

        # Command method
        def run_command(device, arg=None):
            """Write the attribute of the remote device with the value."""
            # Get data
            name, is_attr, value, reset, delay = device._command_dict[key]
            # Get value
            if self.dtype_in:
                value = arg
            # Check attribute
            if name.strip().lower() == NONE_STRING:
                if is_attr:
                    msg = "No attribute to write for commmand {0}"
                else:
                    msg = "No sub-command to run for command {0}"
                raise ValueError(msg.format(key))
            # Prepare
            proxy_name = device._device_dict[key]
            device_proxy = device._proxy_dict[proxy_name]
            if is_attr:
                write = device_proxy.write_attribute
            else:
                write = device_proxy.command_inout
            # Write
            result = write(name, value)
            # Reset
            if reset is not None:
                time.sleep(delay)
                result = write(name, reset)
            # Return
            if not self.dtype_out:
                return
            if not is_attr:
                return result
            # Read attribute
            result = device_proxy.read_attribute(name)
            return result.value

        # Set command
        cmd = patched_command(**self.kwargs)
        run_command.__name__ = key
        if self.is_attr:
            doc = "Write the attribute '{0}' of '{1}' with value {2}"
            run_command.__doc__ = doc.format(self.prop or self.attr,
                                             self.device, self.value)
        else:
            doc = "Run the command '{0}' of '{1}' with value {2}"
            run_command.__doc__ = doc.format(self.prop or self.cmd,
                                             self.device, self.value)
        dct[key] = cmd(run_command)

        # Is allowed method
        def is_allowed(device):
            """The method is allowed if the device is connected."""
            return device.connected

        # Set is allowed method
        method_name = "is_" + key + "_allowed"
        if method_name not in dct:
            is_allowed.__name__ = method_name
            dct[method_name] = is_allowed

        # Create properties
        if self.prop:
            default = self.attr if self.is_attr else self.cmd
            if not isinstance(default, basestring):
                default = None
            if self.is_attr:
                doc = "Attribute of '{0}' to write "
            else:
                doc = "Command of '{0}' to run "
            doc += "when command {1} is executed"
            dct[self.prop] = device_property(dtype=str, default_value=default,
                                             doc=doc.format(self.device, key))
Example #28
0
class PowerSupply(Device):
    """
    Dummy Power Supply for testing
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(PowerSupply.class_variable) ENABLED START #

    # PROTECTED REGION END #    //  PowerSupply.class_variable

    # -----------------
    # Device Properties
    # -----------------

    LoadImpedance = device_property(dtype='double', mandatory=True)

    HWUpdatetime = device_property(dtype='double', default_value=1)

    # ----------
    # Attributes
    # ----------

    Voltage = attribute(
        dtype='double',
        access=AttrWriteType.READ_WRITE,
        label="PSV",
        unit="V",
        max_value=100,
        min_value=0,
        max_alarm=50,
        max_warning=30,
        memorized=True,
    )

    Current = attribute(
        dtype='double',
        unit="A",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(PowerSupply.init_device) ENABLED START #
        self.voltage = 0.
        self.current = 0.
        self.set_state(DevState.OFF)
        # PROTECTED REGION END #    //  PowerSupply.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(PowerSupply.always_executed_hook) ENABLED START #
        t = '%s state is %s\n' % (self.get_name(), self.get_state())
        t += 'Voltage = %s, Current = %s' % (self.voltage, self.current)
        self.set_status(t)
        print(t)
        # PROTECTED REGION END #    //  PowerSupply.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(PowerSupply.delete_device) ENABLED START #
        self.set_state(DevState.UNKNOWN)
        # PROTECTED REGION END #    //  PowerSupply.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_Voltage(self):
        # PROTECTED REGION ID(PowerSupply.Voltage_read) ENABLED START #
        return self.voltage
        # PROTECTED REGION END #    //  PowerSupply.Voltage_read

    def write_Voltage(self, value):
        # PROTECTED REGION ID(PowerSupply.Voltage_write) ENABLED START #
        self.voltage = value
        self.current = self.voltage / self.LoadImpedance
        # PROTECTED REGION END #    //  PowerSupply.Voltage_write

    def read_Current(self):
        # PROTECTED REGION ID(PowerSupply.Current_read) ENABLED START #
        return self.current
        # PROTECTED REGION END #    //  PowerSupply.Current_read

    # --------
    # Commands
    # --------

    @command()
    @DebugIt()
    def On(self):
        # PROTECTED REGION ID(PowerSupply.On) ENABLED START #
        self.set_state(DevState.ON)
        # PROTECTED REGION END #    //  PowerSupply.On

    @command()
    @DebugIt()
    def Off(self):
        # PROTECTED REGION ID(PowerSupply.Off) ENABLED START #
        self.set_state(DevState.OFF)
                        self.attr_ok.append(a)
                elif v[1] is None:
                    # Value is readable but not from DB
                    self.attr_err.append(a)
                else:
                    self.attr_ok.append(a)
        return
    
    # PROTECTED REGION END #    //  SchemaManager.class_variable

    # -----------------
    # Device Properties
    # -----------------

    Schemas = device_property(
        dtype=('str',),
    )

    Threaded = device_property(
        dtype='bool', default_value=False
    )

    ValuesFile = device_property(
        dtype='str',
    )

    CacheTime = device_property(
        dtype='int', default_value=600
    )

    # ----------
Example #30
0
class MicosPollux(PTS.Device, metaclass=PTS.DeviceMeta):

    # Device properties
    proxy = PTS.device_property(dtype=str,
                                doc="Proxy device for serial communication")
    polling = PTS.device_property(dtype=np.uint32, doc="Polling period in ms")
    axis = PTS.device_property(dtype=np.uint32, doc="Axis number")

    # Attributes
    Position = PTS.attribute(label="Position",
                             dtype=PT.DevDouble,
                             format="%.4f",
                             access=PT.AttrWriteType.READ_WRITE,
                             unit="mm",
                             doc="")

    Velocity = PTS.attribute(label="Velocity",
                             dtype=PT.DevDouble,
                             format="%.2f",
                             access=PT.AttrWriteType.READ_WRITE,
                             unit="mm/s",
                             memorized=True,
                             hw_memorized=True,
                             doc="")

    Acceleration = PTS.attribute(label="Acceleration",
                                 dtype=PT.DevDouble,
                                 format="%.2f",
                                 access=PT.AttrWriteType.READ_WRITE,
                                 unit="mm/s^2",
                                 memorized=True,
                                 hw_memorized=True,
                                 doc="")

    def init_device(self):
        """ Initialize device
        """
        # Set INIT state
        self.set_state(PT.DevState.INIT)

        # Call parent init
        PTS.Device.init_device(self)

        # Set polling on State
        self.poll_command("State", 500)

        # Start monitor thread
        self.monitor = PolluxPolling(self)

    def delete_device(self):
        if self.monitor:
            self.monitor.terminate()
            self.monitor.join()

    def read_Position(self):
        return self.monitor.getPosition()

    def write_Position(self, value):
        self.monitor.moveTo(value)

    def read_Velocity(self):
        return self.monitor.getVelocity()

    def write_Velocity(self, value):
        self.monitor.setVelocity(value)

    def read_Acceleration(self):
        return self.monitor.getAcceleration()

    def write_Acceleration(self, value):
        self.monitor.setAcceleration(value)

    @PTS.command()
    def setHome(self):
        self.monitor.setHome()

    @PTS.command()
    def goHome(self):
        self.monitor.moveTo(0.0)
Example #31
0
class MyDevice(Device):
    """
    """
    __metaclass__ = DeviceMeta
    # PROTECTED REGION ID(MyDevice.class_variable) ENABLED START #
    image_maximum = 0.0
    polled_ds = 0.0
    quality_counter = 0
    quality_list = [
        AttrQuality.ATTR_VALID, AttrQuality.ATTR_INVALID,
        AttrQuality.ATTR_ALARM, AttrQuality.ATTR_CHANGING,
        AttrQuality.ATTR_WARNING
    ]
    # PROTECTED REGION END #    //  MyDevice.class_variable
    # ----------------
    # Class Properties
    # ----------------

    # -----------------
    # Device Properties
    # -----------------

    DeviceToRead = device_property(dtype='str', default_value="sys/tg_test/1")

    # ----------
    # Attributes
    # ----------

    PolledDoubleScalar = attribute(dtype='double', )

    ImagineMaximum = attribute(dtype='double', )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(MyDevice.init_device) ENABLED START #
        self.set_state(DevState.ON)
        # PROTECTED REGION END #    //  MyDevice.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(MyDevice.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  MyDevice.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(MyDevice.delete_device) ENABLED START #
        pass
        # PROTECTED REGION END #    //  MyDevice.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_PolledDoubleScalar(self):
        # PROTECTED REGION ID(MyDevice.PolledDoubleScalar_read) ENABLED START #
        attr_proxy = PyTango.AttributeProxy(self.DeviceToRead +
                                            '/double_scalar')
        self.polled_ds = attr_proxy.read().value
        self.debug_stream(str(self.polled_ds))
        return self.polled_ds
        # PROTECTED REGION END #    //  MyDevice.PolledDoubleScalar_read

    def read_ImagineMaximum(self):
        # PROTECTED REGION ID(MyDevice.ImagineMaximum_read) ENABLED START #
        attr_proxy = PyTango.AttributeProxy(self.DeviceToRead +
                                            '/double_image_ro')
        value = attr_proxy.read().value
        maximums = []
        for row in value:
            maximums.append(max(row))
        self.image_maximum = max(maximums)
        attr_quality = AttrQuality.ATTR_VALID
        self.push_change_event("ImagineMaximum", self.image_maximum, time(),
                               attr_quality)
        self.push_archive_event("ImagineMaximum", self.image_maximum, time(),
                                attr_quality)
        if (self.image_maximum < 20):
            self.set_state(DevState.OFF)
        else:
            if (self.image_maximum < 30):
                self.set_state(DevState.WARNING)
            else:
                self.set_state(DevState.ON)

        return float(self.image_maximum), time(), attr_quality
        # PROTECTED REGION END #    //  MyDevice.ImagineMaximum_read

    # --------
    # Commands
    # --------

    @command
    @DebugIt()
    def ChangeDoubleScalarQuality(self):
        # PROTECTED REGION ID(MyDevice.ChangeDoubleScalarQuality) ENABLED START #
        self.quality_counter = (self.quality_counter + 1) % 5
        self.PolledDoubleScalar.set_quality(
            self.quality_list[self.quality_counter])
Example #32
0
class PfeifferDCU002(Device):
    """
    This is a server that provides the same funcionality as the Pfeiffer DCU display unit.
    """
    __metaclass__ = DeviceMeta

    # PROTECTED REGION ID(PfeifferDCU002.class_variable) ENABLED START #

    def sendcommand(self, address, action, parameter, data):
        cmd_string = address + action + parameter + "%02d" % len(data) + data
        cmd = cmd_string + "%03d" % self.crc_code(cmd_string) + "\r"
        self.ser.write(cmd)
        resp = self.ser.read_until(terminator="\r")
        raddress = resp[0:3]
        raction = resp[3:5]
        rparameter = resp[5:8]
        rdata = resp[10:10 + int(resp[8:10])]
        rcrc = resp[-4:-1]
        return (raddress, raction, rparameter, rdata, rcrc)

    def crc_code(self, a):
        result = 0
        for i in range(0, len(a)):
            result = result + ord(a[i])
        result %= 256
        return (result)

    # PROTECTED REGION END #    //  PfeifferDCU002.class_variable

    # -----------------
    # Device Properties
    # -----------------

    SerialPort = device_property(dtype='str', )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(PfeifferDCU002.init_device) ENABLED START #
        self.ser = serial.Serial(self.SerialPort,
                                 9600,
                                 bytesize=8,
                                 parity="N",
                                 stopbits=1)
        # PROTECTED REGION END #    //  PfeifferDCU002.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(PfeifferDCU002.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  PfeifferDCU002.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(PfeifferDCU002.delete_device) ENABLED START #
        self.ser.close()
        # PROTECTED REGION END #    //  PfeifferDCU002.delete_device

    # --------
    # Commands
    # --------

    @command(
        dtype_in='str',
        dtype_out='str',
    )
    @DebugIt()
    def readParameter(self, argin):
        # PROTECTED REGION ID(PfeifferDCU002.readParameter) ENABLED START #
        (radd, raction, rparameter, rdata,
         rcrc) = self.sendcommand("001", "00", argin[0:3], "=?")
        return rdata
        # PROTECTED REGION END #    //  PfeifferDCU002.readParameter

    @command(
        dtype_in=('str', ),
        dtype_out='str',
    )
    @DebugIt()
    def setParameter(self, argin):
        # PROTECTED REGION ID(PfeifferDCU002.setParameter) ENABLED START #
        parameter = argin[0]
        data = argin[1]
        parameter = parameter[0:3]
        (radd, raction, rparameter, rdata,
         rcrc) = self.sendcommand("001", "10", parameter, data)
        return rdata
class SpectrometerCameraDS(Device):
    __metaclass__ = DeviceMeta

    exposuretime = attribute(
        label='ExposureTime',
        dtype=float,
        access=pt.AttrWriteType.READ_WRITE,
        unit="us",
        format="%8.1f",
        min_value=0.0,
        max_value=1e7,
        fget="get_exposuretime",
        fset="set_exposuretime",
        doc="Camera exposure time in us",
        memorized=True,
    )
    # hw_memorized=True)

    gain = attribute(
        label='Gain',
        dtype=float,
        access=pt.AttrWriteType.READ_WRITE,
        unit="dB",
        format="%3.2f",
        min_value=0.0,
        max_value=1e2,
        fget="get_gain",
        fset="set_gain",
        doc="Camera gain in dB",
        memorized=True,
    )
    # hw_memorized=True)

    wavelengthvector = attribute(
        label='WavelengthVector',
        dtype=[np.double],
        access=pt.AttrWriteType.READ,
        max_dim_x=16384,
        display_level=pt.DispLevel.OPERATOR,
        unit="m",
        format="%5.2e",
        fget="get_wavelengthvector",
        doc="Wavelength vector",
    )

    spectrum = attribute(
        label='Spectrum',
        dtype=[np.double],
        access=pt.AttrWriteType.READ,
        max_dim_x=16384,
        display_level=pt.DispLevel.OPERATOR,
        unit="a.u.",
        format="%5.2f",
        fget="get_spectrum",
        doc="Spectrum",
    )

    width = attribute(
        label='Spectrum width FWHM',
        dtype=np.double,
        access=pt.AttrWriteType.READ,
        display_level=pt.DispLevel.OPERATOR,
        unit="m",
        format="%5.2e",
        fget="get_width",
        doc=
        "FWHM for the peak in spectrum. Basic thresholding and peak detection is used.",
    )

    peak = attribute(
        label='Spectrum peak',
        dtype=np.double,
        access=pt.AttrWriteType.READ,
        display_level=pt.DispLevel.OPERATOR,
        unit="m",
        format="%5.2e",
        fget="get_peak",
        doc=
        "Wavelength for the peak in spectrum. Basic thresholding and peak detection is used.",
    )

    sat_lvl = attribute(
        label='Saturation level',
        dtype=np.double,
        access=pt.AttrWriteType.READ,
        display_level=pt.DispLevel.OPERATOR,
        unit="relative",
        format="%2.2e",
        fget="get_satlvl",
        doc=
        "Relative amount of pixels that are saturated. This should be zero.",
    )

    camera_name = device_property(
        dtype=str,
        doc="Tango name of the camera device",
        default_value="gunlaser/cameras/spectrometer_camera")

    watchdog_timeout = device_property(
        dtype=float,
        doc="Timeout for the watchdog resetting the hardware in s",
        default_value="2.0")

    dispersion = device_property(
        dtype=float,
        doc="Dispersion of the spectrometer in nm/px. "
        "Positive if wavelength increases to the right",
        default_value="0.056")

    central_wavelength = device_property(
        dtype=float,
        doc="Wavelength of the central pixel of the ROI in nm",
        default_value="2.0")

    roi = device_property(
        dtype=[int],
        doc="Pixel coordinates for the ROI: [left, top, width, height]",
        default_value=[0, 0, 100, 100])

    saturation_level = device_property(
        dtype=int,
        doc="Saturation pixel value, used for estimating overexposure",
        default_value=65536)

    def __init__(self, klass, name):
        self.wavelengthvector_data = np.array([])
        self.max_value = 1.0
        self.dev_controller = None
        self.db = None
        Device.__init__(self, klass, name)

    def init_device(self):
        self.debug_stream("In init_device:")
        Device.init_device(self)
        self.db = pt.Database()
        self.set_state(pt.DevState.UNKNOWN)
        self.debug_stream("Init camera controller {0}".format(
            self.camera_name))
        params = dict()
        params["imageoffsetx"] = self.roi[0]
        params["imageoffsety"] = self.roi[1]
        params["imagewidth"] = self.roi[2]
        params["imageheight"] = self.roi[3]
        params["triggermode"] = "Off"
        try:
            if self.dev_controller is not None:
                self.dev_controller.stop_thread()
        except Exception as e:
            self.error_info("Error stopping camera controller: {0}".format(e))
        try:
            self.setup_spectrometer()
            self.dev_controller = SpectrometerCameraDeviceController(
                self.camera_name, params, self.wavelengthvector_data,
                self.max_value)
            # self.dev_controller = CameraDeviceController(self.camera_name, params)
        except Exception as e:
            self.error_stream(
                "Error creating camera controller: {0}".format(e))
            return

        self.debug_stream("init_device finished")
        # self.set_state(pt.DevState.ON)
        self.dev_controller.add_state_callback(self.change_state)

    def setup_spectrometer(self):
        self.info_stream("Entering setup_camera")
        self.wavelengthvector_data = (self.central_wavelength + np.arange(
            -self.roi[2] / 2, self.roi[2] / 2) * self.dispersion) * 1e-9
        self.max_value = self.saturation_level

    def change_state(self, new_state, new_status=None):
        self.debug_stream("Change state from {0} to {1}".format(
            self.get_state(), new_state))
        if self.get_state(
        ) is pt.DevState.INIT and new_state is not pt.DevState.UNKNOWN:
            self.debug_stream("Set memorized attributes")
            data = self.db.get_device_attribute_property(
                self.get_name(), "gain")
            self.debug_stream(
                "Database returned data for \"gain\": {0}".format(
                    data["gain"]))
            try:
                new_value = float(data["gain"]["__value"][0])
                self.debug_stream("{0}".format(new_value))
                self.dev_controller.write_attribute("gain", new_value)
            except (KeyError, TypeError, IndexError, ValueError):
                pass
            data = self.db.get_device_attribute_property(
                self.get_name(), "exposuretime")
            self.debug_stream(
                "Database returned data for \"exposuretime\": {0}".format(
                    data["exposuretime"]))
            try:
                new_value = float(data["exposuretime"]["__value"][0])
                self.dev_controller.write_attribute("exposuretime", new_value)
            except (KeyError, TypeError, IndexError, ValueError):
                pass
        self.set_state(new_state)
        if new_status is not None:
            self.debug_stream("Setting status {0}".format(new_status))
            self.set_status(new_status)

    def get_spectrum(self):
        attr = self.dev_controller.get_attribute("image")
        try:
            spectrum = attr.value.sum(0)
        except AttributeError:
            spectrum = []
        return spectrum, attr.time.totime(), attr.quality

    def get_wavelengthvector(self):
        self.debug_stream("get_wavelengthvector: size {0}".format(
            self.wavelengthvector_data.shape))
        return self.wavelengthvector_data, time.time(
        ), pt.AttrQuality.ATTR_VALID

    def get_exposuretime(self):
        attr = self.dev_controller.get_attribute("exposuretime")
        return attr.value, attr.time.totime(), attr.quality

    def set_exposuretime(self, new_exposuretime):
        self.debug_stream(
            "In set_exposuretime: New value {0}".format(new_exposuretime))
        self.debug_stream("Type dev_controller: {0}".format(
            type(self.dev_controller)))
        self.dev_controller.write_attribute("exposuretime", new_exposuretime)

    def get_gain(self):
        attr = self.dev_controller.get_attribute("gain")
        return attr.value, attr.time.totime(), attr.quality

    def set_gain(self, new_gain):
        self.debug_stream("In set_gain: New value {0}".format(new_gain))
        self.dev_controller.write_attribute("gain", new_gain)

    def get_width(self):
        attr = self.dev_controller.get_attribute("width")
        return attr

    def get_peak(self):
        attr = self.dev_controller.get_attribute("peak")
        return attr

    def get_satlvl(self):
        attr = self.dev_controller.get_attribute("satlvl")
        return attr
Example #34
0
class TMCM6110MotoraxisDS(Device):
    __metaclass__ = DeviceMeta

    # --- Operator attributes
    #
    Position = attribute(label="position",
                         dtype=float,
                         access=pt.AttrWriteType.READ_WRITE,
                         unit="mm",
                         format="%6.2f",
                         min_value=-100000.0,
                         max_value=100000.0,
                         fget="get_position",
                         fset="set_position",
                         doc="Motor position in mm",
                         memorized=True,
                         hw_memorized=True)

    Velocity = attribute(label="velocity",
                         dtype=float,
                         access=pt.AttrWriteType.READ_WRITE,
                         unit="mm / s",
                         format="%6.2f",
                         min_value=-100000.0,
                         max_value=100000.0,
                         fget="get_velocity",
                         fset="set_velocity",
                         doc="Motor velocity in mm/s",
                         memorized=True,
                         hw_memorized=True)

    DialPosition = attribute(
        label="dial position",
        dtype=float,
        access=pt.AttrWriteType.READ,
        unit="mm",
        format="%6.2f",
        min_value=-100000.0,
        max_value=100000.0,
        fget="get_dialposition",
        fset="set_dialposition",
        doc="Absolute motor position in mm with offset applied",
    )

    Offset = attribute(label="offset",
                       dtype=float,
                       access=pt.AttrWriteType.READ_WRITE,
                       unit="mm",
                       format="%6.2f",
                       min_value=-100000.0,
                       max_value=100000.0,
                       fget="get_offset",
                       fset="set_offset",
                       doc="Motor offset in mm",
                       memorized=True,
                       hw_memorized=True)

    Acceleration = attribute(label="acceleration",
                             dtype=float,
                             access=pt.AttrWriteType.READ_WRITE,
                             unit="mm / s**2",
                             format="%6.2f",
                             min_value=-1000000.0,
                             max_value=1000000.0,
                             fget="get_acceleration",
                             fset="set_acceleration",
                             doc="Motor acceleration in mm/s**2",
                             memorized=True,
                             hw_memorized=True)

    Deceleration = attribute(label="deceleration",
                             dtype=float,
                             access=pt.AttrWriteType.READ_WRITE,
                             unit="mm / s**2",
                             format="%6.2f",
                             min_value=-1000000.0,
                             max_value=1000000.0,
                             fget="get_deceleration",
                             fset="set_deceleration",
                             doc="Motor deceleration in mm/s**2",
                             memorized=True,
                             hw_memorized=True)

    Base_rate = attribute(
        label="base rate",
        dtype=float,
        access=pt.AttrWriteType.READ_WRITE,
        unit="a.u.",
        format="%6.2f",
        min_value=-1000000.0,
        max_value=1000000.0,
        fget="get_baserate",
        fset="set_baserate",
        doc="Motor base rate... whatever that is",
        memorized=True,
    )

    SimulationMode = attribute(
        label="simulation mode",
        dtype=bool,
        access=pt.AttrWriteType.READ,
        unit="",
        fget="get_simulationmode",
        doc="Motor simulation mode",
    )

    Step_per_unit = attribute(label="step per unit",
                              dtype=float,
                              access=pt.AttrWriteType.READ_WRITE,
                              unit="steps/mm",
                              format="%6.2f",
                              min_value=-1000000.0,
                              max_value=1000000.0,
                              fget="get_stepperunit",
                              fset="set_stepperunit",
                              doc="Motor steps per unit",
                              memorized=True,
                              hw_memorized=True)

    Backlash = attribute(label="backlash",
                         dtype=bool,
                         access=pt.AttrWriteType.READ_WRITE,
                         unit="",
                         format="%d",
                         fget="get_backlash",
                         fset="set_backlash",
                         doc="Motor backlash",
                         memorized=True,
                         hw_memorized=True)

    Limit_switches = attribute(
        label="limit switches",
        dtype=(bool, ),
        max_dim_x=3,
        access=pt.AttrWriteType.READ,
        unit="",
        format="%d",
        fget="get_limitswitches",
        doc="Limit switches state",
    )

    Load_level = attribute(
        label="load level",
        dtype=float,
        access=pt.AttrWriteType.READ,
        unit="",
        format="%6.2f",
        min_value=-1000000.0,
        max_value=1000000.0,
        fget="get_loadlevel",
        doc="Motor load level in normalized units",
    )

    # --- Device properties
    #
    TMCM6110_device = device_property(
        dtype=str,
        doc="Tango name of mother Trinamic_TMCM6110_DS",
    )

    Axis = device_property(
        dtype=int,
        doc="Motor axis",
    )

    Motor_current = device_property(
        dtype=float,
        doc="Motor maxiumum current",
    )

    Microsteps = device_property(
        dtype=int,
        doc="Microstep resolution: 1, 2, 4, 8, or 16",
    )

    Limit0Enable = device_property(
        dtype=bool,
        doc="Enable limit switch 0?",
    )

    Limit1Enable = device_property(
        dtype=bool,
        doc="Enable limit switch 1?",
    )

    def __init__(self, klass, name):
        self.controller = None  # type: TMCM6110MotoraxisController
        self.setup_attr_params = dict()
        self.state_dispatcher = None  # type: StateDispatcher
        self.state_thread = None  # type: threading.Thread
        self.stop_state_thread = False

        self.offset_value = 0
        self.baserate_value = 0
        self.backlash_value = False
        self.simulation_value = False

        Device.__init__(self, klass, name)

    def init_device(self):
        self.debug_stream("In init_device:")
        Device.init_device(self)
        if self.controller is not None:
            self.stop_state_thread = True
            self.state_thread.join(1.0)
            self.controller.close()
        self.debug_stream(
            "Device: {0}, axis {1}, motor_current {2}, microsteps {3}".format(
                self.TMCM6110_device, self.Axis, self.Motor_current,
                self.Microsteps))
        self.controller = TMCM6110MotoraxisController(
            self.TMCM6110_device, self.Axis, self.Motor_current, 1,
            self.Microsteps, self.Limit0Enable, self.Limit1Enable)
        self.state_thread = threading.Thread(target=self._read_state)
        self.state_thread.daemon = True
        self.state_thread.start()

    def get_position(self):
        # self.debug_stream("In get_position:")
        if self.controller is None:
            self.error_stream("No controller")
            return None
        data = self.controller.get_position()
        try:
            value = data.value
            t = data.time.totime()
            quality = pt.AttrQuality.ATTR_VALID
        except AttributeError:
            value = 0
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def set_position(self, pos):
        self.debug_stream("In set_position: {0}".format(pos))
        if self.controller is None:
            self.error_stream("set_position: NO CONTROLLER")
            return
        self.controller.set_position(pos)
        return 0

    def get_velocity(self):
        # self.debug_stream("In get_velocity:")
        data = self.controller.get_speed()
        try:
            value = data.value
            t = data.time.totime()
            quality = pt.AttrQuality.ATTR_VALID
        except AttributeError:
            value = 0
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def set_velocity(self, value):
        self.debug_stream("In set_velocity: {0}".format(value))
        if self.controller is None:
            self.error_stream("set_velocity: NO CONTROLLER")
            return
        self.controller.set_speed(value)
        return 0

    def get_dialposition(self):
        # self.debug_stream("In get_dialposition:")
        data = self.controller.get_position()
        try:
            value = data.value - self.offset_value
            t = data.time.totime()
            quality = pt.AttrQuality.ATTR_VALID
        except AttributeError:
            value = 0
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def get_offset(self):
        # self.debug_stream("In get_offset:")
        value = self.offset_value
        quality = pt.AttrQuality.ATTR_VALID
        t = time.time()
        return value, t, quality

    def set_offset(self, value):
        self.debug_stream("In set_offset: {0}".format(value))
        self.offset_value = value
        return 0

    def get_acceleration(self):
        # self.debug_stream("In get_acceleration:")
        data = self.controller.get_acceleration()
        try:
            value = data.value
            t = data.time.totime()
            quality = pt.AttrQuality.ATTR_VALID
        except AttributeError:
            value = 0
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def set_acceleration(self, value):
        self.debug_stream("In set_acceleration: {0}".format(value))
        if self.controller is None:
            self.error_stream("set_acceleration: NO CONTROLLER")
            return
        self.controller.set_acceleration(value)

        return 0

    def get_deceleration(self):
        # self.debug_stream("In get_deceleration:")
        data = self.controller.get_acceleration()
        try:
            value = data.value
            t = data.time.totime()
            quality = pt.AttrQuality.ATTR_VALID
        except AttributeError:
            value = 0
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def set_deceleration(self, value):
        self.debug_stream("In set_deceleration: {0}".format(value))
        if self.controller is None:
            self.error_stream("set_deceleration: NO CONTROLLER")
            return
        self.controller.set_acceleration(value)

        return 0

    def get_baserate(self):
        # self.debug_stream("In get_baserate:")
        value = self.baserate_value
        quality = pt.AttrQuality.ATTR_VALID
        t = time.time()
        return value, t, quality

    def set_baserate(self, value):
        self.debug_stream("In set_baserate: {0}".format(value))
        self.baserate_value = value
        return 0

    def get_simulationmode(self):
        # self.debug_stream("In get_simulationmode:")
        value = self.simulation_value
        quality = pt.AttrQuality.ATTR_VALID
        t = time.time()
        return value, t, quality

    def set_simulationmode(self, value):
        self.debug_stream("In set_simulationmode: {0}".format(value))
        self.simulation_value = value
        return 0

    def get_stepperunit(self):
        # self.debug_stream("In get_stepperunit:")
        if self.controller is None:
            return None

        value = self.controller.get_stepperunit()
        quality = pt.AttrQuality.ATTR_VALID
        t = time.time()
        return value, t, quality

    def set_stepperunit(self, value):
        self.debug_stream("In set_stepperunit: {0}".format(value))
        if self.controller is None:
            return
        self.controller.set_stepperunit(value)
        return 0

    def get_backlash(self):
        # self.debug_stream("In get_backlash:")
        value = self.backlash_value
        quality = pt.AttrQuality.ATTR_VALID
        t = time.time()
        return value, t, quality

    def set_backlash(self, value):
        self.debug_stream("In set_backlash: {0}".format(value))
        self.backlash_value = value
        return 0

    def get_limitswitches(self):
        # self.debug_stream("In get_limitswitches:")
        data = self.controller.get_limitswitches()
        try:
            value = [data[0].value, data[1].value]
            t = data[0].time.totime()
            quality = pt.AttrQuality.ATTR_VALID

        except AttributeError:
            value = [False, False]
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def get_loadlevel(self):
        # self.debug_stream("In get_loadlevel:")
        data = self.controller.get_loadlevel()
        try:
            value = data.value
            t = data.time.totime()
            quality = pt.AttrQuality.ATTR_VALID
        except AttributeError:
            value = 0
            quality = pt.AttrQuality.ATTR_INVALID
            t = time.time()
        return value, t, quality

    def _read_state(self):
        self.debug_stream("Starting read state thread")
        old_state = "--"
        while not self.stop_state_thread:
            state, status = self.controller.get_state()
            if state in ["unknown"]:
                if old_state != state:
                    self.info_stream("Changing state to UNKNOWN")
                    self.set_state(pt.DevState.UNKNOWN)
                    self.set_status(status)
            elif state in ["init"]:
                if old_state != state:
                    self.info_stream("Changing state to INIT")
                    self.set_state(pt.DevState.INIT)
                    self.set_status(status)
            elif state in ["on"]:
                if old_state != state:
                    self.info_stream("Changing state to ON")
                    self.set_state(pt.DevState.ON)
                    self.set_status(status)
            elif state in ["moving"]:
                if old_state != state:
                    self.info_stream("Changing state to MOVING")
                    self.set_state(pt.DevState.MOVING)
                    self.set_status(status)
            elif state in ["fault"]:
                if old_state != state:
                    self.info_stream("Changing state to FAULT")
                    self.set_state(pt.DevState.FAULT)
                    self.set_status(status)
            elif state in ["alarm"]:
                if old_state != state:
                    self.info_stream("Changing state to ALARM")
                    self.set_state(pt.DevState.ALARM)
                    self.set_status(status)
            else:
                self.info_stream("Unknown state,setting UNKNOWN")
                self.set_state(pt.DevState.UNKNOWN)
            old_state = state
            time.sleep(0.1)
class SEAWaterflowmeter(Device,metaclass=DeviceMeta):
    """
    Device server to interface a Raspberry PI using the GPIO to the SEA YF-S201 water flow sensor.
    """
    # PROTECTED REGION ID(SEAWaterflowmeter.class_variable) ENABLED START #
   
 
    # PROTECTED REGION END #    //  SEAWaterflowmeter.class_variable

    # -----------------
    # Device Properties
    # -----------------

    channels = device_property(
        dtype='str', default_value="6,13,19,26"
    )

    channelnames = device_property(
        dtype='str', default_value="turbo,xraygun,doser,p2lens"
    )

    calibration = device_property(
        dtype='double', default_value=7.5
    )

    time = device_property(
        dtype='double', default_value=1.0
    )

    # ----------
    # Attributes
    # ----------

    channel0 = attribute(
        dtype='double',
        label="turbo",
        unit="l/min",
        format="%3.1f",
    )

    channel1 = attribute(
        dtype='double',
        label="xray gun",
        unit="l/min",
        format="%3.1f",
    )

    channel2 = attribute(
        dtype='double',
        label="doser",
        unit="l/min",
        format="%3.1f",
    )

    channel3 = attribute(
        dtype='double',
        label="p2 lens",
        unit="l/min",
        format="%3.1f",
    )

    # ---------------
    # General methods
    # ---------------

    def init_device(self):
        Device.init_device(self)
        # PROTECTED REGION ID(SEAWaterflowmeter.init_device) ENABLED START #
        self.channel0data=0.0
        self.channel1data=0.0
        self.channel2data=0.0
        self.channel3data=0.0
        for i in self.channels.split(","):
            count[int(i)]=0.0
        self.listofnames=self.channelnames.split(",")
        #print(self.channel0.get_attribute_list)
        #self.channel0.set_label(listofnames[0])
        #self.channel1.set_label(listofnames[1])
        #self.channel2.set_label(listofnames[2])
        #self.channel3.set_label(listofnames[3])        
        GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering  
        for i in count:
            GPIO.setup(i,GPIO.IN)
        for i in count:
            GPIO.add_event_detect(i, GPIO.RISING, callback=my_callback)  
        self.set_state(PyTango.DevState.ON)
        self.set_status("Measurement thread is running")
        self.stop_ctrloop = 0
        ctrlloop = ControlThread(self)
        ctrlloop.start()
        # PROTECTED REGION END #    //  SEAWaterflowmeter.init_device

    def always_executed_hook(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.always_executed_hook) ENABLED START #
        pass
        # PROTECTED REGION END #    //  SEAWaterflowmeter.always_executed_hook

    def delete_device(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.delete_device) ENABLED START #
        self.ds.stop_ctrloop = 0
        GPIO.cleanup()
        # PROTECTED REGION END #    //  SEAWaterflowmeter.delete_device

    # ------------------
    # Attributes methods
    # ------------------

    def read_channel0(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.channel0_read) ENABLED START #
        return self.channel0data
        # PROTECTED REGION END #    //  SEAWaterflowmeter.channel0_read

    def read_channel1(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.channel1_read) ENABLED START #
        return self.channel1data
        # PROTECTED REGION END #    //  SEAWaterflowmeter.channel1_read

    def read_channel2(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.channel2_read) ENABLED START #
        return self.channel2data
        # PROTECTED REGION END #    //  SEAWaterflowmeter.channel2_read

    def read_channel3(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.channel3_read) ENABLED START #
        return self.channel3data
        # PROTECTED REGION END #    //  SEAWaterflowmeter.channel3_read


    # --------
    # Commands
    # --------

    @command(
    )
    @DebugIt()
    def turnON(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.turnON) ENABLED START #
        state=self.get_state()
        if (state==PyTango.DevState.ON):
            return
        elif (state==PyTango.DevState.OFF):
            self.stop_ctrloop = 0
            ctrlloop = ControlThread(self)
            ctrlloop.start()
            self.set_state(PyTango.DevState.ON)
            self.set_status("Measurement thread is running")
        # PROTECTED REGION END #    //  SEAWaterflowmeter.turnON

    @command(
    )
    @DebugIt()
    def turnOFF(self):
        # PROTECTED REGION ID(SEAWaterflowmeter.turnOFF) ENABLED START #
        state=self.get_state()
        if (state==PyTango.DevState.OFF):
            return
        elif (state==PyTango.DevState.ON):
            self.stop_ctrloop = 1
            self.set_state(PyTango.DevState.OFF)
            self.set_status("Measurement thread is NOT running")