idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
16,500 | def parse_device_list ( device_list_str , key ) : clean_lines = new_str ( device_list_str , 'utf-8' ) . strip ( ) . split ( '\n' ) results = [ ] for line in clean_lines : tokens = line . strip ( ) . split ( '\t' ) if len ( tokens ) == 2 and tokens [ 1 ] == key : results . append ( tokens [ 0 ] ) return results | Parses a byte string representing a list of devices . |
16,501 | def list_adb_devices_by_usb_id ( ) : out = adb . AdbProxy ( ) . devices ( [ '-l' ] ) clean_lines = new_str ( out , 'utf-8' ) . strip ( ) . split ( '\n' ) results = [ ] for line in clean_lines : tokens = line . strip ( ) . split ( ) if len ( tokens ) > 2 and tokens [ 1 ] == 'device' : results . append ( tokens [ 2 ] ) return results | List the usb id of all android devices connected to the computer that are detected by adb . |
16,502 | def get_instances ( serials ) : results = [ ] for s in serials : results . append ( AndroidDevice ( s ) ) return results | Create AndroidDevice instances from a list of serials . |
16,503 | def get_instances_with_configs ( configs ) : results = [ ] for c in configs : try : serial = c . pop ( 'serial' ) except KeyError : raise Error ( 'Required value "serial" is missing in AndroidDevice config %s.' % c ) is_required = c . get ( KEY_DEVICE_REQUIRED , True ) try : ad = AndroidDevice ( serial ) ad . load_config ( c ) except Exception : if is_required : raise ad . log . exception ( 'Skipping this optional device due to error.' ) continue results . append ( ad ) return results | Create AndroidDevice instances from a list of dict configs . |
16,504 | def get_all_instances ( include_fastboot = False ) : if include_fastboot : serial_list = list_adb_devices ( ) + list_fastboot_devices ( ) return get_instances ( serial_list ) return get_instances ( list_adb_devices ( ) ) | Create AndroidDevice instances for all attached android devices . |
16,505 | def filter_devices ( ads , func ) : results = [ ] for ad in ads : if func ( ad ) : results . append ( ad ) return results | Finds the AndroidDevice instances from a list that match certain conditions . |
16,506 | def get_devices ( ads , ** kwargs ) : def _get_device_filter ( ad ) : for k , v in kwargs . items ( ) : if not hasattr ( ad , k ) : return False elif getattr ( ad , k ) != v : return False return True filtered = filter_devices ( ads , _get_device_filter ) if not filtered : raise Error ( 'Could not find a target device that matches condition: %s.' % kwargs ) else : return filtered | Finds a list of AndroidDevice instance from a list that has specific attributes of certain values . |
16,507 | def get_device ( ads , ** kwargs ) : filtered = get_devices ( ads , ** kwargs ) if len ( filtered ) == 1 : return filtered [ 0 ] else : serials = [ ad . serial for ad in filtered ] raise Error ( 'More than one device matched: %s' % serials ) | Finds a unique AndroidDevice instance from a list that has specific attributes of certain values . |
16,508 | def take_bug_reports ( ads , test_name , begin_time , destination = None ) : begin_time = mobly_logger . normalize_log_line_timestamp ( str ( begin_time ) ) def take_br ( test_name , begin_time , ad , destination ) : ad . take_bug_report ( test_name , begin_time , destination = destination ) args = [ ( test_name , begin_time , ad , destination ) for ad in ads ] utils . concurrent_exec ( take_br , args ) | Takes bug reports on a list of android devices . |
16,509 | def _normalized_serial ( self ) : if self . _serial is None : return None normalized_serial = self . _serial . replace ( ' ' , '_' ) normalized_serial = normalized_serial . replace ( ':' , '-' ) return normalized_serial | Normalized serial name for usage in log filename . |
16,510 | def device_info ( self ) : info = { 'serial' : self . serial , 'model' : self . model , 'build_info' : self . build_info , 'user_added_info' : self . _user_added_device_info } return info | Information to be pulled into controller info . |
16,511 | def debug_tag ( self , tag ) : self . log . info ( 'Logging debug tag set to "%s"' , tag ) self . _debug_tag = tag self . log . extra [ 'tag' ] = tag | Setter for the debug tag . |
16,512 | def log_path ( self , new_path ) : if self . has_active_service : raise DeviceError ( self , 'Cannot change `log_path` when there is service running.' ) old_path = self . _log_path if new_path == old_path : return if os . listdir ( new_path ) : raise DeviceError ( self , 'Logs already exist at %s, cannot override.' % new_path ) if os . path . exists ( old_path ) : shutil . rmtree ( new_path , ignore_errors = True ) shutil . copytree ( old_path , new_path ) shutil . rmtree ( old_path , ignore_errors = True ) self . _log_path = new_path | Setter for log_path use with caution . |
16,513 | def update_serial ( self , new_serial ) : new_serial = str ( new_serial ) if self . has_active_service : raise DeviceError ( self , 'Cannot change device serial number when there is service running.' ) if self . _debug_tag == self . serial : self . _debug_tag = new_serial self . _serial = new_serial self . adb . serial = new_serial self . fastboot . serial = new_serial | Updates the serial number of a device . |
16,514 | def handle_reboot ( self ) : self . services . stop_all ( ) try : yield finally : self . wait_for_boot_completion ( ) if self . is_rootable : self . root_adb ( ) self . services . start_all ( ) | Properly manage the service life cycle when the device needs to temporarily disconnect . |
16,515 | def build_info ( self ) : if self . is_bootloader : self . log . error ( 'Device is in fastboot mode, could not get build ' 'info.' ) return info = { } info [ 'build_id' ] = self . adb . getprop ( 'ro.build.id' ) info [ 'build_type' ] = self . adb . getprop ( 'ro.build.type' ) return info | Get the build info of this Android device including build id and build type . |
16,516 | def is_adb_root ( self ) : try : return '0' == self . adb . shell ( 'id -u' ) . decode ( 'utf-8' ) . strip ( ) except adb . AdbError : time . sleep ( 0.2 ) return '0' == self . adb . shell ( 'id -u' ) . decode ( 'utf-8' ) . strip ( ) | True if adb is running as root for this device . |
16,517 | def model ( self ) : if self . is_bootloader : out = self . fastboot . getvar ( 'product' ) . strip ( ) lines = out . decode ( 'utf-8' ) . split ( '\n' , 1 ) if lines : tokens = lines [ 0 ] . split ( ' ' ) if len ( tokens ) > 1 : return tokens [ 1 ] . lower ( ) return None model = self . adb . getprop ( 'ro.build.product' ) . lower ( ) if model == 'sprout' : return model return self . adb . getprop ( 'ro.product.name' ) . lower ( ) | The Android code name for the device . |
16,518 | def load_config ( self , config ) : for k , v in config . items ( ) : if hasattr ( self , k ) : raise DeviceError ( self , ( 'Attribute %s already exists with value %s, cannot set ' 'again.' ) % ( k , getattr ( self , k ) ) ) setattr ( self , k , v ) | Add attributes to the AndroidDevice object based on config . |
16,519 | def root_adb ( self ) : self . adb . root ( ) self . adb . wait_for_device ( timeout = DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND ) | Change adb to root mode for this device if allowed . |
16,520 | def load_snippet ( self , name , package ) : if hasattr ( self , name ) : raise SnippetError ( self , 'Attribute "%s" already exists, please use a different name.' % name ) self . services . snippets . add_snippet_client ( name , package ) | Starts the snippet apk with the given package name and connects . |
16,521 | def take_bug_report ( self , test_name , begin_time , timeout = 300 , destination = None ) : new_br = True try : stdout = self . adb . shell ( 'bugreportz -v' ) . decode ( 'utf-8' ) if 'not found' in stdout : new_br = False except adb . AdbError : new_br = False if destination : br_path = utils . abs_path ( destination ) else : br_path = os . path . join ( self . log_path , 'BugReports' ) utils . create_dir ( br_path ) base_name = ',%s,%s.txt' % ( begin_time , self . _normalized_serial ) if new_br : base_name = base_name . replace ( '.txt' , '.zip' ) test_name_len = utils . MAX_FILENAME_LEN - len ( base_name ) out_name = test_name [ : test_name_len ] + base_name full_out_path = os . path . join ( br_path , out_name . replace ( ' ' , r'\ ' ) ) self . wait_for_boot_completion ( ) self . log . info ( 'Taking bugreport for %s.' , test_name ) if new_br : out = self . adb . shell ( 'bugreportz' , timeout = timeout ) . decode ( 'utf-8' ) if not out . startswith ( 'OK' ) : raise DeviceError ( self , 'Failed to take bugreport: %s' % out ) br_out_path = out . split ( ':' ) [ 1 ] . strip ( ) self . adb . pull ( [ br_out_path , full_out_path ] ) else : self . adb . bugreport ( ' > "%s"' % full_out_path , shell = True , timeout = timeout ) self . log . info ( 'Bugreport for %s taken at %s.' , test_name , full_out_path ) | Takes a bug report on the device and stores it in a file . |
16,522 | def run_iperf_client ( self , server_host , extra_args = '' ) : out = self . adb . shell ( 'iperf3 -c %s %s' % ( server_host , extra_args ) ) clean_out = new_str ( out , 'utf-8' ) . strip ( ) . split ( '\n' ) if 'error' in clean_out [ 0 ] . lower ( ) : return False , clean_out return True , clean_out | Start iperf client on the device . |
16,523 | def wait_for_boot_completion ( self , timeout = DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND ) : timeout_start = time . time ( ) self . adb . wait_for_device ( timeout = timeout ) while time . time ( ) < timeout_start + timeout : try : if self . is_boot_completed ( ) : return except adb . AdbError : pass time . sleep ( 5 ) raise DeviceError ( self , 'Booting process timed out' ) | Waits for Android framework to broadcast ACTION_BOOT_COMPLETED . |
16,524 | def is_boot_completed ( self ) : completed = self . adb . getprop ( 'sys.boot_completed' ) if completed == '1' : self . log . debug ( 'Device boot completed.' ) return True return False | Checks if device boot is completed by verifying system property . |
16,525 | def is_adb_detectable ( self ) : serials = list_adb_devices ( ) if self . serial in serials : self . log . debug ( 'Is now adb detectable.' ) return True return False | Checks if USB is on and device is ready by verifying adb devices . |
16,526 | def expect_true ( condition , msg , extras = None ) : try : asserts . assert_true ( condition , msg , extras ) except signals . TestSignal as e : logging . exception ( 'Expected a `True` value, got `False`.' ) recorder . add_error ( e ) | Expects an expression evaluates to True . |
16,527 | def expect_false ( condition , msg , extras = None ) : try : asserts . assert_false ( condition , msg , extras ) except signals . TestSignal as e : logging . exception ( 'Expected a `False` value, got `True`.' ) recorder . add_error ( e ) | Expects an expression evaluates to False . |
16,528 | def expect_equal ( first , second , msg = None , extras = None ) : try : asserts . assert_equal ( first , second , msg , extras ) except signals . TestSignal as e : logging . exception ( 'Expected %s equals to %s, but they are not.' , first , second ) recorder . add_error ( e ) | Expects the equality of objects otherwise fail the test . |
16,529 | def expect_no_raises ( message = None , extras = None ) : try : yield except Exception as e : e_record = records . ExceptionRecord ( e ) if extras : e_record . extras = extras msg = message or 'Got an unexpected exception' details = '%s: %s' % ( msg , e_record . details ) logging . exception ( details ) e_record . details = details recorder . add_error ( e_record ) | Expects no exception is raised in a context . |
16,530 | def reset_internal_states ( self , record = None ) : self . _record = None self . _count = 0 self . _record = record | Resets the internal state of the recorder . |
16,531 | def add_error ( self , error ) : self . _count += 1 self . _record . add_error ( 'expect@%s+%s' % ( time . time ( ) , self . _count ) , error ) | Record an error from expect APIs . |
16,532 | def _enable_logpersist ( self ) : if not self . _ad . is_rootable : return logpersist_warning = ( '%s encountered an error enabling persistent' ' logs, logs may not get saved.' ) if not self . _ad . adb . has_shell_command ( 'logpersist.start' ) : logging . warning ( logpersist_warning , self ) return try : self . _ad . adb . shell ( 'logpersist.stop --clear' ) self . _ad . adb . shell ( 'logpersist.start' ) except adb . AdbError : logging . warning ( logpersist_warning , self ) | Attempts to enable logpersist daemon to persist logs . |
16,533 | def clear_adb_log ( self ) : try : self . _ad . adb . logcat ( '-c' ) except adb . AdbError as e : if b'failed to clear' in e . stderr : self . _ad . log . warning ( 'Encountered known Android error to clear logcat.' ) else : raise | Clears cached adb content . |
16,534 | def cat_adb_log ( self , tag , begin_time ) : if not self . adb_logcat_file_path : raise Error ( self . _ad , 'Attempting to cat adb log when none has been collected.' ) end_time = mobly_logger . get_log_line_timestamp ( ) self . _ad . log . debug ( 'Extracting adb log from logcat.' ) adb_excerpt_path = os . path . join ( self . _ad . log_path , 'AdbLogExcerpts' ) utils . create_dir ( adb_excerpt_path ) f_name = os . path . basename ( self . adb_logcat_file_path ) out_name = f_name . replace ( 'adblog,' , '' ) . replace ( '.txt' , '' ) out_name = ',%s,%s.txt' % ( begin_time , out_name ) out_name = out_name . replace ( ':' , '-' ) tag_len = utils . MAX_FILENAME_LEN - len ( out_name ) tag = tag [ : tag_len ] out_name = tag + out_name full_adblog_path = os . path . join ( adb_excerpt_path , out_name ) with io . open ( full_adblog_path , 'w' , encoding = 'utf-8' ) as out : in_file = self . adb_logcat_file_path with io . open ( in_file , 'r' , encoding = 'utf-8' , errors = 'replace' ) as f : in_range = False while True : line = None try : line = f . readline ( ) if not line : break except : continue line_time = line [ : mobly_logger . log_line_timestamp_len ] if not mobly_logger . is_valid_logline_timestamp ( line_time ) : continue if self . _is_timestamp_in_range ( line_time , begin_time , end_time ) : in_range = True if not line . endswith ( '\n' ) : line += '\n' out . write ( line ) else : if in_range : break | Takes an excerpt of the adb logcat log from a certain time point to current time . |
16,535 | def start ( self ) : self . _assert_not_running ( ) if self . _configs . clear_log : self . clear_adb_log ( ) self . _start ( ) | Starts a standing adb logcat collection . |
16,536 | def _start ( self ) : self . _enable_logpersist ( ) logcat_file_path = self . _configs . output_file_path if not logcat_file_path : f_name = 'adblog,%s,%s.txt' % ( self . _ad . model , self . _ad . _normalized_serial ) logcat_file_path = os . path . join ( self . _ad . log_path , f_name ) utils . create_dir ( os . path . dirname ( logcat_file_path ) ) cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % ( adb . ADB , self . _ad . serial , self . _configs . logcat_params , logcat_file_path ) process = utils . start_standing_subprocess ( cmd , shell = True ) self . _adb_logcat_process = process self . adb_logcat_file_path = logcat_file_path | The actual logic of starting logcat . |
16,537 | def stop ( self ) : if not self . _adb_logcat_process : return try : utils . stop_standing_subprocess ( self . _adb_logcat_process ) except : self . _ad . log . exception ( 'Failed to stop adb logcat.' ) self . _adb_logcat_process = None | Stops the adb logcat service . |
16,538 | def connect ( self , uid = UNKNOWN_UID , cmd = JsonRpcCommand . INIT ) : self . _counter = self . _id_counter ( ) self . _conn = socket . create_connection ( ( 'localhost' , self . host_port ) , _SOCKET_CONNECTION_TIMEOUT ) self . _conn . settimeout ( _SOCKET_READ_TIMEOUT ) self . _client = self . _conn . makefile ( mode = 'brw' ) resp = self . _cmd ( cmd , uid ) if not resp : raise ProtocolError ( self . _ad , ProtocolError . NO_RESPONSE_FROM_HANDSHAKE ) result = json . loads ( str ( resp , encoding = 'utf8' ) ) if result [ 'status' ] : self . uid = result [ 'uid' ] else : self . uid = UNKNOWN_UID | Opens a connection to a JSON RPC server . |
16,539 | def clear_host_port ( self ) : if self . host_port : self . _adb . forward ( [ '--remove' , 'tcp:%d' % self . host_port ] ) self . host_port = None | Stops the adb port forwarding of the host port used by this client . |
16,540 | def _client_send ( self , msg ) : try : self . _client . write ( msg . encode ( "utf8" ) + b'\n' ) self . _client . flush ( ) self . log . debug ( 'Snippet sent %s.' , msg ) except socket . error as e : raise Error ( self . _ad , 'Encountered socket error "%s" sending RPC message "%s"' % ( e , msg ) ) | Sends an Rpc message through the connection . |
16,541 | def _client_receive ( self ) : try : response = self . _client . readline ( ) self . log . debug ( 'Snippet received: %s' , response ) return response except socket . error as e : raise Error ( self . _ad , 'Encountered socket error reading RPC response "%s"' % e ) | Receives the server s response of an Rpc message . |
16,542 | def _rpc ( self , method , * args ) : with self . _lock : apiid = next ( self . _counter ) data = { 'id' : apiid , 'method' : method , 'params' : args } request = json . dumps ( data ) self . _client_send ( request ) response = self . _client_receive ( ) if not response : raise ProtocolError ( self . _ad , ProtocolError . NO_RESPONSE_FROM_SERVER ) result = json . loads ( str ( response , encoding = 'utf8' ) ) if result [ 'error' ] : raise ApiError ( self . _ad , result [ 'error' ] ) if result [ 'id' ] != apiid : raise ProtocolError ( self . _ad , ProtocolError . MISMATCHED_API_ID ) if result . get ( 'callback' ) is not None : if self . _event_client is None : self . _event_client = self . _start_event_client ( ) return callback_handler . CallbackHandler ( callback_id = result [ 'callback' ] , event_client = self . _event_client , ret_value = result [ 'result' ] , method_name = method , ad = self . _ad ) return result [ 'result' ] | Sends an rpc to the app . |
16,543 | def disable_hidden_api_blacklist ( self ) : version_codename = self . _ad . adb . getprop ( 'ro.build.version.codename' ) sdk_version = int ( self . _ad . adb . getprop ( 'ro.build.version.sdk' ) ) if self . _ad . is_rootable and ( sdk_version >= 28 or version_codename == 'P' ) : self . _ad . adb . shell ( 'settings put global hidden_api_blacklist_exemptions "*"' ) | If necessary and possible disables hidden api blacklist . |
16,544 | def start ( self , extra_args = "" , tag = "" ) : if self . started : return utils . create_dir ( self . log_path ) if tag : tag = tag + ',' out_file_name = "IPerfServer,{},{}{}.log" . format ( self . port , tag , len ( self . log_files ) ) full_out_path = os . path . join ( self . log_path , out_file_name ) cmd = '%s %s > %s' % ( self . iperf_str , extra_args , full_out_path ) self . iperf_process = utils . start_standing_subprocess ( cmd , shell = True ) self . log_files . append ( full_out_path ) self . started = True | Starts iperf server on specified port . |
16,545 | def _post_process ( self ) : self . _process = None shutil . move ( self . _temp_capture_file_path , self . _capture_file_path ) | Utility function which is executed after a capture is done . It moves the capture file to the requested location . |
16,546 | def list_occupied_adb_ports ( ) : out = AdbProxy ( ) . forward ( '--list' ) clean_lines = str ( out , 'utf-8' ) . strip ( ) . split ( '\n' ) used_ports = [ ] for line in clean_lines : tokens = line . split ( ' tcp:' ) if len ( tokens ) != 3 : continue used_ports . append ( int ( tokens [ 1 ] ) ) return used_ports | Lists all the host ports occupied by adb forward . |
16,547 | def _exec_cmd ( self , args , shell , timeout , stderr ) : if timeout and timeout <= 0 : raise ValueError ( 'Timeout is not a positive value: %s' % timeout ) try : ( ret , out , err ) = utils . run_command ( args , shell = shell , timeout = timeout ) except psutil . TimeoutExpired : raise AdbTimeoutError ( cmd = args , timeout = timeout , serial = self . serial ) if stderr : stderr . write ( err ) logging . debug ( 'cmd: %s, stdout: %s, stderr: %s, ret: %s' , utils . cli_cmd_to_string ( args ) , out , err , ret ) if ret == 0 : return out else : raise AdbError ( cmd = args , stdout = out , stderr = err , ret_code = ret , serial = self . serial ) | Executes adb commands . |
16,548 | def _execute_and_process_stdout ( self , args , shell , handler ) : proc = subprocess . Popen ( args , stdout = subprocess . PIPE , stderr = subprocess . PIPE , shell = shell , bufsize = 1 ) out = '[elided, processed via handler]' try : while True : line = proc . stdout . readline ( ) if line : handler ( line ) else : break finally : ( unexpected_out , err ) = proc . communicate ( ) if unexpected_out : out = '[unexpected stdout] %s' % unexpected_out for line in unexpected_out . splitlines ( ) : handler ( line ) ret = proc . returncode logging . debug ( 'cmd: %s, stdout: %s, stderr: %s, ret: %s' , utils . cli_cmd_to_string ( args ) , out , err , ret ) if ret == 0 : return err else : raise AdbError ( cmd = args , stdout = out , stderr = err , ret_code = ret ) | Executes adb commands and processes the stdout with a handler . |
16,549 | def _construct_adb_cmd ( self , raw_name , args , shell ) : args = args or '' name = raw_name . replace ( '_' , '-' ) if shell : args = utils . cli_cmd_to_string ( args ) if self . serial : adb_cmd = '"%s" -s "%s" %s %s' % ( ADB , self . serial , name , args ) else : adb_cmd = '"%s" %s %s' % ( ADB , name , args ) else : adb_cmd = [ ADB ] if self . serial : adb_cmd . extend ( [ '-s' , self . serial ] ) adb_cmd . append ( name ) if args : if isinstance ( args , basestring ) : adb_cmd . append ( args ) else : adb_cmd . extend ( args ) return adb_cmd | Constructs an adb command with arguments for a subprocess call . |
16,550 | def getprop ( self , prop_name ) : return self . shell ( [ 'getprop' , prop_name ] , timeout = DEFAULT_GETPROP_TIMEOUT_SEC ) . decode ( 'utf-8' ) . strip ( ) | Get a property of the device . |
16,551 | def has_shell_command ( self , command ) : try : output = self . shell ( [ 'command' , '-v' , command ] ) . decode ( 'utf-8' ) . strip ( ) return command in output except AdbError : return False | Checks to see if a given check command exists on the device . |
16,552 | def instrument ( self , package , options = None , runner = None , handler = None ) : if runner is None : runner = DEFAULT_INSTRUMENTATION_RUNNER if options is None : options = { } options_list = [ ] for option_key , option_value in options . items ( ) : options_list . append ( '-e %s %s' % ( option_key , option_value ) ) options_string = ' ' . join ( options_list ) instrumentation_command = 'am instrument -r -w %s %s/%s' % ( options_string , package , runner ) logging . info ( 'AndroidDevice|%s: Executing adb shell %s' , self . serial , instrumentation_command ) if handler is None : self . _exec_adb_cmd ( 'shell' , instrumentation_command , shell = False , timeout = None , stderr = None ) else : return self . _execute_adb_and_process_stdout ( 'shell' , instrumentation_command , shell = False , handler = handler ) | Runs an instrumentation command on the device . |
16,553 | def assert_equal ( first , second , msg = None , extras = None ) : my_msg = None try : _pyunit_proxy . assertEqual ( first , second ) except AssertionError as e : my_msg = str ( e ) if msg : my_msg = "%s %s" % ( my_msg , msg ) if my_msg is not None : raise signals . TestFailure ( my_msg , extras = extras ) | Assert the equality of objects otherwise fail the test . |
16,554 | def waitAndGet ( self , event_name , timeout = DEFAULT_TIMEOUT ) : if timeout : if timeout > MAX_TIMEOUT : raise Error ( self . _ad , 'Specified timeout %s is longer than max timeout %s.' % ( timeout , MAX_TIMEOUT ) ) timeout_ms = int ( timeout * 1000 ) try : raw_event = self . _event_client . eventWaitAndGet ( self . _id , event_name , timeout_ms ) except Exception as e : if 'EventSnippetException: timeout.' in str ( e ) : raise TimeoutError ( self . _ad , 'Timed out after waiting %ss for event "%s" triggered by' ' %s (%s).' % ( timeout , event_name , self . _method_name , self . _id ) ) raise return snippet_event . from_dict ( raw_event ) | Blocks until an event of the specified name has been received and return the event or timeout . |
16,555 | def waitForEvent ( self , event_name , predicate , timeout = DEFAULT_TIMEOUT ) : deadline = time . time ( ) + timeout while time . time ( ) <= deadline : rpc_timeout = deadline - time . time ( ) if rpc_timeout < 0 : break rpc_timeout = min ( rpc_timeout , MAX_TIMEOUT ) try : event = self . waitAndGet ( event_name , rpc_timeout ) except TimeoutError : break if predicate ( event ) : return event raise TimeoutError ( self . _ad , 'Timed out after %ss waiting for an "%s" event that satisfies the ' 'predicate "%s".' % ( timeout , event_name , predicate . __name__ ) ) | Wait for an event of a specific name that satisfies the predicate . |
16,556 | def getAll ( self , event_name ) : raw_events = self . _event_client . eventGetAll ( self . _id , event_name ) return [ snippet_event . from_dict ( msg ) for msg in raw_events ] | Gets all the events of a certain name that have been received so far . This is a non - blocking call . |
16,557 | def _validate_config ( config ) : required_keys = [ KEY_ADDRESS , KEY_MODEL , KEY_PORT , KEY_PATHS ] for key in required_keys : if key not in config : raise Error ( "Required key %s missing from config %s" , ( key , config ) ) | Verifies that a config dict for an attenuator device is valid . |
16,558 | def get_instances ( serials ) : objs = [ ] for s in serials : objs . append ( Monsoon ( serial = s ) ) return objs | Create Monsoon instances from a list of serials . |
16,559 | def GetStatus ( self ) : STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH" STATUS_FIELDS = [ "packetType" , "firmwareVersion" , "protocolVersion" , "mainFineCurrent" , "usbFineCurrent" , "auxFineCurrent" , "voltage1" , "mainCoarseCurrent" , "usbCoarseCurrent" , "auxCoarseCurrent" , "voltage2" , "outputVoltageSetting" , "temperature" , "status" , "leds" , "mainFineResistor" , "serialNumber" , "sampleRate" , "dacCalLow" , "dacCalHigh" , "powerUpCurrentLimit" , "runTimeCurrentLimit" , "powerUpTime" , "usbFineResistor" , "auxFineResistor" , "initialUsbVoltage" , "initialAuxVoltage" , "hardwareRevision" , "temperatureLimit" , "usbPassthroughMode" , "mainCoarseResistor" , "usbCoarseResistor" , "auxCoarseResistor" , "defMainFineResistor" , "defUsbFineResistor" , "defAuxFineResistor" , "defMainCoarseResistor" , "defUsbCoarseResistor" , "defAuxCoarseResistor" , "eventCode" , "eventData" , ] self . _SendStruct ( "BBB" , 0x01 , 0x00 , 0x00 ) while 1 : read_bytes = self . _ReadPacket ( ) if not read_bytes : return None calsize = struct . calcsize ( STATUS_FORMAT ) if len ( read_bytes ) != calsize or read_bytes [ 0 ] != 0x10 : logging . warning ( "Wanted status, dropped type=0x%02x, len=%d" , read_bytes [ 0 ] , len ( read_bytes ) ) continue status = dict ( zip ( STATUS_FIELDS , struct . unpack ( STATUS_FORMAT , read_bytes ) ) ) p_type = status [ "packetType" ] if p_type != 0x10 : raise MonsoonError ( "Package type %s is not 0x10." % p_type ) for k in status . keys ( ) : if k . endswith ( "VoltageSetting" ) : status [ k ] = 2.0 + status [ k ] * 0.01 elif k . endswith ( "FineCurrent" ) : pass elif k . endswith ( "CoarseCurrent" ) : pass elif k . startswith ( "voltage" ) or k . endswith ( "Voltage" ) : status [ k ] = status [ k ] * 0.000125 elif k . endswith ( "Resistor" ) : status [ k ] = 0.05 + status [ k ] * 0.0001 if k . startswith ( "aux" ) or k . startswith ( "defAux" ) : status [ k ] += 0.05 elif k . endswith ( "CurrentLimit" ) : status [ k ] = 8 * ( 1023 - status [ k ] ) / 1023.0 return status | Requests and waits for status . |
16,560 | def SetVoltage ( self , v ) : if v == 0 : self . _SendStruct ( "BBB" , 0x01 , 0x01 , 0x00 ) else : self . _SendStruct ( "BBB" , 0x01 , 0x01 , int ( ( v - 2.0 ) * 100 ) ) | Set the output voltage 0 to disable . |
16,561 | def SetMaxCurrent ( self , i ) : if i < 0 or i > 8 : raise MonsoonError ( ( "Target max current %sA, is out of acceptable " "range [0, 8]." ) % i ) val = 1023 - int ( ( i / 8 ) * 1023 ) self . _SendStruct ( "BBB" , 0x01 , 0x0a , val & 0xff ) self . _SendStruct ( "BBB" , 0x01 , 0x0b , val >> 8 ) | Set the max output current . |
16,562 | def SetMaxPowerUpCurrent ( self , i ) : if i < 0 or i > 8 : raise MonsoonError ( ( "Target max current %sA, is out of acceptable " "range [0, 8]." ) % i ) val = 1023 - int ( ( i / 8 ) * 1023 ) self . _SendStruct ( "BBB" , 0x01 , 0x08 , val & 0xff ) self . _SendStruct ( "BBB" , 0x01 , 0x09 , val >> 8 ) | Set the max power up current . |
16,563 | def _FlushInput ( self ) : self . ser . flush ( ) flushed = 0 while True : ready_r , ready_w , ready_x = select . select ( [ self . ser ] , [ ] , [ self . ser ] , 0 ) if len ( ready_x ) > 0 : logging . error ( "Exception from serial port." ) return None elif len ( ready_r ) > 0 : flushed += 1 self . ser . read ( 1 ) self . ser . flush ( ) else : break | Flush all read data until no more available . |
16,564 | def average_current ( self ) : len_data_pt = len ( self . data_points ) if len_data_pt == 0 : return 0 cur = sum ( self . data_points ) * 1000 / len_data_pt return round ( cur , self . sr ) | Average current in the unit of mA . |
16,565 | def total_charge ( self ) : charge = ( sum ( self . data_points ) / self . hz ) * 1000 / 3600 return round ( charge , self . sr ) | Total charged used in the unit of mAh . |
16,566 | def total_power ( self ) : power = self . average_current * self . voltage return round ( power , self . sr ) | Total power used . |
16,567 | def save_to_text_file ( monsoon_data , file_path ) : if not monsoon_data : raise MonsoonError ( "Attempting to write empty Monsoon data to " "file, abort" ) utils . create_dir ( os . path . dirname ( file_path ) ) with io . open ( file_path , 'w' , encoding = 'utf-8' ) as f : for md in monsoon_data : f . write ( str ( md ) ) f . write ( MonsoonData . delimiter ) | Save multiple MonsoonData objects to a text file . |
16,568 | def from_text_file ( file_path ) : results = [ ] with io . open ( file_path , 'r' , encoding = 'utf-8' ) as f : data_strs = f . read ( ) . split ( MonsoonData . delimiter ) for data_str in data_strs : results . append ( MonsoonData . from_string ( data_str ) ) return results | Load MonsoonData objects from a text file generated by MonsoonData . save_to_text_file . |
16,569 | def _validate_data ( self ) : msg = "Error! Expected {} timestamps, found {}." . format ( len ( self . _data_points ) , len ( self . _timestamps ) ) if len ( self . _data_points ) != len ( self . _timestamps ) : raise MonsoonError ( msg ) | Verifies that the data points contained in the class are valid . |
16,570 | def update_offset ( self , new_offset ) : self . offset = new_offset self . data_points = self . _data_points [ self . offset : ] self . timestamps = self . _timestamps [ self . offset : ] | Updates how many data points to skip in caculations . |
16,571 | def get_data_with_timestamps ( self ) : result = [ ] for t , d in zip ( self . timestamps , self . data_points ) : result . append ( t , round ( d , self . lr ) ) return result | Returns the data points with timestamps . |
16,572 | def get_average_record ( self , n ) : history_deque = collections . deque ( ) averages = [ ] for d in self . data_points : history_deque . appendleft ( d ) if len ( history_deque ) > n : history_deque . pop ( ) avg = sum ( history_deque ) / len ( history_deque ) averages . append ( round ( avg , self . lr ) ) return averages | Returns a list of average current numbers each representing the average over the last n data points . |
16,573 | def set_voltage ( self , volt , ramp = False ) : if ramp : self . mon . RampVoltage ( self . mon . start_voltage , volt ) else : self . mon . SetVoltage ( volt ) | Sets the output voltage of monsoon . |
16,574 | def take_samples ( self , sample_hz , sample_num , sample_offset = 0 , live = False ) : sys . stdout . flush ( ) voltage = self . mon . GetVoltage ( ) self . log . info ( "Taking samples at %dhz for %ds, voltage %.2fv." , sample_hz , ( sample_num / sample_hz ) , voltage ) sample_num += sample_offset self . mon . StopDataCollection ( ) status = self . mon . GetStatus ( ) native_hz = status [ "sampleRate" ] * 1000 self . mon . StartDataCollection ( ) emitted = offset = 0 collected = [ ] history_deque = collections . deque ( ) current_values = [ ] timestamps = [ ] try : last_flush = time . time ( ) while emitted < sample_num or sample_num == - 1 : need = int ( ( native_hz - offset + sample_hz - 1 ) / sample_hz ) if need > len ( collected ) : samples = self . mon . CollectData ( ) if not samples : break collected . extend ( samples ) else : offset += need * sample_hz while offset >= native_hz : this_sample = sum ( collected [ : need ] ) / need this_time = int ( time . time ( ) ) timestamps . append ( this_time ) if live : self . log . info ( "%s %s" , this_time , this_sample ) current_values . append ( this_sample ) sys . stdout . flush ( ) offset -= native_hz emitted += 1 collected = collected [ need : ] now = time . time ( ) if now - last_flush >= 0.99 : sys . stdout . flush ( ) last_flush = now except Exception as e : pass self . mon . StopDataCollection ( ) try : return MonsoonData ( current_values , timestamps , sample_hz , voltage , offset = sample_offset ) except : return None | Take samples of the current value supplied by monsoon . |
16,575 | def usb ( self , state ) : state_lookup = { "off" : 0 , "on" : 1 , "auto" : 2 } state = state . lower ( ) if state in state_lookup : current_state = self . mon . GetUsbPassthrough ( ) while ( current_state != state_lookup [ state ] ) : self . mon . SetUsbPassthrough ( state_lookup [ state ] ) time . sleep ( 1 ) current_state = self . mon . GetUsbPassthrough ( ) return True return False | Sets the monsoon s USB passthrough mode . This is specific to the USB port in front of the monsoon box which connects to the powered device NOT the USB that is used to talk to the monsoon itself . |
16,576 | def measure_power ( self , hz , duration , tag , offset = 30 ) : num = duration * hz oset = offset * hz data = None self . usb ( "auto" ) time . sleep ( 1 ) with self . dut . handle_usb_disconnect ( ) : time . sleep ( 1 ) try : data = self . take_samples ( hz , num , sample_offset = oset ) if not data : raise MonsoonError ( "No data was collected in measurement %s." % tag ) data . tag = tag self . dut . log . info ( "Measurement summary: %s" , repr ( data ) ) return data finally : self . mon . StopDataCollection ( ) self . log . info ( "Finished taking samples, reconnecting to dut." ) self . usb ( "on" ) self . dut . adb . wait_for_device ( timeout = DEFAULT_TIMEOUT_USB_ON ) time . sleep ( 10 ) self . dut . log . info ( "Dut reconnected." ) | Measure power consumption of the attached device . |
16,577 | def _set_details ( self , content ) : try : self . details = str ( content ) except UnicodeEncodeError : if sys . version_info < ( 3 , 0 ) : self . details = unicode ( content ) else : logging . error ( 'Unable to decode "%s" in Py3, encoding in utf-8.' , content ) self . details = content . encode ( 'utf-8' ) | Sets the details field . |
16,578 | def _load_config_file ( path ) : with io . open ( utils . abs_path ( path ) , 'r' , encoding = 'utf-8' ) as f : conf = yaml . load ( f ) return conf | Loads a test config file . |
16,579 | def add_snippet_client ( self , name , package ) : if name in self . _snippet_clients : raise Error ( self , 'Name "%s" is already registered with package "%s", it cannot ' 'be used again.' % ( name , self . _snippet_clients [ name ] . client . package ) ) for snippet_name , client in self . _snippet_clients . items ( ) : if package == client . package : raise Error ( self , 'Snippet package "%s" has already been loaded under name' ' "%s".' % ( package , snippet_name ) ) client = snippet_client . SnippetClient ( package = package , ad = self . _device ) client . start_app_and_connect ( ) self . _snippet_clients [ name ] = client | Adds a snippet client to the management . |
16,580 | def remove_snippet_client ( self , name ) : if name not in self . _snippet_clients : raise Error ( self . _device , MISSING_SNIPPET_CLIENT_MSG % name ) client = self . _snippet_clients . pop ( name ) client . stop_app ( ) | Removes a snippet client from management . |
16,581 | def start ( self ) : for client in self . _snippet_clients . values ( ) : if not client . is_alive : self . _device . log . debug ( 'Starting SnippetClient<%s>.' , client . package ) client . start_app_and_connect ( ) else : self . _device . log . debug ( 'Not startng SnippetClient<%s> because it is already alive.' , client . package ) | Starts all the snippet clients under management . |
16,582 | def stop ( self ) : for client in self . _snippet_clients . values ( ) : if client . is_alive : self . _device . log . debug ( 'Stopping SnippetClient<%s>.' , client . package ) client . stop_app ( ) else : self . _device . log . debug ( 'Not stopping SnippetClient<%s> because it is not alive.' , client . package ) | Stops all the snippet clients under management . |
16,583 | def pause ( self ) : for client in self . _snippet_clients . values ( ) : self . _device . log . debug ( 'Clearing host port %d of SnippetClient<%s>.' , client . host_port , client . package ) client . clear_host_port ( ) | Pauses all the snippet clients under management . |
16,584 | def resume ( self ) : for client in self . _snippet_clients . values ( ) : if client . is_alive and client . host_port is None : self . _device . log . debug ( 'Resuming SnippetClient<%s>.' , client . package ) client . restore_app_connection ( ) else : self . _device . log . debug ( 'Not resuming SnippetClient<%s>.' , client . package ) | Resumes all paused snippet clients . |
16,585 | def poll_events ( self ) : while self . started : event_obj = None event_name = None try : event_obj = self . _sl4a . eventWait ( 50000 ) except : if self . started : print ( "Exception happened during polling." ) print ( traceback . format_exc ( ) ) raise if not event_obj : continue elif 'name' not in event_obj : print ( "Received Malformed event {}" . format ( event_obj ) ) continue else : event_name = event_obj [ 'name' ] if event_name in self . handlers : self . handle_subscribed_event ( event_obj , event_name ) if event_name == "EventDispatcherShutdown" : self . _sl4a . closeSl4aSession ( ) break else : self . lock . acquire ( ) if event_name in self . event_dict : self . event_dict [ event_name ] . put ( event_obj ) else : q = queue . Queue ( ) q . put ( event_obj ) self . event_dict [ event_name ] = q self . lock . release ( ) | Continuously polls all types of events from sl4a . |
16,586 | def register_handler ( self , handler , event_name , args ) : if self . started : raise IllegalStateError ( ( "Can't register service after polling is" " started" ) ) self . lock . acquire ( ) try : if event_name in self . handlers : raise DuplicateError ( 'A handler for {} already exists' . format ( event_name ) ) self . handlers [ event_name ] = ( handler , args ) finally : self . lock . release ( ) | Registers an event handler . |
16,587 | def start ( self ) : if not self . started : self . started = True self . executor = ThreadPoolExecutor ( max_workers = 32 ) self . poller = self . executor . submit ( self . poll_events ) else : raise IllegalStateError ( "Dispatcher is already started." ) | Starts the event dispatcher . |
16,588 | def clean_up ( self ) : if not self . started : return self . started = False self . clear_all_events ( ) self . _sl4a . disconnect ( ) self . poller . set_result ( "Done" ) self . executor . shutdown ( wait = False ) | Clean up and release resources after the event dispatcher polling loop has been broken . |
16,589 | def pop_event ( self , event_name , timeout = DEFAULT_TIMEOUT ) : if not self . started : raise IllegalStateError ( "Dispatcher needs to be started before popping." ) e_queue = self . get_event_q ( event_name ) if not e_queue : raise TypeError ( "Failed to get an event queue for {}" . format ( event_name ) ) try : if timeout : return e_queue . get ( True , timeout ) elif timeout == 0 : return e_queue . get ( False ) else : return e_queue . get ( True ) except queue . Empty : raise queue . Empty ( 'Timeout after {}s waiting for event: {}' . format ( timeout , event_name ) ) | Pop an event from its queue . |
16,590 | def wait_for_event ( self , event_name , predicate , timeout = DEFAULT_TIMEOUT , * args , ** kwargs ) : deadline = time . time ( ) + timeout while True : event = None try : event = self . pop_event ( event_name , 1 ) except queue . Empty : pass if event and predicate ( event , * args , ** kwargs ) : return event if time . time ( ) > deadline : raise queue . Empty ( 'Timeout after {}s waiting for event: {}' . format ( timeout , event_name ) ) | Wait for an event that satisfies a predicate to appear . |
16,591 | def pop_events ( self , regex_pattern , timeout ) : if not self . started : raise IllegalStateError ( "Dispatcher needs to be started before popping." ) deadline = time . time ( ) + timeout while True : results = self . _match_and_pop ( regex_pattern ) if len ( results ) != 0 or time . time ( ) > deadline : break time . sleep ( 1 ) if len ( results ) == 0 : raise queue . Empty ( 'Timeout after {}s waiting for event: {}' . format ( timeout , regex_pattern ) ) return sorted ( results , key = lambda event : event [ 'time' ] ) | Pop events whose names match a regex pattern . |
16,592 | def get_event_q ( self , event_name ) : self . lock . acquire ( ) if not event_name in self . event_dict or self . event_dict [ event_name ] is None : self . event_dict [ event_name ] = queue . Queue ( ) self . lock . release ( ) event_queue = self . event_dict [ event_name ] return event_queue | Obtain the queue storing events of the specified name . |
16,593 | def handle_subscribed_event ( self , event_obj , event_name ) : handler , args = self . handlers [ event_name ] self . executor . submit ( handler , event_obj , * args ) | Execute the registered handler of an event . |
16,594 | def _handle ( self , event_handler , event_name , user_args , event_timeout , cond , cond_timeout ) : if cond : cond . wait ( cond_timeout ) event = self . pop_event ( event_name , event_timeout ) return event_handler ( event , * user_args ) | Pop an event of specified type and calls its handler on it . If condition is not None block until condition is met or timeout . |
16,595 | def handle_event ( self , event_handler , event_name , user_args , event_timeout = None , cond = None , cond_timeout = None ) : worker = self . executor . submit ( self . _handle , event_handler , event_name , user_args , event_timeout , cond , cond_timeout ) return worker | Handle events that don t have registered handlers |
16,596 | def pop_all ( self , event_name ) : if not self . started : raise IllegalStateError ( ( "Dispatcher needs to be started before " "popping." ) ) results = [ ] try : self . lock . acquire ( ) while True : e = self . event_dict [ event_name ] . get ( block = False ) results . append ( e ) except ( queue . Empty , KeyError ) : return results finally : self . lock . release ( ) | Return and remove all stored events of a specified name . |
16,597 | def clear_events ( self , event_name ) : self . lock . acquire ( ) try : q = self . get_event_q ( event_name ) q . queue . clear ( ) except queue . Empty : return finally : self . lock . release ( ) | Clear all events of a particular name . |
16,598 | def clear_all_events ( self ) : self . lock . acquire ( ) self . event_dict . clear ( ) self . lock . release ( ) | Clear all event queues and their cached events . |
16,599 | def from_dict ( event_dict ) : return SnippetEvent ( callback_id = event_dict [ 'callbackId' ] , name = event_dict [ 'name' ] , creation_time = event_dict [ 'time' ] , data = event_dict [ 'data' ] ) | Create a SnippetEvent object from a dictionary . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.