Esempio n. 1
0
 def __init__(self, pvs, timeout=30.0, skip_first=True):
     self.pvnames = pvs
     self.values = dict()
     self.timeout = timeout
     self.first = [skip_first] * len(pvs)
     self.pvs = [
         epics.PV(pv, callback=self.channel_changed, auto_monitor=True)
         for pv in pvs
     ]
Esempio n. 2
0
def check_pv_online(pvname, timeout=1.0, use_prefix=True):
    """Return whether a PV is online."""
    if use_prefix:
        pvname = _envars.VACA_PREFIX + pvname
    pvobj = _epics.PV(pvname=pvname, connection_timeout=timeout)
    status = pvobj.wait_for_connection(timeout=timeout)
    # invoke pv disconnect and explicitly signal to GC that PV object may be collected.
    del pvobj
    return status
Esempio n. 3
0
    def __init__(self, daq_host, daq_platform, laser_delay_pv_name,
                 tt_stage_position_pv_name, t0_pv_name, laser_lock_pv_name):
        """
        Create a Timescaner instance, providing control over the timetool
        and laser delay stages.

        Parameters
        ----------
        daq_host : str
        daq_platform : int
        laser_delay_pv_name : str
        tt_stage_position_pv_name : str
        t0_pv_name : str
        laser_lock_pv_name : str

        See Also
        --------
        Timescaner.from_rc() : function
            Create a timescaner instance from a file.
        """

        self._daq_host = daq_host
        self._daq_platform = daq_platform
        self.daq = pydaq.Control(daq_host, daq_platform)

        self._laser_delay = epics.PV(laser_delay_pv_name)
        self._tt_stage_position = epics.PV(tt_stage_position_pv_name)
        self._t0 = epics.PV(t0_pv_name)
        self._laser_lock = epics.PV(laser_lock_pv_name)

        self.tt_travel_offset = 0.0
        self.tt_fit_coeff = np.array([0.0, 1.0, 0.0])
        self.calibrated = False

        time.sleep(0.1)  # time for PVs to connect
        for pv in [
                self._laser_delay, self._tt_stage_position, self._t0,
                self._laser_lock
        ]:
            if not pv.connected:
                raise RuntimeError('Cannot connect to PV: %s' % pv.pvname)

        return
Esempio n. 4
0
    def __init__(self, parent=None, args=None):
        super(BetaScan, self).__init__(parent=parent, args=args)
        self.ui.imageView.mousePressEvent = self.get_coord
        self.ui.imageView.process_image = self.process_image

        self.motorRead = self.ui.EmbeddedMotor.findChild(
            PyDMLabel, "motorPosRead")
        self.motorSet = self.ui.EmbeddedMotor.findChild(
            PyDMLineEdit, "motorPosSet")

        self.motorGo = self.ui.EmbeddedMotor.findChild(QPushButton,
                                                       "motorMove")
        self.motorGo.mousePressEvent = self.move_motor

        self.imageXSize = epics.PV('PelmeniNDSA:cam1:ArraySize0_RBV')
        self.imageYSize = epics.PV('PelmeniNDSA:cam1:ArraySize1_RBV')
        self.binYSize = epics.PV('PelmeniDet:ROI1:BinY_RBV')
        self.zoomedSize = 1
        self.imageHeight = 672.0
Esempio n. 5
0
 def connectPv(self, pvname):
     if pvname is None:
         raise RuntimeError("pvname must not be 'None'")
         if len(pvname) == 0:
             raise RuntimeError("pvname must not be ''")
     self.pv = epics.PV(self.pvName)
     self.startval = self.pv.get()
     self.pv.add_callback(self.onChangePv)
     self.myFig.addData(self.startval)
     QCoreApplication.processEvents()
def emitter():
    'return a random value with probability p, else 0'
    dxpMca1PV = epics.PV('BL7D:dxpXMAP:mca1')
    dxpAcqPV = epics.PV('BL7D:dxpXMAP:Acquiring')
    mcas = 0.0
    oldAcqStatus = 1
    nowAcqStatus = 0

    while True:
        nowAcqStatus = dxpAcqPV.get()

        if nowAcqStatus is 1 and oldAcqStatus is 0:
            mcas = sum(dxpMca1PV.get())
            oldAcqStatus = nowAcqStatus
            yield mcas

        else:
            oldAcqStatus = nowAcqStatus
            yield mcas
Esempio n. 7
0
    def __init__(self, busy_pv_name, motor_pv_name, calc_pv_name):
        self.busy = epics.PV(busy_pv_name)

        # motor: the independent variable
        self.motor = epics.Motor(motor_pv_name)

        # calc: the detector signal
        self.calc = epics.PV(calc_pv_name)
        self.calc_proc = epics.PV(calc_pv_name + ".PROC")
        epics.caput(calc_pv_name + ".CALC", "RNDM")  # report random numbers
        self.calc_proc.put(1)  # get a new value

        self.cb_index = None
        self.processing = False

        # arbitrary choices for a demo program
        self.num_steps = 5
        self.step_size = 2.1
        self.origin = 0
Esempio n. 8
0
    def pre_change(self):
        puck_check = False
        fill_check = False
        fill_level = epics.PV('XF:17IDB-ES:AMX{CS8}Ln2Level-I').get()
        user_name = getpass.getuser()
        # Input file name to CSS
        epics.PV('XF:17IDB-ES:AMX{Cam:14}JPEG1:FileName').put(user_name)

        plates = (plate_check(1, 180), plate_check(2, 135), plate_check(3, 90),
                  plate_check(4, 45), plate_check(5, 0), plate_check(6, 315),
                  plate_check(7, 270), plate_check(8, 225))
        holder = 0
        ##### Comment/Uncomment below to set directory by user and not date #####
        for plate in plates:
            if (epics.PV('XF:17IDB-ES:AMX{Dew:1-Ax:R}Mtr.VAL').get() +
                    135) == plate.degree or (
                        epics.PV('XF:17IDB-ES:AMX{Dew:1-Ax:R}Mtr.VAL').get() -
                        225) == plate.degree:
                holder = plate.plate
        if epics.PV('XF:17IDB-ES:AMX{Wago:1}Puck' + str(holder) +
                    'C-Sts').get() != 1:
            print('There is no puck on position: {}. No image taken'.format(
                holder))
        else:
            puck_check = True

        epics.PV('XF:17IDB-ES:AMX{Cam:14}JPEG1:FilePath').put(image_path)

        if fill_level >= 85:
            fill_check = True
        else:
            print('Fill Violation, Fill Level Is: ' + str('%.2f' % fill_level))
            print('Please Fill Dewar to Continue')

        if puck_check and fill_check:
            # A one minute buffer to allow the dewar to rotate
            time.sleep(60)
            print('Images are in: {}'.format(image_path))
            epics.PV('XF:17IDB-ES:AMX{Cam:14}Proc1:EnableFilter').put(1)
            for i in range(1, 4):
                print('Taking image: ' + str(i) + ' of 3')
                # Change the settings to take the picture and capture the image
                acq.put(0)
                img_mode.put(0)
                data_type.put(0)
                time.sleep(2)
                acq.put(1)
                time.sleep(2)
                save_file.put(1)

                # Put the camera back to the original settings
                time.sleep(2)
                img_mode.put(2)
                data_type.put(1)
                acq.put(1)

                time.sleep(15)
        self.post_change()
Esempio n. 9
0
    def __init__(self,
                 pv,
                 scaler_pv=None,
                 moving_pv=None,
                 moving_val=0,
                 precision=3,
                 limit_hi=9,
                 *args,
                 **kwargs):

        super().__init__(*args, **kwargs)

        if scaler_pv:
            self.count_mode = epics.PV(scaler_pv + '.CONT')
            self.count_time = epics.PV(scaler_pv + '.TP')
            self.auto_count_time = epics.PV(scaler_pv + '.TP1')

        self.setMinimumSize(qt.QSize(120, 30))
        self.setMaximumSize(qt.QSize(120, 30))

        self.precision = precision
        self.setFrameShape(qt.QFrame.Panel)
        self.setFrameShadow(qt.QFrame.Sunken)
        self.setAlignment(qt.Qt.AlignCenter)
        self.setText("not connected")

        self.formatStr = "{:." + str(self.precision) + "f}"

        self.moving_val = moving_val

        self.pv = epics.PV(pv, auto_monitor=True)
        self.pv.add_callback(self.update_value)

        if moving_pv is not None:
            self.moving_pv = epics.PV(moving_pv, auto_monitor=True)
            self.moving_pv.add_callback(self.update_color)

        self.limit_hi = limit_hi
        self._dummyIndex = 0

        self.notifyTimer = qt.QTimer()
        self.notifyTimer.timeout.connect(self._notifyColor)
        self.notifyTimer.start(1000)
Esempio n. 10
0
 def __init__(self):
     """ Initialize parameters for the scanner class. """
     self.secs_to_ave = 2  #time to integrate gas detector
     self.getter = EpicsGet()  #getter class for channel access
     self.caput = epics.caput
     self.state = lambda text: epics.PV(str(text), connection_timeout=0.1
                                        ).get()
     self.inputNormParams = None  #normalization parameters
     self.norm_params_bool = False  #normalization parameters
     self.taperParams = None
Esempio n. 11
0
 def connect(self):
     # Set is_ready to True when there is new data using a callback
     print('Connecting ' + self.dev_type)
     if(self._callback_pvname):
         print('Connecting ' + self._callback_pvname)
         pv = epics.PV(self._callback_pvname,
                       auto_monitor=True,
                       callback=lambda pvname=None, value=None, timestamp=None, **fw: self.set_ready(pvname, value, timestamp))
         self.connected_pvs.append(pv)
     return(self)
Esempio n. 12
0
def monChan(chanNames):
    chanList = []
    cnameList = []
    for cn in chanNames:
        chan = epics.PV(cn)
        chanStatus = chan.status
        if not (chanStatus == None):
            cnameList.append(cn)
            chanList.append(chan)
    return chanList, cnameList
class Test(unittest.TestCase):
    lib = motor_lib()
    motor = os.getenv("TESTEDMOTORAXIS")
    pv_Err = epics.PV(os.getenv("TESTEDMOTORAXIS") + "-Err")
    pv_nErrorId = epics.PV(os.getenv("TESTEDMOTORAXIS") + "-ErrId")
    pv_nErrRst = epics.PV(os.getenv("TESTEDMOTORAXIS") + "-ErrRst")
    saved_CNEN = epics.caget(motor + '.CNEN')

    # Jog, wait for start, power off, check error, reset error
    def test_TC_212(self):
        motor = self.motor
        tc_no = "TC-212-EnabledFailed"
        setValueOnSimulator(self, motor, tc_no, "bAmplifierLockedToBeOff",
                            AMPLIFIER_LOCKED_TO_BE_OFF_SILENT)

        epics.caput(motor + '.CNEN', 1, wait=True)

        mstaErr = int(epics.caget(motor + '.MSTA', use_monitor=False))
        print '%s Error mstaErr=%s' % (tc_no, self.lib.getMSTAtext(mstaErr))
        self.pv_nErrRst.put(1, wait=True)

        setValueOnSimulator(self, motor, tc_no, "bAmplifierLockedToBeOff", 0)

        mstaOKagain = int(epics.caget(motor + '.MSTA', use_monitor=False))
        bError = self.pv_Err.get(use_monitor=False)
        nErrorId = self.pv_nErrorId.get(use_monitor=False)
        print '%s Clean self.lib.MSTA_BIT_PROBLEM=%x mstaOKagain=%s bError=%d nErrorId=%d' % (
            tc_no, self.lib.MSTA_BIT_PROBLEM,
            self.lib.getMSTAtext(mstaOKagain), bError, nErrorId)

        epics.caput(motor + '.CNEN', self.saved_CNEN)

        self.assertNotEqual(0, mstaErr & self.lib.MSTA_BIT_PROBLEM,
                            'Error MSTA.Problem should be set)')
        self.assertEqual(0, mstaErr & self.lib.MSTA_BIT_SLIP_STALL,
                         'Error MSTA.Slip stall Error should not be set)')
        self.assertEqual(0, mstaErr & self.lib.MSTA_BIT_MOVING,
                         'Error MSTA.Moving)')

        self.assertEqual(0, mstaOKagain & self.lib.MSTA_BIT_MOVING,
                         'Clean MSTA.Moving)')
        self.assertEqual(0, bError, 'bError')
        self.assertEqual(0, nErrorId, 'nErrorId')
Esempio n. 14
0
 def build_getter_setter(self, beam_line, device, config, rbv):
     for key, value in config.items():
         if (rbv):
             setattr(
                 self, '_{0}_rbv'.format(key),
                 epics.PV(
                     self.get_device_command_str(
                         beam_line, device, '{0}{1}'.format(value,
                                                            '_RBV'))))
         setattr(
             self, '_{0}'.format(key),
             epics.PV(self.get_device_command_str(beam_line, device,
                                                  value)))
         setattr(
             self, 'get_{0}'.format(key),
             getattr(self, '_{0}{1}'.format(key,
                                            '_rbv' if rbv else '')).get)
         setattr(self, 'set_{0}'.format(key),
                 getattr(self, '_{0}'.format(key)).put)
Esempio n. 15
0
 def connect_pv(self, pvname, wid=None):
     """try to connect newly added epics PVs"""
     if pvname is None or len(pvname) < 1:
         return
     if pvname not in self.connecting_pvs:
         if pvname not in self.epics_pvs:
             self.epics_pvs[pvname] = epics.PV(pvname)
         self.connecting_pvs[pvname] = (wid, time.time())
         if not self.etimer.IsRunning():
             self.etimer.Start(150)
def fautomated_repeated_scan_busy(trigger_busy='7bmb1:busy4',
                                  action_name='7bmb1:busy5',
                                  action_value='Busy',
                                  shutter='A'):
    '''Performs a repeated scan.
    '''
    repeated_scan_busy_PV = epics.PV(trigger_busy)
    counter = 0
    try:
        while True:
            if repeated_scan_busy_PV.value == 1:
                num_repeats = int(epics.caget('7bmb1:var:int1'))
                sec_between_pts = float(epics.caget('7bmb1:var:float6'))
                for i in range(num_repeats):
                    if repeated_scan_busy_PV.value == 0:
                        break
                    print("In the repeat loop on scan #{:3d}".format(i))
                    #Monitor for good beam
                    while epics.caget(
                            "S:SRcurrentAI.VAL") < 30.0 or epics.caget(
                                'PA:07BM:STA_A_BEAMREADY_PL.VAL') < 0.5:
                        print("Waiting for beam to come back at time " +
                              time.strftime('%H:%M:%S', time.localtime()))
                        time.sleep(5.0)
                    if shutter == 'A':
                        fopen_A_shutter()
                    else:
                        fopen_shutters()
                    #Start the scan
                    epics.caput(action_name, action_value)
                    time.sleep(1.0)
                    for t in range(int(sec_between_pts), 0, -1):
                        #Check to make sure we haven't clicked "Done" on repeated_scan_busy to abort this.
                        print(
                            "Waiting for the next scan, {0:d} s left.".format(
                                t))
                        if repeated_scan_busy_PV.value == 0:
                            print("Scan aborted!")
                            break
                        time.sleep(1.0)
                repeated_scan_busy_PV.value = 0
                time.sleep(0.5)
            if counter == 100:
                print("Looking for repeated scan busy at time " +
                      time.strftime('%H:%M:%S', time.localtime()))
                counter = 0
            else:
                counter += 1
            time.sleep(0.01)
    finally:
        print("Problem in repeated scan loop.")
        if shutter == 'A':
            fclose_A_shutter()
        else:
            fclose_B_shutter()
Esempio n. 17
0
    def caget(self, update: Update, cont: CallbackContext) -> None:
        answer = ""

        for PV in cont.args:
            pv = epics.PV(PV, connection_timeout=0.2)
            if pv.value is not None and pv.units is not None:
                answer += "\n{}: {} {}".format(PV, pv.value, pv.units)
            else:
                answer += "\n{} is not available".format(PV)

        update.message.reply_text(answer)
Esempio n. 18
0
 def testLogDeadband(self):
     '''DBE_LOG monitor on an ai with an ADEL - leaving the deadband generates events.'''
     # gateway:passiveADEL has ADEL=10
     ioc = epics.PV("ioc:passiveADEL", auto_monitor=epics.dbr.DBE_LOG)
     gw = epics.PV("gateway:passiveADEL", auto_monitor=epics.dbr.DBE_LOG)
     gw.add_callback(self.onChange)
     ioc.get()
     gw.get()
     for val in range(35):
         ioc.put(val, wait=True)
     time.sleep(.1)
     # We get 5 events: at connection, first put, then at 11 22 33
     self.assertTrue(
         self.eventsReceived == 5,
         'events expected: 5; events received: ' + str(self.eventsReceived))
     # Any updates inside deadband are an error
     self.assertTrue(
         self.diffInsideDeadband == 0,
         str(self.diffInsideDeadband) +
         ' events with change <= deadband received')
Esempio n. 19
0
def benchmark_psconnsofb_kick_setpoint_delay(delay_before, delay_after):
    """."""
    trigger = _epics.PV('AS-RaMO:TI-EVG:OrbSIExtTrig-Cmd')
    trigger.wait_for_connection()

    pssofb = PSConnSOFB(EthBridgeClient)
    pssofb.bsmp_slowrefsync()

    exectimes = [0] * 150

    pssofb.bsmp_update_sofb()
    kick_refmon = pssofb.sofb_kick_refmon

    for i, _ in enumerate(exectimes):

        # calc new kick
        kick_sp = kick_refmon + 1 * 0.01 * _np.random.randn(len(kick_refmon))

        # start clock
        time0 = _time.time()

        # set kick values
        curr_sp = pssofb.bsmp_sofb_kick_set(kick_sp)

        # sleep for a while
        _time.sleep(delay_before)

        # send trigger
        trigger.value = 1

        # stop clock
        time1 = _time.time()
        exectimes[i] = 1000 * (time1 - time0)

        # make sure trigger signal gets to power supplies.
        _time.sleep(delay_after)

        # read from power supplies
        pssofb.bsmp_update_sofb()
        curr_rb = pssofb.sofb_current_refmon

        # comparison
        issame = pssofb.sofb_vector_issame(curr_sp, curr_rb)

        if not issame:
            print('SP<>RB in event {}'.format(i))

    # restore state
    pssofb.bsmp_sofb_kick_set(kick_refmon)

    for exectime in exectimes:
        print(exectime)

    pssofb.threads_shutdown()
Esempio n. 20
0
    def connect(self, pvname):
        if pvname is None:
            raise RuntimeError("pvname must not be 'None'")

        if len(pvname) == 0:
            raise RuntimeError("pvname must not be ''")

        self.axisDiagPvName = pvname
        self.axisDiagPv = epics.PV(self.axisDiagPvName)
        self.axisDiagPv.add_callback(self.onChangeAxisDiagPv)
        self.trend.setTitle(self.axisDiagPvName)
Esempio n. 21
0
    def reconnect(self):
        # Clear Epics cache
        epics.ca._cache.clear()
        #epics.ca._put_done.clear()

        # Reconnect PV
        self.pv = epics.PV(self.pv_name, auto_monitor = self.auto_monitor)
        self.pv_connected = self.pv.connect()

        # Return the result of get()
        return self.pv.get(as_string = self.read_as_str, timeout=0.2)
Esempio n. 22
0
 def _create_pvs(self, psnames, propty):
     """Create PVs."""
     new_pvs = dict()
     for psn in psnames:
         pvname = self._get_pvname(psn, propty)
         auto_monitor = '(from Array)' not in propty
         if pvname in _PVHandler._pvs:
             continue
         new_pvs[pvname] = epics.PV(
             pvname, auto_monitor=auto_monitor, connection_timeout=0.05)
     _PVHandler._pvs.update(new_pvs)
Esempio n. 23
0
def pv_error(pv_str, valid, msg_list=[]):
    tmp = pv_str
    pv_tmp = epics.PV(tmp)
    msg = str(tmp) + ' ' + str(pv_tmp.value)
    if round(pv_tmp.value) != valid:
        msg = "ERROR " + msg
    else:
        msg = "INFO " + msg
    msg_list.append(msg)
    print(msg)
    return pv_tmp.value
Esempio n. 24
0
 def _connect(self):
     if self.pvname is not None:
         self.pv = epics.PV(self.pvname)
         self.pv.wait_for_connection(timeout=self.TIMEOUT)
         if self.pv is None:
             logging.warning("Failed to connect to PV.")
         else:
             self.pv.get(timeout=self.TIMEOUT)
             self.size = self.pv.count
     else:
         self.pv = None
Esempio n. 25
0
 def __init__(self,
              motor='7bmb1:aero:m1',
              asynRec='7bmb1:PSOFly1:cmdWriteRead',
              axis='Z',
              PSOInput=3,
              encoder_multiply=1e5):
     self.motor = epics.Motor(motor)
     self.asynRec = epics.PV(asynRec + '.BOUT')
     self.axis = axis
     self.PSOInput = PSOInput
     self.encoder_multiply = encoder_multiply
Esempio n. 26
0
    def setPV(self, pvname, prec=5, type=float):
        self.prec = prec
        self.type = type
        if self.pv is not None and self.cb_index is not None:
            self.pvChanging.disconnect()
            self.pv.remove_callback(self.cb_index)

        self.pv = epics.PV(BYTES2STR(pvname))
        self.setText(self.pv.get(as_string=True))
        self.cb_index = self.pv.add_callback(self.onPVChange)
        self.pvChanging.connect(self.updatePV)
Esempio n. 27
0
    def set_value(self, channel, val):
        """
        Method to set value to a channel

        :param channel: (str) String of the devices name used in doocs
        :param val: value
        :return: None
        """
        # print("SETTING")
        epics.PV(channel).put(val)
        return
Esempio n. 28
0
def pvs():
    pvlist = ['test:ao', 'test:ao.DRVH', 'test:bo', 'test:ao2', 'test:permit']
    pvs = dict()
    for name in pvlist:
        pv = epics.PV(name)
        pv.wait_for_connection()
        pvs[pv.pvname] = pv

    yield pvs
    for pv in pvs.values():
        pv.disconnect()
Esempio n. 29
0
    def connectPvs(self):        
        if self.pvNameY is None:            
            raise RuntimeError("pvname y must not be 'None'")
        if len(self.pvNameY)==0:
            raise RuntimeError("pvname  y must not be ''")

        self.pvY = epics.PV(self.pvNameY)        
        #print('self.pvY: ' + self.pvY.info)
        
        self.pvY.add_callback(self.onChangePvY)        
        QCoreApplication.processEvents()
Esempio n. 30
0
    def __init__(self, name):
        self._name = name
        self._data = {}  # keep all infos arriving with change callback
        self._conn = False  # keeps all infos arriving with connection callback

        self._attached = set()  # set of finite state machines using this IO
        self._pv = epics.PV(name,
                            callback=self.chgcb,
                            connection_callback=self.concb,
                            auto_monitor=True)
        self._cond = threading.Condition()