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
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()]
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)
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)
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)
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')
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')
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
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
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 string = string.strip() STRING = string.upper() while True: if string == 'get_status': self.message('status hw_connected=%s out_load=%g volt_offs=%g, volt_unit=%s' % (self.object['hw_connected'],self.object['out_load'],self.object['volt_offs'],self.object['volt_unit'])) break if STRING == '*IDN?': self.sendCommand('*IDN?', keep=True) break regex = re.compile(r'\:?(OUTP|OUTPUT)\:(LOAD)\?') if re.match(regex, STRING) or string == 'get_out_load': hw.messageAll(':OUTP:LOAD?\n', type='hw', keep=True, source=self.name) break regex = re.compile(r'(\:?(OUTP|OUTPUT)\:(LOAD) (?P<val>(50|INF|MIN|MAX)))') match = re.match(regex, STRING) if match: hw.messageAll(':OUTP:LOAD ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) daemon.log('Output load set to ' + match.group('val')) break regex = re.compile(r'\:?(VOLT|VOLTAGE)\:(OFFS|OFFSET)\?') if re.match(regex, STRING) or string == 'get_volt_offs': hw.messageAll(':VOLT:OFFS?\n', type='hw', keep=True, source=self.name) break regex = re.compile(r'(\:?(VOLT|VOLTAGE)\:(OFFS|OFFSET) (?P<val>(MIN|MAX|0\.\d+?$|2e\-\d?$|2E\-\d?$)))') match = re.match(regex, STRING) if match: hw.messageAll(':VOLT:OFFS ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) daemon.log('Voltage Offset set to' + match.group('val')) break regex = re.compile(r'\:?(VOLT|VOLTAGE)\:(UNIT)\?') if re.match(regex, STRING) or string == 'get_volt_unit': hw.messageAll(':VOLT:UNIT?\n', type='hw', keep=True, source=self.name) break regex = re.compile(r'(\:?(VOLT|VOLTAGE)\:(UNIT) (?P<val>(VPP|VRMS|DBM|DEF)))') match = re.match(regex, STRING) if match: hw.messageAll(':VOLT:UNIT ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) daemon.log('Voltage Unit set to ' + match.group('val')) break regex = re.compile(r'\:?(FUNC|FUNCTION)\:(USER)\?') if re.match(regex, STRING) or string == 'get_func_user': hw.messageAll(':FUNC:USER?\n', type='hw', keep=True, source=self.name) break regex = re.compile(r'(\:?(FUNC|FUNCTION)\:(USER) (?P<val>(SINC|NEG_RAMP|EXP_RISE|EXP_FALL|CARDIAC)))') match = re.match(regex, STRING) if match: hw.messageAll(':FUNC:USER ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) daemon.log('Function user set to ' + match.group('val')) break regex = re.compile(r'\:?(APPL|APPLY)\?') if re.match(regex, STRING) or string == 'get_apply': hw.messageAll(':APPL?\n', type='hw', keep=True, source=self.name) break regex = re.compile(r'(\:?(APPL|APPLY)\:(?P<val0>(USER|SIN|SQU|TRI|RAMP|NOIS|DC)) (?P<val1>(DEF|[1-9]\d*(\.\d+)?)|0(\.\d+)),(?P<val2>(DEF|[1-9]\d*(\.\d+)?)|0(\.\d+))((?P<val3>((,[1-9]\d*(\.\d+)?)|0(\.\d+))?)))') match = re.match(regex, STRING) if match: msgstr = 'APPL:' + match.group('val0') + ' '+ match.group('val1') + ','+ match.group('val2') + match.group('val3') print ('msgstr',msgstr) hw.messageAll(msgstr + '\n', type='hw', keep=False, source=self.name) daemon.log(msgstr) break if string[-1] == '?': print ('unrecog query cmd', string) hw.messageAll(string, type='hw', keep=True, source=self.name) else: hw.messageAll(string, type='hw', keep=False, source=self.name) break
def processMessage(self, string): SimpleProtocol.processMessage(self, string) daemon = self.object['daemon'] id = int(string[1:3], 16) # Process the device reply if string[0] == '?': print "Error reply for command: %s" % (self.commands.get(id, '')) daemon.log('Error reply: ' + self.commands.get(id, ''), 'error') self.commands.pop(id, '') return elif string[0] != '<': print "Wrong reply from controller: %s" % string return body = string[3:] cmd = Command(body) # Process and transform specific fields to be more understandable for key in cmd.kwargs: newkey = key.replace('/', '_') if newkey != key: # Rename the argument key cmd.kwargs[newkey] = cmd.kwargs.pop(key) should_update_status = False if self.commands.get(id, '') == 'SYSTEM': cmd.kwargs['BACKPLANE_TYPE'] = { '0': 'None', '1': 'X12', '2': 'X16' }.get(cmd.kwargs['BACKPLANE_TYPE'], 'unknown') self.object[ 'Nmods'] = 12 if cmd.kwargs['BACKPLANE_TYPE'] == 'X12' else 16 for _ in xrange(1, self.object['Nmods'] + 1): cmd.kwargs['MOD%d_TYPE' % _] = { '0': 'None', '1': 'Driver', '2': 'AD', '3': 'LVBias', '4': 'HVBias', '5': 'Heater', '6': 'Atlas', '7': 'HS', '8': 'HVXBias', '9': 'LVXBias', '10': 'LVDS', '11': 'HeaterX', '12': 'XVBias', '13': 'ADF' }.get(cmd.kwargs['MOD%d_TYPE' % _], 'unknown') should_update_status = True elif self.commands.get(id, '') == 'STATUS': cmd.kwargs['POWER'] = { '0': 'Unknown', '1': 'NotConfigured', '2': 'Off', '3': 'Intermediate', '4': 'On', '5': 'Standby' }.get(cmd.kwargs['POWER'], 'unknown') if cmd.kwargs.has_key('LOG') and int(cmd.kwargs['LOG']) > 0: # We have some unread LOG messages for _ in xrange(int(cmd.kwargs['LOG'])): self.message('FETCHLOG') should_update_status = True elif self.commands.get(id, '') == 'FETCHLOG': # We just fetched some log message, let's send it outwards daemon.log(body, 'message') print "Log:", body elif self.commands.get(id, '') == 'FRAME': should_update_status = True else: print "ARCHON >> %s" % body self.commands.pop(id, '') if should_update_status: self.object['status'].update(cmd.kwargs)
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 string = string.strip() STRING = string.upper() while True: if string == 'get_status': self.message( 'status hw_connected=%s value=%g units=%s timestamp=%g I_range=%g Zero_Check=%s Auto=%s Auto_Ulim=%g Auto_Llim=%g ErrorQ=%i' % (self.object['hw_connected'], self.object['value'], self.object['units'], self.object['timestamp'], self.object['I_range'], self.object['Zero_Check'], self.object['Auto'], self.object['Auto_Ulim'], self.object['Auto_Llim'], obj['ErrorQ'])) break if string == 'reset': daemon.log('Resetting Keithley 6485') self.sendCommand('*RST') break if STRING == '*IDN?': self.sendCommand('*IDN?', keep=True) break if STRING == 'INIT': hw.messageAll('INIT\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'\:?(SYST|SYSTE|SYSTEM)\:(ZCH|ZCHE|ZCHEC|ZCHECK)\:(STAT|STATE)\?' ) if re.match(regex, STRING) or string == 'get_zcheck_state': hw.messageAll(':SYST:ZCH:STAT?\n', type='hw', keep=True, source=self.name) break regex = re.compile( r'(\:?(SYST|SYSTE|SYSTEM)\:(ZCH|ZCHE|ZCHEC|ZCHECK)\:(STAT|STATE)|SET_ZCHECK_STATE) (?P<state>(ON|OFF))' ) match = re.match(regex, STRING) if match: hw.messageAll(':SYST:ZCH:STAT ' + match.group('state') + '\n', type='hw', keep=False, source=self.name) daemon.log('Zero-check state set to ' + match.group('state')) break regex = re.compile( r'(\:?(SYST|SYST|SYSTEM)\:(ZCOR|ZCORR|ZCORRE|ZCORREC|ZCORRECT)\:(ACQ|ACQU|ACQUI|ACQUIR|AQUIRE))' ) match = re.match(regex, STRING) if match: hw.messageAll(':SYST:ZCOR:ACQ\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(SYST|SYST|SYSTEM)\:(ZCOR|ZCORR|ZCORRE|ZCORREC|ZCORRECT)\:(STAT|STATE)|SET_ZCOR_STATE) (?P<state>(ON|OFF))' ) match = re.match(regex, STRING) if match: hw.messageAll(':SYST:ZCOR:STAT' + match.group('state') + '\n', type='hw', keep=False, source=self.name) daemon.log('Zero-correct state set to' + match.group('state')) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE)|SET_CURRENT_RANGE) (?P<val>(AUTO|0\.\d+?$|2e\-\d?$|2E\-\d?$))' ) match = re.match(regex, STRING) if match: if match.group('val') == 'AUTO': hw.messageAll(':CURR:RANG:AUTO ON\n', type='hw', keep=False, source=self.name) daemon.log('Range set to AUTO') break if match.group('val') not in self._allowed_IRange_values: daemon.log('WARNING wrong range value ' + match.group('val')) break hw.messageAll(':CURR:RANG:AUTO OFF\n', type='hw', keep=False, source=self.name) hw.messageAll(':CURR:RANG ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) daemon.log('Range set to ' + match.group('val')) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE)\?)|GET_CURRENT_RANGE$' ) if re.match(regex, STRING): hw.messageAll(':CURR:RANG?\n', type='hw', keep=True, source=self.name) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE):AUTO\?)|GET_CURRENT_RANGE_AUTO' ) if re.match(regex, STRING): hw.messageAll(':CURR:RANG:AUTO?\n', type='hw', keep=True, source=self.name) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE)\:(AUTO)\:(ULIM|ULIMI|ULIMIT)|SET_CURRENT_AUTO_ULIM) (?P<val>(0\.\d+?$|2e\-\d?$|2E\-\d?$))' ) match = re.match(regex, STRING) if match: if match.group('val') not in self._allowed_IRange_values: daemon.log('WARNING wrong range value ' + match.group('val')) break if match.group('val') < obj['Auto_Llim']: daemon.log( 'WARNING the upper limit to be set is bellow the lower limit ' + match.group('val')) break hw.messageAll(':CURR:RANGE:AUTO:ULIM' + match.group('val') + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE)\:(AUTO)\:(LLIM|LLIMI|LLIMIT)|SET_CURRENT_AUTO_LLIM) (?P<val>(0\.\d+?$|2e\-\d?$|2E\-\d?$))' ) match = re.match(regex, STRING) if match: if match.group('val') not in self._allowed_IRange_values: daemon.log('WARNING wrong range value ' + match.group('val')) break if match.group('val') > obj['Auto_Ulim']: daemon.log( 'WARNING the lower limit to be set is above the upper limit ' + match.group('val')) break hw.messageAll(':CURR:RANGE:AUTO:LLIM' + match.group('val') + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE)\:(AUTO)\:(ULIM|ULIMI|ULIMIT)\?|GET_CURRENT_AUTO_ULIM)' ) match = re.match(regex, STRING) if match: hw.messageAll(':CURR:RANGE:AUTO:ULIM?\n', type='hw', keep=True, source=self.name) break regex = re.compile( r'(\:?(CURR|CURRE|CURREN|CURRENT)\:(RANG|RANGE)\:(AUTO)\:(LLIM|LLIMI|LLIMIT)\?|GET_CURRENT_AUTO_LLIM)' ) match = re.match(regex, STRING) if match: hw.messageAll(':CURR:RANGE:AUTO:LLIM?\n', type='hw', keep=True, source=self.name) break regex = re.compile( r'do_zero_check (?P<val>(0$|0\.\d+?$|2e\-\d?$|2E\-\d?$))') match = re.match(regex, string) if match: if match.group('val') == 0: val = 2E-9 else: val = match.group('val') if float( match.group('val')) not in self._allowed_IRange_values: daemon.log('WARNING wrong range value ' + match.group('val')) break hw.messageAll(':SYST:ZCH ON\n', type='hw', keep=False, source=self.name) hw.messageAll(':CURR:RANG ' + val + '\n', type='hw', keep=False, source=self.name) hw.messageAll(':INIT', type='hw', keep=False, source=self.name) hw.messageAll(':SYST:ZCOR:ACQ\n', type='hw', keep=False, source=self.name) hw.messageAll(':SYST:ZCH OFF\n', type='hw', keep=False, source=self.name) hw.messageAll(':SYSR:ZCOR ON\n', type='hw', keep=False, source=self.name) break if string[-1] == '?': print 'unrecog query cmd', string hw.messageAll(string, type='hw', keep=True, source=self.name) else: hw.messageAll(string, type='hw', keep=False, source=self.name) break
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', 'lamp', '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'))) lamp = cmd.get('lamp', obj.get('lamp')) 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 lamp != obj.get('lamp'): self.factory.log('Swithing to '+lamp+' lamp') if hw.set_mirror_position(1, self.lampDict[lamp]) != 0: self.factory.log(hw.GetErrorName(hw.result)) 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)) if string.startswith('init '): tti = string.split()[1] num = -1 if tti == 'turret': num = 1 elif tti == 'filter': num = 3 elif tti == 'mirror': num = 4 if num != -1: hw.initialise_device(num=num) else: self.factory.log('unknown device to init: '+tti, type='info')
def processMessage(self, string): cmd = SimpleProtocol.processMessage(self, string) if cmd is None: return obj = self.object daemon = self.factory hw = obj['hw'] string = string.strip() STRING = string.upper() while True: if string == 'get_status': self.message( 'status hw_connected=%s Current_Limit=%g Voltage=%g CurrentActual=%g VoltageActual=%g Vstatus=%g' % (self.object['hw_connected'], self.object['Current_Limit'], self.object['Voltage'], self.object['CurrentActual'], self.object['VoltageActual'], self.object['Vstatus'])) break if STRING in ['RESET', '*RST']: self.sendCommand('*RST', keep=True) break if STRING in ['IDN', '*IDN?']: self.sendCommand('*IDN?', keep=True) break if STRING in ['CONFIG', 'CONFIG?']: self.sendCommand('CONFIG?', keep=True) break if STRING in ['GET_VOLTAGE', 'V1?']: self.sendCommand('V1?', keep=True) break if STRING in ['GET_VOLTAGEACTUAL', 'V1O?']: self.sendCommand('V1O?', keep=True) break if STRING in ['GET_CURRENTACTUAL', 'I1O?']: self.sendCommand('I1O?', keep=True) break if STRING in ['GET_VOLTAGE_LIMIT', 'OVP1?']: self.sendCommand('OVP1?', keep=True) break if STRING in ['GET_CURRENT_LIMIT', 'I1?']: self.sendCommand('I1?', keep=True) break if STRING in ['STEP_SIZE_VOLTAGE', 'DELTAV1?']: self.sendCommand('DELTAV1?', keep=True) break if STRING in ['GET_CURRENT_TRIP', 'OCP1?']: self.sendCommand('OCP1?', keep=True) break if STRING in ['ENGAGE']: self.sendCommand('OP1 1', keep=False) obj['Vstatus'] = 1 break if STRING in ['DISENGAGE']: self.sendCommand('OP1 0', keep=False) obj['Vstatus'] = 0 break if STRING in ['GET_ON_OFF', 'OP1?']: self.sendCommand('OP1?', keep=True) break regex = re.compile( r'(\:?(V1|SET_VOLTAGE) (?P<val>(\d+\.\d+?$|\d+?$)))') match = re.match(regex, STRING) if match: hw.messageAll('V1 ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(I1|SET_Current_Limit) (?P<val>(\d+\.\d+?$|\d+?$)))') match = re.match(regex, STRING) if match: hw.messageAll('I1 ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(OVP1|SET_VOLTAGE_LIMIT) (?P<val>(\d+\.\d+?$|\d+?$)))') match = re.match(regex, STRING) if match: hw.messageAll('OVP1 ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(DELTAV1|SET_STEP_SIZE_VOLTAGE) (?P<val>(\d+\.\d+?$|\d+?$)))' ) match = re.match(regex, STRING) if match: hw.messageAll('DELTAV1 ' + match.group('val') + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(INCV1|INCREMENT_VOLTAGE) (?P<val>(\d+\.\d+?$|\d+?$)))') match = re.match(regex, STRING) if match: hw.messageAll('INCV1 ' + '\n', type='hw', keep=False, source=self.name) break regex = re.compile( r'(\:?(DECV1|DECREMENT_VOLTAGE) (?P<val>(\d+\.\d+?$|\d+?$)))') match = re.match(regex, STRING) if match: hw.messageAll('DECV1 ' + '\n', type='hw', keep=False, source=self.name) break if STRING[-1] == '?': self.sendCommand(STRING, keep=True) else: self.sendCommand(STRING, keep=False) break
def processMessage(self, string): cmd = SimpleProtocol.processMessage(self, string) if cmd is None: return Sstring = (string.strip('\n')).split(';') for sstring in Sstring: if self._debug: print('received string:', sstring) sstring = sstring.strip(' ').lower() while True: if sstring == 'get_status': self.message( 'status hw_connected={hw_connected} position={position} hw_limit={hw_limit} moving={moving} jogg={jogg} home={home} tracking={tracking} settled={settled} motion_limit_err={motion_limit_err} curr_limit_err={curr_limit_err} channel_enabled={channel_enabled}' .format(**self.object)) break if sstring == 'flash_led': obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOD_IDENTIFY), 'source': self.name, 'get_c': 0 }) break if sstring == 'get_info': obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_HW_REQ_INFO), 'source': self.name, 'get_c': Message.MGMSG_HW_GET_INFO }) break if sstring.startswith('get_hw_status'): obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_REQ_STATUSUPDATE), 'source': self.name, 'get_c': Message.MGMSG_MOT_GET_STATUSUPDATE, 'unit': 'mm' if sstring == 'get_pos_mm' else 'counts' }) break if sstring == 'get_enable_state': obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOD_REQ_CHANENABLESTATE, param1=1), 'source': self.name, 'get_c': Message.MGMSG_MOD_GET_CHANENABLESTATE }) break if sstring.startswith('set_enable_state'): ss = sstring.split(':') assert len(ss) == 2, 'command ' + sstring + ' is not valid' if ss[1] not in ['0', '1']: print('command ' + sstring + ' is not valid') return obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOD_SET_CHANENABLESTATE, param1=1, param2=int(ss[1])), 'source': self.name, 'get_c': 0 }) break if sstring.startswith('get_home_pars'): obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_REQ_HOMEPARAMS, param1=1), 'source': self.name, 'get_c': Message.MGMSG_MOT_GET_HOMEPARAMS, 'unit': 'mm' if sstring == 'get_home_pars_mm' else 'counts' }) break if sstring.startswith('set_home_pars'): ss = sstring.split(',') assert len( ss ) == 5, 'command ' + sstring + ' is not valid ' + str( len(ss)) vals = {} for input_ex in ss[1:]: try: input_ex = input_ex.split(':') if input_ex[0] == 'dir' and input_ex[1] in [ '1', '2' ]: vals[input_ex[0]] = int(input_ex[1]) elif input_ex[0] == 'lim' and input_ex[1] in [ '1', '4' ]: vals[input_ex[0]] = int(input_ex[1]) elif input_ex[0] == 'v': vals[input_ex[0]] = float(input_ex[1]) if sstring.startswith('set_home_pars_mm'): vals[input_ex[0]] *= obj[ 'hw']._velocity_scale elif input_ex[0] == 'offset': vals[input_ex[0]] = float(input_ex[1]) if sstring.startswith('set_home_pars_mm'): vals[input_ex[0]] *= obj[ 'hw']._position_scale except: print('command ' + sstring + ' is not valid') return if {'dir', 'lim', 'v', 'offset'} != vals.keys(): print('command ' + sstring + ' is not valid') params = st.pack('<HHHII', 1, int(vals['dir']), int(vals['lim']), int(vals['v']), int(vals['offset'])) obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_SET_HOMEPARAMS, data=params), 'source': self.name, 'get_c': 0 }) if sstring == 'get_power_pars': obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_REQ_POWERPARAMS, param1=1), 'source': self.name, 'get_c': Message.MGMSG_MOT_GET_POWERPARAMS }) break if sstring.startswith('set_power_pars'): ss = sstring.split(',') assert len( ss ) == 3, 'command ' + sstring + ' is not valid, wrong number of parameters: ' + str( len(ss)) vals = {} for input_ex in ss[1:]: try: input_ex = input_ex.split(':') vals[input_ex[0]] = int(input_ex[1]) except: print( 'command ' + sstring + ' is not valid, parameter error: ', input_ex) return if {'rest_factor', 'move_factor'} != vals.keys(): print( 'command ' + sstring + ' is not valid, parameter missing, pars:', vals.keys()) return params = st.pack('<HHH', 1, int(vals['rest_factor']), int(vals['move_factor'])) obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_SET_POWERPARAMS, data=params), 'source': self.name, 'get_c': 0 }) break if sstring.startswith('get_lim_pars'): obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_REQ_LIMSWITCHPARAMS, param1=1), 'source': self.name, 'get_c': Message.MGMSG_MOT_GET_LIMSWITCHPARAMS, 'unit': 'mm' if sstring == 'get_lim_pars_mm' else 'counts' }) break if sstring.startswith('set_lim_pars'): ss = sstring.split(',') assert len( ss ) == 6, 'command ' + sstring + ' is not valid, wrong number of parameters: ' + str( len(ss)) vals = {} for input_ex in ss[1:]: try: input_ex = input_ex.split(':') if input_ex[0] in [ 'cw_hw_lim', 'ccw_hw_lim' ] and input_ex[1] in ['1', '2', '3']: vals[input_ex[0]] = int(input_ex[1]) if input_ex[0] in ['cw_sw_lim', 'ccw_sw_lim']: vals[input_ex[0]] = int(input_ex[1]) if (sstring == 'set_lim_pars_mm'): vals[input_ex[0]] *= obj[ 'hw']._position_scale if input_ex[0] == 'sw_lim_mode' and input_ex[ 1] in ['1', '2', '3']: vals[input_ex[0]] = int(input_ex[1]) except: print( 'command ' + sstring + ' is not valid, parameter error: ', input_ex) return if { 'cw_hw_lim', 'ccw_hw_lim', 'cw_sw_lim', 'ccw_sw_lim', 'sw_lim_mode' } != vals.keys(): print( 'command ' + sstring + ' is not valid, parameter missing, pars:', vals.keys()) return params = st.pack('<HHHIIH', 1, int(vals['cw_hw_lim']), int(vals['ccw_hw_lim']), int(vals['cw_sw_lim']), int(vals['ccw_sw_lim']), int(vals['sw_lim_mode'])) obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_SET_LIMSWITCHPARAMS, data=params), 'source': self.name, 'get_c': 0, 'unit': 'mm' if sstring == 'get_lim_pars_mm' else 'counts' }) break if sstring.startswith('get_pos'): obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_REQ_POSCOUNTER, param1=1), 'source': self.name, 'get_c': Message.MGMSG_MOT_GET_POSCOUNTER, 'unit': 'mm' if sstring == 'get_pos_mm' else 'counts' }) break if sstring.startswith('get_v_pars'): obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_REQ_VELPARAMS, param1=1), 'source': self.name, 'get_c': Message.MGMSG_MOT_GET_VELPARAMS, 'unit': 'mm' if sstring == 'get_v_pars_mm' else 'counts' }) break if sstring.startswith('set_v_pars'): # sould look like: set_v_pars(_mm),v:value,a:value # the pars order does not matter ss = sstring.split(',') assert len(ss) == 3, 'command ' + sstring + ' is not valid' vals = {} for input_ex in ss[1:]: try: input_ex = input_ex.split(':') vals[input_ex[0]] = float(input_ex[1]) except: print('command ' + sstring + ' is not valid') return if {'v', 'a'} != vals.keys(): print('command ' + sstring + ' is not valid') return if sstring.startswith('set_v_pars_mm'): vals['a'] *= obj['hw']._acceleration_scale vals['v'] *= obj['hw']._velocity_scale if vals['a'] > obj['hw']._max_acceleration: daemon.log( 'requested acc of {} [counts*s^-2] is above the limit of {} [counts*s^-2], using the limit value' .format(vals['a'], obj['hw']._max_acceleration), 'warning') vals['a'] = obj['hw']._max_acceleration if vals['v'] > obj['hw']._max_velocity: daemon.log( 'requested v of {} [counts*s^-1] is above the limit of {} [counts*s^-1], using the limit value' .format(vals['v'], obj['hw']._max_acceleration), 'warning') vals['v'] = obj['hw']._max_velocity params = st.pack('<HIII', 1, 0, int(vals['a']), int(vals['v'])) obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_SET_VELPARAMS, data=params), 'source': self.name, 'get_c': 0 }) break if sstring == 'home': obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_MOVE_HOME, param1=1), 'source': self.name, 'get_c': 0 }) break if sstring.startswith('move_abs'): # sould look like: move_abs(_mm):value ss = sstring.split(':') assert len(ss) == 2, 'command ' + sstring + ' is not valid' apos = 0 try: apos = float(ss[1]) except: print('command ' + sstring + ' is not valid') return if sstring.startswith('move_abs_mm'): apos *= obj['hw']._position_scale if apos < obj['hw']._linear_range[0]: daemon.log( 'requested abs position of {} [counts] is below the limit of {} [counts], using the limit value' .format(apos, obj['hw']._linear_range[0]), 'warning') apos = obj['hw']._linear_range[0] if apos > obj['hw']._linear_range[1]: daemon.log( 'requested abs position of {} [counts] is above the limit of {} [counts], using the limit value' .format(apos, obj['hw']._linear_range[1]), 'warning') apos = obj['hw']._linear_range[1] params = st.pack('<Hi', 1, int(apos)) obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_MOVE_ABSOLUTE, data=params), 'source': self.name, 'get_c': 0 }) break if sstring.startswith('stop'): ss = sstring.split(':') assert len(ss) == 2, 'command ' + sstring + ' is not valid' if ss[1] == 'now': p2 = 0x01 elif ss[1] == 'slow': p2 = 0x02 else: print('command ' + sstring + ' is not valid') break obj['hw'].commands.append({ 'msg': Message(Message.MGMSG_MOT_MOVE_STOP, param1=1, param2=p2), 'source': self.name, 'get_c': 0 }) break break
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
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
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 V1=%g V2=%g V3=%g I1=%g I2=%g I3=%g O1=%i O2=%i O3=%i' % ( self.object['hw_connected'], self.object['V1'], self.object['V2'], self.object['V3'], self.object['I1'], self.object['I2'], self.object['I3'], self.object['O1'], self.object['O2'], self.object['O3'], )) break regex = re.compile(r'(APP|APPLY):(VOLT|VOLTAGE)\?') if re.match(regex, STRING): hw.messageAll(':APP:VOLT?', type='hw', keep=True, source=self.name) break regex = re.compile(r'(APP|APPLY):(CURR|CURRENT)\?') if re.match(regex, STRING): hw.messageAll(':APP:CURR?', type='hw', keep=True, source=self.name) break regex = re.compile(r'(CHAN|CHANNEL):(OUTP|OUTPUT):(ALL)\?') if re.match(regex, STRING): hw.messageAll('CHAN:OUTP:ALL?', type='hw', keep=True, source=self.name) break regex = re.compile(r'(INST|INSTRUMENT):(NSEL|NSELECT)\?') if re.match(regex, STRING): hw.messageAll('INST:NSEL?', type='hw', keep=True, source=self.name) break regex = re.compile( r'(INST|INSTRUMENT):(NSEL|NSELECT) (?P<val>(1|2|3))') match = re.match(regex, STRING) if match: hw.messageAll('INST:NSEL ' + match.group('val'), type='hw', keep=False, 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