Esempio n. 1
0
    def __init__(self, parent, prefix, pvdata, **kws):
        wx.Panel.__init__(self, parent, -1, **kws)
        self.sizer = sizer = wx.GridBagSizer(3, 3)
        self.wids = {}
        self.prefix = prefix
        irow = -1
        for label, pvsuff, dtype, rsuff, wsize in pvdata:

            pvname = prefix + pvsuff
            ctrl = pv_control(dtype)
            self.wids[label] = ctrl(self, pv=get_pv(pvname), size=(wsize, -1))

            title = wx.StaticText(self,
                                  label=label,
                                  size=(8 * len(label), -1),
                                  style=labstyle)
            irow += 1
            sizer.Add(title, (irow, 0), (1, 1), labstyle)

            if rsuff:
                rlabel = label + rsuff
                rname = pvname + rsuff
                self.wids[rlabel] = PVStaticText(self,
                                                 pv=get_pv(rname),
                                                 size=(wsize, -1))

                sizer.Add(self.wids[label], (irow, 1), (1, 1), labstyle)
                sizer.Add(self.wids[rlabel], (irow, 2), (1, 1), labstyle)
            else:
                sizer.Add(self.wids[label], (irow, 1), (1, 2), labstyle)
        pack(self, sizer)
Esempio n. 2
0
    def __init__(self, parent, prefix, pvdata, **kws):
        wx.Panel.__init__(self, parent, -1,  **kws)
        self.sizer = sizer = wx.GridBagSizer(3, 3)
        self.wids = {}
        self.prefix = prefix
        irow = -1
        for label, pvsuff, dtype, rsuff, wsize in pvdata:

            pvname = prefix + pvsuff
            ctrl  = pv_control(dtype)
            self.wids[label] = ctrl(self, pv=get_pv(pvname), size=(wsize, -1))

            title = wx.StaticText(self, label=label, size=(8*len(label), -1),
                                  style=labstyle)
            irow += 1
            sizer.Add(title, (irow, 0), (1, 1), labstyle)

            if rsuff:
                rlabel = label + rsuff
                rname = pvname + rsuff
                self.wids[rlabel] = PVStaticText(self, pv=get_pv(rname),
                                                 size=(wsize, -1))

                sizer.Add(self.wids[label], (irow, 1), (1, 1), labstyle)
                sizer.Add(self.wids[rlabel], (irow, 2), (1, 1), labstyle)
            else:
                sizer.Add(self.wids[label], (irow, 1), (1, 2), labstyle)
        pack(self, sizer)
Esempio n. 3
0
    def jesdTXReset(prefix):
        logging.error('[%s] ' % str(datetime.now()) +
                      ' JesdTx went down, will attempt to recover...')

        # for recovery
        PwrUpSysRef = epics.get_pv(
            prefix +
            ':AMCc:FpgaTopLevel:AppTop:AppCore:MicrowaveMuxCore[0]:LMK:PwrUpSysRef'
        )
        JesdTxEnable = epics.get_pv(
            prefix + ':AMCc:FpgaTopLevel:AppTop:AppTopJesd[0]:JesdTx:Enable')
        DAC0JesdRstN = epics.get_pv(
            prefix +
            ':AMCc:FpgaTopLevel:AppTop:AppCore:MicrowaveMuxCore[0]:DAC[0]:JesdRstN'
        )
        DAC1JesdRstN = epics.get_pv(
            prefix +
            ':AMCc:FpgaTopLevel:AppTop:AppCore:MicrowaveMuxCore[0]:DAC[1]:JesdRstN'
        )

        #1. Toggle JesdRx:Enable 0x3CF -> 0x0 -> 0x3CF
        JesdTxEnable.put(0x0)
        JesdTxEnable.put(0x3CF)

        #2. Toggle AMCcc:FpgaTopLevel:AppTop:AppCore:MicrowaveMuxCore[0]:DAC[0]:JesdRstN 0x1 -> 0x0 -> 0x1
        DAC0JesdRstN.put(0x0)
        DAC0JesdRstN.put(0x1)

        #3. Toggle AMCcc:FpgaTopLevel:AppTop:AppCore:MicrowaveMuxCore[0]:DAC[1]:JesdRstN 0x1 -> 0x0 -> 0x1
        DAC1JesdRstN.put(0x0)
        DAC1JesdRstN.put(0x1)

        # SYSREF is the last step
        PwrUpSysRef.put(1)
Esempio n. 4
0
def test_with_getPV():
    # create 2 PV objects connecting to the same PV signal using get_pv()
    pv1 = get_pv(mypv)
    pv2 = get_pv(mypv)

    pv1.wait_for_connection()
    pv2.wait_for_connection()

    # check that both PVs are connected
    assert pv1.connected is True
    assert pv2.connected is True

    # check that data is received
    assert pv1.get() is not None
    assert pv2.get() is not None

    # disconnect 1 PV
    pv1.disconnect()

    time.sleep(1)

    # check that the first PV is disconnected and doesn't receive data
    assert pv1.connected is False
    assert pv1.get() is None

    # check that the other PV is also disconnected and doesn't receive data either
    assert pv2.connected is False
    assert pv2.get() is None
Esempio n. 5
0
 def __init__(self, prefix, value=1, **kws):
     Trigger.__init__(self, prefix, value=value, **kws)
     self._start = get_pv(prefix + 'det1:Acquire')
     self._erase = get_pv(prefix + 'det1:ERASE')
     self.prefix = prefix
     self._val = value
     self.done = False
     self._t0 = 0
     self.runtime = -1
Esempio n. 6
0
    def thread():
        epics.ca.create_context()
        pv = epics.get_pv(pvnames.double_pv2)
        assert pv.wait_for_connection()
        result.append(pv.get())
        epics.ca.detach_context()

        epics.ca.attach_context(ctx)
        pv = epics.get_pv(pvnames.double_pv)
        assert pv.wait_for_connection()
        result.append(pv.get())
Esempio n. 7
0
    def jesdRXReset(prefix):
        logging.error('[%s] ' % str(datetime.now()) + ' JesdRx went down, will attempt to recover...')

        # for recovery
        PwrUpSysRef = epics.get_pv(prefix + ':AMCc:FpgaTopLevel:AppTop:AppCore:MicrowaveMuxCore[0]:LMK:PwrUpSysRef')
        JesdRxEnable = epics.get_pv(prefix + ':AMCc:FpgaTopLevel:AppTop:AppTopJesd[0]:JesdRx:Enable')

        #1. Toggle JesdRx:Enable 0x3F3 -> 0x0 -> 0x3F3
        JesdRxEnable.put(0x0)
        JesdRxEnable.put(0x3F3)
        # SYSREF is the last step
        PwrUpSysRef.put(1)
Esempio n. 8
0
    def __init__(self, prefix):
        self.logfile = '/tmp/JesdWatchdog.log'
        logging.basicConfig(filename=self.logfile,level=logging.ERROR)

        self.prefix = prefix
        self.enabledPv     = epics.get_pv('SIOC:SMRF:ML00:AO001', callback=self.enableChanged, auto_monitor=True)
        self.enable        = self.enabledPv.get()
        self.jesdtxreset_thread = None
        self.jesdrxreset_thread = None
        self.counterPv     = epics.get_pv('SIOC:SMRF:ML00:AO001CNT')
        self.counterPvProc = epics.get_pv('SIOC:SMRF:ML00:AO001CNT.PROC')
        self.JesdRxValidPv = epics.get_pv(prefix + ':AMCc:FpgaTopLevel:AppTop:AppTopJesd[0]:JesdRx:DataValid', callback=self.jesdValidChanged, auto_monitor=True)
        self.JesdTxValidPv = epics.get_pv(prefix + ':AMCc:FpgaTopLevel:AppTop:AppTopJesd[0]:JesdTx:DataValid', callback=self.jesdValidChanged, auto_monitor=True)
Esempio n. 9
0
    def qxafs_prep(self):
        self.idarray = self.idarray_pv.get()
        self.dtime = float(self.get_info(key='qxafs_dwelltime', default=0.5))
        self.pulse = 0
        self.last_move_time = 0
        self.counters = []
        for c in self.scandb.get_scandata():
            pv = get_pv(c.pvname)

        time.sleep(0.05)
        for c in self.scandb.get_scandata():
            pv = get_pv(c.pvname)
            pv.connect()
            self.counters.append((c.name, pv, pv.nelm))
Esempio n. 10
0
  def __enter__(self):
    self.pv_image_channel = epics.get_pv(self.pv_image)
    self.pv_uniqueId_channel = epics.get_pv(self.pv_uniqueId)
    #y, x = (1920,1200) #self.pv_channel.get('field()')['dimension']
    self.dims=(1920, 1200)
    if self.num_sinograms>0:
      if (self.beg_sinogram<0) or (self.beg_sinogram+self.num_sinograms>self.dims[0]): 
        raise Exception("Exceeds the sinogram boundary: {} vs. {}".format(
                            self.beg_sinogram+self.num_sinograms, self.dims[0]))
      self.beg_index = self.beg_sinogram*self.dims[1]
      self.end_index = self.beg_sinogram*self.dims[1] + self.num_sinograms*self.dims[1]
    self.pv_image_channel.subscribe(self.push_image_data)
    self.pv_uniqueId_channel.subscribe(self.push_uniqueId)

    return self
Esempio n. 11
0
    def __init__(self,
                 parent,
                 pv=None,
                 pushValue=1,
                 disablePV=None,
                 disableValue=1,
                 **kw):
        """
        pv = pv to write back to
        pushValue = value to write when button is pressed
        disablePV = read this PV in order to disable the button
        disableValue = disable the button if/when the disablePV has this value

        """
        wx.Button.__init__(self, parent, **kw)
        PVCtrlMixin.__init__(self, pv=pv, font="", fg=None, bg=None)
        self.pushValue = pushValue
        self.Bind(wx.EVT_BUTTON, self.OnPress)
        if isinstance(disablePV, (str, unicode)):
            disablePV = epics.get_pv(disablePV)
            disablePV.connect()
        self.disablePV = disablePV
        self.disableValue = disableValue
        if disablePV is not None:
            ncback = len(self.disablePV.callbacks) + 1
            self.disablePV.add_callback(self._disableEvent,
                                        wid=self.GetId(),
                                        cb_info=ncback)
        self.maskedEnabled = True
Esempio n. 12
0
 def __init__(self, pvname, value=1, **kws):
     Saveable.__init__(self, pvname, value=value, **kws)
     self.pv = get_pv(pvname)
     self._val = value
     self.done = False
     self._t0 = 0
     self.runtime = -1
Esempio n. 13
0
    def __init__(self, target=None):
        if target is not None:
            target = target.lower()

        instrument = target if target in INSTRUMENTS else None
        beamline = target if target in BEAMLINES else None

        if beamline is None:
            beamline = get_beamline(instrument)

        pvname = get_pvname_reprate(instrument, beamline)

        beamline = beamline.capitalize()
        self.name = f"{beamline} Rep. Rate"

        if pvname is None:
            self.name = self.value = self.units = None
            return

        self.pv = pv = epics.get_pv(pvname)
        self.value = pv.value
        self.units = pv.units

        def on_value_change(value=None, units=None, **kwargs):
            self.value = value
            self.units = units

        pv.add_callback(callback=on_value_change)
Esempio n. 14
0
    def __init__(self, prefix, outpvs=None, nmcas=4,
                 nrois=32, rois=None, nscas=1, use_unlabeled=False,
                 use_full=False, mode=None):

        # ROI #8 for DTFactor is a recent addition,
        # here we get ready to test if it is connected.
        self.sca8 = get_pv('%sC1SCA8:Value_RBV' % prefix)

        self.mode = mode
        self.nmcas, self.nrois = int(nmcas), int(nrois)
        self.nscas = int(nscas)
        self.use_full = use_full
        self.use_unlabeled = False
        DeviceCounter.__init__(self, prefix, rtype=None, outpvs=outpvs)

        prefix = self.prefix
        self._fields = []
        self.extra_pvs = []
        pvs = self._pvs = {}

        time.sleep(0.01)
        # use roilist to set ROI to those listed:
        if rois is None:
            rois = ['']
        self.rois = [r.strip() for r in rois]
Esempio n. 15
0
    def __init__(self, parent, label, pvname, id=wx.ID_ANY):
        super().__init__(wx.HORIZONTAL)

        if not label.endswith(":"):
            label += ":"

        self.st_label = st_label = wx.StaticText(parent, label=label)
        self.st_value = st_value = wx.StaticText(parent, label="")

        self.Add(st_label, 1, flag=wx.EXPAND)
        self.Add(st_value, 1, flag=wx.EXPAND)

        self.pv = self.value = self.units = None
        self.update(None)

        if pvname is None:
            return  # cannot create PV, thus stop early

        self.pv = pv = epics.get_pv(pvname)
        self.value = pv.value
        self.units = pv.units
        self.update(None)

        def on_value_change(value=None, units=None, **kwargs):
            self.value = value
            self.units = units
            wx.CallAfter(self.update, None)  # thread safe widget update

        pv.add_callback(callback=on_value_change)

        self.st_value.Bind(wx.EVT_WINDOW_DESTROY, self.on_destroy)
Esempio n. 16
0
    def __init__(self, master_pvname=None,  slave_pvname=None, scan=None,
                 values=None, maxpts=8192, wait_time=0.05, dead_time=1.1,
                 offset=3, ready_pv=None, ready_val=0):
        Thread.__init__(self)
        self.maxpts = maxpts
        self.offset = offset
        self.wait_time = wait_time
        self.dead_time = dead_time
        self.last_move_time = time.time() - 100.0
        self.last = -1
        self.pulse = -1
        self.scan = scan
        self.running = False
        self.vals = values
        self.ready_pv = None
        self.ready_val = ready_val
        # if ready_pv is None:
        #     ready_pv = 'ID13us:Busy.VAL'

        if self.vals is None:
            self.vals  = np.zeros(self.maxpts)
        self.master = None
        self.slave = None
        if master_pvname is not None:
            self.set_master(master_pvname)
        if slave_pvname is not None:
            self.set_slave(slave_pvname)
        if ready_pv is not None:
            self.ready_pv = get_pv(ready_pv)
Esempio n. 17
0
    def SetPV(self, pv=None):
        "set pv, either an epics.PV object or a pvname"
        if pv is None:
            return
        if isinstance(pv, epics.PV):
            self.pv = pv
        elif isinstance(pv, (str, unicode)):
            self.pv = epics.get_pv(pv)
            self.pv.connect()

        epics.poll()
        self.pv.connection_callbacks.append(self.OnEpicsConnect)

        self.pv.get_ctrlvars()

        self.OnPVChange(self.pv.get(as_string=True))
        ncback = len(self.pv.callbacks) + 1
        self.pv.add_callback(self._pvEvent, wid=self.GetId(), cb_info=ncback)

        self.Bind(wx.EVT_CHOICE, self._onChoice)
        
        pv_value = pv.get(as_string=True)
        enum_strings = pv.enum_strs
            
        self.Clear()
        self.AppendItems(enum_strings)
        self.SetStringSelection(pv_value)
Esempio n. 18
0
def test_force_connect():
    pv = get_pv(pvnames.double_arrays[0], auto_monitor=True)

    print("Connecting")
    assert pv.wait_for_connection(5.0)

    print("SUM", pv.get().sum())

    time.sleep(3)

    print("Disconnecting")
    pv.disconnect()
    print("Reconnecting")

    pv.force_connect()
    assert pv.wait_for_connection(5.0)

    called = {'called': False}

    def callback(value=None, **kwargs):
        called['called'] = True
        print("update", value.sum())

    pv.add_callback(callback)

    time.sleep(1)
    assert pv.get() is not None
    assert called['called']
Esempio n. 19
0
 def testEnumPut(self):
     pv = get_pv(pvnames.enum_pv)
     self.assertIsNot(pv, None)
     pv.put('Stop')
     time.sleep(0.1)
     val = pv.get()
     self.assertEqual(val, 0)
Esempio n. 20
0
def test_with_PV_and_getPV():
    # create 2 PV objects connecting to the same PV signal, one using PV class and the other one using get_pv()
    pv1 = PV(mypv, auto_monitor=True, callback=lambda **args:...)
    pv2 = get_pv(mypv)

    pv1.wait_for_connection()
    pv2.wait_for_connection()

    # check that both PVs are connected
    assert pv1.connected is True
    assert pv2.connected is True

    # check that data is received
    assert pv1.get() is not None
    assert pv2.get() is not None

    # disconnect 1 PV
    pv1.disconnect()

    time.sleep(1)

    # check that the first PV is disconnected and doesn't receive data
    assert pv1.connected is False
    assert pv1.get() is None

    # check that the other PV is connected and still receives data
    assert pv2.connected is True
    assert pv2.get() is not None
Esempio n. 21
0
    def SetPV(self, pv=None):
        "set pv, either an epics.PV object or a pvname"
        if isinstance(pv, epics.PV):
            self.pv = pv
        elif isinstance(pv, (str, unicode)):
            self.pv = epics.get_pv(pv)
        if self.pv is None:
            return
        self.pv.connection_callbacks.append(self.OnEpicsConnect)
        self.pv.get()
        self.pv.get_ctrlvars()
        # be sure to set precision before value!! or PV may be moved!!
        prec = self.pv.precision
        if prec is None:
            prec = 0
        self.SetPrecision(prec)

        self.SetValue(self.pv.char_value, act=False)

        if self.pv.type in ('string', 'char'):
            try:
                x = float(self.pv.value)
            except:
                self._warn('pvFloatCtrl needs a double or float PV')

        llim = set_float(self.pv.lower_ctrl_limit)
        hlim = set_float(self.pv.upper_ctrl_limit)
        if hlim is not None and llim is not None and hlim > llim:
            self.SetMax(hlim)
            self.SetMin(llim)
        ncback = len(self.pv.callbacks) + 1
        self.pv.add_callback(self._pvEvent, wid=self.GetId(), cb_info=ncback)
        self.SetAction(self._onEnter)
Esempio n. 22
0
 def __init__(self, pvname, value=1, **kws):
     Saveable.__init__(self, pvname, value=value, **kws)
     self.pv = get_pv(pvname)
     self._val = value
     self.done = False
     self._t0 = 0
     self.runtime = -1
Esempio n. 23
0
    def __init__(self, pvname, label=None, array=None, units=None,
                 extra_pvs=None, **kws):
        Saveable.__init__(self, pvname, label=label, units=units,
                          array=array, extra_pvs=extra_pvs, **kws)
        if isinstance(pvname, PV):
            self.pv = pvname
        else:
            self.pv = get_pv(pvname)
        self.pv.connect()
        self.done = False
        self.units = units
        if self.pv.connected:
            self.pv.get_ctrlvars()
            if units is None:
                self.units = self.pv.units

        self.label = label
        if label is None and self.pv.connected:
            desc = pvname
            if '.' in pvname:
                idot = pvname.index('.')
                descpv = pvname[:idot] + '.DESC'
            else:
                descpv = pvname + '.DESC'
            try:
                desc = caget(descpv)
            except:
                pass
            self.label = desc
        if array is None: array  = []
        self.array = array

        if extra_pvs is None: extra_pvs = {}
        self.extra_pvs = extra_pvs
Esempio n. 24
0
    def SetPV(self, pv=None):
        "set pv, either an epics.PV object or a pvname"
        if isinstance(pv, epics.PV):
            self.pv = pv
        elif isinstance(pv, (str, unicode)):
            self.pv = epics.get_pv(pv)
        if self.pv is None:
            return
        self.pv.connection_callbacks.append(self.OnEpicsConnect)
        self.pv.get()
        self.pv.get_ctrlvars()
        # be sure to set precision before value!! or PV may be moved!!
        prec = self.pv.precision
        if prec is None:
            prec = 0
        self.SetPrecision(prec)

        self.SetValue(self.pv.char_value, act=False)

        if self.pv.type in ('string', 'char'):
            try:
                x = float(self.pv.value)
            except:
                self._warn('pvFloatCtrl needs a double or float PV')

        llim = set_float(self.pv.lower_ctrl_limit)
        hlim = set_float(self.pv.upper_ctrl_limit)
        if hlim is not None and llim is not None and hlim > llim:
            self.SetMax(hlim)
            self.SetMin(llim)
        ncback = len(self.pv.callbacks) + 1
        self.pv.add_callback(self._pvEvent, wid=self.GetId(), cb_info=ncback)
        self.SetAction(self._onEnter)
Esempio n. 25
0
def test_multithreaded_put_complete(num_threads):
    def callback(pvname, data):
        result.append(data)

    def thread(thread_idx):
        pv.put(thread_idx,
               callback=callback,
               callback_data=dict(data=thread_idx),
               wait=True)
        time.sleep(0.1)

    result = []
    ca.use_initial_context()
    pv = get_pv(pvnames.double_pv)

    threads = [
        ca.CAThread(target=thread, args=(i, )) for i in range(num_threads)
    ]

    with no_simulator_updates():
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()

    assert len(result) == num_threads
    print(result)
    assert set(result) == set(range(num_threads))
Esempio n. 26
0
    def SetPV(self, pv=None):
        "set pv, either an epics.PV object or a pvname"
        if pv is None:
            return
        if isinstance(pv, epics.PV):
            self.pv = pv
        elif isinstance(pv, (str, unicode)):
            self.pv = epics.get_pv(pv)
            self.pv.connect()

        epics.poll()
        self.pv.connection_callbacks.append(self.OnEpicsConnect)

        self.pv.get_ctrlvars()

        self.OnPVChange(self.pv.get(as_string=True))
        ncback = len(self.pv.callbacks) + 1
        self.pv.add_callback(self._pvEvent, wid=self.GetId(), cb_info=ncback)

        self.Bind(wx.EVT_CHOICE, self._onChoice)

        pv_value = pv.get(as_string=True)
        enum_strings = pv.enum_strs

        self.Clear()
        self.AppendItems(enum_strings)
        self.SetStringSelection(pv_value)
Esempio n. 27
0
def test_get1():
    write('Simple Test: test value and char_value on an integer\n')
    with no_simulator_updates():
        pv = get_pv(pvnames.int_pv)
        val = pv.get()
        cval = pv.get(as_string=True)
        assert int(cval) == val
Esempio n. 28
0
def test_multithreaded_get(num_threads, thread_class):
    def thread(thread_idx):
        result[thread_idx] = (
            pv.get(),
            pv.get_with_metadata(form='ctrl')['value'],
            pv.get_with_metadata(form='time')['value'],
        )

    result = {}
    ca.use_initial_context()
    pv = get_pv(pvnames.double_pv)

    threads = [
        thread_class(target=thread, args=(i, )) for i in range(num_threads)
    ]

    with no_simulator_updates():
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()

    assert len(result) == num_threads
    print(result)
    values = set(result.values())
    assert len(values) != 0

    value, = values
    assert value is not None
Esempio n. 29
0
    def __init__(self,
                 prefix,
                 outpvs=None,
                 nmcas=4,
                 nrois=32,
                 rois=None,
                 nscas=1,
                 use_unlabeled=False,
                 use_full=False,
                 mode=None):

        # ROI #8 for DTFactor is a recent addition,
        # here we get ready to test if it is connected.
        self.sca8 = get_pv('%sC1SCA8:Value_RBV' % prefix)

        self.mode = mode
        self.nmcas, self.nrois = int(nmcas), int(nrois)
        self.nscas = int(nscas)
        self.use_full = use_full
        self.use_unlabeled = False
        DeviceCounter.__init__(self, prefix, rtype=None, outpvs=outpvs)

        prefix = self.prefix
        self._fields = []
        self.extra_pvs = []
        pvs = self._pvs = {}

        time.sleep(0.01)
        # use roilist to set ROI to those listed:
        if rois is None:
            rois = ['']
        self.rois = [r.strip() for r in rois]
Esempio n. 30
0
def test_CreatedWithConn():
    write('Simple Test: create pv with conn callback\n')
    pv = get_pv(pvnames.int_pv, connection_callback=onConnect)
    val = pv.get()

    global CONN_DAT
    conn = CONN_DAT.get(pvnames.int_pv, None)
    assert conn
Esempio n. 31
0
def test_put_string_waveform():
    write('String Array: put\n')
    with no_simulator_updates():
        pv = get_pv(pvnames.string_arr_pv)
        put_value = ['a', 'b', 'c']
        pv.put(put_value, wait=True)
        get_value = pv.get(use_monitor=False, as_numpy=False)
        numpy.testing.assert_array_equal(get_value, put_value)
Esempio n. 32
0
 def __init__(self, pvname, label=None, units=''):
     Saveable.__init__(self, pvname, label=label, units=units)
     self.pv = get_pv(pvname)
     if label is None:
         label = pvname
     self.label = label
     self.units = units
     self.clear()
    def __init__(self, pvname, ID=None, name=None, units=None, internal=False):
        self.pvname = pvname
        self.pv = pv = get_pv(pvname)

        ID = ID or pvname
        super().__init__(ID, name=name, units=units, internal=internal)

        self.states = Enum(pv.enum_strs)
Esempio n. 34
0
 def __init__(self, pvname, label=None, units=''):
     Saveable.__init__(self, pvname, label=label, units=units)
     self.pv = get_pv(pvname)
     if label is None:
         label = pvname
     self.label = label
     self.units = units
     self.clear()
Esempio n. 35
0
    def testA_CreatedWithConn(self):
        write('Simple Test: create pv with conn callback\n')
        pv = get_pv(pvnames.int_pv, connection_callback=onConnect)
        val = pv.get()

        global CONN_DAT
        conn = CONN_DAT.get(pvnames.int_pv, None)
        self.assertEqual(conn, True)
Esempio n. 36
0
def test_putwait():
    write('Put with wait (using real motor!) \n')
    pv = get_pv(pvnames.motor1)
    # this works with a real motor, fail if it doesn't connect quickly
    if not pv.wait_for_connection(timeout=0.2):
        return

    val = pv.get()

    t0 = time.time()
    if val < 5:
        pv.put(val + 1.0, wait=True)
    else:
        pv.put(val - 1.0, wait=True)
    dt = time.time() - t0
    write('    put took %s sec\n' % dt)
    assert dt > 0.1

    # now with a callback!
    global put_callback_called
    put_callback_called = False

    def onPutdone(pvname=None, **kws):
        print('put done ', pvname, kws)
        global put_callback_called
        put_callback_called = True

    val = pv.get()
    if val < 5:
        pv.put(val + 1.0, callback=onPutdone)
    else:
        pv.put(val - 1.0, callback=onPutdone)

    t0 = time.time()
    while time.time() - t0 < dt * 1.50:
        time.sleep(0.02)

    write('    put should be done by now?  %s \n' % put_callback_called)
    assert put_callback_called

    # now using pv.put_complete
    val = pv.get()
    if val < 5:
        pv.put(val + 1.0, use_complete=True)
    else:
        pv.put(val - 1.0, use_complete=True)
    t0 = time.time()
    count = 0
    while time.time() - t0 < dt * 1.50:
        if pv.put_complete:
            break
        count = count + 1
        time.sleep(0.02)
    write(
        '    put_complete=%s (should be True), and count=%i (should be>3)\n' %
        (pv.put_complete, count))
    assert pv.put_complete
    assert count > 3
Esempio n. 37
0
def test_put_string_waveform_zero_length_strings():
    write('String Array: put zero length strings\n')
    with no_simulator_updates():
        pv = get_pv(pvnames.string_arr_pv)
        put_value = ['', '', '']
        pv.put(put_value, wait=True)
        time.sleep(0.05)
        get_value = pv.get(use_monitor=False, as_numpy=False)
        numpy.testing.assert_array_equal(get_value, put_value)
Esempio n. 38
0
def test_put_string_waveform_empty_list():
    write('String Array: put empty list\n')
    with no_simulator_updates():
        pv = get_pv(pvnames.string_arr_pv)
        put_value = []
        pv.put(put_value, wait=True)
        time.sleep(0.05)
        get_value = pv.get(use_monitor=False, as_numpy=False)
        assert '' == ''.join(get_value)
Esempio n. 39
0
def test_put_string_waveform_mixed_types():
    write('String Array: put mixed types\n')
    with no_simulator_updates():
        pv = get_pv(pvnames.string_arr_pv)
        put_value = ['a', 2, 'b']
        pv.put(put_value, wait=True)
        time.sleep(0.05)
        get_value = pv.get(use_monitor=False, as_numpy=False)
        numpy.testing.assert_array_equal(get_value, ['a', '2', 'b'])
Esempio n. 40
0
    def addPV(self, name):
        if name is not None and name not in self.pvlist:
            basename = str(name)
            pv = get_pv(basename, callback=self.onPVChange)
            pv.get()
            self.pvs.append(pv)
            conn = False
            if pv is not None:
                if not pv.connected:
                    pv.wait_for_connection()
                conn = pv.connected

            msg = 'PV not found: %s' % name
            if conn:
                msg = 'PV found: %s' % name
            self.pvmsg.SetLabel(msg)
            if not conn:
                return
            self.pvlist.append(name)
            self.pvdata[name] = [(time.time(), pv.get())]
            if basename.endswith('.VAL'):
                basename = basename[:-4]
            descname = basename + '.DESC'
            descpv = get_pv(descname)
            desc =  descpv.get(timeout=1.0)
            if desc is None or len(desc) < 1:
                desc = basename

            self.pv_desc[basename] = desc
            
            i_new = len(self.pvdata)
            new_shown = False
            for ix, choice in enumerate(self.pvchoices):
                if choice is None:
                    continue
                cur = choice.GetSelection()
                choice.Clear()
                choice.SetItems(self.pvlist)
                choice.SetSelection(cur)
                if cur == 0 and not new_shown:
                    choice.SetSelection(i_new)
                    self.pvlabels[ix].SetValue(desc)
                    new_shown = True
            self.needs_refresh = True
Esempio n. 41
0
    def __init__(self, prefix, data_pv=None, nrois=None, roi_prefix=None):

        self._prefix = prefix
        Device.__init__(self, self._prefix, delim='',
                              attrs=self._attrs, with_poll=False)
        if data_pv is not None:
            self._pvs['VAL'] = PV(data_pv)
        self._npts = None
        self._nrois = nrois
        if self._nrois is None:
            self._nrois = MAX_ROIS

        self._roi_prefix = roi_prefix
        for i in range(self._nrois):
            p = get_pv('%s:%i:Name' % (self._roi_prefix, i+1))
            p = get_pv('%s:%i:MinX' % (self._roi_prefix, i+1))
            p = get_pv('%s:%i:SizeX' % (self._roi_prefix, i+1))
        self.get_rois()
        poll()
Esempio n. 42
0
 def _pv_check(self, val):
     """ check if pv string of val is alive
     """
     if val == '':
         return False
     pv = epics.get_pv(val, connect=True, timeout=0.5)
     if pv.connected:
         return True
     else:
         return False
Esempio n. 43
0
    def init_connect(self, pvname, is_motor=False):
        """try to connect epics PV, executing
        action(wid=wid, pvname=pvname, pv=pv)
        """
        if pvname is None or len(pvname) < 1:
            return
        if '.' not in pvname:
            pvname = '%s.VAL' % pvname
        pvname = str(pvname)

        if pvname in self.pvs:
            return
        self.pvs[pvname] = epics.get_pv(pvname)
        self.in_progress[pvname] = (None, None, time.time())
        if is_motor:
            idot = pvname.find('.')
            basname = pvname[:idot]
            for ext in MOTOR_FIELDS:
                pvname = "%s%s" % (basname, ext)
                self.pvs[pvname] = epics.get_pv(pvname)
                self.in_progress[pvname] = (None, None, time.time())
Esempio n. 44
0
    def add_extra_pvs(self, extra_pvs):
        """add extra pvs (tuple of (desc, pvname))"""
        if extra_pvs is None or len(extra_pvs) == 0:
            return
        for desc, pvname in extra_pvs:
            if isinstance(pvname, PV):
                pv = pvname
            else:
                pv = get_pv(pvname)

            if (desc, pv) not in self.extra_pvs:
                self.extra_pvs.append((desc, pv))
Esempio n. 45
0
 def __init__(self, prefix, nrois=32, rois=None,
              use_net=False, use_full=False, **kws):
     nrois = int(nrois)
     DetectorMixin.__init__(self, prefix, **kws)
     self.mca = MCA(prefix)
     self.dwelltime_pv = get_pv('%s.PRTM' % prefix)
     self.dwelltime = None
     self.trigger = Trigger("%sEraseStart" % prefix)
     self._counter = McaCounter(prefix, nrois=nrois, rois=rois,
                                use_full=use_full, use_net=use_net)
     self.counters = self._counter.counters
     self._repr_extra = self.repr_fmt % (nrois, repr(use_net), repr(use_full))
Esempio n. 46
0
 def qxafs_connect_counters(self):
     self.counters = []
     time.sleep(0.1)
     pvs = []
     for c in self.scandb.get_scandata():
         pv = get_pv(c.pvname)
         pvs.append((c.name, pv))
     time.sleep(0.1)
     for cname, pv in pvs:
         pv.connect()
         self.counters.append((cname, pv))
     if self.verbose:
         self.write("QXAFS_connect_counters %i counters" % (len(self.counters)))
Esempio n. 47
0
    def __init__(self, prefix, nchan=8, use_calc=True, mode="scaler", rois=None, **kws):
        DetectorMixin.__init__(self, prefix, **kws)
        nchan = int(nchan)
        self.scaler = Scaler(prefix, nchan=nchan)
        self._counter = ScalerCounter(prefix, nchan=nchan, use_calc=use_calc)
        self.dwelltime_pv = get_pv("%s.TP" % prefix)
        self.dwelltime = None
        self.mode = mode
        self.counters = self._counter.counters
        self.extra_pvs = [("Scaler.frequency", "%s.FREQ" % prefix), ("Scaler.read_delay", "%s.DLY" % prefix)]
        self._repr_extra = ", nchans=%i, use_calc=%s" % (nchan, repr(use_calc))

        self.extra_pvs.extend(self._counter.extra_pvs)
Esempio n. 48
0
    def __init__(self, parent, prefix, pvdata, **kws):
        wx.Panel.__init__(self, parent, -1,  **kws)
        self.sizer = sizer = wx.GridBagSizer(3, 3)
        self.wids = {}
        self.prefix = prefix
        irow = -1
        for label, pvname, use_prefix, dtype, rsuff, wsize, fontsize in pvdata:
            if use_prefix:
                pvname = prefix + pvname
            get_pv(pvname)
        poll(0.02)

        for label, pvname, use_prefix, dtype, rsuff, wsize, fontsize in pvdata:
            label = '  %s' % label
            if use_prefix:
                pvname = prefix + pvname
            ctrl  = pv_control(dtype)
            opts = dict(pv=get_pv(pvname), size=(wsize, -1))

            self.wids[label] = ctrl(self, **opts)
            self.wids[label].SetFont(Font(fontsize))

            title = wx.StaticText(self, label=label, size=(8*len(label), -1),
                                  style=labstyle)
            title.SetFont(Font(fontsize))
            irow += 1
            sizer.Add(title, (irow, 0), (1, 1), labstyle)

            if rsuff:
                rlabel = label + rsuff
                rname = pvname + rsuff
                self.wids[rlabel] = PVStaticText(self, pv=get_pv(rname),
                                                 size=(wsize, -1))
                self.wids[rlabel].SetFont(Font(fontsize))
                sizer.Add(self.wids[label], (irow, 1), (1, 1), labstyle)
                sizer.Add(self.wids[rlabel], (irow, 2), (1, 1), labstyle)
            else:
                sizer.Add(self.wids[label], (irow, 1), (1, 2), labstyle)
        pack(self, sizer)
Esempio n. 49
0
    def restore_position(self, instname, posname, wait=False, timeout=5.0,
                         exclude_pvs=None):
        """
        restore named position for instrument
        """
        inst = self.get_instrument(instname)
        if inst is None:
            raise ScanDBException('restore_postion needs valid instrument')

        posname = posname.strip()
        pos  = self.get_position(inst, posname)

        if pos is None:
            raise ScanDBException(
                "restore_postion  position '%s' not found" % posname)

        if exclude_pvs is None:
            exclude_pvs = []

        pv_vals = []
        ppos_cls, ppos_tab = self.scandb.get_table('position_pv')
        pv_cls, pv_tab     = self.scandb.get_table('pv')
        pvnames = dict([(pv.id, str(pv.name)) for pv in pv_tab.select().execute().fetchall()])

        pv_vals = []
        for pvval in ppos_tab.select().where(ppos_tab.c.position_id == pos.id).execute().fetchall():
            pvname = pvnames[pvval.pv_id]
            if pvname not in exclude_pvs:
                val = pvval.value
                try:
                    val = float(pvval.value)
                except ValueError:
                    pass
                pv_vals.append((epics.get_pv(pvname), val))

        epics.ca.poll()
        # put values without waiting
        for thispv, val in pv_vals:
            if not thispv.connected:
                thispv.wait_for_connection(timeout=timeout)
            try:
                thispv.put(val)
            except:
                pass

        if wait:
            for thispv, val in pv_vals:
                try:
                    thispv.put(val, wait=True)
                except:
                    pass
Esempio n. 50
0
 def connect_pv(self, pvname, wid=None, action=None):
     """try to connect epics PV, executing
     action(wid=wid, pvname=pvname, pv=pv)
     """
     if pvname is None or len(pvname) < 1:
         return
     if '.' not in pvname:
         pvname = '%s.VAL' % pvname
     pvname = str(pvname)
     if pvname in self.pvs:
         return
     if pvname not in self.in_progress:
         self.pvs[pvname] = epics.get_pv(pvname)
         self.in_progress[pvname] = (wid, action, time.time())
Esempio n. 51
0
    def __init__(self, prefix, nchan=8, use_calc=True, **kws):
        DetectorMixin.__init__(self, prefix, **kws)
        nchan = int(nchan)
        self.scaler = Scaler(prefix, nchan=nchan)
        self._counter = ScalerCounter(prefix, nchan=nchan,
                                      use_calc=use_calc)
        self.dwelltime_pv = get_pv('%s.TP' % prefix)
        self.dwelltime = None
        self.counters = self._counter.counters
        self.extra_pvs = [('Scaler.frequency', '%s.FREQ' % prefix),
                          ('Scaler.read_delay', '%s.DLY' % prefix)]
        self._repr_extra = ', nchans=%i, use_calc=%s' % (nchan,
                                                         repr(use_calc))

        self.extra_pvs.extend(self._counter.extra_pvs)
Esempio n. 52
0
    def get_ordered_position(self, posname, inst, exclude_pvs=None):
        """
        returns ordered list of PVname, positions for restore position
        """
        inst = self.get_instrument(inst)
        if inst is None:
            raise InstrumentDBException(
                'restore_postion needs valid instrument')

        posname = posname.strip()
        pos  = self.get_position(posname, inst)
        if pos is None:
            raise InstrumentDBException(
                "restore_postion  position '%s' not found" % posname)

        if exclude_pvs is None:
            exclude_pvs = []

        pv_values = {}
        for pvpos in pos.pvs:
            pvname = pvpos.pv.name
            if pvname not in exclude_pvs:
                pv_values[pvname] = pvpos.value

        # ordered_pvs will hold ordered list of pv, vals in "move order"
        IPV = Instrument_PV
        instpvs =  self.query(IPV).filter(IPV.instrument_id==inst.id).all()
        max_order = 1
        for i in instpvs:
            move_order = getattr(i, 'move_order', 1)
            if move_order is None:
                move_order = 1
            if move_order > max_order:
                max_order = move_order

        ordered_pvs = [[] for i  in range(1+max_order)]
        # print(" Get Ordered position: ")
        for ipv in instpvs:
            move_order = getattr(ipv, 'move_order', 1)
            if move_order is None:
                move_order = 1
            i = move_order - 1
            pvname = ipv.pv.name
            # print(" -- ", i, pvname, epics.get_pv(pvname), pv_values[pvname])
            if pvname in pv_values:
                ordered_pvs[i].append((epics.get_pv(pvname), pv_values[pvname]))

        return  ordered_pvs
Esempio n. 53
0
 def __init__(self, prefix, file_plugin=None, fileroot='', **kws):
     if not prefix.endswith(':'):
         prefix = "%s:" % prefix
     self.fileroot = fileroot
     DetectorMixin.__init__(self, prefix, **kws)
     self.dwelltime_pv = get_pv('%scam1:AcquireTime' % prefix)
     self.dwelltime = None
     self.file_plugin = None
     self.counters = [Counter("%scam1:ArrayCounter_RBV" % prefix,
                              label='Image Counter')]
     if file_plugin in AD_FILE_PLUGINS:
         self.file_plugin = file_plugin
         f_counter = Counter("%s%s:FileNumber_RBV" % (prefix, file_plugin),
                             label='File Counter')
         self.counters.append(f_counter)
     self._repr_extra = ', file_plugin=%s' % repr(file_plugin)
Esempio n. 54
0
    def __connect(self, pvname):
        """if a new epics PV has connected, run the requested action"""

        if pvname not in self.pvs:
            self.pvs[pvname] = epics.get_pv(pvname, form='native')
        pv = self.pvs[pvname]
        if not self.pvs[pvname].connected:
            return

        try:
            wid, action, itime = self.in_progress.pop(pvname)
        except KeyError:
            wid, action, itime = None, None, 0
        pv.get_ctrlvars()

        if hasattr(action, '__call__'):
            action(wid=wid, pvname=pvname, pv=self.pvs[pvname])
Esempio n. 55
0
    def __init__(self, prefix, nchan=4,
                 mode='scaler', rois=None, sis_prefix=None, **kws):

        DetectorMixin.__init__(self, prefix, **kws)
        nchan = int(nchan)
        self.tetramm  = TetrAMM(prefix, sis_prefix=sis_prefix)
        self._counter = TetrAMMCounter(prefix, nchan=nchan)
        self.dwelltime_pv = get_pv('%sAveragingTime' % prefix)
        self.dwelltime = None
        self.mode = mode
        self.counters = self._counter.counters

        extra_pvs = [('TetrAMM.Range', '%sRange_RBV' % (prefix)),
                     ('TetrAMM.SampleTime', '%sSampleTime_RBV' % (prefix)),
                     ('TetrAMM.ValuesPerRead', '%sValuesPerRead_RBV' % (prefix)),
                     ('TetrAMM.NumAverage', '%sNumAverage_RBV' % (prefix))]

        self.extra_pvs.extend(self._counter.extra_pvs)
Esempio n. 56
0
 def __init__(self, prefix, label=None, nmcas=4, nrois=32, rois=None,
              search_all=False, use_net=False,
              use_unlabeled=False, use_full=False, **kws):
     DetectorMixin.__init__(self, prefix, label=label)
     nmcas, nrois = int(nmcas), int(nrois)
     if not prefix.endswith(':'):
         prefix = "%s:" % prefix
     self.prefix = prefix
     self.dwelltime_pv = get_pv('%sPresetReal' % prefix)
     self.trigger = Trigger("%sEraseStart" % prefix)
     self.dwelltime = None
     self.extra_pvs = None
     self._counter = None
     self._connect_args = dict(nmcas=nmcas, nrois=nrois, rois=rois,
                               search_all=search_all, use_net=use_net,
                               use_unlabeled=use_unlabeled,
                               use_full=use_full)
     self._repr_extra = self.repr_fmt % (nmcas, nrois,
                                         repr(use_net), repr(use_full))
Esempio n. 57
0
    def init_connect(self, pvname, is_motor=False):
        """try to connect epics PV, executing
        action(wid=wid, pvname=pvname, pv=pv)
        """
        if pvname is None or len(pvname) < 1:
            return
        if '.' not in pvname:
            pvname = '%s.VAL' % pvname
        pvname = str(pvname)

        if pvname in self.pvs:
            return
        self.pvs[pvname] = epics.get_pv(pvname, form='native')
        self.in_progress[pvname] = (None, None, time.time())
        # print(" init_connect ", pvname, self.pvs[pvname])
        if is_motor:
            idot = pvname.find('.')
            basname = pvname[:idot]
            x = Motor(basname)
Esempio n. 58
0
    def __connect(self, pvname):
        """if a new epics PV has connected, run the requested action"""
        # print ' __connect!! ', pvname
        if pvname not in self.pvs:
            self.pvs[pvname] = epics.get_pv(pvname)
        pv = self.pvs[pvname]
        time.sleep(0.001)

        if not self.pvs[pvname].connected:
            return

        try:
            wid, action, itime = self.in_progress.pop(pvname)
        except KeyError:
            wid, action, itime = None, None, 0
        pv.get_ctrlvars()
        # print 'PV connected: ', pv
        if hasattr(action, '__call__'):
            action(wid=wid, pvname=pvname, pv=self.pvs[pvname])
Esempio n. 59
0
    def add_pv(self, name, notes=None, attributes=None, pvtype=None, **kws):
        """add pv
        notes and attributes optional
        returns PV instance"""
        name = normalize_pvname(name)
        out =  self.query(PV).filter(PV.name==name).all()
        if len(out) > 0:
            return

        kws['notes'] = notes
        kws['attributes'] = attributes
        row = self.__addRow(PV, ('name',), (name,), **kws)
        if pvtype is None:
            self.pvs[name] = epics.get_pv(name, form='native')
            self.pvs[name].get()
            pvtype = get_pvtypes(self.pvs[name])[0]
        self.set_pvtype(name, pvtype)
        self.session.add(row)
        self.commit()
        return row