Пример #1
0
    def test_monitor(self):
        self.assertIOCRunning()
        longout = self.testprefix + 'longout'

        values = []

        def callback(value):
            values.append(value)

        m = catools.camonitor(longout, callback, notify_disconnect=True)

        # Wait for connection
        while not values:
            cothread.Sleep(0.1)
        catools.caput(longout, 43, wait=True)
        catools.caput(longout, 44, wait=True)
        self.iocStop()

        # Can't call iocStop twice...
        def iocStop():
            return

        self.iocStop = iocStop
        m.close()

        self.assertEqual(len(values), 4)
        self.assertEqual(values[:3], [42, 43, 44])
        self.assertEqual([v.ok for v in values], [True, True, True, False])
Пример #2
0
    def test_monitor(self):
        self.assertIOCRunning()
        longout = self.testprefix + 'longout'

        values = []

        def callback(value):
            values.append(value)

        m = catools.camonitor(longout, callback, notify_disconnect=True)

        # Wait for connection
        while not values:
            cothread.Sleep(0.1)
        catools.caput(longout, 43, wait=True)
        catools.caput(longout, 44, wait=True)
        self.iocStop()

        # Can't call iocStop twice...
        def iocStop():
            return

        self.iocStop = iocStop
        m.close()

        self.assertEqual(len(values), 4)
        self.assertEqual(values[:3], [42, 43, 44])
        self.assertEqual([v.ok for v in values], [True, True, True, False])
Пример #3
0
def animate(i, ax1, thread_1):
    if thread_1.new_data == 1:
        axis_bk = axis()
        ax1.clear()
        sca(ax1)
        xlabel('Bunch #')
        ylabel('Amplitude')
        title("Bunch " + thread_1.axis +
              " oscillation amplitude @ NCO={:.5f}".format(thread_1.tune))
        plot(thread_1.I, '-o')
        plot(thread_1.Q, '-o')
        if not thread_1.reset_axis:
            axis(axis_bk)
        else:
            thread_1.reset_axis = False
        thread_1.new_data = 0
    # Ask for a new capture as soon as previous mem_read is finished
    with thread_1.trigger_cdt:
        thread_1.tune = catools.caget(thread_1.device + ':' + thread_1.axis +
                                      ':NCO:FREQ_S')
        # Capture command doesn't work so well (mis-aligned data)
        #catools.caput(thread_1.device+':MEM:CAPTURE_S', 1, wait=True)
        catools.caput(thread_1.device + ':TRG:MEM:ARM_S', 1, wait=True)
        catools.caput(thread_1.device + ':TRG:SOFT_S', 1, wait=True)
        # Wait for memory to be actually triggered
        Sleep(0.05)
        thread_1.trigger_cdt.notify()
Пример #4
0
def position(**args):
    '''
    Users can define their own angle-value pair dictionaries.The motors will be moved to these positions 
    if the defined positions are within motors' hardware limits
    Usage:
        position() for return values of position
        position(angle1=value1,angle2=value2) to move motors
    '''
    hw = diff.getHardware()
    if len(args) == 0:
        i = 0
        while i < len(diff.getAngleNames()):
            print str(diff.getAngleNames()[i]) + ': ' + str(diff.getAngleValues()[i])
            i += 1
    else:
        pvList = list()
        posList = list()
        for entry in diff.getangleList():
            if entry.getName() in args:
                pvList.append(entry.getPV())
                posList.append(args[entry.getName()])
        if len(posList) != 0:
            caput(pvList, posList,timeout=100)
            angs = getAngleValues()
            roundedangles = [round(elem, 2) for elem in angs]
            roundedsetpoints = [round(elem, 2) for elem in diff.getAngleSetPoints()]
            print 'Motor Motion in Progress'
            while roundedangles != roundedsetpoints:
                sleep(7.5)
                angs = getAngleValues()
                roundedangles = [round(elem, 2) for elem in angs]
            print 'Motor Motion Completed'
        print diff.getAngleValues()
        hw.position = diff.getAngleSetPoints()
Пример #5
0
def orbit_dev(x, lat, hclst):
    #hc1="SR:C01-MG:G02A<HCM:H1>Fld:SP"
    #hc2="SR:C01-MG:G02A<HCM:H2>Fld:SP"
    #hc3="SR:C01-MG:G04B<HCM:M1>Fld:SP"

    # check against boundary of corrector strength
    print "Setting % .4e % .4e" % (x[0], x[1]),
    for cx in x:
        if abs(cx) > 1e-2:
            print ""
            return 1e30

    catools.caput(hclst[1], x[0])
    catools.caput(hclst[2], x[1])
    # wait for 4 seconds
    time.sleep(6)
    s, x, y = get_orbit(lat)
    plt.clf()
    plt.plot(s, x, 'r-')
    plt.plot(s, y, 'g-')
    plt.plot(s[1:4], x[1:4], 'ro')
    plt.plot(s[1:4], y[1:4], 'gx')
    plt.savefig("orbit.png")

    #sys.exit(0)

    orb = 0.0
    for i in range(len(x)):
        # skip bpms close to correctors
        if i > 0 and i < 4: continue
        orb += x[i]**2 + y[i]**2
    print "% .6e" % orb
    return orb
Пример #6
0
    def _load(self, ramp_image):
        if ramp_image.image == None or self.pv_name == None:
            return None

        if __debug__ == True:
            print(
                "I am going to write the stepping binary image to PV: {0}...".
                format(self.pv_name))
            if _NO_CATOOLS_ == True:
                print("...but I see no catools module imported.")
            print("Image: ", ramp_image.image)
            print("Image len, bytes:", len(ramp_image.image))

        if _NO_CATOOLS_ == True:
            return None

        try:
            connect(self.pv_name, throw=False)
            caput(self.pv_name, ramp_image.image, wait=True)
        except:
            if __debug__ == True:
                print("My write to CA has failed.")
            return None

        return 0
Пример #7
0
def orbit_dev(x, lat, hclst):
    #hc1="SR:C01-MG:G02A<HCM:H1>Fld:SP"
    #hc2="SR:C01-MG:G02A<HCM:H2>Fld:SP"
    #hc3="SR:C01-MG:G04B<HCM:M1>Fld:SP"
    
    # check against boundary of corrector strength
    print "Setting % .4e % .4e" % (x[0], x[1]),
    for cx in x:
        if abs(cx) > 1e-2: 
            print ""
            return 1e30

    catools.caput(hclst[1], x[0])
    catools.caput(hclst[2], x[1])
    # wait for 4 seconds
    time.sleep(6)
    s, x, y = get_orbit(lat)
    plt.clf()
    plt.plot(s, x, 'r-')
    plt.plot(s, y, 'g-')
    plt.plot(s[1:4], x[1:4], 'ro')
    plt.plot(s[1:4], y[1:4], 'gx')
    plt.savefig("orbit.png")

    #sys.exit(0)

    orb = 0.0
    for i in range(len(x)):
        # skip bpms close to correctors
        if i > 0 and i < 4: continue
        orb += x[i]**2 + y[i]**2
    print "% .6e" % orb
    return orb
Пример #8
0
def theo_local_bump1(lat):
    """Given a lattice list, calculate the theoretical local bump
    """
    # all elements
    betax = [v for v in catools.caget("SR:C00-Glb:G00<BETA:00>RB:X")]
    phix = [v for v in catools.caget("SR:C00-Glb:G00<PHI:00>RB:X")]
    bpm_idx = lat.group_index("BPMX")
    ch_idx = lat.group_index("TRIMX")

    # two kicker, 11*2pi phase advance.
    hc1 = "SR:C01-MG:G02A<HCM:H1>Fld:SP"
    hc2 = hc1
    hc3 = "SR:C10-MG:G06A<HCM:H2>Fld:SP"

    ic1 = lat.pvindex(hc1)
    ic2 = lat.pvindex(hc2)
    ic3 = lat.pvindex(hc3)
    print "index:", ic1, ic2, ic3
    print "beta", betax[ic1], betax[ic2], betax[ic3]
    print "s_end", lat.s_end(hc1), lat.s_end(hc2), lat.s_end(hc3)
    print "phase:", phix[ic1], phix[ic2], phix[ic3]
    c1 = 1e-5
    catools.caput(hc1, c1)
    catools.caput(hc3, -c1 * sqrt(betax[ic1] / betax[ic3]))
    time.sleep(4)
    s, x1, y1 = get_orbit(lat, 4)
    print "get orbit"
Пример #9
0
 def go_direct(self, position, wait=True, callback=None):
     ca.caput(self.direct_demand,
              position,
              wait=wait,
              timeout=60,
              callback=callback)
     Sleep(.05)  # test clipper reports in position a little early sometimes
Пример #10
0
def theo_local_bump1(lat):
    """Given a lattice list, calculate the theoretical local bump
    """
    # all elements
    betax = [v for v in catools.caget("SR:C00-Glb:G00<BETA:00>RB:X")]
    phix = [v for v in catools.caget("SR:C00-Glb:G00<PHI:00>RB:X")]
    bpm_idx = lat.group_index("BPMX")
    ch_idx = lat.group_index("TRIMX")

    # two kicker, 11*2pi phase advance.
    hc1="SR:C01-MG:G02A<HCM:H1>Fld:SP"
    hc2=hc1
    hc3="SR:C10-MG:G06A<HCM:H2>Fld:SP"
    
    ic1 = lat.pvindex(hc1)
    ic2 = lat.pvindex(hc2)
    ic3 = lat.pvindex(hc3)
    print "index:", ic1, ic2, ic3
    print "beta", betax[ic1], betax[ic2], betax[ic3]
    print "s_end", lat.s_end(hc1), lat.s_end(hc2), lat.s_end(hc3)
    print "phase:", phix[ic1], phix[ic2], phix[ic3]
    c1 = 1e-5
    catools.caput(hc1, c1)
    catools.caput(hc3, -c1*sqrt(betax[ic1]/betax[ic3]))
    time.sleep(4)
    s,x1,y1 = get_orbit(lat, 4)
    print "get orbit"
Пример #11
0
 def startCounter(self):
     if self.runmode == 1 and self.counterRun == 0:
         self.runRequested = 1
         catools.caput("V5:SYN:StartC.PROC", 1)  # run
     else:
         print("running")
         catools.caput("V5:SYN:StartC.PROC", 1)
Пример #12
0
    def set_single(self, pv, value, throw=True):
        """Set the value of a given PV.

        Args:
            pv (string): PV to set the value of.
            value (object): The value to set the PV to.
            throw (bool): On failure: if True, raise ControlSystemException: if
                           False, log a warning.

        Returns:
            bool: True for success, False for failure

        Raises:
            ControlSystemException: if it cannot connect to the specified PV.
        """
        try:
            caput(pv, value, timeout=self._timeout, throw=True)
            return True
        except ca_nothing:
            error_msg = f"Cannot connect to {pv}."
            if throw:
                raise ControlSystemException(error_msg)
            else:
                logging.warning(error_msg)
                return False
Пример #13
0
    def put(self, pv, value):
        """ Set the value for a given.

        Args:
            pv(string): The pv to set the value of. It must be a setpoint pv.
            value(Number): The value to set the pv to.
        """
        caput(pv, value)
Пример #14
0
 def set_cs_group(self, group):
     ca.caput(self.pv_cs_group, group, wait=True)
     # TODO we have race conditions on switch of CS:-
     #  (1) if the direct demand resolutions need to change there is a small delay
     #  (2) the brick itself may take a short time to do the CS mappings
     # for now we require a short wait after a switch
     # (this may not be fixable - (1) showed up on ppmac (2) showed up on VMXI)
     Sleep(.3)
Пример #15
0
 def testMaskedSp(self):
     v1 = []
     for v in self._v0[-20:]:
         v1.extend([v+3.0, 1.0])
     v1[-1] = 0
     v1[-3] = 0
     v1[-5] = 0
     caput("l:SR:APHLA:SOFB{COR}I:Sp1Mark_wfm_8_", v1)
     time.sleep(15)
Пример #16
0
    def _writePv(self, v):
        """
        """
        c = QObject.sender(self)
        i = self.spinbox.index(c)
        #print i, c.text(), "changed"

        #print self.pvs_sp[i], v
        caput(self.pvs_sp[i], v)
def capture_one_image_stream():
    settings = [("13SIM1:HDF1:FileWriteMode", "Stream", None)]
    load_settings(settings)
    print "Start capture mode"
    caput("13SIM1:HDF1:Capture", 1, wait=False)
    # Wait for a brief moment to allow the file saving plugin to create the file
    cothread.Sleep(1.0)
    print "Acquire a single frame"
    caput("13SIM1:cam1:Acquire", 1, wait=False)
Пример #18
0
 def setValue(self, value):
     try:
         self._value = value
         caput(self._pv, value)
     except:
         logInstance.logger.error(
             'Connection with IOC failed. Make sure EPICS motor record PVs are accessible under this subnet')
         raise RuntimeWarning(
             'Connection with IOC failed. Make sure EPICS motor record PVs are accessible under this subnet')
Пример #19
0
 def set_vertical_xbpm_scale_factor(self, energy):
     ky = (-26 * energy + 1120) / self.optics
     kx = 1200 / self.optics
     catools.caput(self.tetramm_prefix + str(self.xbpm_num) +
                   ':DRV:PositionScaleY', ky)
     logging.info("Position scale Y set to " + str(ky))
     catools.caput(self.tetramm_prefix + str(self.xbpm_num) +
                   ':DRV:PositionScaleX', kx)
     logging.info("Position scale X set to " + str(kx))
Пример #20
0
    def _writePv(self, v):
        """
        """
        c = QObject.sender(self)
        i = self.spinbox.index(c)
        #print i, c.text(), "changed"

        #print self.pvs_sp[i], v
        caput(self.pvs_sp[i], v)
Пример #21
0
 def testDx(self):
     v1 = [v + 0.1 for v in self._v0]
     caput(self._pvs, v1, wait=True)
     time.sleep(5)
     v1r = caget(self._pvsrb)
     v1w = caget(self._pvs)
     for i,vi in enumerate(v1):
         self.assertAlmostEqual(v1[i], v1r[i], places=1,
                                msg= "{0} != {1} for {2}".format(v1[i], v1r[i], self._pvs[i]))
         self.assertAlmostEqual(v1[i], v1w[i], places=5)
Пример #22
0
    def configure_axes(self):

        for axis in ALL_AXES:
            this_axis = getattr(self, 'axis'+axis)
            ca.caput("{}{}:UseAxis".format(self.pv_root, axis), this_axis.use)

            if this_axis.use:
                print("PUTTING positions {} TO {}{}:Positions".format(this_axis.positions, self.pv_root, axis))
                ca.caput("{}{}:Positions".format(self.pv_root, axis), this_axis.positions,
                         wait=True)
    def _trigger_epics(self):
        """Private method to update the EPICS variables
        
        This will write a value to the .PROC record that will update all of the 
        process variables on that database. 

        Args: 

        Returns: 
        """
        caput(self.epicsID + ".PROC", 1)  # Write to the .PROC data base to update all of the values
Пример #24
0
    def test_si(self):
        self.assertIOCRunning()
        si = self.testprefix + 'si'

        v = catools.caget(si)
        self.assertNotEqual(v, 'hello world')

        catools.caput(si, 'hello world')

        v = catools.caget(si)
        self.assertEqual(v, 'hello world')
Пример #25
0
    def test_si(self):
        self.assertIOCRunning()
        si = self.testprefix+'si'

        v = catools.caget(si)
        self.assertNotEqual(v, 'hello world')

        catools.caput(si, 'hello world')

        v = catools.caget(si)
        self.assertEqual(v, 'hello world')
    def _write_epics_pv(self, pv, value):
        """Private method to read an Epics process variable.

        Args:
            pv (str): Name of the Epics process variable to read. 
            value (variant): The value to be written to the epics variable

        Returns: 
            variant: Value of requested process variable after writing to it
        """
        caput(self.epicsID + pv, value)  # Write to EPICs PV
        return self._read_epics_pv(pv)
Пример #27
0
def test_cothread_ioc(cothread_ioc):
    import cothread
    from cothread.catools import ca_nothing, caget, caput, camonitor

    pre = cothread_ioc.pv_prefix

    with Listener(ADDRESS) as listener, listener.accept() as conn:

        select_and_recv(conn, "R")  # "Ready"

        # Start
        assert caget(pre + ":UPTIME").startswith("00:00:0")
        # WAVEFORM
        caput(pre + ":SINN", 4, wait=True)
        q = cothread.EventQueue()
        m = camonitor(pre + ":SIN", q.Signal, notify_disconnect=True)
        assert len(q.Wait(1)) == 4
        # STRINGOUT
        assert caget(pre + ":STRINGOUT") == "watevah"
        caput(pre + ":STRINGOUT", "something", wait=True)
        assert caget(pre + ":STRINGOUT") == "something"
        # Check pvaccess works
        from p4p.client.cothread import Context
        with Context("pva") as ctx:
            assert ctx.get(pre + ":STRINGOUT") == "something"

        conn.send("D")  # "Done"

        select_and_recv(conn, "D")  # "Done"

        # Stop
        cothread_ioc.proc.send_signal(signal.SIGINT)
        # Disconnect
        assert isinstance(q.Wait(10), ca_nothing)
        m.close()

    # check closed and output
    out, err = cothread_ioc.proc.communicate()
    out = out.decode()
    err = err.decode()
    # check closed and output
    try:
        assert "%s:SINN.VAL 1024 -> 4" % pre in out
        assert 'update_sin_wf 4' in out
        assert "%s:STRINGOUT.VAL watevah -> something" % pre in out
        assert 'on_update \'something\'' in out
        assert 'Starting iocInit' in err
        assert 'iocRun: All initialization complete' in err
    except Exception:
        # Useful printing for when things go wrong!
        print("Out:", out)
        print("Err:", err)
        raise
Пример #28
0
 def check_range(self, val):
     self.r = catools.caget(
         self.tetramm_prefix + self.xbpm_num + ':DRV:Range')
     if self.r == 0:  # 120uA
         if val < self.lower_current_limit:
             catools.caput(
                 self.tetramm_prefix + str(self.xbpm_num) + ':DRV:Range', 1)
             logging.info("Current range set to +-120nA")
     elif self.r == 1:  # 120nA
         if val > self.upper_current_limit:
             catools.caput(
                 self.tetramm_prefix + str(self.xbpm_num) + ':DRV:Range', 0)
             logging.info("Current range set to +-120uA")
def make(*trajectories):
    """The function will do the following:
     * Calculate the maximum length of the arrays
     * Zero pad all trajectories to this length
     * Write them as trajectories for M1..M8
     * Set # Traj Elements to be this length"""
    maxlen = max([len(x) for x in trajectories])
    trajectories = [x + [0] * (maxlen - len(x)) for x in trajectories[:8]]
    setupPVs = [prefix + "Nelements"]
    setupVals = [maxlen]
    caput(setupPVs, setupVals)
    trajPVs = ["%sM%sTraj" % (prefix, i + 1) for i in range(len(trajectories))]
    caput(trajPVs, trajectories)
    print "Wrote trajectories for first %s motors" % len(trajectories)
Пример #30
0
    def _setpvs(self, T, C):

        pvs =  [self.prefix + "EvtCode-SP", self.prefix + "Timestamp-SP"]
        try:
            self.enableAll.emit(False)
            caput(pvs, [C,T], timeout=2.0, wait=True)
            self.msg("Sent", 2000)
        except catools.ca_nothing,E:
            if E.errorcode==cadef.ECA_TIMEOUT:
                M='Timeout'
            else:
                M=cadef.ca_message(E.errorcode)
            self.msg("Sent failed: "+M, 4000)
            return
Пример #31
0
 def undocallback(self, value):
     """
     """
     if value == 1:
         try:
             if self.plane == 0:
                 if self.previoush is None:
                     ca.caput(self.pvmapping.__status__, "There is nothing to undo for horizontal plane",
                              datatype=DBR_CHAR_STR)
                 else:
                     for i, cor in enumerate(self.cors):
                          cor.set("x", self.previoush[i], unitsys=None)
                     self.previoush = None
             elif self.plane == 1:
                 if self.previousv is None:
                     ca.caput(self.pvmapping.__status__, "There is nothing to undo for vertical plane",
                              datatype=DBR_CHAR_STR)
                 else:
                     for i, cor in enumerate(self.cors):
                         cor.set("y", self.previousv[i], unitsys=None)
                     self.previousv = None
             ca.caput(value.name, 0)
         except ca.ca_nothing:
             try:
                 ca.caput(self.pvmapping.__status__, "Failed to undo action.", datatype=DBR_CHAR_STR)
             except ca.ca_nothing:
                 print "Cannot set status pv"
Пример #32
0
    def rampingPut(self):
        try:
            step = int(self.stepLineEdit.text())
            delay = float(self.delayLineEdit.text())
        except:
            print("No ramping: wrong settings of Step or Delay time.")
            QMessageBox.warning(
                self, 'Warning',
                'No ramping: wrong settings of Step or Delay time. Please try again'
            )
            return
        #print("Number of steps: %d; Waiting time between steps: %d"%(step, delay))
        if step < 1:
            print("No ramping: number of steps can't be zero")
            QMessageBox.warning(
                self, 'Warning',
                'No ramping: the number of Steps should be >=1. Please try again'
            )
            return

        try:
            curValues = caget(self.rampPVList, timeout=2, throw=False)
        except:
            print(
                "Oops: can't get PV values to ramp the machine, but will try one-step simple restore"
            )
            traceback.print_exc()
            #QMessageBox.warning(self, 'Warning', "No multiple-step gradual put: some PVs seem disconnected")
            return True  #try one-step simple put
        #print(self.rampPVList)
        #print(curValues)
        #print(self.rampRestoreData)
        try:
            stepSize = [(i - j) / step
                        for i, j in zip(self.rampRestoreData, curValues)]
            #print(stepSize)
            for l in range(1, step):
                stepValues = [l * m + n for m, n in zip(stepSize, curValues)]
                #print(stepValues)
                caput(self.rampPVList, stepValues)
                cothread.Sleep(delay)
        except:
            print(
                "Oops: something wrong with ramping machine, but will try one-step simple restore"
            )
            traceback.print_exc()
            #QMessageBox.warning(self, 'Warning', "Oops: something wrong with multiple-step gradual put")

        return True
Пример #33
0
 def __init__(self, device):
     Thread.__init__(self)
     mem_trig_request_lock = Lock()
     mem_trig_request_lock.acquire()
     self.trigger_cdt = Condition(mem_trig_request_lock)
     self.device = device
     self.axis = catools.caget(device + ':AXIS{}'.format(int(channel)))
     # Set runout to 12.5 %
     catools.caput(device + ':MEM:RUNOUT_S', 0, wait=True)
     self.new_data = 0
     self.stop = 0
     self.do_reset_axis()
     self.mbf = MBF_mem(device)
     self.decimation = self.mbf.get_max_decimation()
     self.max_count = self.mbf.get_count_max(self.decimation)
Пример #34
0
 def configure_file(self, outputfile, xmldef=None):
     if xmldef:
         caput( self.pv['xmlfile'], os.path.abspath(xmldef), datatype=dbr.DBR_CHAR_STR, wait=True)
         validxml = caget( self.pv['xmlvalid'])
         if validxml is 0:
             errmsg = caget( self.pv['xmlerror'] )
             raise StrException(errmsg)
         
     outputfile = os.path.abspath(outputfile)
     fname = os.path.basename(outputfile)
     dname = os.path.dirname(outputfile)
     caput( self.pv['template'], "%s%s", datatype = dbr.DBR_CHAR_STR )
     caput( self.pv['path'], dname, datatype = dbr.DBR_CHAR_STR)
     caput( self.pv['name'], fname, datatype = dbr.DBR_CHAR_STR)
     caput( self.pv['mode'], "Stream", wait=True)
Пример #35
0
 def test_xsel_1x1(self):
     pvs = ["SR:" + s + "Enbl:Ps1OC-Cmd"
            for s in self._cor_dev]
     jl = random.sample(range(len(pvs)), 20)
     pvjl = [pvs[j] for j in jl]
     x0 = caget(pvjl)
     x1 = [1 - x for x in x0]
     caput(pvjl, x1)
     time.sleep(1.5)
     x2 = caget(pvjl)
     x2wfm = caget(P + "SR:APHLA:SOFB{COR}XSel-I")
     for i,j in enumerate(jl):
         self.assertNotEqual(x2[i], x0[i])
         self.assertEqual(x2[i], x2wfm[j])
     caput(pvjl, x0)
Пример #36
0
    def _cleanlocalbump(self):
        """Clean local bump and set all values to zero."""
        try:
            print "clean up local bump"
            bpms = np.zeros(self.bpmcounts)
            cors = np.zeros(self.corscount)
            ca.caput([self.pvmapping.__bpmposition__, self.pvmapping.__bpmorbitx__, self.pvmapping.__bpmorbity__,
                      self.pvmapping.__correctorposition__,
                      self.pvmapping.__hcorrectorcurrent__, self.pvmapping.__hcorrectordiff__,
                      self.pvmapping.__vcorrectorcurrent__, self.pvmapping.__vcorrectordiff__],
                     [bpms, bpms, bpms, cors, cors, cors, cors, cors])

        except ca.ca_nothing:
            print traceback.print_exc()
            print "Cannot clean devices for local bump"
Пример #37
0
 def caput(self, value):
     if self.timeout < 0:
         timeout = None
     else:
         timeout = self.timeout
     self.log.info("caput %s %s", self.pv, value)
     catools.caput(self.pv,
                   value,
                   wait=True,
                   timeout=timeout,
                   datatype=self.datatype)
     # now do a caget
     value = catools.caget(self.rbv,
                           format=catools.FORMAT_TIME,
                           datatype=self.datatype)
     self._update_value(value)
def capture_one_image_single():
    settings = [
        ("13SIM1:cam1:ImageMode", "Single", None),
        ("13SIM1:cam1:ArrayCallbacks", "Enable", None),
        ("13SIM1:cam1:ArrayCounter", 0, None),
        ("13SIM1:HDF1:EnableCallbacks", "Enable", None),
        ("13SIM1:HDF1:ArrayCounter", 0, None),
    ]
    load_settings(settings)
    timeout = caget("13SIM1:cam1:AcquirePeriod_RBV") * 1.5 + 1.0
    print "Acquiring and storing a single image in 'Single' mode"
    caput("13SIM1:cam1:Acquire", 1, wait=True, timeout=timeout)
    # Wait for a brief moment to allow the file saving to complete
    cothread.Sleep(1.0)
    fname = caget("13SIM1:HDF1:FullFileName_RBV", datatype=dbr.DBR_CHAR_STR)
    print "Captured into image file: ", fname
Пример #39
0
 def epicsPut(self, pv, val):
     """Do an epics caput and return status"""
     s = catools.caput(pv, val, throw=False)
     if not s:
         logging.warning("Failed caput on '%s' error = %s", s.name, str(s))
         return False
     return True
Пример #40
0
 def epicsPut(self, pv, val):
     """Do an epics caput and return status"""
     s = catools.caput(pv, val, throw = False)
     if not s:
         logging.warning("Failed caput on '%s' error = %s", s.name, str(s))
         return False
     return True
Пример #41
0
def caput(pvs,
          values,
          repeat_value=None,
          datatype=None,
          wait=True,
          timeout=5,
          callback=None,
          throw=True):
    """
    Convenience function that wraps the cothread.catools.caput()
    function with safe handling of unicode strings in Python 2.X.

    .. note:: The default value of the 'wait' keyword argument
       has been changed from the original cothread function.

    .. note:: The default value of the 'repeat_value' keyword
       argument has been changed from the original cothread
       function. The original cothread function raises an
       exception if the repeat_value argument is given when
       using a single channel. This function permits the
       repeat_value argument to be given with a value of
       None when using a single channel.  When using an
       array of channels, a repeat_value with the value
       of None is the same as the value of False.
    """
    if isinstance(pvs, str):
        if repeat_value is not None:
            raise ValueError("repeat_value must be None for a single channel")
        return catools.caput(_to_str(pvs),
                             values,
                             datatype=datatype,
                             wait=wait,
                             timeout=timeout,
                             callback=callback,
                             throw=throw)
    else:
        if repeat_value is None:
            repeat_value = False
        return catools.caput(_to_str(pvs),
                             values,
                             repeat_value=repeat_value,
                             datatype=datatype,
                             wait=wait,
                             timeout=timeout,
                             callback=callback,
                             throw=throw)
Пример #42
0
    def _aplocalbumpcreation(self, plane, ename, source, bumpsettings):
        """
        plane: 0: X plane, 1: Y plane;
        ename: selected insertion device element name;
        source: s position at source position
        bumpsettings: local bump settings: [shift, angle]

        return: delta correctors [H, V]
        """

        if plane == 0:
            fld = 'x'
            #xc = ((self.idobj.se - self.idobj.sb) / 2.0 - self.sourceposition) * \
            #    bumpsettings[1] + bumpsettings[0]
            #thetac = bumpsettings[1]
        elif plane == 1:
            fld = 'y'
        xc = ((self.idobj.se - self.idobj.sb) / 2.0 - self.sourceposition) * \
            bumpsettings[1] + bumpsettings[0]
        thetac = bumpsettings[1]

        if self.previoush is None:
            self.previoush = [0.0] * self.corscount
        for i, cor in enumerate(self.cors):
            self.previoush[i] = cor.get(fld, unitsys=None, handle="setpoint")

        niter = 10
        for i in range(niter):
            cothread.Yield(0.10)
            norm0, norm1, norm2, corvals = \
                ap.setIdBump(ename, xc, thetac, plane=fld)
            angle, position, _, _ = self._getliveangleandpos(self.bpms[self.bpmcounts/2-1], self.bpms[self.bpmcounts/2])
            # if the achieved angle and offset are very close to desired values, break
            # can not distinguish 10urad and 5um.
            if np.abs(angle - thetac) < 1e-2 and np.abs(xc - position) < 5e-3:
                break
            if corvals is None:
                msg = "{0}/{1} Minimum chi^2 achieved: {2} (predicted: {3})".format(i,niter,norm0, norm1)
            else:
                msg = "{0}/{1} chi^2 decreased {2} from {3} (predicted: {4})".format(
                    i, niter, norm2-norm0, norm0, norm1)
            ca.caput(self.pvmapping.__status__, msg[:255], datatype=DBR_CHAR_STR)

        delta = ap.fget(self.cors, fld, unitsys=None, handle="setpoint") - np.array(self.previoush, 'd')
        return delta
Пример #43
0
    def validate_test_runner(
            self,
            creation_func,
            new_value,
            expected_value,
            validate_pass: bool):

        parent_conn, child_conn = multiprocessing.Pipe()

        device_name = create_random_prefix()

        process = multiprocessing.Process(
            target=self.validate_ioc_test_func,
            args=(device_name, creation_func, child_conn, validate_pass),
        )

        process.start()

        from cothread.catools import caget, caput, _channel_cache

        try:
            # Wait for message that IOC has started
            select_and_recv(parent_conn, "R")


            # Suppress potential spurious warnings
            _channel_cache.purge()

            kwargs = {}
            if creation_func in [builder.longStringIn, builder.longStringOut]:
                from cothread.dbr import DBR_CHAR_STR
                kwargs.update({"datatype": DBR_CHAR_STR})

            put_ret = caput(
                device_name + ":VALIDATE-RECORD",
                new_value,
                wait=True,
                **kwargs,
            )
            assert put_ret.ok, "caput did not succeed"

            ret_val = caget(
                device_name + ":VALIDATE-RECORD",
                timeout=TIMEOUT,
                **kwargs
            )

            if creation_func in [builder.WaveformOut, builder.WaveformIn]:
                assert numpy.array_equal(ret_val, expected_value)
            else:
                assert ret_val == expected_value

        finally:
            # Suppress potential spurious warnings
            _channel_cache.purge()
            parent_conn.send("D")  # "Done"
            process.join(timeout=TIMEOUT)
    def get_mr(self):
        get_command = util.abstract_caget
        beam_current_max_warning = False

        # Only control injection if there are variables that require it.
        if self.measurement_vars_inj:
            # First measure the injection results
            # Begin injecting
            print "Start injection"
            caput('LI-TI-MTGEN-01:START', 1)
            cothread.Sleep(0.1)
            caput('LI-TI-MTGEN-01:START', 0)
            cothread.Sleep(4.0)

            if self.beam_current_bounds[0] is not None:
                beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
                while beam_current < self.beam_current_bounds[0]:
                    print 'waiting for beam current to rise above ', \
                        self.beam_current_bounds[0]
                    cothread.Sleep(1)
                    beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
                    print '...'

            mrs_inj = util.measure_results(self.measurement_vars_inj,
                                           util.abstract_caget)

            # Now for the non-injection measurements
            if self.beam_current_bounds[1] is not None:
                if get_command(
                        'SR-DI-DCCT-01:SIGNAL') > self.beam_current_bounds[1]:
                    beam_current_max_warning = True

            # Stop injection
            print "Stop injection"
            caput('LI-TI-MTGEN-01:STOP', 1)
            cothread.Sleep(0.1)
            caput('LI-TI-MTGEN-01:STOP', 0)
            cothread.Sleep(1)
        else:
            mrs_inj = []

        mrs_noinj = util.measure_results(self.measurement_vars_noinj,
                                         util.abstract_caget)

        # Now combine the results into a single list
        mrs = mrs_noinj + mrs_inj

        if beam_current_max_warning:
            msg = 'Beam current limit exceeded.\nDump the beam before pressing OK.'
            tkMessageBox.showwarning('DUMP THE BEAM', msg)

        return mrs
Пример #45
0
    def test_auto_home_resets_cs_demands(self):
        tb = TestBrick()
        tb.set_cs_group(tb.g3)

        tb.height.go(10)
        tb.cs3.M1.go_direct(10)
        self.assertAlmostEqual(10, tb.height.pos, DECIMALS)
        self.assertAlmostEqual(10, tb.m1.pos, DECIMALS)

        # auto home everything
        ca.caput('PMAC_BRICK_TEST:HM:HMGRP', 'All')
        ca.caput('PMAC_BRICK_TEST:HM:HOME', 1, wait=True, timeout=20)

        self.assertAlmostEqual(0, tb.height.pos, DECIMALS)
        self.assertAlmostEqual(0, tb.m1.pos, DECIMALS)

        # now move a different motor in the CS, the other two would continue to
        # their previous destinations if makeCSDemandsConsistent has failed
        tb.cs3.M2.go_direct(10)
        self.assertAlmostEqual(0, tb.height.pos, DECIMALS)
        self.assertAlmostEqual(0, tb.m1.pos, DECIMALS)
        self.assertAlmostEqual(10, tb.m2.pos, DECIMALS)
Пример #46
0
    def rampingPut(self):
        try:
            step = int(self.stepLineEdit.text())
            delay = float(self.delayLineEdit.text())
        except:
            print("No ramping: wrong settings of Step or Delay time.")
            QMessageBox.warning(self, "Warning", "No ramping: wrong settings of Step or Delay time. Please try again")
            return
        # print("Number of steps: %d; Waiting time between steps: %d"%(step, delay))
        if step < 1:
            print("No ramping: number of steps can't be zero")
            QMessageBox.warning(self, "Warning", "No ramping: the number of Steps should be >=1. Please try again")
            return

        try:
            curValues = caget(self.rampPVList, timeout=2, throw=False)
        except:
            print("Oops: can't get PV values to ramp the machine, but will try one-step simple restore")
            traceback.print_exc()
            # QMessageBox.warning(self, 'Warning', "No multiple-step gradual put: some PVs seem disconnected")
            return True  # try one-step simple put
        # print(self.rampPVList)
        # print(curValues)
        # print(self.rampRestoreData)
        try:
            stepSize = [(i - j) / step for i, j in zip(self.rampRestoreData, curValues)]
            # print(stepSize)
            for l in range(1, step):
                stepValues = [l * m + n for m, n in zip(stepSize, curValues)]
                # print(stepValues)
                caput(self.rampPVList, stepValues)
                cothread.Sleep(delay)
        except:
            print("Oops: something wrong with ramping machine, but will try one-step simple restore")
            traceback.print_exc()
            # QMessageBox.warning(self, 'Warning', "Oops: something wrong with multiple-step gradual put")

        return True
Пример #47
0
    def get_mr(self):
        get_command = util.abstract_caget
        beam_current_max_warning = False

        # First measure the injection results
        # Begin injecting
        print "Start injection"
        caput('LI-TI-MTGEN-01:START', 1)
        cothread.Sleep(0.1)
        caput('LI-TI-MTGEN-01:START', 0)
        cothread.Sleep(4.0)

        if self.beam_current_bounds is not None:
            beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
            while beam_current < self.beam_current_bounds[0]:
                print 'waiting for beam current to rise above ', \
                    self.beam_current_bounds[0]
                cothread.Sleep(1)
                beam_current = get_command('SR-DI-DCCT-01:SIGNAL')
                print '...'

        mrs_inj = util.measure_results(self.measurement_vars_inj,
                                       util.abstract_caget)

        # Now for the non-injection measurements

        if self.beam_current_bounds is not None:
            if get_command(
                    'SR-DI-DCCT-01:SIGNAL') > self.beam_current_bounds[1]:
                beam_current_max_warning = True

        # Stop injection
        print "Stop injection"
        caput('LI-TI-MTGEN-01:STOP', 1)
        cothread.Sleep(0.1)
        caput('LI-TI-MTGEN-01:STOP', 0)
        cothread.Sleep(1)

        mrs_noinj = util.measure_results(self.measurement_vars_noinj,
                                         util.abstract_caget)

        # Now combine the results into a single list

        results = mrs_noinj + mrs_inj

        mrs = results

        return mrs
Пример #48
0
    def setStatus(self, unit, status):
        # Here we just write to PV
        if self.autoActions is None:
            return False

        val = self.autoActions['PVs'][unit][status]

        logging.debug("setStatus() : pv = %s status = %s", val[0], val[1])
        s = catools.caput(val[0],val[1])
        if not s:
            logging.error("setStatus() : Unable to set status on unit %d", unit)
            return False
        else:
            return True
Пример #49
0
def write_epics_pv(epics_id, pv, val):
    """Private method to write to an Epics process variable.

    Wraps up caget call, makes it easy for multiple reads to be programmed
    and a timeout added if required.

    Args:
        epics_id (Str): The EPICS name of the device.
        pv (str): Name of the Epics process variable to read.
        val (str, int, float): Value to write to the process variable.
    Returns:
        variant: Value of requested process variable.
    """
    return caput(':'.join((epics_id, pv)), val)  # Write PV data
Пример #50
0
    def _load(self, ramp_image):
        if ramp_image.image == None or self.pv_name == None:
            return None

        if __debug__ == True:
            print "I am going to write the stepping binary image to PV: {0}...".format(self.pv_name)
            if _NO_CATOOLS_ == True:
                print "...but I see no catools module imported."
            print "Image: ", ramp_image.image
            print "Image len, bytes:", len(ramp_image.image)

        if _NO_CATOOLS_ == True:
            return None

        try:
            connect(self.pv_name, throw=False)
            caput(self.pv_name, ramp_image.image, wait=True)
        except:
            if __debug__ == True:
                print "My write to CA has failed."
            return None

        return 0
Пример #51
0
def moveMultiple(motors):
    hw = diff.getHardware()
    pvList = list()
    posList = list()
    for entry in getangleInstances():
        if motors.has_key(entry.getName()):
            pvList.append(entry.getPV())
            posList.append(motors[entry.getName()])
    if len(posList) != 0:
        caput(pvList, posList)
        rounded_setPoints = [round(elem, 2) for elem in diff.getAngleSetPoints()]
        rounded_angVals = [round(elem, 2) for elem in getAngleValues()]
        mtrs = rounded_angVals
        print 'actual', mtrs
        print 'setPoint', rounded_setPoints
        while rounded_setPoints != mtrs:
            print 'Motor Motion in Progress\n'
            #print 'Actual Motor Positions:', mtrs
            #print 'Motor Position Set Point', rounded_setPoints
            sleep(5)
            rounded_angVals = [round(elem, 2) for elem in getAngleValues()]
            mtrs = rounded_angVals
    hw.position = diff.getAngleSetPoints()
 def set_feedback_pid(self):
     for pid in self.xbpm_pid_params_list:
         catools.caput(pid.feedback_prefix + '.KP',
                       self.pv_dict['KP' + pid.position].get())
         catools.caput(pid.feedback_prefix + '.KI',
                       self.pv_dict['KI' + pid.position].get())
         catools.caput(pid.feedback_prefix + '.KD',
                       self.pv_dict['KD' + pid.position].get())
     logging.debug("Feedback PID values set")
Пример #53
0
    def _load(self, ramp_image):
        if self.pv_name == None:
            return None

        if ramp_image.image == None:
            return None

        if self.channel_index == None:
            return None      

        pRamping = self.pv_name + 'Chan' + str(self.channel_index) + '-Asyn.BOUT'

        if __debug__ == True:
            print "Preparing to load full ramp in channel " + str(self.channel_index) + " using PV:"
            print pRamping
            print "Destination channel index is", self.channel_index
            print "I am going to write the binary image of full ramp to PV with prefix: {0}...".format(self.pv_name)
            if _NO_CATOOLS_ == True:
                print "...but I see no catools module imported."
            #print "Image: ", ramp_image.image
            print "Image len, bytes:", len(ramp_image.image)

        if _NO_CATOOLS_ == True:
            return None

        try:
            #Writing binary ramp table...
            connect(pRamping, throw=False)
            caput(pRamping, ramp_image.image, wait=True)

        except:
            if __debug__ == True:
                print "My write to CA has failed."
            return None

        return 0
Пример #54
0
 def planecallback(self, value):
     """Set source plane when it is changed."""
     self.plane = value
     cothread.Sleep(2.0)
     if self.selecteddevice != "NULL":
         try:
             ca.caput(self.pvmapping.__shift__, ca.caget(self.pvmapping.__positionrb__))
             ca.caput(self.pvmapping.__angle__, ca.caget(self.pvmapping.__anglerb__))
         except ca.ca_nothing:
             # do not do anything for this exception.
             pass
     else:
         try:
             ca.caput(self.pvmapping.__shift__, 0.0)
             ca.caput(self.pvmapping.__angle__, 0.0)
         except ca.ca_nothing:
             # do not do anything for this exception.
             pass
Пример #55
0
def caput(pvs, values, timeout=CA_TIMEOUT, wait=True, throw=True, verbose = 0):
    """channel access write.

    This is simple wrap of `cothread.catools.caput` to support UTF8 string

    see original :func:`cothread.catools.caput` for details

    Parameters
    -----------
    pvs : str, list. process variables
    values : float/int, list. setting values
    timeout : int.
    wait : bool.
    throw : bool.

    Returns
    ---------
    see :func:`cothread.catools.caput`

    Examples
    ----------
    >>> caput('SR:C01-MG:G04B{Quad:M1}Fld-I', 0.1)
    >>> caput(['SR:PV1', 'SR:PV2'], [0.1, 0.2])

    """

    _logger.debug("setting '%s' '%s'" % (str(pvs), str(values)))

    if CA_OFFLINE: return _ca_put_sim(pvs, values)

    if isinstance(pvs, str):
        pvs2 = pvs
    elif isinstance(pvs, unicode):
        pvs2 = pvs.encode("ascii")
    elif isinstance(pvs, list):
        pvs2 = [pv.encode("ascii") for pv in pvs]
    else:
        raise ValueError("Unknown type " + str(type(pvs)))

    try:
        return ct.caput(pvs2, values, timeout=timeout, wait=wait, throw=throw)
    except cothread.Timedout:
        if os.environ.get('APHLAS_DISABLE_CA', 0):
            print "TIMEOUT: reading", pvs
        else:
            raise cothread.Timedout
Пример #56
0
def theo_local_bump2(lat):
    # all elements
    hc1="SR:C03-MG:G02A<HCM:H1>Fld:SP"
    hc2="SR:C03-MG:G02A<HCM:H2>Fld:SP"
    hc3="SR:C03-MG:G04B<HCM:M1>Fld:SP"

    c1 = 1e-5
    c2, c3 = theoretical_strength(lat, (hc1, hc2, hc3), c1)
    catools.caput(hc1, c1)
    catools.caput(hc2, c2)
    catools.caput(hc3, c3)
    time.sleep(6)
    s, x, y = get_orbit(lat)
Пример #57
0
    def uploadCommands(self, prefix):
        print "uploading commands to PVs with prefix %s" % prefix
        # potentially we could enable these PVs before setting them and this
        # would update the GUI nicely HOWEVER - when the records process
        # they are sent to the controller via the stream protocol file
        # there is no way to suppress this for a waveform hooked to streamdevice
        # so we leave these disabled

#         caput("%s:WFSETUP:WR.DISA" % prefix, 0, timeout=1)
#         caput("%s:WFSTART:WR.DISA" % prefix, 0, timeout=1)
#         caput("%s:WFSTOP:WR.DISA" % prefix, 0, timeout=1)
        caput("%s:WFSETUP:WR" % prefix,
              self.commands, timeout=1, datatype=DBR_CHAR_STR)
        caput("%s:WFSTART:WR" % prefix,
              self.startCmd, timeout=1, datatype=DBR_CHAR_STR)
        caput("%s:WFSTOP:WR" % prefix,
              self.stopCmd, timeout=1, datatype=DBR_CHAR_STR)
Пример #58
0
## Running from the same server to avoid EPICS ARRARY SIZE issus #
## export EPICS_CA_MAX_ARRAY_BYTES=800000


from numpy import *
import numpy as np

import sys
import time 
import cothread
from cothread.catools import caput, caget

spPV= 'vSR-SOFB{}SP'
spSet = array(floor(random.rand(360)*0.0))
caput(spPV, spSet,wait=False) 

print "vvvvvvvvvvvvvvvvvvvvvvvvv333"
Пример #59
0
import os
import re
from cothread.catools import caget, caput

if __name__ == "__main__":
    f = open('../machine/nsls2/pvlist_2011_04_08.txt', 'r')
    for pv in f.readlines():
        if not pv.endswith('-SP\n'): continue
        if pv.find('Cor:') < 0: continue
        pv = pv.strip()
        k = caget(pv.encode('ascii'))
        if abs(k) > 0.0: 
            print pv, k
            caput(pv, 0.0)