def run(self): logger.info("Running FetchWaveformCommand") waveform = self.instrument.fetch_waveform(self.channels) waveform['instrument_type'] = self._get_instrument_type() self.response = self.save_to_file(waveform) logger.info("FetchWaveformCommand response: {}".format(self.response)) return self.response
def _write_trace_dict(self, filename=''): if filename == '': filename = 'full-trace-{}.json'.format(self.result_id) self.trace_file = os.path.join(settings.DATADIR, filename) logger.info("Writing full trace to file: {}".format(self.trace_file)) with open(self.trace_file, 'w') as f: f.write(json.dumps(self.trace_dict))
def run(self): """Runs the Fetch Screenshot Command Summary: Fetches the screenshot and writes it to file """ scn = None try: scn = self.instrument.fetch_screenshot() except NotInitializedException as e: logger.warning("instrument not initialized for screenshot") except IOError as e: logger.warning(e) except OSError as e: logger.warning(e) except Exception as e: logger.error("Unexpected error: {}".format(e), exc_info=True) if scn: response = self.save_to_file(scn) else: response = "Unable to fetch screenshot!" logger.warning(response) self.response = response logger.info("FetchScreenshotCommand response: {}".format(response)) return self.response
def test(): manf = 'rohde&schwarz' model = 'hmc8042' logger.info("Testing InstrumentAnalyzer manufacturer " "and model lookup") response = InstrumentAnalyzer()._manf_model_driver_lookup(manf, model) print("response: {}".format(response)) # because rohde&schwarze is not in the InstrumentAnalyzer instr_dict, # we expect the base Instrument class assert response == base.Instrument
def _log_upload_response(self, response): if response and response.status_code == 200: logger.info("File upload succeeded!") else: logger.warning("File upload failed") response_text = None if hasattr(response, 'text'): response_text = response.text if not response_text: logger.warning("No response text to log") else: logger.warning("Non 200 response {}".format(response_text))
def https_request(self, url, data={}, params={}, headers={}, kind='get'): """Makes https requests Summary: Tries to make a https request and logs exceptions. Will retry the Parameters: url: the target url data: a dictionary payload for POST or PUT requests params: a dictionary of params for GET or DEL requests headers: request headers, these will update the base headers that are already assigned by get_default_headers kind: the flavor of the request (GET, POST, etc.) Returs: a requests module response object """ hdrs = self.get_default_headers() hdrs.update(headers) response = None try: if data: response = self.request_dict[kind](url, data=data, headers=hdrs) else: response = self.request_dict[kind](url, params=params, headers=hdrs) except ssl.SSLError: logger.warning("SSLError!", exc_info=True) logger.info("Retrying request to {}".format(url)) response = self._retry_request(url, kind, data, params, headers) except Exception as e: logger.warning("Unexpected request exc: {}".format(e)) logger.debug("The request exception info:", exc_info=True) if not response: logger.warning("No response from {}".format(url)) elif response.status_code in [401, 403]: # refresh headers and try again hdrs = self.get_default_headers(refresh=True) self.session.headers.update(hdrs) response = self._retry_request(url, kind, data, params, headers) elif response.status_code != 200: self._log_http_err_response(response, data, params) # reset the headers to default self.session.headers = self.get_default_headers() return response
def run(self): if self.method == 'ask': try: self.response = self.instrument.ask( self.command).rstrip('\r\n') except UnicodeDecodeError as e: msg = "utf8' codec can't decode" logger.info("Request for binary data detected") if msg in str(e): self.response = self.instrument.ask_raw( self.command).rstrip('\r\n') else: self.response = self.instrument.write(self.command) logger.info("SCPICommand: {}; Response: {}".format( self.command, self.response)) return self.response
def _manf_model_driver_lookup(self, manf, model): """Looks up the instrument driver class to use Parameters: manf: string with the manufacturer name model: string with the model name Returns: a class that most closely matches the manf and model args that are passed. At the very least this will be an Instrument class, though it could also be a more precise match like a RigolDS2000. This will just return the instrument class, not an instance, so the class will still need to be instantiated before commands can be passed to the real instrument. """ manf = manf.lower() model = model.lower() i_key = manf + '_' + model instr_dict = { 'agilent': AgilentInstrument, 'rigol': RigolInstrument, 'rigol technologies': RigolInstrument, 'rigol_ds2000': RigolDS2000, 'tektronix': TektronixInstrument, 'tektronix_dpo5000': TektronixDPO5000, } while i_key not in instr_dict: i_key = i_key[0:len(i_key) - 1] if i_key == '': break # check for most specific the manf and model match first if i_key in instr_dict: return instr_dict[i_key] # else check for at least a manufacter match for next best elif manf in instr_dict: return instr_dict[manf] # else by default just return an Instrument class else: logger.info("Using default Instrument class. " "Only basic SCPI command strings are supported.") return base.Instrument
def run(self): for i in range(self.maxcount): for command in self.commands: try: response = command.run() except TimeoutError: response = "G1Loop: '{}' timed out!".format(command) logger.warning(response) except Exception as e: response = ("G1Loop: '{}' encountered an unexpected " "exception: {};".format(command, e)) logger.warning(response) self.responses.append(response) if self.break_on is not None and response == self.break_on: # Note: will break from the outer range() loop also logger.info( "Received response {}; Breaking from loop".format( response)) return
def _open_instrument(self, cmdstr, retry=True): """Opens connection with the Instrument""" addr = cmdstr.upper().split('G1:OPEN:')[-1] logger.info("Initializing instrument at: {}".format(addr)) try: raw_instr = Instrument(addr) except socket.error as serr: if serr.errno != errno.ECONNREFUSED: raise serr # handle connection refused if retry: return self._open_instrument(addr, retry=False) else: raise serr ianalyzer = instrument_drivers.InstrumentAnalyzer() self.instrument = ianalyzer.open_instrument(raw_instr) if not self.instrument: raise InstrumentConnectionError else: return self.instrument
def _create_waveform_result(self): """Creates a waveform result on the server""" dt_str = datetime.datetime.now().isoformat() waveform_id = 'waveform-' + dt_str.split(',')[0] if 'instrument_type' in self.trace_dict: instrument_type = self.trace_dict.pop('instrument_type') else: instrument_type = 'sample_instrument_type' data = { 'command_id': waveform_id, 'config_name': waveform_id, 'instrument_type': instrument_type, 'kind': 'Result_Summary', 'upload_kind': 'Waveform', 'info': {}, 'waveform': self.trace_dict, } # assuming these are set in settings them # data['instrument_type'] = settings.INSTRUMENT_TYPE, # data['device_under_test'] = settings.DUT r_url = BASE_URL + '/results' json_data = json.dumps(data, ensure_ascii=True) response = self.requester.https_post(r_url, data=json_data) result_id = '' if not response: return logger.info("Request to {} response.status_code: {}".format( r_url, response.status_code)) try: result_id = json.loads(response.text)['result']['id'] except ValueError: logger.warning("ValueError in _create_waveform_results") logger.info("response text: {}".format(response.text)) except KeyError: logger.warning("KeyError in _create_waveform_results") except Exception as e: logger.warning("Unexpected error: {}".format(e), exc_info=True) else: logger.info( "Result created successfully with result_id: {}".format( result_id)) rid_url = r_url + '/{}'.format(result_id) logger.info("You can view the result at: {}".format(rid_url)) self.trace_dict['result_id'] = result_id return result_id
def run(self): """Posts the screenshot file to the server Summary: Transmits the screenshot file with a file_key to look up the file at a later date. The file_key is set with date and time to the second, e.g. "screenshot-2019-08-14T15:50:43" If this was successful a result_id is generated and will be logged. """ transmitter = FileTransmitter(category='fetch_screenshot') dt_str = datetime.datetime.now().isoformat() file_key = 'screenshot-' + dt_str.split(',')[0] logger.info("Using file_key: " + file_key) response = transmitter.transmit(SCREENSHOT_FILE, file_key=file_key) result_id = self._handle_response(response) if result_id: logger.info("Result ID for screenshot: {}".format(result_id)) rid_url = BASE_URL + '/results/{}'.format(result_id) logger.info("You can view the result at: {}".format(rid_url)) else: logger.warning("No Result ID from waveform upload")
def __init__(self, commands): script = [str(command) for command in commands] logger.info("building G1Script: {}".format(script)) self.commands = commands