idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
22,300 | def calculate_report_size ( self , current_type , report_header ) : fmt = self . known_formats [ current_type ] return fmt . ReportLength ( report_header ) | Determine the size of a report given its type and header | 41 | 13 |
22,301 | def parse_report ( self , current_type , report_data ) : fmt = self . known_formats [ current_type ] return fmt ( report_data ) | Parse a report into an IOTileReport subclass | 36 | 11 |
22,302 | def _handle_report ( self , report ) : keep_report = True if self . report_callback is not None : keep_report = self . report_callback ( report , self . context ) if keep_report : self . reports . append ( report ) | Try to emit a report and possibly keep a copy of it | 55 | 12 |
22,303 | def _POInitBuilder ( env , * * kw ) : import SCons . Action from SCons . Tool . GettextCommon import _init_po_files , _POFileBuilder action = SCons . Action . Action ( _init_po_files , None ) return _POFileBuilder ( env , action = action , target_alias = '$POCREATE_ALIAS' ) | Create builder object for POInit builder . | 85 | 8 |
22,304 | def generate ( env , * * kw ) : import SCons . Util from SCons . Tool . GettextCommon import _detect_msginit try : env [ 'MSGINIT' ] = _detect_msginit ( env ) except : env [ 'MSGINIT' ] = 'msginit' msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' + ' $MSGINITFLAGS -i $SOURCE -o $TARGET' # NOTE: We set POTSUFFIX here, in case the 'xgettext' is not loaded # (sometimes we really don't need it) env . SetDefault ( POSUFFIX = [ '.po' ] , POTSUFFIX = [ '.pot' ] , _MSGINITLOCALE = '${TARGET.filebase}' , _MSGNoTranslator = _optional_no_translator_flag , MSGINITCOM = msginitcom , MSGINITCOMSTR = '' , MSGINITFLAGS = [ ] , POAUTOINIT = False , POCREATE_ALIAS = 'po-create' ) env . Append ( BUILDERS = { '_POInitBuilder' : _POInitBuilder ( env ) } ) env . AddMethod ( _POInitBuilderWrapper , 'POInit' ) env . AlwaysBuild ( env . Alias ( '$POCREATE_ALIAS' ) ) | Generate the msginit tool | 336 | 7 |
22,305 | def open_bled112 ( port , logger ) : if port is not None and port != '<auto>' : logger . info ( "Using BLED112 adapter at %s" , port ) return serial . Serial ( port , _BAUD_RATE , timeout = 0.01 , rtscts = True , exclusive = True ) return _find_available_bled112 ( logger ) | Open a BLED112 adapter either by name or the first available . | 84 | 14 |
22,306 | def _find_ble_controllers ( self ) : controllers = self . bable . list_controllers ( ) return [ ctrl for ctrl in controllers if ctrl . powered and ctrl . low_energy ] | Get a list of the available and powered BLE controllers | 47 | 11 |
22,307 | def stop_scan ( self ) : try : self . bable . stop_scan ( sync = True ) except bable_interface . BaBLEException : # If we errored our it is because we were not currently scanning pass self . scanning = False | Stop to scan . | 53 | 4 |
22,308 | def _open_rpc_interface ( self , connection_id , callback ) : try : context = self . connections . get_context ( connection_id ) except ArgumentError : callback ( connection_id , self . id , False , "Could not find connection information" ) return self . connections . begin_operation ( connection_id , 'open_interface' , callback , self . get_config ( 'default_timeout' ) ) try : service = context [ 'services' ] [ TileBusService ] header_characteristic = service [ ReceiveHeaderChar ] payload_characteristic = service [ ReceivePayloadChar ] except KeyError : self . connections . finish_operation ( connection_id , False , "Can't find characteristics to open rpc interface" ) return # Enable notification from ReceiveHeaderChar characteristic (ReceivePayloadChar will be enable just after) self . bable . set_notification ( enabled = True , connection_handle = context [ 'connection_handle' ] , characteristic = header_characteristic , on_notification_set = [ self . _on_interface_opened , context , payload_characteristic ] , on_notification_received = self . _on_notification_received , sync = False ) | Enable RPC interface for this IOTile device | 264 | 9 |
22,309 | def _open_streaming_interface ( self , connection_id , callback ) : try : context = self . connections . get_context ( connection_id ) except ArgumentError : callback ( connection_id , self . id , False , "Could not find connection information" ) return self . _logger . info ( "Attempting to enable streaming" ) self . connections . begin_operation ( connection_id , 'open_interface' , callback , self . get_config ( 'default_timeout' ) ) try : characteristic = context [ 'services' ] [ TileBusService ] [ StreamingChar ] except KeyError : self . connections . finish_operation ( connection_id , False , "Can't find characteristic to open streaming interface" ) return context [ 'parser' ] = IOTileReportParser ( report_callback = self . _on_report , error_callback = self . _on_report_error ) context [ 'parser' ] . context = connection_id def on_report_chunk_received ( report_chunk ) : """Callback function called when a report chunk has been received.""" context [ 'parser' ] . add_data ( report_chunk ) # Register our callback function in the notifications callbacks self . _register_notification_callback ( context [ 'connection_handle' ] , characteristic . value_handle , on_report_chunk_received ) self . bable . set_notification ( enabled = True , connection_handle = context [ 'connection_handle' ] , characteristic = characteristic , on_notification_set = [ self . _on_interface_opened , context ] , on_notification_received = self . _on_notification_received , timeout = 1.0 , sync = False ) | Enable streaming interface for this IOTile device | 373 | 9 |
22,310 | def _open_tracing_interface ( self , connection_id , callback ) : try : context = self . connections . get_context ( connection_id ) except ArgumentError : callback ( connection_id , self . id , False , "Could not find connection information" ) return self . _logger . info ( "Attempting to enable tracing" ) self . connections . begin_operation ( connection_id , 'open_interface' , callback , self . get_config ( 'default_timeout' ) ) try : characteristic = context [ 'services' ] [ TileBusService ] [ TracingChar ] except KeyError : self . connections . finish_operation ( connection_id , False , "Can't find characteristic to open tracing interface" ) return # Register a callback function in the notifications callbacks, to trigger `on_trace` callback when a trace is # notified. self . _register_notification_callback ( context [ 'connection_handle' ] , characteristic . value_handle , lambda trace_chunk : self . _trigger_callback ( 'on_trace' , connection_id , bytearray ( trace_chunk ) ) ) self . bable . set_notification ( enabled = True , connection_handle = context [ 'connection_handle' ] , characteristic = characteristic , on_notification_set = [ self . _on_interface_opened , context ] , on_notification_received = self . _on_notification_received , timeout = 1.0 , sync = False ) | Enable the tracing interface for this IOTile device | 322 | 10 |
22,311 | def _close_rpc_interface ( self , connection_id , callback ) : try : context = self . connections . get_context ( connection_id ) except ArgumentError : callback ( connection_id , self . id , False , "Could not find connection information" ) return self . connections . begin_operation ( connection_id , 'close_interface' , callback , self . get_config ( 'default_timeout' ) ) try : service = context [ 'services' ] [ TileBusService ] header_characteristic = service [ ReceiveHeaderChar ] payload_characteristic = service [ ReceivePayloadChar ] except KeyError : self . connections . finish_operation ( connection_id , False , "Can't find characteristics to open rpc interface" ) return self . bable . set_notification ( enabled = False , connection_handle = context [ 'connection_handle' ] , characteristic = header_characteristic , on_notification_set = [ self . _on_interface_closed , context , payload_characteristic ] , timeout = 1.0 ) | Disable RPC interface for this IOTile device | 228 | 9 |
22,312 | def _on_report ( self , report , connection_id ) : self . _logger . info ( 'Received report: %s' , str ( report ) ) self . _trigger_callback ( 'on_report' , connection_id , report ) return False | Callback function called when a report has been processed . | 58 | 10 |
22,313 | def _on_report_error ( self , code , message , connection_id ) : self . _logger . critical ( "Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s" , code , message ) | Callback function called if an error occured while parsing a report | 57 | 12 |
22,314 | def _register_notification_callback ( self , connection_handle , attribute_handle , callback , once = False ) : notification_id = ( connection_handle , attribute_handle ) with self . notification_callbacks_lock : self . notification_callbacks [ notification_id ] = ( callback , once ) | Register a callback as a notification callback . It will be called if a notification with the matching connection_handle and attribute_handle is received . | 66 | 28 |
22,315 | def periodic_callback ( self ) : if self . stopped : return # Check if we should start scanning again if not self . scanning and len ( self . connections . get_connections ( ) ) == 0 : self . _logger . info ( "Restarting scan for devices" ) self . start_scan ( self . _active_scan ) self . _logger . info ( "Finished restarting scan for devices" ) | Periodic cleanup tasks to maintain this adapter should be called every second . | 92 | 15 |
22,316 | def format_snippet ( sensor_graph ) : output = [ ] # Clear any old sensor graph output . append ( "disable" ) output . append ( "clear" ) output . append ( "reset" ) # Load in the nodes for node in sensor_graph . dump_nodes ( ) : output . append ( 'add_node "{}"' . format ( node ) ) # Load in the streamers for streamer in sensor_graph . streamers : line = "add_streamer '{}' '{}' {} {} {}" . format ( streamer . selector , streamer . dest , streamer . automatic , streamer . format , streamer . report_type ) if streamer . with_other is not None : line += ' --withother {}' . format ( streamer . with_other ) output . append ( line ) # Load all the constants for stream , value in sorted ( sensor_graph . constant_database . items ( ) , key = lambda x : x [ 0 ] . encode ( ) ) : output . append ( "set_constant '{}' {}" . format ( stream , value ) ) # Persist the sensor graph output . append ( "persist" ) output . append ( "back" ) # If we have an app tag and version set program them in app_tag = sensor_graph . metadata_database . get ( 'app_tag' ) app_version = sensor_graph . metadata_database . get ( 'app_version' ) if app_tag is not None : if app_version is None : app_version = "0.0" output . append ( "test_interface" ) output . append ( "set_version app %d --version '%s'" % ( app_tag , app_version ) ) output . append ( "back" ) # Load in the config variables if any output . append ( "config_database" ) output . append ( "clear_variables" ) for slot , conf_vars in sensor_graph . config_database . items ( ) : for conf_var , conf_def in conf_vars . items ( ) : conf_type , conf_val = conf_def if conf_type == 'binary' : conf_val = 'hex:' + hexlify ( conf_val ) elif isinstance ( conf_val , str ) : conf_val = '"%s"' % conf_val output . append ( "set_variable '{}' {} {} {}" . format ( slot , conf_var , conf_type , conf_val ) ) # Restart the device to load in the new sg output . append ( "back" ) output . append ( "reset" ) return "\n" . join ( output ) + '\n' | Format this sensor graph as iotile command snippets . | 595 | 11 |
22,317 | def find_bled112_devices ( cls ) : found_devs = [ ] ports = serial . tools . list_ports . comports ( ) for port in ports : if not hasattr ( port , 'pid' ) or not hasattr ( port , 'vid' ) : continue # Check if the device matches the BLED112's PID/VID combination if port . pid == 1 and port . vid == 9304 : found_devs . append ( port . device ) return found_devs | Look for BLED112 dongles on this computer and start an instance on each one | 108 | 18 |
22,318 | def get_scan_stats ( self ) : time_spent = time . time ( ) return self . _scan_event_count , self . _v1_scan_count , self . _v1_scan_response_count , self . _v2_scan_count , self . _device_scan_counts . copy ( ) , ( time_spent - self . _last_reset_time ) | Return the scan event statistics for this adapter | 91 | 8 |
22,319 | def reset_scan_stats ( self ) : self . _scan_event_count = 0 self . _v1_scan_count = 0 self . _v1_scan_response_count = 0 self . _v2_scan_count = 0 self . _device_scan_counts = { } self . _last_reset_time = time . time ( ) | Clears the scan event statistics and updates the last reset time | 81 | 12 |
22,320 | def start_scan ( self , active ) : self . _command_task . sync_command ( [ '_start_scan' , active ] ) self . scanning = True | Start the scanning task | 37 | 4 |
22,321 | def _open_tracing_interface ( self , conn_id , callback ) : try : handle = self . _find_handle ( conn_id ) services = self . _connections [ handle ] [ 'services' ] except ( ValueError , KeyError ) : callback ( conn_id , self . id , False , 'Connection closed unexpectedly before we could open the streaming interface' ) return self . _command_task . async_command ( [ '_enable_tracing' , handle , services ] , self . _on_interface_finished , { 'connection_id' : conn_id , 'callback' : callback } ) | Enable the debug tracing interface for this IOTile device | 135 | 11 |
22,322 | def _process_scan_event ( self , response ) : payload = response . payload length = len ( payload ) - 10 if length < 0 : return rssi , packet_type , sender , _addr_type , _bond , data = unpack ( "<bB6sBB%ds" % length , payload ) string_address = ':' . join ( [ format ( x , "02X" ) for x in bytearray ( sender [ : : - 1 ] ) ] ) # Scan data is prepended with a length if len ( data ) > 0 : data = bytearray ( data [ 1 : ] ) else : data = bytearray ( [ ] ) self . _scan_event_count += 1 # If this is an advertisement packet, see if its an IOTile device # packet_type = 4 is scan_response, 0, 2 and 6 are advertisements if packet_type in ( 0 , 2 , 6 ) : if len ( data ) != 31 : return if data [ 22 ] == 0xFF and data [ 23 ] == 0xC0 and data [ 24 ] == 0x3 : self . _v1_scan_count += 1 self . _parse_v1_advertisement ( rssi , string_address , data ) elif data [ 3 ] == 27 and data [ 4 ] == 0x16 and data [ 5 ] == 0xdd and data [ 6 ] == 0xfd : self . _v2_scan_count += 1 self . _parse_v2_advertisement ( rssi , string_address , data ) else : pass # This just means the advertisement was from a non-IOTile device elif packet_type == 4 : self . _v1_scan_response_count += 1 self . _parse_v1_scan_response ( string_address , data ) | Parse the BLE advertisement packet . | 399 | 8 |
22,323 | def _parse_v2_advertisement ( self , rssi , sender , data ) : if len ( data ) != 31 : return # We have already verified that the device is an IOTile device # by checking its service data uuid in _process_scan_event so # here we just parse out the required information device_id , reboot_low , reboot_high_packed , flags , timestamp , battery , counter_packed , broadcast_stream_packed , broadcast_value , _mac = unpack ( "<LHBBLBBHLL" , data [ 7 : ] ) reboots = ( reboot_high_packed & 0xF ) << 16 | reboot_low counter = counter_packed & ( ( 1 << 5 ) - 1 ) broadcast_multiplex = counter_packed >> 5 broadcast_toggle = broadcast_stream_packed >> 15 broadcast_stream = broadcast_stream_packed & ( ( 1 << 15 ) - 1 ) # Flags for version 2 are: # bit 0: Has pending data to stream # bit 1: Low voltage indication # bit 2: User connected # bit 3: Broadcast data is encrypted # bit 4: Encryption key is device key # bit 5: Encryption key is user key # bit 6: broadcast data is time synchronized to avoid leaking # information about when it changes self . _device_scan_counts . setdefault ( device_id , { 'v1' : 0 , 'v2' : 0 } ) [ 'v2' ] += 1 info = { 'connection_string' : sender , 'uuid' : device_id , 'pending_data' : bool ( flags & ( 1 << 0 ) ) , 'low_voltage' : bool ( flags & ( 1 << 1 ) ) , 'user_connected' : bool ( flags & ( 1 << 2 ) ) , 'signal_strength' : rssi , 'reboot_counter' : reboots , 'sequence' : counter , 'broadcast_toggle' : broadcast_toggle , 'timestamp' : timestamp , 'battery' : battery / 32.0 , 'advertising_version' : 2 } self . _trigger_callback ( 'on_scan' , self . id , info , self . ExpirationTime ) # If there is a valid reading on the advertising data, broadcast it if broadcast_stream != 0xFFFF & ( ( 1 << 15 ) - 1 ) : if self . _throttle_broadcast and self . _check_update_seen_broadcast ( sender , timestamp , broadcast_stream , broadcast_value , broadcast_toggle , counter = counter , channel = broadcast_multiplex ) : return reading = IOTileReading ( timestamp , broadcast_stream , broadcast_value , reading_time = datetime . datetime . utcnow ( ) ) report = BroadcastReport . FromReadings ( info [ 'uuid' ] , [ reading ] , timestamp ) self . _trigger_callback ( 'on_report' , None , report ) | Parse the IOTile Specific advertisement packet | 633 | 9 |
22,324 | def probe_services ( self , handle , conn_id , callback ) : self . _command_task . async_command ( [ '_probe_services' , handle ] , callback , { 'connection_id' : conn_id , 'handle' : handle } ) | Given a connected device probe for its GATT services and characteristics | 59 | 12 |
22,325 | def probe_characteristics ( self , conn_id , handle , services ) : self . _command_task . async_command ( [ '_probe_characteristics' , handle , services ] , self . _probe_characteristics_finished , { 'connection_id' : conn_id , 'handle' : handle , 'services' : services } ) | Probe a device for all characteristics defined in its GATT table | 78 | 13 |
22,326 | def _on_disconnect ( self , result ) : success , _ , context = self . _parse_return ( result ) callback = context [ 'callback' ] connection_id = context [ 'connection_id' ] handle = context [ 'handle' ] callback ( connection_id , self . id , success , "No reason given" ) self . _remove_connection ( handle ) | Callback called when disconnection command finishes | 82 | 7 |
22,327 | def _parse_return ( cls , result ) : return_value = None success = result [ 'result' ] context = result [ 'context' ] if 'return_value' in result : return_value = result [ 'return_value' ] return success , return_value , context | Extract the result return value and context from a result object | 62 | 12 |
22,328 | def _get_connection ( self , handle , expect_state = None ) : conndata = self . _connections . get ( handle ) if conndata and expect_state is not None and conndata [ 'state' ] != expect_state : self . _logger . error ( "Connection in unexpected state, wanted=%s, got=%s" , expect_state , conndata [ 'state' ] ) return conndata | Get a connection object logging an error if its in an unexpected state | 98 | 13 |
22,329 | def _on_connection_finished ( self , result ) : success , retval , context = self . _parse_return ( result ) conn_id = context [ 'connection_id' ] callback = context [ 'callback' ] if success is False : callback ( conn_id , self . id , False , 'Timeout opening connection' ) with self . count_lock : self . connecting_count -= 1 return handle = retval [ 'handle' ] context [ 'disconnect_handler' ] = self . _on_connection_failed context [ 'connect_time' ] = time . time ( ) context [ 'state' ] = 'preparing' self . _connections [ handle ] = context self . probe_services ( handle , conn_id , self . _probe_services_finished ) | Callback when the connection attempt to a BLE device has finished | 171 | 12 |
22,330 | def _on_connection_failed ( self , conn_id , handle , clean , reason ) : with self . count_lock : self . connecting_count -= 1 self . _logger . info ( "_on_connection_failed conn_id=%d, reason=%s" , conn_id , str ( reason ) ) conndata = self . _get_connection ( handle ) if conndata is None : self . _logger . info ( "Unable to obtain connection data on unknown connection %d" , conn_id ) return callback = conndata [ 'callback' ] conn_id = conndata [ 'connection_id' ] failure_reason = conndata [ 'failure_reason' ] # If this was an early disconnect from the device, automatically retry if 'error_code' in conndata and conndata [ 'error_code' ] == 0x23e and conndata [ 'retries' ] > 0 : self . _remove_connection ( handle ) self . connect_async ( conn_id , conndata [ 'connection_string' ] , callback , conndata [ 'retries' ] - 1 ) else : callback ( conn_id , self . id , False , failure_reason ) self . _remove_connection ( handle ) | Callback called from another thread when a connection attempt has failed . | 282 | 12 |
22,331 | def _probe_services_finished ( self , result ) : #If we were disconnected before this function is called, don't proceed handle = result [ 'context' ] [ 'handle' ] conn_id = result [ 'context' ] [ 'connection_id' ] conndata = self . _get_connection ( handle , 'preparing' ) if conndata is None : self . _logger . info ( 'Connection disconnected before prob_services_finished, conn_id=%d' , conn_id ) return if result [ 'result' ] is False : conndata [ 'failed' ] = True conndata [ 'failure_reason' ] = 'Could not probe GATT services' self . disconnect_async ( conn_id , self . _on_connection_failed ) else : conndata [ 'services_done_time' ] = time . time ( ) self . probe_characteristics ( result [ 'context' ] [ 'connection_id' ] , result [ 'context' ] [ 'handle' ] , result [ 'return_value' ] [ 'services' ] ) | Callback called after a BLE device has had its GATT table completely probed | 241 | 16 |
22,332 | def _probe_characteristics_finished ( self , result ) : handle = result [ 'context' ] [ 'handle' ] conn_id = result [ 'context' ] [ 'connection_id' ] conndata = self . _get_connection ( handle , 'preparing' ) if conndata is None : self . _logger . info ( 'Connection disconnected before probe_char... finished, conn_id=%d' , conn_id ) return callback = conndata [ 'callback' ] if result [ 'result' ] is False : conndata [ 'failed' ] = True conndata [ 'failure_reason' ] = 'Could not probe GATT characteristics' self . disconnect_async ( conn_id , self . _on_connection_failed ) return # Validate that this is a proper IOTile device services = result [ 'return_value' ] [ 'services' ] if TileBusService not in services : conndata [ 'failed' ] = True conndata [ 'failure_reason' ] = 'TileBus service not present in GATT services' self . disconnect_async ( conn_id , self . _on_connection_failed ) return conndata [ 'chars_done_time' ] = time . time ( ) service_time = conndata [ 'services_done_time' ] - conndata [ 'connect_time' ] char_time = conndata [ 'chars_done_time' ] - conndata [ 'services_done_time' ] total_time = service_time + char_time conndata [ 'state' ] = 'connected' conndata [ 'services' ] = services # Create a report parser for this connection for when reports are streamed to us conndata [ 'parser' ] = IOTileReportParser ( report_callback = self . _on_report , error_callback = self . _on_report_error ) conndata [ 'parser' ] . context = conn_id del conndata [ 'disconnect_handler' ] with self . count_lock : self . connecting_count -= 1 self . _logger . info ( "Total time to connect to device: %.3f (%.3f enumerating services, %.3f enumerating chars)" , total_time , service_time , char_time ) callback ( conndata [ 'connection_id' ] , self . id , True , None ) | Callback when BLE adapter has finished probing services and characteristics for a device | 534 | 14 |
22,333 | def periodic_callback ( self ) : if self . stopped : return # Check if we should start scanning again if not self . scanning and len ( self . _connections ) == 0 and self . connecting_count == 0 : self . _logger . info ( "Restarting scan for devices" ) self . start_scan ( self . _active_scan ) self . _logger . info ( "Finished restarting scan for devices" ) | Periodic cleanup tasks to maintain this adapter should be called every second | 95 | 14 |
22,334 | def convert_to_BuildError ( status , exc_info = None ) : if not exc_info and isinstance ( status , Exception ) : exc_info = ( status . __class__ , status , None ) if isinstance ( status , BuildError ) : buildError = status buildError . exitstatus = 2 # always exit with 2 on build errors elif isinstance ( status , ExplicitExit ) : status = status . status errstr = 'Explicit exit, status %s' % status buildError = BuildError ( errstr = errstr , status = status , # might be 0, OK here exitstatus = status , # might be 0, OK here exc_info = exc_info ) elif isinstance ( status , ( StopError , UserError ) ) : buildError = BuildError ( errstr = str ( status ) , status = 2 , exitstatus = 2 , exc_info = exc_info ) elif isinstance ( status , shutil . SameFileError ) : # PY3 has a exception for when copying file to itself # It's object provides info differently than below try : filename = status . filename except AttributeError : filename = None buildError = BuildError ( errstr = status . args [ 0 ] , status = status . errno , exitstatus = 2 , filename = filename , exc_info = exc_info ) elif isinstance ( status , ( EnvironmentError , OSError , IOError ) ) : # If an IOError/OSError happens, raise a BuildError. # Report the name of the file or directory that caused the # error, which might be different from the target being built # (for example, failure to create the directory in which the # target file will appear). try : filename = status . filename except AttributeError : filename = None buildError = BuildError ( errstr = status . strerror , status = status . errno , exitstatus = 2 , filename = filename , exc_info = exc_info ) elif isinstance ( status , Exception ) : buildError = BuildError ( errstr = '%s : %s' % ( status . __class__ . __name__ , status ) , status = 2 , exitstatus = 2 , exc_info = exc_info ) elif SCons . Util . is_String ( status ) : buildError = BuildError ( errstr = status , status = 2 , exitstatus = 2 ) else : buildError = BuildError ( errstr = "Error %s" % status , status = status , exitstatus = 2 ) #import sys #sys.stderr.write("convert_to_BuildError: status %s => (errstr %s, status %s)\n"%(status,buildError.errstr, buildError.status)) return buildError | Convert any return code a BuildError Exception . | 595 | 10 |
22,335 | def format_config ( sensor_graph ) : cmdfile = CommandFile ( "Config Variables" , "1.0" ) for slot in sorted ( sensor_graph . config_database , key = lambda x : x . encode ( ) ) : for conf_var , conf_def in sorted ( sensor_graph . config_database [ slot ] . items ( ) ) : conf_type , conf_val = conf_def if conf_type == 'binary' : conf_val = 'hex:' + hexlify ( conf_val ) cmdfile . add ( "set_variable" , slot , conf_var , conf_type , conf_val ) return cmdfile . dump ( ) | Extract the config variables from this sensor graph in ASCII format . | 151 | 13 |
22,336 | def generate ( env ) : path , _f77 , _shf77 , version = get_xlf77 ( env ) if path : _f77 = os . path . join ( path , _f77 ) _shf77 = os . path . join ( path , _shf77 ) f77 . generate ( env ) env [ 'F77' ] = _f77 env [ 'SHF77' ] = _shf77 | Add Builders and construction variables for the Visual Age FORTRAN compiler to an Environment . | 95 | 18 |
22,337 | def DirScanner ( * * kw ) : kw [ 'node_factory' ] = SCons . Node . FS . Entry kw [ 'recursive' ] = only_dirs return SCons . Scanner . Base ( scan_on_disk , "DirScanner" , * * kw ) | Return a prototype Scanner instance for scanning directories for on - disk files | 69 | 14 |
22,338 | def DirEntryScanner ( * * kw ) : kw [ 'node_factory' ] = SCons . Node . FS . Entry kw [ 'recursive' ] = None return SCons . Scanner . Base ( scan_in_memory , "DirEntryScanner" , * * kw ) | Return a prototype Scanner instance for scanning directory Nodes for their in - memory entries | 68 | 17 |
22,339 | def scan_on_disk ( node , env , path = ( ) ) : try : flist = node . fs . listdir ( node . get_abspath ( ) ) except ( IOError , OSError ) : return [ ] e = node . Entry for f in filter ( do_not_scan , flist ) : # Add ./ to the beginning of the file name so if it begins with a # '#' we don't look it up relative to the top-level directory. e ( './' + f ) return scan_in_memory ( node , env , path ) | Scans a directory for on - disk files and directories therein . | 128 | 13 |
22,340 | def scan_in_memory ( node , env , path = ( ) ) : try : entries = node . entries except AttributeError : # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [ ] entry_list = sorted ( filter ( do_not_scan , list ( entries . keys ( ) ) ) ) return [ entries [ n ] for n in entry_list ] | Scans a Node . FS . Dir for its in - memory entries . | 122 | 15 |
22,341 | def set_result ( self , result ) : if self . is_finished ( ) : raise InternalError ( "set_result called on finished AsynchronousResponse" , result = self . _result , exception = self . _exception ) self . _result = result self . finish ( ) | Finish this response and set the result . | 61 | 8 |
22,342 | def set_exception ( self , exc_class , exc_info , exc_stack ) : if self . is_finished ( ) : raise InternalError ( "set_exception called on finished AsynchronousResponse" , result = self . _result , exception = self . _exception ) self . _exception = ( exc_class , exc_info , exc_stack ) self . finish ( ) | Set an exception as the result of this operation . | 86 | 10 |
22,343 | def get_released_versions ( component ) : releases = get_tags ( ) releases = sorted ( [ ( x [ 0 ] , [ int ( y ) for y in x [ 1 ] . split ( '.' ) ] ) for x in releases ] , key = lambda x : x [ 1 ] ) [ : : - 1 ] return [ ( x [ 0 ] , "." . join ( map ( str , x [ 1 ] ) ) ) for x in releases if x [ 0 ] == component ] | Get all released versions of the given component ordered newest to oldest | 106 | 12 |
22,344 | def load_dependencies ( orig_tile , build_env ) : if 'DEPENDENCIES' not in build_env : build_env [ 'DEPENDENCIES' ] = [ ] dep_targets = [ ] chip = build_env [ 'ARCH' ] raw_arch_deps = chip . property ( 'depends' ) # Properly separate out the version information from the name of the dependency # The raw keys come back as name,version arch_deps = { } for key , value in raw_arch_deps . items ( ) : name , _ , _ = key . partition ( ',' ) arch_deps [ name ] = value for dep in orig_tile . dependencies : try : tile = IOTile ( os . path . join ( 'build' , 'deps' , dep [ 'unique_id' ] ) ) # Make sure we filter products using the view of module dependency products # as seen in the target we are targeting. if dep [ 'name' ] not in arch_deps : tile . filter_products ( [ ] ) else : tile . filter_products ( arch_deps [ dep [ 'name' ] ] ) except ( ArgumentError , EnvironmentError ) : raise BuildError ( "Could not find required dependency" , name = dep [ 'name' ] ) build_env [ 'DEPENDENCIES' ] . append ( tile ) target = os . path . join ( tile . folder , 'module_settings.json' ) dep_targets . append ( target ) return dep_targets | Load all tile dependencies and filter only the products from each that we use | 336 | 14 |
22,345 | def find_dependency_wheels ( tile ) : return [ os . path . join ( x . folder , 'python' , x . support_wheel ) for x in _iter_dependencies ( tile ) if x . has_wheel ] | Return a list of all python wheel objects created by dependencies of this tile | 52 | 14 |
22,346 | def _check_ver_range ( self , version , ver_range ) : lower , upper , lower_inc , upper_inc = ver_range #If the range extends over everything, we automatically match if lower is None and upper is None : return True if lower is not None : if lower_inc and version < lower : return False elif not lower_inc and version <= lower : return False if upper is not None : if upper_inc and version > upper : return False elif not upper_inc and version >= upper : return False # Prereleases have special matching requirements if version . is_prerelease : # Prereleases cannot match ranges that are not defined as prereleases if ( lower is None or not lower . is_prerelease ) and ( upper is None or not upper . is_prerelease ) : return False # Prereleases without the same major.minor.patch as a range end point cannot match if ( lower is not None and version . release_tuple != lower . release_tuple ) and ( upper is not None and version . release_tuple != upper . release_tuple ) : return False return True | Check if version is included in ver_range | 243 | 9 |
22,347 | def _check_insersection ( self , version , ranges ) : for ver_range in ranges : if not self . _check_ver_range ( version , ver_range ) : return False return True | Check that a version is inside all of a list of ranges | 44 | 12 |
22,348 | def check ( self , version ) : for disjunct in self . _disjuncts : if self . _check_insersection ( version , disjunct ) : return True return False | Check that a version is inside this SemanticVersionRange | 42 | 11 |
22,349 | def filter ( self , versions , key = lambda x : x ) : return [ x for x in versions if self . check ( key ( x ) ) ] | Filter all of the versions in an iterable that match this version range | 33 | 14 |
22,350 | def FromString ( cls , range_string ) : disjuncts = None range_string = range_string . strip ( ) if len ( range_string ) == 0 : raise ArgumentError ( "You must pass a finite string to SemanticVersionRange.FromString" , range_string = range_string ) # Check for * if len ( range_string ) == 1 and range_string [ 0 ] == '*' : conj = ( None , None , True , True ) disjuncts = [ [ conj ] ] # Check for ^X.Y.Z elif range_string [ 0 ] == '^' : ver = range_string [ 1 : ] try : ver = SemanticVersion . FromString ( ver ) except DataError as err : raise ArgumentError ( "Could not parse ^X.Y.Z version" , parse_error = str ( err ) , range_string = range_string ) lower = ver upper = ver . inc_first_nonzero ( ) conj = ( lower , upper , True , False ) disjuncts = [ [ conj ] ] elif range_string [ 0 ] == '=' : ver = range_string [ 1 : ] try : ver = SemanticVersion . FromString ( ver ) except DataError as err : raise ArgumentError ( "Could not parse =X.Y.Z version" , parse_error = str ( err ) , range_string = range_string ) conj = ( ver , ver , True , True ) disjuncts = [ [ conj ] ] if disjuncts is None : raise ArgumentError ( "Invalid range specification that could not be parsed" , range_string = range_string ) return SemanticVersionRange ( disjuncts ) | Parse a version range string into a SemanticVersionRange | 371 | 12 |
22,351 | def _call_rpc ( self , address , rpc_id , payload ) : # FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but # this should be long enough to accommodate any actual RPCs we need to send. status , response = self . hw . stream . send_rpc ( address , rpc_id , payload , timeout = 1.1 ) return response | Call an RPC with the given information and return its response . | 91 | 12 |
22,352 | def FromReadings ( cls , uuid , readings ) : if len ( readings ) != 1 : raise ArgumentError ( "IndividualReading reports must be created with exactly one reading" , num_readings = len ( readings ) ) reading = readings [ 0 ] data = struct . pack ( "<BBHLLLL" , 0 , 0 , reading . stream , uuid , 0 , reading . raw_time , reading . value ) return IndividualReadingReport ( data ) | Generate an instance of the report format from a list of readings and a uuid | 98 | 17 |
22,353 | def decode ( self ) : fmt , _ , stream , uuid , sent_timestamp , reading_timestamp , reading_value = unpack ( "<BBHLLLL" , self . raw_report ) assert fmt == 0 # Estimate the UTC time when this device was turned on time_base = self . received_time - datetime . timedelta ( seconds = sent_timestamp ) reading = IOTileReading ( reading_timestamp , stream , reading_value , time_base = time_base ) self . origin = uuid self . sent_timestamp = sent_timestamp return [ reading ] , [ ] | Decode this report into a single reading | 134 | 8 |
22,354 | def encode ( self ) : reading = self . visible_readings [ 0 ] data = struct . pack ( "<BBHLLLL" , 0 , 0 , reading . stream , self . origin , self . sent_timestamp , reading . raw_time , reading . value ) return bytearray ( data ) | Turn this report into a serialized bytearray that could be decoded with a call to decode | 67 | 21 |
22,355 | def is_LaTeX ( flist , env , abspath ) : # We need to scan files that are included in case the # \documentclass command is in them. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var ( env , 'TEXINPUTS' , abspath ) paths = env [ 'ENV' ] [ 'TEXINPUTS' ] if SCons . Util . is_List ( paths ) : pass else : # Split at os.pathsep to convert into absolute path paths = paths . split ( os . pathsep ) # now that we have the path list restore the env if savedpath is _null : try : del env [ 'ENV' ] [ 'TEXINPUTS' ] except KeyError : pass # was never set else : env [ 'ENV' ] [ 'TEXINPUTS' ] = savedpath if Verbose : print ( "is_LaTeX search path " , paths ) print ( "files to search :" , flist ) # Now that we have the search path and file list, check each one for f in flist : if Verbose : print ( " checking for Latex source " , str ( f ) ) content = f . get_text_contents ( ) if LaTeX_re . search ( content ) : if Verbose : print ( "file %s is a LaTeX file" % str ( f ) ) return 1 if Verbose : print ( "file %s is not a LaTeX file" % str ( f ) ) # now find included files inc_files = [ ] inc_files . extend ( include_re . findall ( content ) ) if Verbose : print ( "files included by '%s': " % str ( f ) , inc_files ) # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. # search the included files for src in inc_files : srcNode = FindFile ( src , [ '.tex' , '.ltx' , '.latex' ] , paths , env , requireExt = False ) # make this a list since is_LaTeX takes a list. fileList = [ srcNode , ] if Verbose : print ( "FindFile found " , srcNode ) if srcNode is not None : file_test = is_LaTeX ( fileList , env , abspath ) # return on first file that finds latex is needed. if file_test : return file_test if Verbose : print ( " done scanning " , str ( f ) ) return 0 | Scan a file list to decide if it s TeX - or LaTeX - flavored . | 573 | 18 |
22,356 | def TeXLaTeXStrFunction ( target = None , source = None , env = None ) : if env . GetOption ( "no_exec" ) : # find these paths for use in is_LaTeX to search for included files basedir = os . path . split ( str ( source [ 0 ] ) ) [ 0 ] abspath = os . path . abspath ( basedir ) if is_LaTeX ( source , env , abspath ) : result = env . subst ( '$LATEXCOM' , 0 , target , source ) + " ..." else : result = env . subst ( "$TEXCOM" , 0 , target , source ) + " ..." else : result = '' return result | A strfunction for TeX and LaTeX that scans the source file to decide the flavor of the source and then returns the appropriate command string . | 150 | 29 |
22,357 | def tex_eps_emitter ( target , source , env ) : ( target , source ) = tex_emitter_core ( target , source , env , TexGraphics ) return ( target , source ) | An emitter for TeX and LaTeX sources when executing tex or latex . It will accept . ps and . eps graphics files | 43 | 27 |
22,358 | def tex_pdf_emitter ( target , source , env ) : ( target , source ) = tex_emitter_core ( target , source , env , LatexGraphics ) return ( target , source ) | An emitter for TeX and LaTeX sources when executing pdftex or pdflatex . It will accept graphics files of types . pdf . jpg . png . gif and . tif | 44 | 42 |
22,359 | def generate ( env ) : global TeXLaTeXAction if TeXLaTeXAction is None : TeXLaTeXAction = SCons . Action . Action ( TeXLaTeXFunction , strfunction = TeXLaTeXStrFunction ) env . AppendUnique ( LATEXSUFFIXES = SCons . Tool . LaTeXSuffixes ) generate_common ( env ) from . import dvi dvi . generate ( env ) bld = env [ 'BUILDERS' ] [ 'DVI' ] bld . add_action ( '.tex' , TeXLaTeXAction ) bld . add_emitter ( '.tex' , tex_eps_emitter ) | Add Builders and construction variables for TeX to an Environment . | 147 | 13 |
22,360 | def is_win64 ( ) : # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit affects what it returns, # so nothing in sys.* or os.* help. # Apparently the best solution is to use env vars that Windows # sets. If PROCESSOR_ARCHITECTURE is not x86, then the python # process is running in 64 bit mode (on a 64-bit OS, 64-bit # hardware, obviously). # If this python is 32-bit but the OS is 64, Windows will set # ProgramW6432 and PROCESSOR_ARCHITEW6432 to non-null. # (Checking for HKLM\Software\Wow6432Node in the registry doesn't # work, because some 32-bit installers create it.) global _is_win64 if _is_win64 is None : # I structured these tests to make it easy to add new ones or # add exceptions in the future, because this is a bit fragile. _is_win64 = False if os . environ . get ( 'PROCESSOR_ARCHITECTURE' , 'x86' ) != 'x86' : _is_win64 = True if os . environ . get ( 'PROCESSOR_ARCHITEW6432' ) : _is_win64 = True if os . environ . get ( 'ProgramW6432' ) : _is_win64 = True return _is_win64 | Return true if running on windows 64 bits . | 338 | 9 |
22,361 | def has_reg ( value ) : try : SCons . Util . RegOpenKeyEx ( SCons . Util . HKEY_LOCAL_MACHINE , value ) ret = True except SCons . Util . WinError : ret = False return ret | Return True if the given key exists in HKEY_LOCAL_MACHINE False otherwise . | 57 | 20 |
22,362 | def normalize_env ( env , keys , force = False ) : normenv = { } if env : for k in list ( env . keys ( ) ) : normenv [ k ] = copy . deepcopy ( env [ k ] ) for k in keys : if k in os . environ and ( force or not k in normenv ) : normenv [ k ] = os . environ [ k ] # This shouldn't be necessary, since the default environment should include system32, # but keep this here to be safe, since it's needed to find reg.exe which the MSVC # bat scripts use. sys32_dir = os . path . join ( os . environ . get ( "SystemRoot" , os . environ . get ( "windir" , r"C:\Windows\system32" ) ) , "System32" ) if sys32_dir not in normenv [ 'PATH' ] : normenv [ 'PATH' ] = normenv [ 'PATH' ] + os . pathsep + sys32_dir # Without Wbem in PATH, vcvarsall.bat has a "'wmic' is not recognized" # error starting with Visual Studio 2017, although the script still # seems to work anyway. sys32_wbem_dir = os . path . join ( sys32_dir , 'Wbem' ) if sys32_wbem_dir not in normenv [ 'PATH' ] : normenv [ 'PATH' ] = normenv [ 'PATH' ] + os . pathsep + sys32_wbem_dir debug ( "PATH: %s" % normenv [ 'PATH' ] ) return normenv | Given a dictionary representing a shell environment add the variables from os . environ needed for the processing of . bat files ; the keys are controlled by the keys argument . | 357 | 33 |
22,363 | def get_output ( vcbat , args = None , env = None ) : if env is None : # Create a blank environment, for use in launching the tools env = SCons . Environment . Environment ( tools = [ ] ) # TODO: This is a hard-coded list of the variables that (may) need # to be imported from os.environ[] for v[sc]*vars*.bat file # execution to work. This list should really be either directly # controlled by vc.py, or else derived from the common_tools_var # settings in vs.py. vs_vc_vars = [ 'COMSPEC' , # VS100 and VS110: Still set, but modern MSVC setup scripts will # discard these if registry has values. However Intel compiler setup # script still requires these as of 2013/2014. 'VS140COMNTOOLS' , 'VS120COMNTOOLS' , 'VS110COMNTOOLS' , 'VS100COMNTOOLS' , 'VS90COMNTOOLS' , 'VS80COMNTOOLS' , 'VS71COMNTOOLS' , 'VS70COMNTOOLS' , 'VS60COMNTOOLS' , ] env [ 'ENV' ] = normalize_env ( env [ 'ENV' ] , vs_vc_vars , force = False ) if args : debug ( "Calling '%s %s'" % ( vcbat , args ) ) popen = SCons . Action . _subproc ( env , '"%s" %s & set' % ( vcbat , args ) , stdin = 'devnull' , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) else : debug ( "Calling '%s'" % vcbat ) popen = SCons . Action . _subproc ( env , '"%s" & set' % vcbat , stdin = 'devnull' , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) # Use the .stdout and .stderr attributes directly because the # .communicate() method uses the threading module on Windows # and won't work under Pythons not built with threading. stdout = popen . stdout . read ( ) stderr = popen . stderr . read ( ) # Extra debug logic, uncomment if necessary # debug('get_output():stdout:%s'%stdout) # debug('get_output():stderr:%s'%stderr) if stderr : # TODO: find something better to do with stderr; # this at least prevents errors from getting swallowed. import sys sys . stderr . write ( stderr ) if popen . wait ( ) != 0 : raise IOError ( stderr . decode ( "mbcs" ) ) output = stdout . decode ( "mbcs" ) return output | Parse the output of given bat file with given args . | 653 | 12 |
22,364 | def generate ( env ) : for t in SCons . Tool . tool_list ( env [ 'PLATFORM' ] , env ) : SCons . Tool . Tool ( t ) ( env ) | Add default tools . | 42 | 4 |
22,365 | def subst_path ( self , env , target , source ) : result = [ ] for type , value in self . pathlist : if type == TYPE_STRING_SUBST : value = env . subst ( value , target = target , source = source , conv = node_conv ) if SCons . Util . is_Sequence ( value ) : result . extend ( SCons . Util . flatten ( value ) ) elif value : result . append ( value ) elif type == TYPE_OBJECT : value = node_conv ( value ) if value : result . append ( value ) elif value : result . append ( value ) return tuple ( result ) | Performs construction variable substitution on a pre - digested PathList for a specific target and source . | 144 | 20 |
22,366 | def _PathList_key ( self , pathlist ) : if SCons . Util . is_Sequence ( pathlist ) : pathlist = tuple ( SCons . Util . flatten ( pathlist ) ) return pathlist | Returns the key for memoization of PathLists . | 50 | 11 |
22,367 | def PathList ( self , pathlist ) : pathlist = self . _PathList_key ( pathlist ) try : memo_dict = self . _memo [ 'PathList' ] except KeyError : memo_dict = { } self . _memo [ 'PathList' ] = memo_dict else : try : return memo_dict [ pathlist ] except KeyError : pass result = _PathList ( pathlist ) memo_dict [ pathlist ] = result return result | Returns the cached _PathList object for the specified pathlist creating and caching a new object as necessary . | 103 | 21 |
22,368 | def DefaultEnvironment ( * args , * * kw ) : global _default_env if not _default_env : import SCons . Util _default_env = SCons . Environment . Environment ( * args , * * kw ) if SCons . Util . md5 : _default_env . Decider ( 'MD5' ) else : _default_env . Decider ( 'timestamp-match' ) global DefaultEnvironment DefaultEnvironment = _fetch_DefaultEnvironment _default_env . _CacheDir_path = None return _default_env | Initial public entry point for creating the default construction Environment . | 120 | 11 |
22,369 | def _concat ( prefix , list , suffix , env , f = lambda x : x , target = None , source = None ) : if not list : return list l = f ( SCons . PathList . PathList ( list ) . subst_path ( env , target , source ) ) if l is not None : list = l return _concat_ixes ( prefix , list , suffix , env ) | Creates a new list from list by first interpolating each element in the list using the env dictionary and then calling f on the list and finally calling _concat_ixes to concatenate prefix and suffix onto each element of the list . | 87 | 50 |
22,370 | def _concat_ixes ( prefix , list , suffix , env ) : result = [ ] # ensure that prefix and suffix are strings prefix = str ( env . subst ( prefix , SCons . Subst . SUBST_RAW ) ) suffix = str ( env . subst ( suffix , SCons . Subst . SUBST_RAW ) ) for x in list : if isinstance ( x , SCons . Node . FS . File ) : result . append ( x ) continue x = str ( x ) if x : if prefix : if prefix [ - 1 ] == ' ' : result . append ( prefix [ : - 1 ] ) elif x [ : len ( prefix ) ] != prefix : x = prefix + x result . append ( x ) if suffix : if suffix [ 0 ] == ' ' : result . append ( suffix [ 1 : ] ) elif x [ - len ( suffix ) : ] != suffix : result [ - 1 ] = result [ - 1 ] + suffix return result | Creates a new list from list by concatenating the prefix and suffix arguments onto each element of the list . A trailing space on prefix or leading space on suffix will cause them to be put into separate list elements rather than being concatenated . | 207 | 50 |
22,371 | def processDefines ( defs ) : if SCons . Util . is_List ( defs ) : l = [ ] for d in defs : if d is None : continue elif SCons . Util . is_List ( d ) or isinstance ( d , tuple ) : if len ( d ) >= 2 : l . append ( str ( d [ 0 ] ) + '=' + str ( d [ 1 ] ) ) else : l . append ( str ( d [ 0 ] ) ) elif SCons . Util . is_Dict ( d ) : for macro , value in d . items ( ) : if value is not None : l . append ( str ( macro ) + '=' + str ( value ) ) else : l . append ( str ( macro ) ) elif SCons . Util . is_String ( d ) : l . append ( str ( d ) ) else : raise SCons . Errors . UserError ( "DEFINE %s is not a list, dict, string or None." % repr ( d ) ) elif SCons . Util . is_Dict ( defs ) : # The items in a dictionary are stored in random order, but # if the order of the command-line options changes from # invocation to invocation, then the signature of the command # line will change and we'll get random unnecessary rebuilds. # Consequently, we have to sort the keys to ensure a # consistent order... l = [ ] for k , v in sorted ( defs . items ( ) ) : if v is None : l . append ( str ( k ) ) else : l . append ( str ( k ) + '=' + str ( v ) ) else : l = [ str ( defs ) ] return l | process defines resolving strings lists dictionaries into a list of strings | 373 | 12 |
22,372 | def _defines ( prefix , defs , suffix , env , c = _concat_ixes ) : return c ( prefix , env . subst_path ( processDefines ( defs ) ) , suffix , env ) | A wrapper around _concat_ixes that turns a list or string into a list of C preprocessor command - line definitions . | 48 | 27 |
22,373 | def Scanner ( function , * args , * * kw ) : if SCons . Util . is_Dict ( function ) : return Selector ( function , * args , * * kw ) else : return Base ( function , * args , * * kw ) | Public interface factory function for creating different types of Scanners based on the different types of functions that may be supplied . | 59 | 23 |
22,374 | def ReportLength ( cls , header ) : parsed_header = cls . _parse_header ( header ) auth_size = cls . _AUTH_BLOCK_LENGTHS . get ( parsed_header . auth_type ) if auth_size is None : raise DataError ( "Unknown auth block size in BroadcastReport" ) return cls . _HEADER_LENGTH + parsed_header . reading_length + auth_size | Given a header of HeaderLength bytes calculate the size of this report . | 95 | 14 |
22,375 | def FromReadings ( cls , uuid , readings , sent_timestamp = 0 ) : header = struct . pack ( "<BBHLLL" , cls . ReportType , 0 , len ( readings ) * 16 , uuid , sent_timestamp , 0 ) packed_readings = bytearray ( ) for reading in readings : packed_reading = struct . pack ( "<HHLLL" , reading . stream , 0 , reading . reading_id , reading . raw_time , reading . value ) packed_readings += bytearray ( packed_reading ) return BroadcastReport ( bytearray ( header ) + packed_readings ) | Generate a broadcast report from a list of readings and a uuid . | 142 | 15 |
22,376 | def decode ( self ) : parsed_header = self . _parse_header ( self . raw_report [ : self . _HEADER_LENGTH ] ) auth_size = self . _AUTH_BLOCK_LENGTHS . get ( parsed_header . auth_type ) assert auth_size is not None assert parsed_header . reading_length % 16 == 0 time_base = self . received_time - datetime . timedelta ( seconds = parsed_header . sent_timestamp ) readings = self . raw_report [ self . _HEADER_LENGTH : self . _HEADER_LENGTH + parsed_header . reading_length ] parsed_readings = [ ] for i in range ( 0 , len ( readings ) , 16 ) : reading = readings [ i : i + 16 ] stream , _ , reading_id , timestamp , value = struct . unpack ( "<HHLLL" , reading ) parsed = IOTileReading ( timestamp , stream , value , time_base = time_base , reading_id = reading_id ) parsed_readings . append ( parsed ) self . sent_timestamp = parsed_header . sent_timestamp self . origin = parsed_header . uuid return parsed_readings , [ ] | Decode this report into a list of visible readings . | 269 | 11 |
22,377 | def start ( self , device ) : super ( NativeBLEVirtualInterface , self ) . start ( device ) self . set_advertising ( True ) | Start serving access to this VirtualIOTileDevice | 30 | 10 |
22,378 | def register_gatt_table ( self ) : services = [ BLEService , TileBusService ] characteristics = [ NameChar , AppearanceChar , ReceiveHeaderChar , ReceivePayloadChar , SendHeaderChar , SendPayloadChar , StreamingChar , HighSpeedChar , TracingChar ] self . bable . set_gatt_table ( services , characteristics ) | Register the GATT table into baBLE . | 79 | 9 |
22,379 | def set_advertising ( self , enabled ) : if enabled : self . bable . set_advertising ( enabled = True , uuids = [ TileBusService . uuid ] , name = "V_IOTile " , company_id = ArchManuID , advertising_data = self . _advertisement ( ) , scan_response = self . _scan_response ( ) , sync = True ) else : try : self . bable . set_advertising ( enabled = False , sync = True ) except bable_interface . BaBLEException : # If advertising is already disabled pass | Toggle advertising . | 124 | 4 |
22,380 | def _advertisement ( self ) : # Flags are # bit 0: whether we have pending data # bit 1: whether we are in a low voltage state # bit 2: whether another user is connected # bit 3: whether we support robust reports # bit 4: whether we allow fast writes flags = int ( self . device . pending_data ) | ( 0 << 1 ) | ( 0 << 2 ) | ( 1 << 3 ) | ( 1 << 4 ) return struct . pack ( "<LH" , self . device . iotile_id , flags ) | Create advertisement data . | 116 | 4 |
22,381 | def _scan_response ( self ) : voltage = struct . pack ( "<H" , int ( self . voltage * 256 ) ) reading = struct . pack ( "<HLLL" , 0xFFFF , 0 , 0 , 0 ) response = voltage + reading return response | Create scan response data . | 57 | 5 |
22,382 | def stop_sync ( self ) : # Disconnect connected device if self . connected : self . disconnect_sync ( self . _connection_handle ) # Disable advertising self . set_advertising ( False ) # Stop the baBLE interface self . bable . stop ( ) self . actions . queue . clear ( ) | Safely stop this BLED112 instance without leaving it in a weird state . | 65 | 16 |
22,383 | def disconnect_sync ( self , connection_handle ) : self . bable . disconnect ( connection_handle = connection_handle , sync = True ) | Synchronously disconnect from whoever has connected to us | 31 | 10 |
22,384 | def _stream_data ( self , chunk = None ) : # If we failed to transmit a chunk, we will be requeued with an argument self . _stream_sm_running = True if chunk is None : chunk = self . _next_streaming_chunk ( 20 ) if chunk is None or len ( chunk ) == 0 : self . _stream_sm_running = False return try : self . _send_notification ( StreamingChar . value_handle , chunk ) self . _defer ( self . _stream_data ) except bable_interface . BaBLEException as err : if err . packet . status == 'Rejected' : # If we are streaming too fast, back off and try again time . sleep ( 0.05 ) self . _defer ( self . _stream_data , [ chunk ] ) else : self . _audit ( 'ErrorStreamingReport' ) # If there was an error, stop streaming but don't choke self . _logger . exception ( "Error while streaming data" ) | Stream reports to the ble client in 20 byte chunks | 221 | 10 |
22,385 | def _send_trace ( self , chunk = None ) : self . _trace_sm_running = True # If we failed to transmit a chunk, we will be requeued with an argument if chunk is None : chunk = self . _next_tracing_chunk ( 20 ) if chunk is None or len ( chunk ) == 0 : self . _trace_sm_running = False return try : self . _send_notification ( TracingChar . value_handle , chunk ) self . _defer ( self . _send_trace ) except bable_interface . BaBLEException as err : if err . packet . status == 'Rejected' : # If we are streaming too fast, back off and try again time . sleep ( 0.05 ) self . _defer ( self . _send_trace , [ chunk ] ) else : self . _audit ( 'ErrorStreamingTrace' ) # If there was an error, stop streaming but don't choke self . _logger . exception ( "Error while tracing data" ) | Stream tracing data to the ble client in 20 byte chunks | 223 | 11 |
22,386 | def process ( self ) : super ( NativeBLEVirtualInterface , self ) . process ( ) if ( not self . _stream_sm_running ) and ( not self . reports . empty ( ) ) : self . _stream_data ( ) if ( not self . _trace_sm_running ) and ( not self . traces . empty ( ) ) : self . _send_trace ( ) | Periodic nonblocking processes | 83 | 6 |
22,387 | async def _populate_name_map ( self ) : services = await self . sync_services ( ) with self . _state_lock : self . services = services for i , name in enumerate ( self . services . keys ( ) ) : self . _name_map [ i ] = name | Populate the name map of services as reported by the supervisor | 65 | 12 |
22,388 | def local_service ( self , name_or_id ) : if not self . _loop . inside_loop ( ) : self . _state_lock . acquire ( ) try : if isinstance ( name_or_id , int ) : if name_or_id not in self . _name_map : raise ArgumentError ( "Unknown ID used to look up service" , id = name_or_id ) name = self . _name_map [ name_or_id ] else : name = name_or_id if name not in self . services : raise ArgumentError ( "Unknown service name" , name = name ) return copy ( self . services [ name ] ) finally : if not self . _loop . inside_loop ( ) : self . _state_lock . release ( ) | Get the locally synced information for a service . | 170 | 10 |
22,389 | def local_services ( self ) : if not self . _loop . inside_loop ( ) : self . _state_lock . acquire ( ) try : return sorted ( [ ( index , name ) for index , name in self . _name_map . items ( ) ] , key = lambda element : element [ 0 ] ) finally : if not self . _loop . inside_loop ( ) : self . _state_lock . release ( ) | Get a list of id name pairs for all of the known synced services . | 94 | 16 |
22,390 | async def sync_services ( self ) : services = { } servs = await self . list_services ( ) for i , serv in enumerate ( servs ) : info = await self . service_info ( serv ) status = await self . service_status ( serv ) messages = await self . get_messages ( serv ) headline = await self . get_headline ( serv ) services [ serv ] = states . ServiceState ( info [ 'short_name' ] , info [ 'long_name' ] , info [ 'preregistered' ] , i ) services [ serv ] . state = status [ 'numeric_status' ] for message in messages : services [ serv ] . post_message ( message . level , message . message , message . count , message . created ) if headline is not None : services [ serv ] . set_headline ( headline . level , headline . message , headline . created ) return services | Poll the current state of all services . | 197 | 8 |
22,391 | def post_state ( self , name , state ) : self . post_command ( OPERATIONS . CMD_UPDATE_STATE , { 'name' : name , 'new_status' : state } ) | Asynchronously try to update the state for a service . | 44 | 12 |
22,392 | def post_error ( self , name , message ) : self . post_command ( OPERATIONS . CMD_POST_MESSAGE , _create_message ( name , states . ERROR_LEVEL , message ) ) | Asynchronously post a user facing error message about a service . | 48 | 13 |
22,393 | def post_warning ( self , name , message ) : self . post_command ( OPERATIONS . CMD_POST_MESSAGE , _create_message ( name , states . WARNING_LEVEL , message ) ) | Asynchronously post a user facing warning message about a service . | 48 | 13 |
22,394 | def post_info ( self , name , message ) : self . post_command ( OPERATIONS . CMD_POST_MESSAGE , _create_message ( name , states . INFO_LEVEL , message ) ) | Asynchronously post a user facing info message about a service . | 48 | 13 |
22,395 | async def _on_status_change ( self , update ) : info = update [ 'payload' ] new_number = info [ 'new_status' ] name = update [ 'service' ] if name not in self . services : return with self . _state_lock : is_changed = self . services [ name ] . state != new_number self . services [ name ] . state = new_number # Notify about this service state change if anyone is listening if self . _on_change_callback and is_changed : self . _on_change_callback ( name , self . services [ name ] . id , new_number , False , False ) | Update a service that has its status updated . | 143 | 9 |
22,396 | async def _on_heartbeat ( self , update ) : name = update [ 'service' ] if name not in self . services : return with self . _state_lock : self . services [ name ] . heartbeat ( ) | Receive a new heartbeat for a service . | 49 | 9 |
22,397 | async def _on_message ( self , update ) : name = update [ 'service' ] message_obj = update [ 'payload' ] if name not in self . services : return with self . _state_lock : self . services [ name ] . post_message ( message_obj [ 'level' ] , message_obj [ 'message' ] ) | Receive a message from a service . | 78 | 8 |
22,398 | async def _on_headline ( self , update ) : name = update [ 'service' ] message_obj = update [ 'payload' ] new_headline = False if name not in self . services : return with self . _state_lock : self . services [ name ] . set_headline ( message_obj [ 'level' ] , message_obj [ 'message' ] ) if self . services [ name ] . headline . count == 1 : new_headline = True # Notify about this service state change if anyone is listening # headline changes are only reported if they are not duplicates if self . _on_change_callback and new_headline : self . _on_change_callback ( name , self . services [ name ] . id , self . services [ name ] . state , False , True ) | Receive a headline from a service . | 178 | 8 |
22,399 | async def _on_rpc_command ( self , event ) : payload = event [ 'payload' ] rpc_id = payload [ 'rpc_id' ] tag = payload [ 'response_uuid' ] args = payload [ 'payload' ] result = 'success' response = b'' if self . _rpc_dispatcher is None or not self . _rpc_dispatcher . has_rpc ( rpc_id ) : result = 'rpc_not_found' else : try : response = self . _rpc_dispatcher . call_rpc ( rpc_id , args ) if inspect . iscoroutine ( response ) : response = await response except RPCInvalidArgumentsError : result = 'invalid_arguments' except RPCInvalidReturnValueError : result = 'invalid_response' except Exception : #pylint:disable=broad-except;We are being called in a background task self . _logger . exception ( "Exception handling RPC 0x%04X" , rpc_id ) result = 'execution_exception' message = dict ( response_uuid = tag , result = result , response = response ) try : await self . send_command ( OPERATIONS . CMD_RESPOND_RPC , message , MESSAGES . RespondRPCResponse ) except : #pylint:disable=bare-except;We are being called in a background worker self . _logger . exception ( "Error sending response to RPC 0x%04X" , rpc_id ) | Received an RPC command that we should execute . | 341 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.