Example #1
0
 def __init__(self):
     SimpleProtocol.__init__(self)
     self.commands = [
     ]  # Queue of command sent to the device which will provide replies, each entry is a dict with keys "cmd","source","timeStamp"
     self.name = 'hw'
     self.type = 'hw'
     self.lastAutoRead = datetime.datetime.utcnow()
Example #2
0
 def __init__(self):
     SimpleProtocol.__init__(self)
     self.commands = [
     ]  # Queue of command sent to the device which will provide replies, each entry is a dict with keys "cmd","source","keep", and "sent"
     self.name = 'hw'
     self.type = 'hw'
     self.status_commands = [':APP:VOLT?', ':APP:CURR?', 'CHAN:OUTP:ALL?']
Example #3
0
 def connectionMade(self):
     self.object['hw_connected'] = 1
     self.name = 'hw'
     self.type = 'hw'
     SimpleProtocol.connectionMade(self)
     # make sure the units are Celsius
     self.message('input a,b,c,d:units c;:loop 1:load 50;:loop 2:load 0;')
Example #4
0
    def connectionMade(self):
        SimpleProtocol.connectionMade(self)

        self.object['hw_connected'] = 1
        self.object['status'] = {}

        self.object['state'] = 'idle'

        self.message('SYSTEM')
Example #5
0
 def __init__(self):
     SimpleProtocol.__init__(self)
     self.command_id = 0
     self.commands = []
     self.name = 'hw'
     self.type = 'hw'
     self.next_addr = -1
     self.daemonQs = {}  # queues for GPIB devices commands, the key as the address
     self.gpibAddrList = []  # a list of the active GPIB connection addresses
     self.readBusy = [False,time.time()]
Example #6
0
    def message(self, string):
        if string in ['SYSTEM', 'STATUS', 'FRAME']:
            if string in self.commands.values():
                # Such command is already sent and still without reply
                return

        SimpleProtocol.message(self, '>%02X%s' % (self.command_id, string))
        self.commands[self.command_id] = string
        self.command_id = (self.command_id + 1) % 0x100

        if string not in ['STATUS', 'FRAME', 'SYSTEM']:
            print 'ARCHON << %s' % string
Example #7
0
 def connectionLost(self, reason):
     self.object['hw_connected'] = 0
     self.object['V1'] = np.nan
     self.object['V2'] = np.nan
     self.object['V3'] = np.nan
     self.object['I1'] = np.nan
     self.object['I2'] = np.nan
     self.object['I3'] = np.nan
     self.object['O1'] = -1
     self.object['O2'] = -1
     self.object['O3'] = -1
     SimpleProtocol.connectionLost(self, reason)
Example #8
0
 def message(self, string, keep=False, source='itself'):
     """
     Send the message to the controller. If keep=True, append the command name to
     internal queue so that we may properly recognize the reply
     """
     if keep:
         self.commands.append({'cmd': string,
                               'source': source,
                               'timeStamp': datetime.datetime.utcnow(),
                               'keep': keep})
         SimpleProtocol.message(self, '?$%s' % string)
     else:
         SimpleProtocol.message(self, string)
Example #9
0
 def __init__(self):
     SimpleProtocol.__init__(self)
     self.commands = [
     ]  # Queue of command sent to the device which will provide replies, each entry is a dict with keys "cmd","source"
     self.name = 'hw'
     self.type = 'hw'
     self.status_commands = [
         "input? a,b,c,d;:cont?",
         ":loop 1:err?;rang?;type?;load?;outp?;htrr?;sour?;setp?;ramp?;rate?;pman?;",
         ":loop 2:err?;rang?;type?;load?;outp?;htrr?;sour?;setp?;ramp?;rate?;pman?;",
         ":loop 3:err?;rang?;type?;load?;outp?;htrr?;sour?;setp?;ramp?;rate?;pman?;",
         ":loop 4:err?;rang?;type?;load?;outp?;htrr?;sour?;setp?;ramp?;rate?;pman?;"
     ]
Example #10
0
 def update(self):
     # Request the hardware state from the device
     if len(self.commands):
         SimpleProtocol.message(self, self.commands[0]['cmd'])
         if not self.commands[0]['keep']:
             self.commands.pop(0)
     else:
         for k in self.status_commands:
             self.commands.append({
                 'cmd': k,
                 'source': 'itself',
                 'keep': True
             })
             SimpleProtocol.message(self, self.commands[0]['cmd'])
Example #11
0
 def __init__(self):
     SimpleProtocol.__init__(self)
     self.commands = [
     ]  # Queue of command sent to the device which will provide replies, each entry is a dict with keys "cmd","source","timeStamp"
     self.name = 'hw'
     self.type = 'hw'
     self.lastAutoRead = datetime.datetime.utcnow()
     self.Iranges = {
         '1': '2nA',
         '2': '20nA',
         '3': '200nA',
         '4': '2uA',
         '5': '20uA',
         '6': '200uA',
         '7': '2mA'
     }
Example #12
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        obj = self.object  # Object holding the state
        hw = obj['hw']  # HW factory

        if cmd.name == 'get_status':
            keys = [
                'hw_connected', 'wavelength', 'grating', 'grooves', 'blaze',
                'filter', 'shutter', 'autofilter'
            ]

            self.message('status ' +
                         ' '.join([_ + '=' + str(obj.get(_)) for _ in keys]))

        elif obj['hw_connected']:
            # Accept commands only when HW is connected
            if cmd.name == 'set':
                filter = int(cmd.get('filter', obj.get('filter')))
                shutter = int(cmd.get('shutter', obj.get('shutter')))
                grating = int(cmd.get('grating', obj.get('grating')))
                wavelength = float(cmd.get('wavelength',
                                           obj.get('wavelength')))

                if cmd.has_key('autofilter'):
                    obj['autofilter'] = int(cmd.get('autofilter'))

                if grating != obj.get('grating') or wavelength != obj.get(
                        'wavelength'):
                    self.factory.log("Moving grating %d to wavelength %g" %
                                     (grating, wavelength))

                    if hw.move_to_wavelength(grating, wavelength) != 0:
                        self.factory.log(hw.GetErrorName(hw.result))

                    if obj['autofilter']:
                        filters = [None, 395, 695, 1000, None, None]
                        filter = 1
                        for _, __ in enumerate(filters):
                            if __ and __ < wavelength:
                                filter = _ + 1

                if filter != obj.get('filter'):
                    self.factory.log('Setting filter to %d' % filter)
                    if hw.set_filterwheel_position(obj['hw_filterwheel'],
                                                   filter) != 0:
                        self.factory.log(hw.GetErrorName(hw.result))

                if shutter != obj.get('shutter'):
                    self.factory.log('Setting shutter to %d' % shutter)
                    if (shutter and hw.open_shutter(obj['hw_shutter']) != 0
                        ) or (not shutter
                              and hw.close_shutter(obj['hw_shutter']) != 0):
                        self.factory.log(hw.GetErrorName(hw.result))

            pass
Example #13
0
    def processMessage(self, string):
        if self._debug:
            print ("GPIB >> ", repr(string))

        SimpleProtocol.processMessage(self, string)
        daemon = self.object['daemon']

        # Process the device reply
        if len(self.commands) and self.commands[0] in ['++addr']:
            # We are silently ignoring the results from these commands
            self.commands.pop(0)  # Remove the command from queue
        else:
            for conn in daemon.connections:
                if conn.addr == self.object['current_addr'] and self.object['current_addr'] >= 0:
                    # Send the device reply to the client connection with given address
                    conn.message(string)
        self.readBusy = [False,time.time()]
Example #14
0
    def message(self, string, keep=False, source='self'):
        """
        Send the message to the controller. If keep=True, append the command name to
        internal queue so that we may properly recognize the reply
        """
        self.update_daemonQs()

        if source in self.daemonQs.keys():
            # This is a GPIB connection, add the command to the corresponding queue
            self.daemonQs[source].append({'cmd': string})

            if keep and source != 'itself' and string not in ['++srq']:
                self.daemonQs[source].append({'cmd': '++read eoi'})
        else:
            # Handle non-GPIB messages as usual
            SimpleProtocol.message(self, '%s' % (string))
            if keep:
                self.commands.append(string)
Example #15
0
 def connectionMade(self):
     SimpleProtocol.connectionMade(self)
     self.commands = []
     # We will set this flag when we receive any reply from the device
     self.object['hw_connected'] = 1
     SimpleProtocol.message(self, '*RST')
     SimpleProtocol.message(self, '*IDN?')
Example #16
0
    def update(self):
        print('--------self.commands--------------')
        for cc in self.commands:
            print(cc)
        print('----------------------')
        # first check if device is hw_connected
        if self.object['hw_connected'] == 0:
            # if not connected do not send any commands
            return

        if len(self.commands) and not self.commands[0]['sent']:
            SimpleProtocol.message(self, self.commands[0]['cmd'])
            if not self.commands[0]['keep']:
                self.commands.pop(0)
            else:
                self.commands[0]['sent'] = True
        elif not len(self.commands):
            for k in self.status_commands:
                self.commands.append({
                    'cmd': k,
                    'source': 'itself',
                    'keep': True,
                    'sent': False
                })
Example #17
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        obj = self.object  # Object holding the state
        hw = obj['hw']  # HW factory

        if cmd.name == 'get_status':
            self.message('status hw_connected=%s status=%d pressure=%g' %
                         (self.object['hw_connected'], self.object['status'],
                          self.object['pressure']))
        else:
            if obj['hw_connected']:
                # Pass all other commands directly to hardware
                hw.protocol.message(string)
Example #18
0
    def processMessage(self, string):
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        Sstring = (string.strip('\n')).split(';')
        for sstring in Sstring:
            sstring = sstring.lower()
            payload = None
            while True:
                # managment commands
                if sstring == 'get_status':
                    self.message(
                        'status hw_connected={hw_connected} temp01={temp01} humd01={humd01} temp02={temp02} humd02={humd02} sw01={sw01} sw02={sw02} sw03={sw03} sw04={sw04}'
                        .format(**self.object))
                    break
                if not obj['hw_connected']:
                    break
                queue_frame = obj['hwprotocol'].queue_frame
                source = self.name
                if sstring == 'reset':
                    obj['hwprotocol'].transport_reset()
                    break
                if sstring == 'testcomm':
                    from time import time
                    payload = bytes("hello world {}".format(time()),
                                    encoding='ascii')
                    break
                if sstring in [
                        'get_ardsta', 'get_temp01', 'get_humd01', 'get_temp02',
                        'get_humd02', 'set_sw01on', 'set_sw01of', 'get_sw01st',
                        'set_sw02on', 'set_sw02of', 'get_sw02st', 'set_sw03on',
                        'set_sw03of', 'get_sw03st', 'set_sw04on', 'set_sw04of',
                        'get_sw04st'
                ]:
                    payload = bytes(sstring, encoding='ascii')
                    if sstring in [
                            'set_sw01on', 'set_sw01of', 'set_sw02on',
                            'set_sw02of', 'set_sw03on', 'set_sw03of',
                            'set_sw04on', 'set_sw04of'
                    ]:
                        source = None  # these commands do not expect reply
                    break
                break
            if payload:
                queue_frame(1, payload, source=source)
Example #19
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return
        
        obj = self.object  # Object holding the state
        daemon = self.factory
        hw = obj['hw']  # HW factory

        if cmd.name == 'get_status':
            self.message('status hw_connected=%s current_addr=%d' % (obj['hw_connected'], obj['current_addr']))
        elif cmd.name == 'set_addr':
            self.addr = int(cmd.args[0]) if len(cmd.args) else -1
        elif cmd.name == 'send':
            # TODO: escape all necessary characters in the string
            self.sendCommand(" ".join(cmd.chunks[1:]))
        elif self.addr >= 0:
            # FIXME: we should somehow prevent the commands already processed in superclass from arriving here
            self.sendCommand(string)
Example #20
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        obj = self.object  # Object holding the state
        hw = obj['hw']  # HW factory

        if cmd.name == 'get_status':
            self.message('status hw_connected=%s val1=%s val2=%s val3=%s' %
                         (self.object['hw_connected'], self.object['val1'],
                          self.object['val2'], self.object['val3']))
        elif cmd.name == 'set':
            for varname in ['val1', 'val2', 'val3', 'hw_connected']:
                if cmd.has_key(varname):
                    self.object[varname] = cmd.get(varname)
        else:
            if obj['hw_connected']:
                # Pass all other commands directly to hardware
                hw.messageAll(string, name='hw', type='hw')
Example #21
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        obj = self.object  # Object holding the state
        hw = obj['hw']  # HW factory

        if cmd.name == 'get_status':
            if self._simulator:
                self.message(
                    'status hw_connected=1 status=0 pressure=%g simulator=1' %
                    (np.random.uniform(1.0, 10.0)))
            else:
                self.message('status hw_connected=%s status=%d pressure=%g' %
                             (self.object['hw_connected'],
                              self.object['status'], self.object['pressure']))
        else:
            if obj['hw_connected']:
                # Pass all other commands directly to hardware
                hw.messageAll(string, name='hw', type='hw')
Example #22
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        obj = self.object  # Object holding the state
        daemon = self.factory
        hw = obj['hw']  # HW factory

        if cmd.name == 'get_status':
            self.message(
                'status hw_connected=%s %s' %
                (self.object['hw_connected'], dictToString(obj['status'])))
        elif cmd.name == 'status':
            # Global status message from MONITOR
            obj['global'] = cmd.kwargs
        elif cmd.name in ['start', 'poweron']:
            daemon.log('Powering on')
            self.sendCommand('POWERON')
        elif cmd.name in ['stop', 'poweroff']:
            daemon.log('Powering off')
            self.sendCommand('POWEROFF')
        elif cmd.name == 'clear':
            daemon.log('Clearing configuration')
            self.sendCommand('CLEARCONFIG')
        elif cmd.name == 'apply':
            daemon.log('Applying configuration')
            self.sendCommand('APPLYALL')
        elif cmd.name == 'reboot':
            daemon.log('Initiating reboot', 'warning')
            self.sendCommand('REBOOT')
        elif cmd.name == 'warmboot':
            daemon.log('Initiating warm boot', 'warning')
            self.sendCommand('WARMBOOT')
        else:
            pass
Example #23
0
 def update(self):
     if self._debug:
         print ("Busy flag", self.readBusy)
     if self.readBusy[0]:
         if time.time()-self.readBusy[1]>3:
             SimpleProtocol.message(self, '++read eoi') 
             self.readBusy[1]=time.time()
         return
     self.update_daemonQs()
     if self._debug:
         print ("daemonQs:", self.daemonQs)
     
     last_addr=self.next_addr
     no_commands = True
     for k in range(len(self.gpibAddrList)):
         try:
             d=self.gpibAddrList.index(last_addr) - k - 1
             self.next_addr = self.gpibAddrList[d]
             if self._debug:
                 print ("Found last addr (", self.next_addr, ")")
         except BaseException:
             self.next_addr = self.gpibAddrList[0]
             if self._debug:
                 print ("Last addr not found (perhaps disconnected meanwhile), switching to the first (", self.next_addr, ")")
         if len(self.daemonQs[self.next_addr]):
             if self.object['current_addr'] != self.next_addr:
                 if self._debug:
                     print ("switching to addr (", self.next_addr, ")")
                 SimpleProtocol.message(self, '++addr %i' % self.next_addr)
                 self.object['current_addr'] = self.next_addr
                 #time.sleep(0.1) # we need to wait a bit here to allow the controller to finish changing the addr
             cmd = self.daemonQs[self.next_addr].pop(0)
             no_commands = False
             if cmd['cmd'] in ['++read eoi', '++addr', '++srq']:
                 self.readBusy = [True,time.time()]
             SimpleProtocol.message(self, cmd['cmd'])  
             break
     if no_commands and (time.time()-self.readBusy[1])>1.:
         if self._debug:
             print ("There is either no GPIB connections, or nothing to do for them, doing ++addr to keep the connection alive")
         self.message('++addr', keep=True)
         self.readBusy = [True,time.time()]
Example #24
0
    def processMessage(self, string):
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        Sstring = (string.strip('\n')).split(';')
        for sstring in Sstring:
            sstring = sstring.lower()
            while True:
                # managment commands
                if sstring == 'get_status':
                    self.message(
                        'status hw_connected={hw_connected} position={position} uposition={uposition} encposition={encposition} speed={speed} uspeed={uspeed} accel={accel} decel={decel} anti_play_speed={anti_play_speed} uanti_play_speed={uanti_play_speed}'
                        .format(**self.object))
                    break
                if sstring == 'timeout':
                    self.factory.log(
                        'command timeout - removing command from list and flushing buffer'
                    )
                    hw._buffer = b''  # empty buffer after timeout
                    hw.commands.pop(0)
                    break
                if not obj['hw_connected']:
                    break
                Imessage = obj['hw'].protocol.Imessage
                if string == 'sync':
                    # sync after failed comand
                    Imessage(bytearray(64), nb=64, source=self.name)
                    break

                # general query command (xxxx comands from manual)(for specifically implemented comands see below)
                ss = sstring.split('<')
                if len(ss) == 2 and len(ss[1]) == 4:
                    Imessage(ss[1], nb=int(ss[0]), source=self.name)
                    daemon.log('command ', sstring)
                    break
                elif len(ss) > 1:
                    daemon.log(
                        'unable to parse command, format sould be "nb<xxxx" insted of: '
                        + sstring, 'error')
                    break

                # human readable version for the most useful comands
                if sstring == 'get_device_info':
                    # get some device info (model, etc.)
                    Imessage('gsti', nb=70, source=self.name)
                    break
                if sstring == 'get_move_pars':
                    # get movement parameters
                    Imessage('gmov', nb=30, source=self.name)
                    break
                if sstring == 'get_position':
                    # get movement parameters
                    Imessage('gpos', nb=26, source=self.name)
                    break
                if sstring.startswith('set_move_pars'):
                    # set movement parameters, examples:
                    # set_move_pars speed:2000 uspeed:0 accel:2000 decel:5000 anti_play_speed:2000 uanti_play_speed:0
                    # set_move_pars 2000 0 2000 5000 2000 0
                    pars_o = [[4, 'speed'], [1, 'uspeed'], [2, 'accel'],
                              [2, 'decel'], [4, 'anti_play_speed'],
                              [1, 'uanti_play_speed']]
                    if self.parsePars('smov', pars_o,
                                      sstring.split(' ')[1:], 10):
                        daemon.log('Setting movement parameters to ', sstring)
                        break
                if sstring.startswith('move_in_direction'):
                    # set movement parameters
                    pars_o = [[4, 'dpos'], [2, 'udpos']]
                    if self.parsePars('movr', pars_o,
                                      sstring.split(' ')[1:], 6):
                        daemon.log('move ', sstring)
                        break
                if sstring.startswith('move'):
                    # set movement parameters
                    pars_o = [[4, 'pos'], [2, 'upos']]
                    if self.parsePars('move', pars_o,
                                      sstring.split(' ')[1:], 6):
                        daemon.log('move ', sstring)
                        break
                if sstring == 'set_zero':
                    # set current position as zero
                    Imessage('zero', nb=4, source=self.name)
                    daemon.log('reset zero')
                    break
                # general set command (xxxx comands from manual) (for specifically implemented comands see below)
                # command example: smov 4:2000 1:0 2:2000 2:5000 4:2000 1:0 10:r
                # for these commands one needs to specity the number of bytes given value occupies:
                # nbytes1:value1 nbytes2:value2 nreserved:r
                #
                ss = sstring.split(' ')
                if all(':' in sss for sss in ss[1:]) and all(
                        nnn.split(':')[0].isdigit() for nnn in ss[1:]):
                    cmd = ss[0]
                    ss = ss[1:]
                    rbs = 0
                    if len(ss) > 1 and ss[-1].split(':')[1] == 'r':
                        rbs = int(ss[-1].split(':')[0])
                        ss = ss[:-1]
                    pars = [sss.split(':') for sss in ss]
                    pars = list(map(lambda x: [int(x[0]), x[1]], pars))
                    mstr = self.mbytes(cmd, pars, rbs)
                    if mstr:
                        Imessage(mstr, nb=4, source=self.name)
                        daemon.log('command ', sstring)
                    break
                print('command', sstring, 'not implemented!')
                break
Example #25
0
 def connectionLost(self, reason):
     self.object['hw_connected'] = 0
     SimpleProtocol.connectionLost(self, reason)
Example #26
0
 def connectionMade(self):
     SimpleProtocol.connectionMade(self)
     self.commands = []
     # We will set this flag when we receive any reply from the device
     self.object['hw_connected'] = 0
     SimpleProtocol.message(self, 'set_addr %d' % self.object['addr'])
     SimpleProtocol.message(self, 'L0X')
     SimpleProtocol.message(self, 'K0X')
     SimpleProtocol.message(self, '?$U0X')  # enable EOI and holdoff
     SimpleProtocol.message(self, 'R0X')  # set autorange
Example #27
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command
        # object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return
        obj = self.object  # Object holding the state
        daemon = self.factory
        hw = obj['hw']  # HW factory

        while True:
            if cmd.name == 'get_status':
                self.message(
                    'status hw_connected=%s Current=%g Voltage=%g zero_check=%s zero_check_performed=%s V_source=%s I_auto_range=%s I_range=%s V_range=%s I_limit=%s'
                    % (self.object['hw_connected'], self.object['Current'],
                       self.object['Voltage'], self.object['zero_check'],
                       self.object['zero_check_performed'],
                       self.object['V_source'], self.object['I_auto_range'],
                       self.object['I_range'], self.object['V_range'],
                       self.object['I_limit']))
                if self.object['I_limit'] != '-' and self.object[
                        'zero_check_performed'] == 'no':  # i.e. comunication established , getting some statusupdates
                    cmd.name = 'zero_check'  # forse a zero check
                    self.object['zero_check_performed'] = 'auto_sheduled'
                else:
                    break
            if cmd.name == 'reset':
                daemon.log('Resetting Keithley 487')
                self.sendCommand('L0X')
                self.sendCommand('K0X')  # enable EOI and holdoff
                break
            if cmd.name == 'idn':
                self.sendCommand('U2X', keep=True)
                break
            if cmd.name == 'get_voltage':
                self.sendCommand('U8X', keep=True)
                break
            if cmd.name.split(',')[0] == 'set_voltage':
                # the format is set_voltage,val1,val2,val3
                # val1 -> voltage in V;
                # val2 -> range, 0 is 50V, 1 is 500V;
                # val3 -> curr. limit, 0 is 20 uA, 1 is 2 mA
                volt_pars = cmd.name.split(',')
                if len(volt_pars) != 4:
                    raise ValueError(
                        'KEITHLEY487: unable to parse voltage command')
                    return
                if volt_pars[2] == '0':
                    vlim = 50
                elif volt_pars[2] == '1':
                    vlim = 500
                else:
                    raise ValueError(
                        'KEITHLEY487: unable to parse voltage range')
                    return
                if abs(float(volt_pars[1])) > vlim:
                    raise ValueError(
                        'KEITHLEY487: requested voltage out of range')
                    return
                if volt_pars[3] not in ['0', '1']:
                    raise ValueError(
                        'KEITHLEY487: unable to parse current limit')
                    return
                self.sendCommand('V' + volt_pars[1] + ',' + volt_pars[2] +
                                 ',' + volt_pars[3],
                                 keep=False)
                break
            if cmd.name == 'get_current':
                self.sendCommand('B0X', keep=True)
                break
            if cmd.name == 'zero_check':
                if self.object['zero_check_performed'] == 'auto_sheduled':
                    self.object['zero_check_performed'] = 'auto_performing'
                else:
                    self.object['zero_check_performed'] = 'manual_performing'
                self.sendCommand('C1X', keep=False)
                for curr_range in range(1, 8):
                    self.sendCommand('R' + str(curr_range) + 'X', keep=False)
                    self.sendCommand('C2X', keep=False)
                    # this requests a read value, not so important which one, but makes it wait for the command to finish
                    self.sendCommand('++srq', keep=True)
                self.sendCommand('C0X', keep=False)
                self.sendCommand('R0X', keep=False)
                break
            if cmd.name == 'set_v_on':
                self.sendCommand('O1X', keep=False)
                break
            if cmd.name == 'set_v_off':
                self.sendCommand('O0X', keep=False)
                break
            # We need to recognize query cmd somehow - adding \'?\' to those commands, although the command set for K487 has no such thing
            if cmd.name[-1] == '?':
                self.sendCommand(cmd.name.rstrip('?'), keep=True)
            else:
                self.sendCommand(cmd.name, keep=False)
            if self._debug:
                print 'sending unrecognized command', cmd.name.rstrip('?')
                if cmd.name[-1] == '?':
                    print 'command recognize as query command'
            break
Example #28
0
    def processMessage(self, string):
        # It will handle some generic messages and return pre-parsed Command object
        cmd = SimpleProtocol.processMessage(self, string)
        if cmd is None:
            return

        obj = self.object  # Object holding the state
        hw = obj['hw']  # HW factory
        string = string.strip()
        STRING = string.upper()
        while True:
            if cmd.name == 'get_status':
                self.message(
                    'status hw_connected=%s status=%s temperatureA=%g temperatureB=%g temperatureC=%g temperatureD=%g control=%s\
                            htr_status1=%s range1=%s ctrl_type1=%s pwr_set1=%g pwr_actual1=%g load1=%g source1=%s set_point1=%g ramp1=%s rate1=%g pwr_man1=%s\
                            htr_status2=%s range2=%s ctrl_type2=%s pwr_set2=%g pwr_actual2=%g load2=%g source2=%s set_point2=%g ramp2=%s rate2=%g pwr_man2=%s\
                            htr_status3=%s range3=%s ctrl_type3=%s pwr_set3=%s pwr_actual3=%s load3=%s source3=%s set_point3=%g ramp3=%s rate3=%g pwr_man3=%s\
                            htr_status4=%s range4=%s ctrl_type4=%s pwr_set4=%s pwr_actual4=%s load4=%s source4=%s set_point4=%g ramp4=%s rate4=%g pwr_man4=%s'
                    % (
                        self.object['hw_connected'],
                        self.object['status'],
                        self.object['temperatureA'],
                        self.object['temperatureB'],
                        self.object['temperatureC'],
                        self.object['temperatureD'],
                        self.object['control'],
                        self.object['htr_status1'],
                        self.object['range1'],
                        self.object['ctrl_type1'],
                        self.object['pwr_set1'],
                        self.object['pwr_actual1'],
                        self.object['load1'],
                        self.object['source1'],
                        self.object['set_point1'],
                        self.object['ramp1'],
                        self.object['rate1'],
                        self.object['pwr_man1'],
                        self.object['htr_status2'],
                        self.object['range2'],
                        self.object['ctrl_type2'],
                        self.object['pwr_set2'],
                        self.object['pwr_actual2'],
                        self.object['load2'],
                        self.object['source2'],
                        self.object['set_point2'],
                        self.object['ramp2'],
                        self.object['rate2'],
                        self.object['pwr_man2'],
                        self.object['htr_status3'],
                        self.object['range3'],
                        self.object['ctrl_type3'],
                        self.object['pwr_set3'],
                        self.object['pwr_actual3'],
                        self.object['load3'],
                        self.object['source3'],
                        self.object['set_point3'],
                        self.object['ramp3'],
                        self.object['rate3'],
                        self.object['pwr_man3'],
                        self.object['htr_status4'],
                        self.object['range4'],
                        self.object['ctrl_type4'],
                        self.object['pwr_set4'],
                        self.object['pwr_actual4'],
                        self.object['load4'],
                        self.object['source4'],
                        self.object['set_point4'],
                        self.object['ramp4'],
                        self.object['rate4'],
                        self.object['pwr_man4'],
                    ))
                break
            regex = re.compile(r'(CONT|CONTR|CONTRO|CONTROL)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            if STRING == 'STOP':
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'(CONT|CONTR|CONTRO|CONTROL)')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            if STRING == '*OPC?':
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            if STRING == '*IDN?':
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(SOUR|SOURC|SOURCE)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(SOUR|SOURC|SOURCE) [A-D]')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(RANG|RANGE)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(r'LOOP 1:(RANG|RANGE) (HI|MID|LOW)')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP 2:(RANG|RANGE) (HI|LOW)')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [3-4]:(RANG|RANGE) (5V|10V)')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:([PID]GA|[PID]GAI|[PID]GAIN)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:([PID]GA|[PID]GAI|[PID]GAIN) (\d+?)?\.?(\d+?$)?$')
            if re.match(regex, STRING):
                if float(STRING.split()[-1]) < 0 or float(
                        STRING.split()[-1]) > 1000:
                    daemon.log('WARNING value out of range: ' + string +
                               ' from connection ' + self.name)
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(SETP|SETPT)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(SETP|SETPT) -?(\d+?)?\.?(\d+?$)?$')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(TYP|TYPE)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-2]:(TYP|TYPE) (OFF|PID|MAN|TABLE|RAMPP)')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(
                r'LOOP [3-4]:(TYP|TYPE) (OFF|PID|MAN|TABLE|RAMPP|SCALE)')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(MAXP|MAXPW|MAXPWR)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(MAXP|MAXPW|MAXPWR) (\d+?)?\.?(\d+?$)?$')
            if re.match(regex, STRING):
                if float(STRING.split()[-1]) < 0 or float(
                        STRING.split()[-1]) > 100:
                    daemon.log('WARNING value out of range: ' + string +
                               ' from connection ' + self.name)
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(PMAN|PMANU|PMANUA|PMANUAL)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(PMAN|PMANU|PMANUA|PMANUAL) ?(\d+?)?\.?(\d+?$)?$')
            if re.match(regex, STRING):
                if float(STRING.split()[-1]) < 0 or float(
                        STRING.split()[-1]) > 100:
                    daemon.log('WARNING value out of range: ' + string +
                               ' from connection ' + self.name)
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:RAMP\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(RAT|RATE) ?(\d+?)?\.?(\d+?$)?$')
            if re.match(regex, STRING):
                if float(STRING.split()[-1]) < 0 or float(
                        STRING.split()[-1]) > 100:
                    daemon.log('WARNING value out of range: ' + string +
                               ' from connection ' + self.name)
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(r'LOOP [1-4]:(RAT|RATE)\?')
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(STAR|START|EXIT|SAVE)'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(MOD|MODE)\?'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(MOD|MODE) (P--|PI-|PID)'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(DELT|DELTA|DELTAP)\?'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(DELT|DELTA|DELTAP) ?(\d+?)?\.?(\d+?$)?$'
            )
            if re.match(regex, STRING):
                if float(STRING.split()[-1]) < 0 or float(
                        STRING.split()[-1]) > 100:
                    daemon.log('WARNING value out of range: ' + string +
                               ' from connection ' + self.name)
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(TIM|TIME|TIMEO|TIMEOU|TIMEOUT)\?'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(TIM|TIME|TIMEO|TIMEOU|TIMEOUT) ?(\d+?)?\.?(\d+?$)?$'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=False, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):([PID]GA|[PID]GAI|[PID]GAIN)\?'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break
            regex = re.compile(
                r'LOOP [1-4]:(AUT|AUTO|AUTOT|AUTOTU|AUTOTUN|AUTOTUNE):(STAT|STATU|STATUS)\?'
            )
            if re.match(regex, STRING):
                hw.messageAll(string, type='hw', keep=True, source=self.name)
                break

            if STRING[-1] == '?':
                hw.messageAll(string, type='hw', keep=True, source=self.name)
            else:
                hw.messageAll(string, type='hw', keep=False, source=self.name)
            break
Example #29
0
 def connectionMade(self):
     SimpleProtocol.connectionMade(self)
     self.object['hw_connected'] = 1
     # We are resetting it to be sure that we have proper address later
     self.object['current_addr'] = -1
     self.message('++auto 0')
Example #30
0
 def __init__(self):
     SimpleProtocol.__init__(self)
     self.addr = -1