Exemple #1
0
def sleep(secs):
    """Sleep for a given number of seconds.

    This is different from Python's `time.sleep()` in that it allows breaking
    and stopping the sleep, and supports dry run mode.  Fractional values are
    supported.

    Examples:

    >>> sleep(10)     # sleep for 10 seconds
    >>> sleep(0.5)    # sleep for half a second
    """
    session.log.info('sleeping for %.1f seconds...', secs)

    if session.mode == SIMULATION:
        session.clock.tick(secs)
        return

    def f_notify(tmr):
        session.breakpoint(2)  # allow break and continue here
        session.action('%s left' % formatDuration(tmr.remaining_time()))

    session.beginActionScope('Sleeping')
    session.action('%s left' % formatDuration(secs))
    try:
        tmr = Timer(secs)
        tmr.wait(interval=1.0, notify_func=f_notify)
    finally:
        session.endActionScope()
Exemple #2
0
 def preparePoint(self, num, xvalues):
     if session.mode == SIMULATION and num > self._simpoints:
         session.log.info('skipping %d points...',
                          self._numpoints - self._simpoints)
         duration = session.clock.time - self._sim_start
         session.clock.tick(duration * (self._numpoints - self._simpoints))
         if self._numpoints < 0 and not self._sweepdevices:
             session.log.info('would scan indefinitely, skipping...')
         raise StopScan
     if num == 1:
         self._etime.started = currenttime()
         if self._sweeptargets:
             try:
                 self.moveDevices(self._sweepdevices,
                                  self._sweeptargets,
                                  wait=False)
             except SkipPoint:
                 raise StopScan
     elif self._delay:
         # wait between points, but only from the second point on
         session.action('Delay')
         session.delay(self._delay)
     Scan.preparePoint(self, num, xvalues)
     if session.mode == SIMULATION:
         self._sim_start = session.clock.time
Exemple #3
0
    def doStart(self):
        try:
            if self._attached_rc.read(0) != 'on':
                self.log.warning('radial collimator is not moving!')
        except NicosError:
            self.log.warning('could not check radial collimator', exc=1)

        self._update()

        self._last_time = 0
        self._last_counts = 0
        self._last_moncounts = 0
        self._starttime = currenttime()
        self._setROParam('rates', [[0., 0.], [0., 0.]])

        session.action('run# %06d' % session.experiment.lastpoint)

        GenericDetector.doStart(self)
Exemple #4
0
 def preparePoint(self, num, xvalues):
     if session.mode == SIMULATION and num > self._simpoints:
         session.log.info('skipping %d points...',
                          self._numpoints - self._simpoints)
         duration = session.clock.time - self._sim_start
         session.clock.tick(duration * (self._numpoints -
                                        self._simpoints))
         if self._numpoints < 0 and not self._sweepdevices:
             session.log.info('would scan indefinitely, skipping...')
         raise StopScan
     if num == 1:
         self._etime.started = currenttime()
         if self._sweeptargets:
             try:
                 self.moveDevices(self._sweepdevices, self._sweeptargets,
                                  wait=False)
             except SkipPoint:
                 raise StopScan  # pylint:disable=raise-missing-from
         if self._minstep:
             self._laststep = [dev.read() for dev in self._sweepdevices]
     else:
         if self._delay:
             # wait between points, but only from the second point on
             session.action('Delay')
             session.delay(self._delay)
         if self._sweepdevices and self._minstep:
             # wait until next step
             while True:
                 position = [dev.read() for dev in self._sweepdevices]
                 l = list(zip(self._laststep, position, self._minstep))
                 if any(abs(x-y) > z for x,y,z in l):
                     break
                 if not any(dev.status()[0] == status.BUSY
                            for dev in self._sweepdevices):
                     break
             self._laststep = [(x + z if x < y else x - z) for x,y,z in l]
     Scan.preparePoint(self, num, xvalues)
     if session.mode == SIMULATION:
         self._sim_start = session.clock.time
Exemple #5
0
 def f_notify(tmr):
     session.breakpoint(2)  # allow break and continue here
     session.action('%s left' % formatDuration(tmr.remaining_time()))
Exemple #6
0
def multiWait(devices):
    """Wait for the *devices*.

    Returns a dictionary mapping devices to current values after waiting.

    This is the main waiting loop to be used when waiting for multiple devices.
    It checks the device status until all devices are OK or errored.

    Errors raised are handled like in the following way:
    The error is logged, and the first exception with the highest serverity
    (exception in `CONTINUE_EXECPTIONS` < `SKIP_EXCPTIONS` < other exceptions)
    is re-raised at the end.

    *baseclass* allows to restrict the devices waited on.
    """
    from nicos.core.device import Waitable

    def get_target_str():
        return ', '.join(
            '%s -> %s' %
            (dev,
             dev.format(dev.target)) if hasattr(dev, 'target') else str(dev)
            for dev in reversed(devlist))

    delay = 0.3
    final_exc = None
    devlist = list(devIter(devices, baseclass=Waitable, allwaiters=True))
    session.log.debug('multiWait: initial devices %s, all waiters %s', devices,
                      devlist)
    values = {}
    loops = -2  # wait 2 iterations for full loop
    eta_update = 1 if session.mode != SIMULATION else 0
    first_ts = currenttime()
    session.beginActionScope('Waiting')
    eta_str = ''
    target_str = get_target_str()
    session.action(target_str)
    try:
        while devlist:
            session.log.debug('multiWait: iteration %d, devices left %s',
                              loops, devlist)
            loops += 1
            for dev in devlist[:]:
                try:
                    done = dev.isCompleted()
                    if done:
                        dev.finish()
                except Exception:
                    final_exc = filterExceptions(sys.exc_info(), final_exc)
                    # remove this device from the waiters - we might still have
                    # its subdevices in the list so that multiWait() should not
                    # return until everything is either OK or ERROR
                    devlist.remove(dev)
                    if devlist:
                        # at least one more device left, show the exception now
                        dev.log.exception('while waiting')
                    continue
                if not done:
                    # we found one busy dev, normally go to next iteration
                    # until this one is done (saves going through the whole
                    # list of devices and doing unnecessary HW communication)
                    if loops % 10:
                        break
                    # every 10 loops, go through everything to get an accurate
                    # display in the action line
                    continue
                if dev in devices:
                    # populate the results dictionary, but only with the values
                    # of excplicitly given devices
                    values[dev] = dev.read()
                # this device is done: don't wait for it anymore
                devlist.remove(dev)
                target_str = get_target_str()
                session.action(eta_str + target_str)
            if devlist:
                if eta_update >= 1:
                    eta_update -= 1
                    now = currenttime()
                    eta = {dev.estimateTime(now - first_ts) for dev in devlist}
                    eta.discard(None)
                    # use max here as we wait for ALL movements to finish
                    eta_str = ('estimated %s left / ' %
                               formatDuration(max(eta)) if eta else '')
                    session.action(eta_str + target_str)
                session.delay(delay)
                eta_update += delay
        if final_exc:
            reraise(*final_exc)
    finally:
        session.endActionScope()
        session.log.debug('multiWait: finished')
    return values