Exemple #1
0
 def _commute(self):
     self.log.info('commute: see in speed history: burst for 3min, '
                   'a break of 20sec, an a peak, final break of 2min '
                   'total ca 6min')
     self._attached_comm.writeLine('m4070=5')
     session.delay(0.5)
     self.log.debug('DEVELOPING just wait!')
Exemple #2
0
    def _HW_readParameter_index(self, index):
        LDebug = True
        if index not in self.HW_readable_Params:
            raise UsageError('Reading not possible for parameter index %d' %
                             index)

        index = self.HW_readable_Params.get(index, index)
        self.log.debug('readParameter index %d', index)

        for i in range(10):
            self._writeUpperControlWord((index << 8) | 4)
            session.delay(0.15)
            stat = self._readStatusWord()

            if (stat & 0x8000) != 0:
                if LDebug and i > 0:
                    self.log.info('readParameter %d', i)
                # old return self._readReturn()
                value = self._dev.ReadOutputWords((self.address + 1, 9))
                retindex = value[0] >> 8
                if retindex != index:
                    if LDebug:
                        self.log.debug('read second!')
                    continue
                value = value[7:]
                value = struct.unpack('=i', struct.pack('<2H', *value))[0]
                return value
            if (stat & 0x4000) != 0:
                raise UsageError(
                    self, 'NACK ReadPar command not '
                    'recognized by HW, please retry later...')
        raise UsageError(
            self, 'ReadPar command not recognized by '
            'HW, please retry later ...')
Exemple #3
0
    def _HW_readParameter(self, index):
        if index not in self.HW_readable_Params:
            raise UsageError('Reading not possible for parameter index %s' %
                             index)

        index = self.HW_readable_Params.get(index, index)
        self.log.debug('readParameter %d', index)

        for i in range(10):
            self._writeUpperControlWord((index << 8) | 4)
            session.delay(0.15)
            stat = self._areadStatusWord(self.addresses[0])
            self.log.debug('readStatusWord 0 %d', stat)
            stat = self._areadStatusWord(self.addresses[0])
            self.log.debug('readStatusWord 1 %d', stat)
            if (stat & 0x8000) != 0:
                if i > 0:
                    self.log.debug('readParameter %d', i + 1)
                return self._readReturn()
            if (stat & 0x4000) != 0:
                raise UsageError(
                    self, 'NACK ReadPar command not recognized '
                    'by HW, please retry later...')
        raise UsageError(
            self, 'ReadPar command not recognized by HW, please '
            'retry later ...')
Exemple #4
0
    def _caress_guard_nolog(self, function, *args):

        if not self._initialized or not self._caressObject:
            CARESSDevice.doInit(self, self._mode)

#       self._com_lock.aquire()
        try:
            return function(*args)
        except (CORBA.COMM_FAILURE, CORBA.TRANSIENT) as err:
            tries = self.comtries - 1
            while True and tries > 0:
                self.log.warning('Remaining tries: %d', tries)
                session.delay(self.comdelay)
                if isinstance(err, CORBA.TRANSIENT):
                    CARESSDevice.doShutdown(self)
                    CARESSDevice.doInit(self, self._mode)
                session.delay(self.comdelay)
                try:
                    return function(*args)
                except (CORBA.COMM_FAILURE, CORBA.TRANSIENT) as err:
                    tries -= 1
            raise CommunicationError(
                self, 'CARESS error: %s%r: %s' %
                (function.__name__, args, err)) from err
        finally:
            pass
Exemple #5
0
 def doReset(self):
     BaseSequencer.doReset(self)
     for d in self._adevs:
         d.reset()
         session.delay(2)
     if self.doStatus()[0] == status.OK:
         raise NicosError(self, 'cannot reset')
Exemple #6
0
 def _getCID(self, device):
     if session.sessiontype == POLLER:
         while not self.cid:
             session.delay(0.5)
         return self.cid
     self.log.debug('get CARESS device ID: %r', device)
     answer = createSubprocess(
         'cd %s && %s/dump_u1 -n %s' %
         (self.caresspath, self.toolpath, device),
         shell=True,
         stdout=subprocess.PIPE,
         universal_newlines=True,
     ).communicate()[0]
     self._caress_name = device
     if answer in ('', None):
         if not CARESSDevice._caress_maps:
             CARESSDevice._caress_maps[device] = 4096
         elif device not in CARESSDevice._caress_maps:
             CARESSDevice._caress_maps[device] = 1 + \
                 max(CARESSDevice._caress_maps.values())
         res = CARESSDevice._caress_maps[device]
     else:
         res = int(answer.split('=')[1])
     self.log.debug('get CARESS device ID: %r', res)
     return res
Exemple #7
0
    def doReference(self, *args):
        refswitch = args[0] if args and isinstance(args[0], string_types) \
            else None
        if self.doStatus()[0] == status.BUSY:
            self.stop()
            self.wait()

        # The sixfold and triple cards will be reset as whole card, so values
        # of all channels will reset !!!
        # self.reset()
        # self.wait()

        if self.doStatus()[0] == status.OK:
            if self._refcontrol and self._refcontrol.is_alive():
                self._refcontrol.join()
            self._refcontrol = None

            if self._refcontrol is None:
                threadname = 'referencing %s' % self
                self._refcontrol = createThread(threadname,
                                                self._reference,
                                                args=(refswitch, ))
                session.delay(0.2)
        else:
            raise NicosError(self, 'in error or busy state')
Exemple #8
0
 def _switchpoly(self):
     """Start air pressure cylinder for additional shielding block."""
     if self._stoprequest == 2 or self._errorstate:
         self._poly = 0
     if self._poly != 0 and \
        abs(self.read(0) - self.offset - self.polypos) <= 0.1:
         self.log.debug('Switch poly0, mtt = %s', self.read(0))
         self.log.debug('Switch poly: %d', self._poly)
         if self._poly < 0 and self._attached_polyswitch.read(0) != 1:
             self.log.debug('Move poly block out')
             self._attached_polyswitch.maw(1)
             if self._attached_polyswitch.read(0) != 1:
                 self._setErrorState(
                     MoveError, 'shielding block in way, '
                     'cannot move 2Theta monochromator')
         elif self._poly > 0 and self._attached_polyswitch.read(0) != 0:
             self.log.debug('Move poly block in')
             self._attached_polyswitch.maw(0)
             if self._attached_polyswitch.read(0) != 0:
                 self._setErrorState(
                     MoveError, 'shielding block not on '
                     'position, measurement without'
                     'shielding yields to enlarged '
                     'background')
         # It takes this time to move up/down. There is no switch to
         # indicate the end position is reached
         session.delay(self.polysleep)
Exemple #9
0
 def doWritePhase(self, value):
     # Change sign of offset since the sign of the value is now changed
     # afterwards
     set_to = (value - self.reference) / self.gear  # SB
     self.log.info('Disk %d angle %0.2f Phase %0.2f gear %d ref %.2f',
                   self.chopper, value, set_to, self.gear, self.reference)
     # We think in 0..360 degrees, choppers 1 to 4 in -180..180 degrees
     # and choppers 5 and 6 in -90..90 degrees
     while set_to > (+180. / self.gear):
         set_to -= 360. / self.gear
     while set_to < (-180. / self.gear):
         set_to += 360. / self.gear
     # The Chopper understands "negative hundreths degrees"
     set_to = int(round(set_to * -100))  # SB
     self.log.debug('Disk %d Phase %d gear %d', self.chopper, set_to,
                    self.gear)
     # Notausgang = 10
     # while Notausgang:
     #    Notausgang -= 1
     #    res = self._read_base('m4070')
     #    if res == '0':
     #        break
     #    if Notausgang < 0:
     #        break
     #    self.log.info('warten %s', res)
     #    #session.delay(0.04) 4 loops!
     #    session.delay(0.2)
     #    TODO
     self._write_controller('m4073=%d m4074=0 m4075=%d m4076=%d m4070=7',
                            set_to, self.gear)
     session.delay(5)  # MP: isso
Exemple #10
0
 def doReset(self, t=3):
     # get usbdevfs file name
     if self._io is not None:
         try:
             os.close(self._io)
         except OSError:
             pass
     self.log.debug('resetting...')
     dfile = os.open(self.usbdevice, os.O_RDWR)
     fcntl.ioctl(dfile, USBDEVFS_RESET)
     self.log.debug('USBDEVFS_RESET ioctl done')
     os.close(dfile)
     session.delay(2.5)
     self.log.debug('re-opening device...')
     self._io = os.open(self.device, os.O_RDWR)
     try:
         ident = self._query('*IDN?', binary=False, t=0)
         self.log.debug('sensor identification: %s', ident)
         self._execute('FORMAT INTEGER')
         self.doRead()
     except CommunicationError:
         if t == 0:
             raise
         self.doReset(t - 1)
         return
Exemple #11
0
 def _checkAir(self):
     if self._attached_io_ref.read(0) == 1:
         self._attached_io_air.move(1)
         session.delay(self.timedelay)
         if self._attached_io_ref.read(0) == 1:
             return 0
     return 1
Exemple #12
0
 def timeoutAction(self):
     self.log.warning('did not reach target, trying again...')
     # The output sometimes seems not to come on.  Therefore,
     # switch it off manually and try again...
     self._attached_output.start(0)
     session.delay(1)
     self.start(self.target)
Exemple #13
0
 def doReset(self):
     bus = self._attached_bus
     if self.status(0)[0] != status.OK:  # busy or error
         bus.send(self.addr, 33)  # stop
         try:
             # this might take a while, ignore errors
             self._hw_wait()
         except Exception:
             pass
     # remember current state
     actpos = bus.get(self.addr, 130)
     speed = bus.get(self.addr, 128)
     accel = bus.get(self.addr, 129)
     minstep = bus.get(self.addr, 132)
     maxstep = bus.get(self.addr, 131)
     bus.send(self.addr, 31)  # reset card
     session.delay(0.2)
     if self._hwtype != 'single':
         # triple and sixfold cards need a LONG time for resetting
         session.delay(2)
     # update state
     bus.send(self.addr, 41, speed, 3)
     bus.send(self.addr, 42, accel, 3)
     bus.send(self.addr, 45, minstep, 6)
     bus.send(self.addr, 44, maxstep, 6)
     bus.send(self.addr, 43, actpos, 6)
Exemple #14
0
    def _taco_guard_nolog(self, function, *args):
        """Try running the TACO function, and raise a NicosError on exception.

        A more specific NicosError subclass is chosen if appropriate.  For
        example, database-related errors are converted to
        `.CommunicationError`.
        A TacoDevice subclass can add custom error code to exception class
        mappings by using the `.taco_errorcodes` class attribute.

        If the `comtries` parameter is > 1, the call is retried accordingly.
        """
        if not self._dev:
            raise NicosError(self, 'TACO device not initialised')
        self._com_lock.acquire()
        try:
            return function(*args)
        except TACOError as err:
            # for performance reasons, starting the loop and querying
            # self.comtries only triggers in the error case
            if self.comtries > 1 or err == DevErr_RPCTimedOut:
                tries = 2 if err == DevErr_RPCTimedOut and self.comtries == 1 \
                    else self.comtries - 1
                self.log.warning('TACO %s failed, retrying up to %d times',
                                 function.__name__, tries)
                while True:
                    session.delay(self.comdelay)
                    tries -= 1
                    try:
                        return function(*args)
                    except TACOError as err:
                        if tries == 0:
                            break  # and fall through to _raise_taco
            self._raise_taco(err, '%s%r' % (function.__name__, args))
        finally:
            self._com_lock.release()
Exemple #15
0
    def doStart(self, position):
        try:

            if self.doStatus()[0] != status.OK:
                raise NicosError(self, 'filter returned wrong position')

            if position == self.read(0):
                return

            if position == 'in':
                self._attached_io_set.move(1)
            elif position == 'out':
                self._attached_io_set.move(0)
            else:
                # shouldn't happen...
                self.log.info('PG filter: illegal input')
                return

            session.delay(2)

            if self.doStatus()[0] == status.ERROR:
                raise NicosError(self, 'PG filter is not readable, please '
                                 'check device!')
        finally:
            self.log.info('PG filter: %s', self.read(0))
Exemple #16
0
    def _step(self, devicename, pos):
        """Make one step in the changing sequence.

        evaluates the given keyword argument and
        moves the attached_device with the keyname to the value-position.
        Also checks success
        """
        dev = self._adevs[devicename]
        # now log some info
        if pos == 'open':
            self.log.info("Open '%s'", dev.name)
        elif pos == 'closed':
            self.log.info("Close '%s'", dev.name)
        else:
            self.log.info("Move '%s' to '%s' position", dev.name, pos)
        try:
            dev.start(pos)
            if devicename == 'r3':  # R3 does not wait!
                session.delay(2)
            if devicename == 'grip':  # grip does not wait!
                session.delay(2)
            dev.wait()
        except Exception:
            # most probably it is touching the limit switch
            if devicename == 'lift':
                dev._adevs['moveables'][0].motor.stop()
                self.log.info('Limit switch ?')
            else:
                raise
        if dev.read(0) != pos:
            raise PositionError("Device '%s' did not reach its target '%s', "
                                'aborting' % (dev, pos))
Exemple #17
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 #18
0
    def _HW_rawCommand(self, cmd, par=0):
        if cmd not in self._HW_CMDS:
            raise ValueError('Command code %r not supported, check code and '
                             'docu!' % cmd)
        cmd = int(self._HW_CMDS.get(cmd, cmd))

        pswd = 16082008 + ((int(cmd) + int(par)) % 228)
        self.log.debug('Initiate command %d with par %d and pswd %d',
                       cmd, par, pswd)
        self._writeU32(16, int(par))
        self._writeU32(12, int(pswd))
        self._writeU32(14, int(cmd))

        self.log.debug('checking reaction')
        session.delay(0.1)
        for _ in range(10):
            ack = bool(self._HW_readACK())
            nack = bool(self._HW_readNACK())
            self.log.debug('%s %s', ack, nack)
            if ack and not nack:
                self.log.debug('Command accepted')
                return
            elif nack and not ack:
                raise NicosError('Command rejected by Beckhoff')
        raise NicosTimeoutError('Command not recognized by Beckhoff within 1s!')
Exemple #19
0
 def _hw_wait(self, devices):
     loops = 0
     final_exc = None
     devlist = devices[:]  # make a 'real' copy of the list
     while devlist:
         loops += 1
         for dev in devlist[:]:
             try:
                 done = dev.doStatus(0)[0]
             except Exception:
                 dev.log.exception('while waiting')
                 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 _hw_wait()
                 # should not return until everything is either OK or
                 # ERROR
                 devlist.remove(dev)
             if done == status.BUSY:
                 # 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
             devlist.remove(dev)
         if devlist:
             session.delay(self._base_loop_delay)
     if final_exc:
         reraise(*final_exc)
Exemple #20
0
 def doReset(self):
     self._lasterror = None
     try:
         self._attached_bus.send(self.addr, 153)
     except NicosError:
         pass
     else:
         session.delay(0.5)
Exemple #21
0
 def doReference(self):
     bus = self._attached_bus
     bus.send(self.addr, 34)  # always go forward (positive)
     bus.send(self.addr, 47, self.speed, 3)  # reference with normal speed
     # may need to sleep a little here....
     session.delay(0.1)
     self.wait()
     self.doSetPosition(self.refpos)
Exemple #22
0
 def doStart(self, value):
     if abs(self.read(0)) < 10 and self.waittime:
         self.log.warning('Please make sure the Cascade detector '
                          'is supplied with counting gas!  Waiting '
                          'for %d seconds before ramping up the HV.',
                          self.waittime)
         session.delay(self.waittime)
     return Actuator.doStart(self, value)
Exemple #23
0
 def transferSettings(self):
     import epics
     for epicsid, pvs in iteritems(self.pv_values):
         for pvname, pvvalue in pvs:
             fullpvname = '%s:%s_W' % (epicsid, pvname)
             self.log.debug('setting %s = %s' % (fullpvname, pvvalue))
             epics.caput(fullpvname, pvvalue)
     session.delay(2)
Exemple #24
0
 def _writeControlBit(self, bit, value):
     self._busy_until = time.time() + 3
     self.log.debug('_writeControlBit %r, %r', bit, value)
     tmpval = uint16(self._dev.ReadOutputWord(self.address))
     tmpval &= ~(1 << int(bit))
     tmpval |= (int(value) << int(bit))
     self._dev.WriteOutputWord((self.address, uint16(tmpval)))
     session.delay(0.5)  # work around race conditions inside plc....
Exemple #25
0
 def doStart(self, value):
     self.log.info('requested position %d', value)
     what = 'm4077=%d' % value
     self.log.debug('doWritePos what: %s', what)
     res = self._attached_comm.writeLine(what)
     self.log.debug('doWritePos res: %d', res)
     # Better solution would be to take the solution from TOFTOF
     session.delay(.1)  # time is needed to transfer and initiate start
Exemple #26
0
 def doStart(self, target):
     if target == 'open':
         self._attached_open.start(1)
         session.delay(0.01)
         self._attached_open.start(0)
     else:
         self._attached_close.start(1)
         session.delay(0.01)
         self._attached_close.start(0)
Exemple #27
0
 def doStart(self):
     max_pow = 0
     results = []
     for _ in range(5):
         session.delay(0.1)
         val = pvget(self.pv_name)
         max_pow = max(val, max_pow)
         results.append(val)
     self.answer = sum(results) / len(results)
Exemple #28
0
 def _start_measurement(self):
     self.log.debug('starting new FTIR measurement')
     # wait for READY signal - otherwise no measurement is planned
     self._wait_for(READY, 'READY')
     # a \_/ flank is needed to trigger start
     self._attached_trigger_out.start(0)
     session.delay(0.05)
     self._attached_trigger_out.start(1)
     self._wait_for(BUSY, 'BUSY')
Exemple #29
0
 def _wait_for(self, sig, name):
     i = 0
     while self._attached_status_in.read(0) != sig:
         session.delay(0.1)
         i += 1
         if i == 100:
             raise NicosTimeoutError(
                 self, 'timeout waiting for %s '
                 'signal from spectrometer' % name)
Exemple #30
0
 def doStart(self):
     self.log.debug('Integral start')
     timeval = time.time() + self._timeout
     if self.detector not in session.experiment.detlist:
         self._attached_pintimer.start(self._preset)
     while self.status(0)[0] != status.BUSY:
         if time.time() > timeval:
             self.log.warning('Pinstate timeout in start')
             return
         session.delay(0.02)