Esempio n. 1
0
    def test_type_converions_1(self):
        write("CA type conversions scalars\n")
        pvlist = (pvnames.str_pv, pvnames.int_pv, pvnames.float_pv,
                  pvnames.enum_pv, pvnames.long_pv, pvnames.double_pv2)
        chids = []
        pause_updating()
        for name in pvlist:
            chid = ca.create_channel(name)
            ca.connect_channel(chid)
            chids.append((chid, name))
            ca.poll(evt=0.025, iot=5.0)
        ca.poll(evt=0.05, iot=10.0)

        values = {}
        for chid, name in chids:
            values[name] = ca.get(chid, as_string=True)

        for promotion in ('ctrl', 'time'):
            for chid, pvname in chids:
                write('=== %s  chid=%s as %s\n' %
                      (ca.name(chid), repr(chid), promotion))
                time.sleep(0.01)
                if promotion == 'ctrl':
                    ntype = ca.promote_type(chid, use_ctrl=True)
                else:
                    ntype = ca.promote_type(chid, use_time=True)

                val = ca.get(chid, ftype=ntype)
                cval = ca.get(chid, as_string=True)
                if ca.element_count(chid) > 1:
                    val = val[:12]
                self.assertEqual(cval, values[pvname])
        resume_updating()
Esempio n. 2
0
    def wait(self):
        """
        Wait until the motor movement finishes
        """

        while (self.isMoving()):
            ca.poll(evt=0.01)
Esempio n. 3
0
def generate_live_data(duration, period, pvnames):
    pvnamelist = tuple(pvnames)
    cols = list(pvnamelist)
    cols.insert(0, 'timestamp')
    pvconn = {}
    alldata = []
    ca.initialize_libca()
    for name in pvnamelist:
        chid = ca.create_channel(name, connect=False, auto_cb=False)
        pvconn[name] = (chid, None)
    for key in list(pvconn):
        state = ca.connect_channel(pvconn.get(key)[0])
        if not state:
            print('PV:', key, 'not connected')
            pvconn.pop(key)
    ca.poll()
    while duration > 0 and pvconn:
        pvdata = []
        for name, data in pvconn.items():
            ca.get(data[0], wait=False)
        ca.poll()
        pvdata.append(datetime.datetime.now())
        for name, data in pvconn.items():
            val = ca.get_complete(data[0])
            pvdata.append(val)
        alldata.append(pvdata)
        time.sleep(period)
        duration = duration - period
    ca.finalize_libca(maxtime=1.0)
    df = pd.DataFrame(alldata, columns=cols)
    return df
Esempio n. 4
0
    def setAbsolutePosition(self, pos, waitComplete=False):
        """
        Move the motor to an absolute position received by an input parameter

        Parameters
        ----------
        pos : `double`
            The desired position to set
        waitComplete : `boolean` (default is **False**)
            .. note::
                If **True**, the function will wait until the movement finish
                to return, otherwise don't.
        """

        global mtrDB
        global A
        global T

        exec(self.__defineMotors())

        ca.poll(evt=0.05)

        ret, msg = self.canPerformMovement(pos)
        if (not ret):
            raise Exception("Can't move motor " + self.name +
                            " to desired position: " + str(pos) + ", " + msg)

        for m in self.forwardDict:
            mtrDB[m].setAbsolutePosition(T[m])

        if (waitComplete):
            self.wait()
Esempio n. 5
0
    def setRelativePosition(self, pos, waitComplete=False):
        """
        Move the motor a distance, received by an input parameter, to a position
        relative to that current one

        Parameters
        ----------
        pos : `double`
            The desired distance to move based on current position
        waitComplete : `boolean` (default is **False**)
            .. note:
                If **True**, the function will wait until the movement finish
                to return, otherwise don't.
        """
        if (pos == 0):
            return

        ret, msg = self.canPerformMovement(self.getRealPosition() + pos)
        if (not ret):
            raise Exception("Can't move motor " + self.motorDesc + " (" +
                            self.pvName + ") to desired position: " +
                            str(self.getRealPosition() + pos) + ", " + msg)

        self.motor.put('RLV', pos)

        ca.poll(evt=0.05)

        self._moving = True
        if (waitComplete):
            self.wait()
Esempio n. 6
0
    def test_type_converions_2(self):
        write("CA type conversions arrays\n")
        pvlist = (pvnames.char_arr_pv, pvnames.long_arr_pv,
                  pvnames.double_arr_pv)
        with no_simulator_updates():
            chids = []
            for name in pvlist:
                chid = ca.create_channel(name)
                ca.connect_channel(chid)
                chids.append((chid, name))
                ca.poll(evt=0.025, iot=5.0)
            ca.poll(evt=0.05, iot=10.0)

            values = {}
            for chid, name in chids:
                values[name] = ca.get(chid)
            for promotion in ('ctrl', 'time'):
                for chid, pvname in chids:
                    write('=== %s  chid=%s as %s\n' %
                          (ca.name(chid), repr(chid), promotion))
                    time.sleep(0.01)
                    if promotion == 'ctrl':
                        ntype = ca.promote_type(chid, use_ctrl=True)
                    else:
                        ntype = ca.promote_type(chid, use_time=True)

                    val = ca.get(chid, ftype=ntype)
                    cval = ca.get(chid, as_string=True)
                    for a, b in zip(val, values[pvname]):
                        self.assertEqual(a, b)
Esempio n. 7
0
def ctr(t=1, use_monitor=False, wait=True):
    from epics import ca
    k, v = findMonitor()
    if (k is not None and use_monitor):
        # We have a monitor, so we start the monitor, wait until it finishes, stop all other counters and grab count values
        v['device'].setPresetValue(v['channel'], t)

        for kT, vT in py4syn.counterDB.items():
            dev = vT['device']
            if (dev == v['device']):
                continue
            if not dev.isCounting() and dev.canStopCount() and v['enable']:
                dev.setCountTime(ICountable.INFINITY_TIME)

        startCounters(use_monitor=True)
        ca.poll()
        if (wait):
            waitAll(monitor=True)
            stopAll()
            return getCountersData()
    else:
        for k, v in py4syn.counterDB.items():
            dev = v['device']
            if not dev.isCounting() and v['enable']:
                dev.setCountTime(t)

        startCounters()

        ca.poll()
        if (wait):
            waitAll()
            return getCountersData()
Esempio n. 8
0
    def setAbsolutePosition(self, pos, waitComplete=False):
        """
        Move the motor to an absolute position received by an input parameter

        Parameters
        ----------
        pos : `double`
            The desired position to set
        waitComplete : `boolean` (default is **False**)
            .. note::
                If **True**, the function will wait until the movement finish
                to return, otherwise don't.
        """

        if (self.getRealPosition() == pos):
            return

        ret, msg = self.canPerformMovement(pos)
        if (not ret):
            raise Exception("Can't move motor " + self.motorDesc + " (" +
                            self.pvName + ") to desired position: " +
                            str(pos) + ", " + msg)

        self._moving = True
        self.motor.put('VAL', pos)

        ca.poll(evt=0.05)

        if (waitComplete):
            self.wait()
Esempio n. 9
0
def _ca_connect(chid,timeout=5.0):
    n  = 0
    t0 = time.time()
    conn = 2==ca.state(chid)
    while (not conn) and (time.time()-t0 < timeout):
        ca.poll(1.e-6,1.e-4)
        conn = 2==ca.state(chid)
        n += 1
    return conn, time.time()-t0, n
Esempio n. 10
0
 def show_info(self):
     " show basic motor settings "
     ca.poll()
     out = []
     out.append(repr(self))
     out.append("--------------------------------------")
     for nam, val in self.get_info().items():
         if len(nam) < 16:
             nam = "%s%s" % (nam, " " * (16 - len(nam)))
         out.append("%s = %s" % (nam, val))
     out.append("--------------------------------------")
     ca.write("\n".join(out))
Esempio n. 11
0
    def setRawPosition(self, position):
        """
        Sets the motor RAW position based on the `RVAL` (Raw Desired Value)
        field of Motor Record

        Returns
        -------
        `double`
        """
        self._moving = True
        self.motor.put('RVAL', position)

        ca.poll(evt=0.05)
Esempio n. 12
0
def batch_get(pv_list):
	chids = {}
	pvdata = {}
	for name in pv_list:
		chid = ca.create_channel(name, connect=False, auto_cb=False)
		chids[name] = chid
	for name, chid in chids.items():
		ca.connect_channel(chid)
	ca.poll()
	for name, chid in chids.items():
		ca.get(chid, wait=False)
	ca.poll()
	for name, chid in chids.items():
		val = ca.get_complete(chid)
		pvdata[name] = val
	return pvdata
Esempio n. 13
0
def run_synchronous_get_optimized(pvs):
    """Run synchronous optimized get test."""
    pvschid = []
    for pvn in pvs:
        chid = ca.create_channel(pvn, connect=False, auto_cb=False)
        pvschid.append(chid)

    for chid in pvschid:
        ca.connect_channel(chid)

    ca.poll()
    for i in range(600):
        t0 = time.time()
        for chid in pvschid:
            ca.get(chid, wait=False)
        out = []
        for chid in pvschid:
            out.append(ca.get_complete(chid))
        print(f'dtime {(time.time()-t0)*1000:.1f}ms   pos {out[0]:.0f}nm')
Esempio n. 14
0
    def run_subprocess(pvs, pipe):
        pvschid = []
        for pv in pvs:
            chid = ca.create_channel(pv, connect=False, auto_cb=False)
            pvschid.append(chid)

        for chid in pvschid:
            ca.connect_channel(chid)
        time.sleep(5)
        for chid in pvschid:
            ftype = ca.promote_type(chid, use_time=True, use_ctrl=False)

        ca.poll()
        while pipe.recv():
            for chid in pvschid:
                ca.get_with_metadata(chid, ftype=ftype, wait=False)
            out = []
            for chid in pvschid:
                data = ca.get_complete_with_metadata(chid, ftype=ftype)
                out.append(data['timestamp'])
            pipe.send(out)
Esempio n. 15
0
 def _set_params2(self):
     """Set run params..."""
     functionName = '_set_params'
     pvdata = {}
     for name in self._pvnamelist:
         chid = ca.create_channel(name, connect=False,
                                  auto_cb=False)  # note 1
         pvdata[name] = [chid, None]
     for name, data in pvdata.items():
         ca.connect_channel(data[0])
     ca.poll()
     for name, data in pvdata.items():
         ca.get(data[0], wait=False)  # note 2
     ca.poll()
     for name, data in pvdata.items():
         val = ca.get_complete(data[0])
         pvdata[name][1] = val
     #return { name: data[1] for name, data in pvdata.items()}
     ret = dict((name, data[1]) for name, data in pvdata.items())
     print(ret)
     return ret
Esempio n. 16
0
def ummvr(**kargs):
    """
    Perform **relative** movement in multiple motors at **almost** the same time and wait until movement finishes
    
    Parameters
    ----------
    kargs : `string`
        The motor name and desired position, e.g. x=10,y=10
    """
    aux = {}
    flag = ""
    for key, value in kargs.items():
        if key not in py4syn.mtrDB:
            flag = key

    if flag == "":

        for key, value in kargs.items():

            mvr(key, float(value), False)
            aux[key] = "MOV"

        try:
            while "MOV" in aux.values():
                for key, value in kargs.items():
                    if not py4syn.mtrDB[key].isMoving():
                        aux[key] = "STP"
                ca.poll(evt=0.01)

        except (KeyboardInterrupt):
            for key, value in kargs.items():
                py4syn.mtrDB[key].stop()
            print("\tStoped")
        except Exception as e:
            for key, value in kargs.items():
                py4syn.mtrDB[key].stop()
            print("\tError: ", e)
    else:
        print("Motor " + flag + " Not Found !!!!")
Esempio n. 17
0
    def show_all(self):
        """ show all motor attributes"""
        out = []
        add = out.append
        add("# Motor %s" % (self._prefix))
        add("#  field               value                 PV name")
        add("#------------------------------------------------------------")
        ca.poll()
        klist = list(self._alias.keys())
        klist.sort()
        for attr in klist:
            suff = self._alias[attr]
            # pvn = self._alias[attr]
            label = attr + " " * (18 - min(18, len(attr)))
            value = self.get(suff, as_string=True)
            pvname = self.PV(suff).pvname
            if value is None:
                value = "Not Connected??"
            value = value + " " * (18 - min(18, len(value)))
            # print " %s  %s  %s" % (label, value, pvname)
            add(" %s  %s  %s" % (label, value, pvname))

        ca.write("\n".join(out))
Esempio n. 18
0
    def waveformWait(self):
        """
        Waits until the whole waveform program finishes, including all repetitions.
        It's only possible to wait for waveform programs with finite repeat counts.

        .. note::
            When using the Kepco power supply with a serial port, it's not possible to
            receive a notification from the device when the waveform finishes, so this
            method works by repeatedly polling the device requesting the operation flag.
            Because of this, the recommended way to use this method is first sleeping
            for as much time as possible to avoid the loop and only on the last second
            call this method. Example of a helper function that accomplishes this:
            
            Examples
            --------
            >>> def runAndWait(bop, totalTime):
            ...     bop.waveformStart()
            ...     sleep(max(totalTime-1, 0))
            ...     bop.waveformWait()
            ...
        """
        while self.isWaveformRunning():
            poll(1e-2)
Esempio n. 19
0
    def __init__(
        self,
        prefix="",
        attrs=None,
        nonpvs=None,
        delim="",
        timeout=None,
        mutable=True,
        aliases={},
        with_poll=True,
    ):

        self._nonpvs = list(self._nonpvs)
        self._delim = delim
        self._prefix = prefix + delim
        self._pvs = {}
        self._mutable = mutable
        self._aliases = aliases
        if nonpvs is not None:
            for npv in nonpvs:
                if npv not in self._nonpvs:
                    self._nonpvs.append(npv)

        if attrs is not None:
            for attr in attrs:
                # self.PV(attr, connect=False, connection_timeout=timeout)
                self.PV(attr, connect=False, timeout=timeout)

        if aliases:
            for attr in aliases.values():
                if attrs is None or attr not in attrs:
                    # self.PV(attr, connect=False, connection_timeout=timeout)
                    self.PV(attr, connect=False, timeout=timeout)

        if with_poll:
            poll()
        self._init = True
Esempio n. 20
0
    def move(self, val, relative=False, wait=False, ignore_limits=False, confirm_move=False, timeout=300.0):
        """
        moves SmarAct drive to position (emulating pyepics Motor class)

        arguments:
        ==========
         val            value to move to (float) [Must be provided]
         relative       move relative to current position    (T/F) [F]
         wait           whether to wait for move to complete (T/F) [F]
         ignore_limits  try move without regard to limits    (T/F) [F]
         confirm_move   try to confirm that move has begun   (T/F) [F]
         timeout        max time for move to complete (in seconds) [300]

        return values:
        ==============
         -13 : invalid value (cannot convert to float).  Move not attempted.
         -12 : target value outside soft limits.         Move not attempted.
         -11 : drive PV is not connected.                Move not attempted.
          -8 : move started, but timed-out.
        # -7 : move started, timed-out, but appears done.
          -5 : move started, unexpected return value from PV.put().
        # -4 : move-with-wait finished, soft limit violation seen.
        # -3 : move-with-wait finished, hard limit violation seen.
           0 : move-with-wait finished OK.
           0 : move-without-wait executed, move not confirmed.
           1 : move-without-wait executed, move confirmed.
        #  3 : move-without-wait finished, hard limit violation seen.
        #  4 : move-without-wait finished, soft limit violation seen.

        """
        INVALID_VALUE  = -13
        OUTSIDE_LIMITS = -12
        NOT_CONNECTED  = -11
        TIMEOUT        =  -8
        UNKNOWN_ERROR  =  -5
        SUCCESS        =   0
        EXECUTED       =   0
        CONFIRMED      =   1

        PUT_SUCCESS    =   1
        PUT_TIMEOUT    =  -1

        try:
            val = float(val)
        except Exception:
            return INVALID_VALUE

        if relative:
            val += self.pvs.drive.get()

        if not ignore_limits:
            if not self.within_epics_limits(val):
                return OUTSIDE_LIMITS

        put_stat = self.pvs.drive.put(val, wait=wait, timeout=timeout)

        if put_stat is None:
            return NOT_CONNECTED

        if wait and put_stat == PUT_TIMEOUT:
            return TIMEOUT

        if put_stat != PUT_SUCCESS:
            return UNKNOWN_ERROR

        stat = self.status

        t0 = time.time()
        thold  = t0 + self.pvs.hold.get() * 0.001
        tstart = t0 + min(timeout, 10)
        tout   = t0 + timeout

        if not wait and not confirm_move:
            return EXECUTED

        while stat == Status.HOLDING and time.time() <= thold:
            ca.poll(evt=1.0e-2)
            stat = self.status

        while stat == Status.STOPPED and time.time() <= tstart:
            ca.poll(evt=1.0e-2)
            stat = self.status

        if stat != Status.TARGETING:
            if time.time() > tout:
                return TIMEOUT
            else:
                return UNKNOWN_ERROR

        if not wait:
            return CONFIRMED

        while stat == Status.TARGETING and time.time() <= tout:
            ca.poll(evt=1.0e-2)
            stat = self.status

        if stat not in (Status.HOLDING, Status.TARGETING):
            return UNKNOWN_ERROR

        if time.time() > tout:
            return TIMEOUT

        twv = self.pvs.twv.get()
        twv = abs(twv)

        while stat == Status.HOLDING and time.time() <= tout:
            ca.poll(evt=1.0e-2)
            stat = self.status

            delta = self.pvs.readback.get() - val
            delta = abs(delta)
            if delta < twv:
                return SUCCESS

        return UNKNOWN_ERROR
Esempio n. 21
0
 def wait(self):
     while (self._counting):
         ca.poll()
Esempio n. 22
0
 def refresh(self):
     """refresh all motor parameters currently in use:
     make sure all used attributes are up-to-date."""
     ca.poll()
Esempio n. 23
0
    def move(
        self,
        val=None,
        relative=False,
        wait=False,
        timeout=300.0,
        dial=False,
        step=False,
        raw=False,
        ignore_limits=False,
        confirm_move=False,
    ):
        """moves motor drive to position

        arguments:
        ==========
         val            value to move to (float) [Must be provided]
         relative       move relative to current position    (T/F) [F]
         wait           whether to wait for move to complete (T/F) [F]
         dial           use dial coordinates                 (T/F) [F]
         raw            use raw coordinates                  (T/F) [F]
         step           use raw coordinates (backward compat)(T/F) [F]
         ignore_limits  try move without regard to limits    (T/F) [F]
         confirm_move   try to confirm that move has begun   (T/F) [F]
         timeout        max time for move to complete (in seconds) [300]

        return values:
          -13 : invalid value (cannot convert to float).  Move not attempted.
          -12 : target value outside soft limits.         Move not attempted.
          -11 : drive PV is not connected:                Move not attempted.
           -8 : move started, but timed-out.
           -7 : move started, timed-out, but appears done.
           -5 : move started, unexpected return value from PV.put()
           -4 : move-with-wait finished, soft limit violation seen
           -3 : move-with-wait finished, hard limit violation seen
            0 : move-with-wait finish OK.
            0 : move-without-wait executed, not cpmfirmed
            1 : move-without-wait executed, move confirmed
            3 : move-without-wait finished, hard limit violation seen
            4 : move-without-wait finished, soft limit violation seen

        """
        step = step or raw

        NONFLOAT, OUTSIDE_LIMITS, UNCONNECTED = -13, -12, -11
        TIMEOUT, TIMEOUT_BUTDONE = -8, -7
        UNKNOWN_ERROR = -5
        DONEW_SOFTLIM, DONEW_HARDLIM = -4, -3
        DONE_OK = 0
        MOVE_BEGUN, MOVE_BEGUN_CONFIRMED = 0, 1
        NOWAIT_SOFTLIM, NOWAIT_HARDLIM = 4, 3
        try:
            val = float(val)
        except TypeError:
            return NONFLOAT

        drv, rbv = ("VAL", "RBV")
        if dial:
            drv, rbv = ("DVAL", "DRBV")
        elif step:
            drv, rbv = ("RVAL", "RRBV")

        if relative:
            val += self.get(drv)

        # Check for limit violations
        if not ignore_limits and not step:
            if not self.within_limits(val, dial=dial):
                return OUTSIDE_LIMITS

        stat = self.put(drv, val, wait=wait, timeout=timeout)
        if stat is None:
            return UNCONNECTED

        if wait and stat == -1:  # move started, exceeded timeout
            if self.get("DMOV") == 0:
                return TIMEOUT
            return TIMEOUT_BUTDONE
        if 1 == stat:
            if wait:  # ... and finished OK
                if 1 == self.get("LVIO"):
                    return DONEW_SOFTLIM
                elif 1 == self.get("HLS") or 1 == self.get("LLS"):
                    return DONEW_HARDLIM
                return DONE_OK
            else:
                if 1 == self.get("LVIO") or confirm_move:
                    ca.poll(evt=1.0e-2)
                moving = False
                if confirm_move:
                    t0 = time.time()
                    while self.get("MOVN") == 0:
                        ca.poll(evt=1.0e-3)
                        if time.time() - t0 > 0.25:
                            break
                if 1 == self.get("MOVN"):
                    return MOVE_BEGUN_CONFIRMED
                elif 1 == self.get("LVIO"):
                    return NOWAIT_SOFTLIM
                elif 1 == self.get("HLS") or 1 == self.get("LLS"):
                    return NOWAIT_HARDLIM
                else:
                    return MOVE_BEGUN
        return UNKNOWN_ERROR
Esempio n. 24
0
    def move(
        self,
        val,
        relative=False,
        wait=False,
        timeout=300.0,
        ignore_limits=False,
        confirm_move=False,
    ):
        """moves smaract drive to position

        arguments:
        ==========
         val            value to move to (float) [Must be provided]
         relative       move relative to current position    (T/F) [F]
         wait           whether to wait for move to complete (T/F) [F]
         ignore_limits  try move without regard to limits    (T/F) [F]
         confirm_move   try to confirm that move has begun   (T/F) [F]
         timeout        max time for move to complete (in seconds) [300]

        return values:
          -13 : invalid value (cannot convert to float).  Move not attempted.
          -12 : target value outside soft limits.         Move not attempted.
          -11 : drive PV is not connected:                Move not attempted.
           -8 : move started, but timed-out.
           -7 : move started, timed-out, but appears done.
           -5 : move started, unexpected return value from PV.put()
           -4 : move-with-wait finished, soft limit violation seen
           -3 : move-with-wait finished, hard limit violation seen
            0 : move-with-wait finish OK.
            0 : move-without-wait executed, not cpmfirmed
            1 : move-without-wait executed, move confirmed
            3 : move-without-wait finished, hard limit violation seen
            4 : move-without-wait finished, soft limit violation seen

        """
        NONFLOAT, OUTSIDE_LIMITS, UNCONNECTED = -13, -12, -11
        TIMEOUT = -8
        UNKNOWN_ERROR = -5
        DONE_OK = 0
        MOVE_BEGUN, MOVE_BEGUN_CONFIRMED = 0, 1
        try:
            val = float(val)
        except TypeError:
            return NONFLOAT

        if relative:
            val += self._drive.get("VAL")

        # Check for limit violations
        if not ignore_limits:
            if not self.within_limits(val):
                return OUTSIDE_LIMITS

        stat = self._drive.put("VAL", val, wait=wait, timeout=timeout)
        if stat is None:
            return UNCONNECTED

        if wait and stat == -1:
            return TIMEOUT

        if 1 == stat:
            s0 = self._statusstg.get("VAL")
            s1 = s0
            t0 = time.time()
            t1 = t0 + min(10.0, timeout)  # should be moving by now
            thold = self._hold.get("VAL") * 0.001 + t0
            tout = t0 + timeout
            if wait or confirm_move:
                while time.time() <= thold and s1 == 3:
                    ca.poll(evt=1.0e-2)
                    s1 = self._statusstg.get("VAL")
                while time.time() <= t1 and s1 == 0:
                    ca.poll(evt=1.0e-2)
                    s1 = self._statusstg.get("VAL")
                if s1 == 4:
                    if wait:
                        while time.time() <= tout and s1 == 4:
                            ca.poll(evt=1.0e-2)
                            s1 = self._statusstg.get("VAL")
                        if s1 == 3 or s1 == 4:
                            if time.time() > tout:
                                return TIMEOUT
                            else:
                                twv = abs(self._twv.get("VAL"))
                                while (s1 == 3 and time.time() <= tout and
                                       abs(self._rbv.get("VAL") - val) >= twv):
                                    ca.poll(evt=1.0e-2)
                                return DONE_OK
                    else:
                        return MOVE_BEGUN_CONFIRMED
                elif time.time() > tout:
                    return TIMEOUT
                else:
                    return UNKNOWN_ERROR
            else:
                return MOVE_BEGUN
        return UNKNOWN_ERROR
Esempio n. 25
0
 def wait(self):
     while (self._counting):
         sleep(0.1)
         ca.poll()
Esempio n. 26
0
ca.pend_event(1.e-2)

for name in pvnames:
    chid = results[name]['chid']
    val = ca.get(chid, wait=False)
    results[name]['value'] =  val

dt.add("did ca.get(wait=False)")
ca.pend_event(1.e-2)
dt.add("pend complete")

for name in pvnames:
    chid = results[name]['chid']    
    val = ca.get_complete(chid)
    results[name]['value'] =  val
    

dt.add("unpacked PV values")
 
f = open('fastconn_pvdata.sav', 'w')
for name, val in results.items():
    f.write("%s %s\n" % (name.strip(), val['value']))
f.close()
dt.add("wrote values PVs")

dt.show()

time.sleep(0.01)
ca.poll()
Esempio n. 27
0
for name in pvnames:
    ca.connect_channel(results[name]['chid'])

time.sleep(0.001)

dt.add("connected to PVs with connect_channel")

ca.pend_event(1.e-2)

for name in pvnames:
    chid = results[name]['chid']
    val = ca.get(chid, wait=False)
    results[name]['value'] = val

dt.add("did ca.get(wait=False)")
ca.poll(2.e-3, 1.0)
dt.add("ca.poll() complete")

for name in pvnames:
    results[name]['value'] = ca.get_complete(results[name]['chid'])

dt.add("ca.get_complete() for all PVs")

f = open('fastconn_pvdata.sav', 'w')
for name, val in results.items():
    f.write("%s %s\n" % (name.strip(), val['value']))
f.close()
dt.add("wrote PV values to disk")

dt.show()
Esempio n. 28
0
def main():
    parser = argparse.ArgumentParser()                            # parser for the inputs - must keep the 2 lines below.
    parser.add_argument("top",                 help="top node")   # must have a top node, -v VERBOSITY is an opion  
    parser.add_argument("-v", "--verbosity",   help="increase verbosity", nargs='?', const=0, default=0)
    #add extra args and opts here
    parser.add_argument("pv",                  help="pvname")   

    args = parser.parse_args()                 #get the input args from the parser
    
    global verbose
    verbose = args.verbosity

    global pvname
    global nChid

    
    pvname = args.pv
    
    #This calls the doNode() (bottom of this file) that works recursively through the tree and calls do_node()
    #which you may overwrite by calling your own function (eg my_node() shown here
    #In this case, it calls my_node() for every element - see below.
    doNode.doNode(args.top,do_node=my_node, v=verbose)

    
    wave=numpy.zeros(nChid)             #create an array for all the values

    pvname_wf = args.top+":"+pvname+"_wf"    #make the names of the PVs for waveform and enable switch
    pvname_en = args.top+":"+pvname+"_en"

    print pvname_wf,pvname_en
    
    pvwf = PV(pvname_wf)          #set the PV
    pven = PV(pvname_en)          #set the PV

    pven.put(1)

    for i in range(len(allids)):        #connect call the channels
        if not ca.connect_channel(allids[i],timeout=0.001):
            allids[i]=0
            print "Warning didn't connect to PV =", allnames[i], "ignoring this one"
            
    ca.poll()                           #Not sure exactly what this does!
    n=0
    while n < 100000:
        for i in range(len(allids)):
            #print i, allids[i]
            if allids[i] > 0:
                ca.get(allids[i], wait=False) #Tell them all to start getting but don't wait
        ca.poll() 
        
        for i in range(len(allids)):           #now finish getting
            if allids[i] > 0:
                val = ca.get_complete(allids[i])
                wave[i]=val
                if verbose:
                    #print allnames[i],val
        pvwf.put(wave)
        time.sleep(0.5)

        if not pven.get():
            exit()
        #print n,pven.get()
        n+=1
Esempio n. 29
0
def main():

    parser = argparse.ArgumentParser(
    )  # parser for the inputs - must keep the 2 lines below.
    parser.add_argument("-f",
                        "--setupfile",
                        help="setup file (default = monitor.dat)",
                        nargs='?',
                        const=0,
                        default="monitor.dat")
    parser.add_argument("-v",
                        "--verbosity",
                        help="increase verbosity",
                        nargs='?',
                        const=0,
                        default=0)

    args = parser.parse_args()  #get the input args from the parser

    global verbose
    verbose = args.verbosity
    setup_file = args.setupfile

    global pvdata
    global mon_line
    global pvf

    global pvfull

    #read the setup file, which has the form
    #index    TOP        PVname  Period(s)

    for line in file(
            setup_file
    ):  #read the lines in the setup file to pvdata monitor list
        if not (line.startswith("#")
                or len(line.split()) < 3):  #skip comments and require 3 fields
            s = line.split()  #split input into fields
            wf = PV(s[pvf.TOP] + ":" + s[pvf.NAME] +
                    "_wf")  #wf, en are PVs for waveform and enable
            en = PV(s[pvf.TOP] + ":" + s[pvf.NAME] + "_en")
            pvdata.append(
                [s[0], s[pvf.TOP], s[pvf.NAME], s[pvf.PERIOD], wf, en,
                 []])  #add to list, with list for IDS

            #Call doNode() which works recursively through the tree and calls do_node()
            #which you may overwrite by calling your own function (eg my_node() shown here)
            #In this case, it calls my_node() for every element - see below.
            doNode.doNode(pvdata[mon_line][pvf.TOP],
                          do_node=my_node,
                          v=verbose)

            #now the pvf.ID array has been filled, try to connect to all the elements
            for n, chid in enumerate(pvdata[mon_line][pvf.ID]):
                if not ca.connect_channel(chid, timeout=0.001):
                    if verbose:
                        print pvfull[n], "... Not connected, chid = 0"
                    pvdata[mon_line][pvf.ID][n] = 0
                else:
                    if verbose:
                        print pvfull[n], "... Connected, chid = ", chid
            pvdata[mon_line].append(numpy.zeros(len(pvdata[mon_line][
                pvf.ID])))  #create a zero numpy array for the data

            pvfull = []  #reset the list of names
            mon_line += 1  #increment the current line number

    #start a monitor thread for each
    for l in range(mon_line):
        t = Thread(target=monitor, args=(l, ))
        t.start()

    #do the poll loop here, to cover all monitor threads
    while mon_line > 0:
        ca.poll()
        time.sleep(1.0)
Esempio n. 30
0
 def wait(self):
     while(not self._done):
         ca.poll(0.001)