idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
13,000 | def Pop ( self ) : if self . tagList : tag = self . tagList [ 0 ] del self . tagList [ 0 ] else : tag = None return tag | Remove the tag from the front of the list and return it . |
13,001 | def get_context ( self , context ) : i = 0 while i < len ( self . tagList ) : tag = self . tagList [ i ] if tag . tagClass == Tag . applicationTagClass : pass elif tag . tagClass == Tag . contextTagClass : if tag . tagNumber == context : return tag elif tag . tagClass == Tag . openingTagClass : keeper = tag . tagNumber == context rslt = [ ] i += 1 lvl = 0 while i < len ( self . tagList ) : tag = self . tagList [ i ] if tag . tagClass == Tag . openingTagClass : lvl += 1 elif tag . tagClass == Tag . closingTagClass : lvl -= 1 if lvl < 0 : break rslt . append ( tag ) i += 1 if lvl >= 0 : raise InvalidTag ( "mismatched open/close tags" ) if keeper : return TagList ( rslt ) else : raise InvalidTag ( "unexpected tag" ) i += 1 return None | Return a tag or a list of tags context encoded . |
13,002 | def decode ( self , pdu ) : while pdu . pduData : self . tagList . append ( Tag ( pdu ) ) | decode the tags from a PDU . |
13,003 | def coerce ( cls , arg ) : try : return cls ( arg ) . value except ( ValueError , TypeError ) : raise InvalidParameterDatatype ( "%s coerce error" % ( cls . __name__ , ) ) | Given an arg return the appropriate value given the class . |
13,004 | def keylist ( self ) : items = self . enumerations . items ( ) items . sort ( lambda a , b : self . cmp ( a [ 1 ] , b [ 1 ] ) ) rslt = [ None ] * ( items [ - 1 ] [ 1 ] + 1 ) for key , value in items : rslt [ value ] = key return rslt | Return a list of names in order by value . |
13,005 | def CalcDayOfWeek ( self ) : year , month , day , day_of_week = self . value day_of_week = 255 if year == 255 : pass elif month in _special_mon_inv : pass elif day in _special_day_inv : pass else : try : today = time . mktime ( ( year + 1900 , month , day , 0 , 0 , 0 , 0 , 0 , - 1 ) ) day_of_week = time . gmtime ( today ) [ 6 ] + 1 except OverflowError : pass self . value = ( year , month , day , day_of_week ) | Calculate the correct day of the week . |
13,006 | def now ( self , when = None ) : if when is None : when = _TaskManager ( ) . get_time ( ) tup = time . localtime ( when ) self . value = ( tup [ 0 ] - 1900 , tup [ 1 ] , tup [ 2 ] , tup [ 6 ] + 1 ) return self | Set the current value to the correct tuple based on the seconds since the epoch . If when is not provided get the current time from the task manager . |
13,007 | def has_device_info ( self , key ) : if _debug : DeviceInfoCache . _debug ( "has_device_info %r" , key ) return key in self . cache | Return true iff cache has information about the device . |
13,008 | def iam_device_info ( self , apdu ) : if _debug : DeviceInfoCache . _debug ( "iam_device_info %r" , apdu ) if not isinstance ( apdu , IAmRequest ) : raise ValueError ( "not an IAmRequest: %r" % ( apdu , ) ) device_instance = apdu . iAmDeviceIdentifier [ 1 ] device_info = self . cache . get ( device_instance , None ) if not device_info : device_info = self . cache . get ( apdu . pduSource , None ) if not device_info : device_info = self . device_info_class ( device_instance , apdu . pduSource ) device_info . deviceIdentifier = device_instance device_info . address = apdu . pduSource device_info . maxApduLengthAccepted = apdu . maxAPDULengthAccepted device_info . segmentationSupported = apdu . segmentationSupported device_info . vendorID = apdu . vendorID self . update_device_info ( device_info ) | Create a device information record based on the contents of an IAmRequest and put it in the cache . |
13,009 | def update_device_info ( self , device_info ) : if _debug : DeviceInfoCache . _debug ( "update_device_info %r" , device_info ) if not hasattr ( device_info , '_ref_count' ) : device_info . _ref_count = 0 cache_id , cache_address = getattr ( device_info , '_cache_keys' , ( None , None ) ) if ( cache_id is not None ) and ( device_info . deviceIdentifier != cache_id ) : if _debug : DeviceInfoCache . _debug ( " - device identifier updated" ) del self . cache [ cache_id ] self . cache [ device_info . deviceIdentifier ] = device_info if ( cache_address is not None ) and ( device_info . address != cache_address ) : if _debug : DeviceInfoCache . _debug ( " - device address updated" ) del self . cache [ cache_address ] self . cache [ device_info . address ] = device_info device_info . _cache_keys = ( device_info . deviceIdentifier , device_info . address ) | The application has updated one or more fields in the device information record and the cache needs to be updated to reflect the changes . If this is a cached version of a persistent record then this is the opportunity to update the database . |
13,010 | def acquire ( self , key ) : if _debug : DeviceInfoCache . _debug ( "acquire %r" , key ) if isinstance ( key , int ) : device_info = self . cache . get ( key , None ) elif not isinstance ( key , Address ) : raise TypeError ( "key must be integer or an address" ) elif key . addrType not in ( Address . localStationAddr , Address . remoteStationAddr ) : raise TypeError ( "address must be a local or remote station" ) else : device_info = self . cache . get ( key , None ) if device_info : if _debug : DeviceInfoCache . _debug ( " - reference bump" ) device_info . _ref_count += 1 if _debug : DeviceInfoCache . _debug ( " - device_info: %r" , device_info ) return device_info | Return the known information about the device and mark the record as being used by a segmenation state machine . |
13,011 | def release ( self , device_info ) : if _debug : DeviceInfoCache . _debug ( "release %r" , device_info ) if device_info . _ref_count == 0 : raise RuntimeError ( "reference count" ) device_info . _ref_count -= 1 | This function is called by the segmentation state machine when it has finished with the device information . |
13,012 | def get_services_supported ( self ) : if _debug : Application . _debug ( "get_services_supported" ) services_supported = ServicesSupported ( ) for service_choice , service_request_class in confirmed_request_types . items ( ) : service_helper = "do_" + service_request_class . __name__ if hasattr ( self , service_helper ) : service_supported = ConfirmedServiceChoice . _xlate_table [ service_choice ] services_supported [ service_supported ] = 1 for service_choice , service_request_class in unconfirmed_request_types . items ( ) : service_helper = "do_" + service_request_class . __name__ if hasattr ( self , service_helper ) : service_supported = UnconfirmedServiceChoice . _xlate_table [ service_choice ] services_supported [ service_supported ] = 1 return services_supported | Return a ServicesSupported bit string based in introspection look for helper methods that match confirmed and unconfirmed services . |
13,013 | def get_next_task ( self ) : if _debug : TaskManager . _debug ( "get_next_task" ) now = _time ( ) task = None delta = None if self . tasks : when , n , nxttask = self . tasks [ 0 ] if when <= now : heappop ( self . tasks ) task = nxttask task . isScheduled = False if self . tasks : when , n , nxttask = self . tasks [ 0 ] delta = max ( when - now , 0.0 ) else : delta = when - now return ( task , delta ) | get the next task if there s one that should be processed and return how long it will be until the next one should be processed . |
13,014 | def match_date ( date , date_pattern ) : year , month , day , day_of_week = date year_p , month_p , day_p , day_of_week_p = date_pattern if year_p == 255 : pass elif year != year_p : return False if month_p == 255 : pass elif month_p == 13 : if ( month % 2 ) == 0 : return False elif month_p == 14 : if ( month % 2 ) == 1 : return False elif month != month_p : return False if day_p == 255 : pass elif day_p == 32 : last_day = calendar . monthrange ( year + 1900 , month ) [ 1 ] if day != last_day : return False elif day_p == 33 : if ( day % 2 ) == 0 : return False elif day_p == 34 : if ( day % 2 ) == 1 : return False elif day != day_p : return False if day_of_week_p == 255 : pass elif day_of_week != day_of_week_p : return False return True | Match a specific date a four - tuple with no special values with a date pattern four - tuple possibly having special values . |
13,015 | def datetime_to_time ( date , time ) : if ( 255 in date ) or ( 255 in time ) : raise RuntimeError ( "specific date and time required" ) time_tuple = ( date [ 0 ] + 1900 , date [ 1 ] , date [ 2 ] , time [ 0 ] , time [ 1 ] , time [ 2 ] , 0 , 0 , - 1 , ) return _mktime ( time_tuple ) | Take the date and time 4 - tuples and return the time in seconds since the epoch as a floating point number . |
13,016 | def _check_reliability ( self , old_value = None , new_value = None ) : if _debug : LocalScheduleObject . _debug ( "_check_reliability %r %r" , old_value , new_value ) try : schedule_default = self . scheduleDefault if schedule_default is None : raise ValueError ( "scheduleDefault expected" ) if not isinstance ( schedule_default , Atomic ) : raise TypeError ( "scheduleDefault must be an instance of an atomic type" ) schedule_datatype = schedule_default . __class__ if _debug : LocalScheduleObject . _debug ( " - schedule_datatype: %r" , schedule_datatype ) if ( self . weeklySchedule is None ) and ( self . exceptionSchedule is None ) : raise ValueError ( "schedule required" ) if self . weeklySchedule : for daily_schedule in self . weeklySchedule : for time_value in daily_schedule . daySchedule : if _debug : LocalScheduleObject . _debug ( " - daily time_value: %r" , time_value ) if time_value is None : pass elif not isinstance ( time_value . value , ( Null , schedule_datatype ) ) : if _debug : LocalScheduleObject . _debug ( " - wrong type: expected %r, got %r" , schedule_datatype , time_value . __class__ , ) raise TypeError ( "wrong type" ) elif 255 in time_value . time : if _debug : LocalScheduleObject . _debug ( " - wildcard in time" ) raise ValueError ( "must be a specific time" ) if self . exceptionSchedule : for special_event in self . exceptionSchedule : for time_value in special_event . listOfTimeValues : if _debug : LocalScheduleObject . _debug ( " - special event time_value: %r" , time_value ) if time_value is None : pass elif not isinstance ( time_value . value , ( Null , schedule_datatype ) ) : if _debug : LocalScheduleObject . _debug ( " - wrong type: expected %r, got %r" , schedule_datatype , time_value . __class__ , ) raise TypeError ( "wrong type" ) obj_prop_refs = self . listOfObjectPropertyReferences if obj_prop_refs : for obj_prop_ref in obj_prop_refs : if obj_prop_ref . deviceIdentifier : raise RuntimeError ( "no external references" ) obj_type = obj_prop_ref . objectIdentifier [ 0 ] datatype = get_datatype ( obj_type , obj_prop_ref . propertyIdentifier ) if _debug : LocalScheduleObject . _debug ( " - datatype: %r" , datatype ) if issubclass ( datatype , Array ) and ( obj_prop_ref . propertyArrayIndex is not None ) : if obj_prop_ref . propertyArrayIndex == 0 : datatype = Unsigned else : datatype = datatype . subtype if _debug : LocalScheduleObject . _debug ( " - datatype: %r" , datatype ) if datatype is not schedule_datatype : if _debug : LocalScheduleObject . _debug ( " - wrong type: expected %r, got %r" , datatype , schedule_datatype , ) raise TypeError ( "wrong type" ) self . reliability = 'noFaultDetected' if _debug : LocalScheduleObject . _debug ( " - no fault detected" ) except Exception as err : if _debug : LocalScheduleObject . _debug ( " - exception: %r" , err ) self . reliability = 'configurationError' | This function is called when the object is created and after one of its configuration properties has changed . The new and old value parameters are ignored this is called after the property has been changed and this is only concerned with the current value . |
13,017 | def present_value_changed ( self , old_value , new_value ) : if _debug : LocalScheduleInterpreter . _debug ( "present_value_changed %s %s" , old_value , new_value ) if not self . sched_obj . _app : if _debug : LocalScheduleInterpreter . _debug ( " - no application" ) return obj_prop_refs = self . sched_obj . listOfObjectPropertyReferences if not obj_prop_refs : if _debug : LocalScheduleInterpreter . _debug ( " - no writes defined" ) return new_value = new_value . value for obj_prop_ref in obj_prop_refs : if obj_prop_ref . deviceIdentifier : if _debug : LocalScheduleInterpreter . _debug ( " - no externals" ) continue obj = self . sched_obj . _app . get_object_id ( obj_prop_ref . objectIdentifier ) if not obj : if _debug : LocalScheduleInterpreter . _debug ( " - no object" ) continue try : obj . WriteProperty ( obj_prop_ref . propertyIdentifier , new_value , arrayIndex = obj_prop_ref . propertyArrayIndex , priority = self . sched_obj . priorityForWriting , ) if _debug : LocalScheduleInterpreter . _debug ( " - success" ) except Exception as err : if _debug : LocalScheduleInterpreter . _debug ( " - error: %r" , err ) | This function is called when the presentValue of the local schedule object has changed both internally by this interpreter or externally by some client using WriteProperty . |
13,018 | def do_gc ( self , args ) : instance_type = getattr ( types , 'InstanceType' , object ) type2count = { } type2all = { } for o in gc . get_objects ( ) : if type ( o ) == instance_type : type2count [ o . __class__ ] = type2count . get ( o . __class__ , 0 ) + 1 type2all [ o . __class__ ] = type2all . get ( o . __class__ , 0 ) + sys . getrefcount ( o ) ct = [ ( t . __module__ , t . __name__ , type2count [ t ] , type2count [ t ] - self . type2count . get ( t , 0 ) , type2all [ t ] - self . type2all . get ( t , 0 ) ) for t in type2count . iterkeys ( ) ] self . type2count = type2count self . type2all = type2all fmt = "%-30s %-30s %6s %6s %6s\n" self . stdout . write ( fmt % ( "Module" , "Type" , "Count" , "dCount" , "dRef" ) ) ct . sort ( lambda x , y : cmp ( y [ 2 ] , x [ 2 ] ) ) for i in range ( min ( 10 , len ( ct ) ) ) : m , n , c , delta1 , delta2 = ct [ i ] self . stdout . write ( fmt % ( m , n , c , delta1 , delta2 ) ) self . stdout . write ( "\n" ) self . stdout . write ( fmt % ( "Module" , "Type" , "Count" , "dCount" , "dRef" ) ) ct . sort ( ) for m , n , c , delta1 , delta2 in ct : if delta1 or delta2 : self . stdout . write ( fmt % ( m , n , c , delta1 , delta2 ) ) self . stdout . write ( "\n" ) | gc - print out garbage collection information |
13,019 | def do_buggers ( self , args ) : args = args . split ( ) if _debug : ConsoleCmd . _debug ( "do_buggers %r" , args ) if not self . handlers : self . stdout . write ( "no handlers\n" ) else : self . stdout . write ( "handlers: " ) self . stdout . write ( ', ' . join ( loggerName or '__root__' for loggerName in self . handlers ) ) self . stdout . write ( "\n" ) loggers = logging . Logger . manager . loggerDict . keys ( ) for loggerName in sorted ( loggers ) : if args and ( not args [ 0 ] in loggerName ) : continue if loggerName in self . handlers : self . stdout . write ( "* %s\n" % loggerName ) else : self . stdout . write ( " %s\n" % loggerName ) self . stdout . write ( "\n" ) | buggers - list the console logging handlers |
13,020 | def do_EOF ( self , args ) : if _debug : ConsoleCmd . _debug ( "do_EOF %r" , args ) return self . do_exit ( args ) | Exit on system end of file character |
13,021 | def do_shell ( self , args ) : if _debug : ConsoleCmd . _debug ( "do_shell %r" , args ) os . system ( args ) | Pass command to a system shell when line begins with ! |
13,022 | def confirmation ( self , pdu ) : if _debug : NetworkAdapter . _debug ( "confirmation %r (net=%r)" , pdu , self . adapterNet ) npdu = NPDU ( user_data = pdu . pduUserData ) npdu . decode ( pdu ) self . adapterSAP . process_npdu ( self , npdu ) | Decode upstream PDUs and pass them up to the service access point . |
13,023 | def process_npdu ( self , npdu ) : if _debug : NetworkAdapter . _debug ( "process_npdu %r (net=%r)" , npdu , self . adapterNet ) pdu = PDU ( user_data = npdu . pduUserData ) npdu . encode ( pdu ) self . request ( pdu ) | Encode NPDUs from the service access point and send them downstream . |
13,024 | def bind ( self , server , net = None , address = None ) : if _debug : NetworkServiceAccessPoint . _debug ( "bind %r net=%r address=%r" , server , net , address ) if net in self . adapters : raise RuntimeError ( "already bound" ) adapter = NetworkAdapter ( self , net ) self . adapters [ net ] = adapter if _debug : NetworkServiceAccessPoint . _debug ( " - adapters[%r]: %r" , net , adapter ) if address and not self . local_address : self . local_adapter = adapter self . local_address = address bind ( adapter , server ) | Create a network adapter object and bind . |
13,025 | def unpack_ip_addr ( addr ) : if isinstance ( addr , bytearray ) : addr = bytes ( addr ) return ( socket . inet_ntoa ( addr [ 0 : 4 ] ) , struct . unpack ( '!H' , addr [ 4 : 6 ] ) [ 0 ] ) | Given a six - octet BACnet address return an IP address tuple . |
13,026 | def ModuleLogger ( globs ) : if not globs . has_key ( '_debug' ) : raise RuntimeError ( "define _debug before creating a module logger" ) logger_name = globs [ '__name__' ] logger = logging . getLogger ( logger_name ) logger . globs = globs if '.' not in logger_name : hdlr = logging . StreamHandler ( ) hdlr . setLevel ( logging . WARNING ) hdlr . setFormatter ( logging . Formatter ( logging . BASIC_FORMAT , None ) ) logger . addHandler ( hdlr ) return logger | Create a module level logger . |
13,027 | def bacpypes_debugging ( obj ) : logger = logging . getLogger ( obj . __module__ + '.' + obj . __name__ ) obj . _logger = logger obj . _debug = logger . debug obj . _info = logger . info obj . _warning = logger . warning obj . _error = logger . error obj . _exception = logger . exception obj . _fatal = logger . fatal return obj | Function for attaching a debugging logger to a class or function . |
13,028 | def add_node ( self , node ) : if _debug : Network . _debug ( "add_node %r" , node ) self . nodes . append ( node ) node . lan = self if not node . name : node . name = '%s:%s' % ( self . name , node . address ) | Add a node to this network let the node know which network it s on . |
13,029 | def remove_node ( self , node ) : if _debug : Network . _debug ( "remove_node %r" , node ) self . nodes . remove ( node ) node . lan = None | Remove a node from this network . |
13,030 | def process_pdu ( self , pdu ) : if _debug : Network . _debug ( "process_pdu(%s) %r" , self . name , pdu ) if self . traffic_log : self . traffic_log ( self . name , pdu ) if self . drop_percent != 0.0 : if ( random . random ( ) * 100.0 ) < self . drop_percent : if _debug : Network . _debug ( " - packet dropped" ) return if pdu . pduDestination == self . broadcast_address : if _debug : Network . _debug ( " - broadcast" ) for node in self . nodes : if ( pdu . pduSource != node . address ) : if _debug : Network . _debug ( " - match: %r" , node ) node . response ( deepcopy ( pdu ) ) else : if _debug : Network . _debug ( " - unicast" ) for node in self . nodes : if node . promiscuous or ( pdu . pduDestination == node . address ) : if _debug : Network . _debug ( " - match: %r" , node ) node . response ( deepcopy ( pdu ) ) | Process a PDU by sending a copy to each node as dictated by the addressing and if a node is promiscuous . |
13,031 | def bind ( self , lan ) : if _debug : Node . _debug ( "bind %r" , lan ) lan . add_node ( self ) | bind to a LAN . |
13,032 | def Match ( addr1 , addr2 ) : if _debug : Match . _debug ( "Match %r %r" , addr1 , addr2 ) if ( addr2 . addrType == Address . localBroadcastAddr ) : return ( addr1 . addrType == Address . localStationAddr ) or ( addr1 . addrType == Address . localBroadcastAddr ) elif ( addr2 . addrType == Address . localStationAddr ) : return ( addr1 . addrType == Address . localStationAddr ) and ( addr1 . addrAddr == addr2 . addrAddr ) elif ( addr2 . addrType == Address . remoteBroadcastAddr ) : return ( ( addr1 . addrType == Address . remoteStationAddr ) or ( addr1 . addrType == Address . remoteBroadcastAddr ) ) and ( addr1 . addrNet == addr2 . addrNet ) elif ( addr2 . addrType == Address . remoteStationAddr ) : return ( addr1 . addrType == Address . remoteStationAddr ) and ( addr1 . addrNet == addr2 . addrNet ) and ( addr1 . addrAddr == addr2 . addrAddr ) elif ( addr2 . addrType == Address . globalBroadcastAddr ) : return ( addr1 . addrType == Address . globalBroadcastAddr ) else : raise RuntimeError , "invalid match combination" | Return true iff addr1 matches addr2 . |
13,033 | def do_WhoIsRequest ( self , apdu ) : if _debug : WhoIsIAmServices . _debug ( "do_WhoIsRequest %r" , apdu ) if not self . localDevice : if _debug : WhoIsIAmServices . _debug ( " - no local device" ) return low_limit = apdu . deviceInstanceRangeLowLimit high_limit = apdu . deviceInstanceRangeHighLimit if ( low_limit is not None ) : if ( high_limit is None ) : raise MissingRequiredParameter ( "deviceInstanceRangeHighLimit required" ) if ( low_limit < 0 ) or ( low_limit > 4194303 ) : raise ParameterOutOfRange ( "deviceInstanceRangeLowLimit out of range" ) if ( high_limit is not None ) : if ( low_limit is None ) : raise MissingRequiredParameter ( "deviceInstanceRangeLowLimit required" ) if ( high_limit < 0 ) or ( high_limit > 4194303 ) : raise ParameterOutOfRange ( "deviceInstanceRangeHighLimit out of range" ) if ( low_limit is not None ) : if ( self . localDevice . objectIdentifier [ 1 ] < low_limit ) : return if ( high_limit is not None ) : if ( self . localDevice . objectIdentifier [ 1 ] > high_limit ) : return self . i_am ( address = apdu . pduSource ) | Respond to a Who - Is request . |
13,034 | def do_IAmRequest ( self , apdu ) : if _debug : WhoIsIAmServices . _debug ( "do_IAmRequest %r" , apdu ) if apdu . iAmDeviceIdentifier is None : raise MissingRequiredParameter ( "iAmDeviceIdentifier required" ) if apdu . maxAPDULengthAccepted is None : raise MissingRequiredParameter ( "maxAPDULengthAccepted required" ) if apdu . segmentationSupported is None : raise MissingRequiredParameter ( "segmentationSupported required" ) if apdu . vendorID is None : raise MissingRequiredParameter ( "vendorID required" ) device_instance = apdu . iAmDeviceIdentifier [ 1 ] if _debug : WhoIsIAmServices . _debug ( " - device_instance: %r" , device_instance ) device_address = apdu . pduSource if _debug : WhoIsIAmServices . _debug ( " - device_address: %r" , device_address ) | Respond to an I - Am request . |
13,035 | def do_WhoHasRequest ( self , apdu ) : if _debug : WhoHasIHaveServices . _debug ( "do_WhoHasRequest, %r" , apdu ) if not self . localDevice : if _debug : WhoIsIAmServices . _debug ( " - no local device" ) return if apdu . limits is not None : low_limit = apdu . limits . deviceInstanceRangeLowLimit high_limit = apdu . limits . deviceInstanceRangeHighLimit if ( low_limit is None ) : raise MissingRequiredParameter ( "deviceInstanceRangeLowLimit required" ) if ( low_limit < 0 ) or ( low_limit > 4194303 ) : raise ParameterOutOfRange ( "deviceInstanceRangeLowLimit out of range" ) if ( high_limit is None ) : raise MissingRequiredParameter ( "deviceInstanceRangeHighLimit required" ) if ( high_limit < 0 ) or ( high_limit > 4194303 ) : raise ParameterOutOfRange ( "deviceInstanceRangeHighLimit out of range" ) if ( self . localDevice . objectIdentifier [ 1 ] < low_limit ) : return if ( self . localDevice . objectIdentifier [ 1 ] > high_limit ) : return if apdu . object . objectIdentifier is not None : obj = self . objectIdentifier . get ( apdu . object . objectIdentifier , None ) elif apdu . object . objectName is not None : obj = self . objectName . get ( apdu . object . objectName , None ) else : raise InconsistentParameters ( "object identifier or object name required" ) if not obj : return self . i_have ( obj , address = apdu . pduSource ) | Respond to a Who - Has request . |
13,036 | def do_IHaveRequest ( self , apdu ) : if _debug : WhoHasIHaveServices . _debug ( "do_IHaveRequest %r" , apdu ) if apdu . deviceIdentifier is None : raise MissingRequiredParameter ( "deviceIdentifier required" ) if apdu . objectIdentifier is None : raise MissingRequiredParameter ( "objectIdentifier required" ) if apdu . objectName is None : raise MissingRequiredParameter ( "objectName required" ) | Respond to a I - Have request . |
13,037 | def set_state ( self , newState , timer = 0 ) : if _debug : SSM . _debug ( "set_state %r (%s) timer=%r" , newState , SSM . transactionLabels [ newState ] , timer ) if ( self . state == COMPLETED ) or ( self . state == ABORTED ) : e = RuntimeError ( "invalid state transition from %s to %s" % ( SSM . transactionLabels [ self . state ] , SSM . transactionLabels [ newState ] ) ) SSM . _exception ( e ) raise e self . stop_timer ( ) self . state = newState if timer : self . start_timer ( timer ) | This function is called when the derived class wants to change state . |
13,038 | def set_segmentation_context ( self , apdu ) : if _debug : SSM . _debug ( "set_segmentation_context %s" , repr ( apdu ) ) self . segmentAPDU = apdu | This function is called to set the segmentation context . |
13,039 | def get_segment ( self , indx ) : if _debug : SSM . _debug ( "get_segment %r" , indx ) if not self . segmentAPDU : raise RuntimeError ( "no segmentation context established" ) if indx >= self . segmentCount : raise RuntimeError ( "invalid segment number %r, APDU has %r segments" % ( indx , self . segmentCount ) ) if self . segmentAPDU . apduType == ConfirmedRequestPDU . pduType : if _debug : SSM . _debug ( " - confirmed request context" ) segAPDU = ConfirmedRequestPDU ( self . segmentAPDU . apduService ) segAPDU . apduMaxSegs = encode_max_segments_accepted ( self . maxSegmentsAccepted ) segAPDU . apduMaxResp = encode_max_apdu_length_accepted ( self . maxApduLengthAccepted ) segAPDU . apduInvokeID = self . invokeID segAPDU . apduSA = self . segmentationSupported in ( 'segmentedReceive' , 'segmentedBoth' ) if _debug : SSM . _debug ( " - segmented response accepted: %r" , segAPDU . apduSA ) elif self . segmentAPDU . apduType == ComplexAckPDU . pduType : if _debug : SSM . _debug ( " - complex ack context" ) segAPDU = ComplexAckPDU ( self . segmentAPDU . apduService , self . segmentAPDU . apduInvokeID ) else : raise RuntimeError ( "invalid APDU type for segmentation context" ) segAPDU . pduUserData = self . segmentAPDU . pduUserData segAPDU . pduDestination = self . pdu_address if ( self . segmentCount != 1 ) : segAPDU . apduSeg = True segAPDU . apduMor = ( indx < ( self . segmentCount - 1 ) ) segAPDU . apduSeq = indx % 256 if indx == 0 : if _debug : SSM . _debug ( " - proposedWindowSize: %r" , self . ssmSAP . proposedWindowSize ) segAPDU . apduWin = self . ssmSAP . proposedWindowSize else : if _debug : SSM . _debug ( " - actualWindowSize: %r" , self . actualWindowSize ) segAPDU . apduWin = self . actualWindowSize else : segAPDU . apduSeg = False segAPDU . apduMor = False offset = indx * self . segmentSize segAPDU . put_data ( self . segmentAPDU . pduData [ offset : offset + self . segmentSize ] ) return segAPDU | This function returns an APDU coorisponding to a particular segment of a confirmed request or complex ack . The segmentAPDU is the context . |
13,040 | def append_segment ( self , apdu ) : if _debug : SSM . _debug ( "append_segment %r" , apdu ) if not self . segmentAPDU : raise RuntimeError ( "no segmentation context established" ) self . segmentAPDU . put_data ( apdu . pduData ) | This function appends the apdu content to the end of the current APDU being built . The segmentAPDU is the context . |
13,041 | def fill_window ( self , seqNum ) : if _debug : SSM . _debug ( "fill_window %r" , seqNum ) if _debug : SSM . _debug ( " - actualWindowSize: %r" , self . actualWindowSize ) for ix in range ( self . actualWindowSize ) : apdu = self . get_segment ( seqNum + ix ) self . ssmSAP . request ( apdu ) if not apdu . apduMor : self . sentAllSegments = True break | This function sends all of the packets necessary to fill out the segmentation window . |
13,042 | def request ( self , apdu ) : if _debug : ClientSSM . _debug ( "request %r" , apdu ) apdu . pduSource = None apdu . pduDestination = self . pdu_address self . ssmSAP . request ( apdu ) | This function is called by client transaction functions when it wants to send a message to the device . |
13,043 | def indication ( self , apdu ) : if _debug : ClientSSM . _debug ( "indication %r" , apdu ) if ( apdu . apduType != ConfirmedRequestPDU . pduType ) : raise RuntimeError ( "invalid APDU (1)" ) self . set_segmentation_context ( apdu ) if ( not self . device_info ) or ( self . device_info . maxApduLengthAccepted is None ) : self . segmentSize = self . maxApduLengthAccepted elif self . device_info . maxNpduLength is None : self . segmentSize = self . device_info . maxApduLengthAccepted else : self . segmentSize = min ( self . device_info . maxNpduLength , self . device_info . maxApduLengthAccepted ) if _debug : ClientSSM . _debug ( " - segment size: %r" , self . segmentSize ) self . invokeID = apdu . apduInvokeID if _debug : ClientSSM . _debug ( " - invoke ID: %r" , self . invokeID ) if not apdu . pduData : self . segmentCount = 1 else : self . segmentCount , more = divmod ( len ( apdu . pduData ) , self . segmentSize ) if more : self . segmentCount += 1 if _debug : ClientSSM . _debug ( " - segment count: %r" , self . segmentCount ) if self . segmentCount > 1 : if self . segmentationSupported not in ( 'segmentedTransmit' , 'segmentedBoth' ) : if _debug : ClientSSM . _debug ( " - local device can't send segmented requests" ) abort = self . abort ( AbortReason . segmentationNotSupported ) self . response ( abort ) return if not self . device_info : if _debug : ClientSSM . _debug ( " - no server info for segmentation support" ) elif self . device_info . segmentationSupported not in ( 'segmentedReceive' , 'segmentedBoth' ) : if _debug : ClientSSM . _debug ( " - server can't receive segmented requests" ) abort = self . abort ( AbortReason . segmentationNotSupported ) self . response ( abort ) return if not self . device_info : if _debug : ClientSSM . _debug ( " - no server info for maximum number of segments" ) elif not self . device_info . maxSegmentsAccepted : if _debug : ClientSSM . _debug ( " - server doesn't say maximum number of segments" ) elif self . segmentCount > self . device_info . maxSegmentsAccepted : if _debug : ClientSSM . _debug ( " - server can't receive enough segments" ) abort = self . abort ( AbortReason . apduTooLong ) self . response ( abort ) return if self . segmentCount == 1 : self . sentAllSegments = True self . retryCount = 0 self . set_state ( AWAIT_CONFIRMATION , self . apduTimeout ) else : self . sentAllSegments = False self . retryCount = 0 self . segmentRetryCount = 0 self . initialSequenceNumber = 0 self . actualWindowSize = None self . set_state ( SEGMENTED_REQUEST , self . segmentTimeout ) self . request ( self . get_segment ( 0 ) ) | This function is called after the device has bound a new transaction and wants to start the process rolling . |
13,044 | def response ( self , apdu ) : if _debug : ClientSSM . _debug ( "response %r" , apdu ) apdu . pduSource = self . pdu_address apdu . pduDestination = None self . ssmSAP . sap_response ( apdu ) | This function is called by client transaction functions when they want to send a message to the application . |
13,045 | def confirmation ( self , apdu ) : if _debug : ClientSSM . _debug ( "confirmation %r" , apdu ) if self . state == SEGMENTED_REQUEST : self . segmented_request ( apdu ) elif self . state == AWAIT_CONFIRMATION : self . await_confirmation ( apdu ) elif self . state == SEGMENTED_CONFIRMATION : self . segmented_confirmation ( apdu ) else : raise RuntimeError ( "invalid state" ) | This function is called by the device for all upstream messages related to the transaction . |
13,046 | def process_task ( self ) : if _debug : ClientSSM . _debug ( "process_task" ) if self . state == SEGMENTED_REQUEST : self . segmented_request_timeout ( ) elif self . state == AWAIT_CONFIRMATION : self . await_confirmation_timeout ( ) elif self . state == SEGMENTED_CONFIRMATION : self . segmented_confirmation_timeout ( ) elif self . state == COMPLETED : pass elif self . state == ABORTED : pass else : e = RuntimeError ( "invalid state" ) ClientSSM . _exception ( "exception: %r" , e ) raise e | This function is called when something has taken too long . |
13,047 | def abort ( self , reason ) : if _debug : ClientSSM . _debug ( "abort %r" , reason ) self . set_state ( ABORTED ) abort_pdu = AbortPDU ( False , self . invokeID , reason ) return abort_pdu | This function is called when the transaction should be aborted . |
13,048 | def segmented_request ( self , apdu ) : if _debug : ClientSSM . _debug ( "segmented_request %r" , apdu ) if apdu . apduType == SegmentAckPDU . pduType : if _debug : ClientSSM . _debug ( " - segment ack" ) self . actualWindowSize = apdu . apduWin if not self . in_window ( apdu . apduSeq , self . initialSequenceNumber ) : if _debug : ClientSSM . _debug ( " - not in window" ) self . restart_timer ( self . segmentTimeout ) elif self . sentAllSegments : if _debug : ClientSSM . _debug ( " - all done sending request" ) self . set_state ( AWAIT_CONFIRMATION , self . apduTimeout ) else : if _debug : ClientSSM . _debug ( " - more segments to send" ) self . initialSequenceNumber = ( apdu . apduSeq + 1 ) % 256 self . segmentRetryCount = 0 self . fill_window ( self . initialSequenceNumber ) self . restart_timer ( self . segmentTimeout ) elif ( apdu . apduType == SimpleAckPDU . pduType ) : if _debug : ClientSSM . _debug ( " - simple ack" ) if not self . sentAllSegments : abort = self . abort ( AbortReason . invalidApduInThisState ) self . request ( abort ) self . response ( abort ) else : self . set_state ( COMPLETED ) self . response ( apdu ) elif ( apdu . apduType == ComplexAckPDU . pduType ) : if _debug : ClientSSM . _debug ( " - complex ack" ) if not self . sentAllSegments : abort = self . abort ( AbortReason . invalidApduInThisState ) self . request ( abort ) self . response ( abort ) elif not apdu . apduSeg : self . set_state ( COMPLETED ) self . response ( apdu ) else : self . set_segmentation_context ( apdu ) self . actualWindowSize = min ( apdu . apduWin , self . ssmSAP . proposedWindowSize ) self . lastSequenceNumber = 0 self . initialSequenceNumber = 0 self . set_state ( SEGMENTED_CONFIRMATION , self . segmentTimeout ) elif ( apdu . apduType == ErrorPDU . pduType ) or ( apdu . apduType == RejectPDU . pduType ) or ( apdu . apduType == AbortPDU . pduType ) : if _debug : ClientSSM . _debug ( " - error/reject/abort" ) self . set_state ( COMPLETED ) self . response = apdu self . response ( apdu ) else : raise RuntimeError ( "invalid APDU (2)" ) | This function is called when the client is sending a segmented request and receives an apdu . |
13,049 | def set_state ( self , newState , timer = 0 ) : if _debug : ServerSSM . _debug ( "set_state %r (%s) timer=%r" , newState , SSM . transactionLabels [ newState ] , timer ) SSM . set_state ( self , newState , timer ) if ( newState == COMPLETED ) or ( newState == ABORTED ) : if _debug : ServerSSM . _debug ( " - remove from active transactions" ) self . ssmSAP . serverTransactions . remove ( self ) if self . device_info : if _debug : ClientSSM . _debug ( " - release device information" ) self . ssmSAP . deviceInfoCache . release ( self . device_info ) | This function is called when the client wants to change state . |
13,050 | def request ( self , apdu ) : if _debug : ServerSSM . _debug ( "request %r" , apdu ) apdu . pduSource = self . pdu_address apdu . pduDestination = None self . ssmSAP . sap_request ( apdu ) | This function is called by transaction functions to send to the application . |
13,051 | def indication ( self , apdu ) : if _debug : ServerSSM . _debug ( "indication %r" , apdu ) if self . state == IDLE : self . idle ( apdu ) elif self . state == SEGMENTED_REQUEST : self . segmented_request ( apdu ) elif self . state == AWAIT_RESPONSE : self . await_response ( apdu ) elif self . state == SEGMENTED_RESPONSE : self . segmented_response ( apdu ) else : if _debug : ServerSSM . _debug ( " - invalid state" ) | This function is called for each downstream packet related to the transaction . |
13,052 | def confirmation ( self , apdu ) : if _debug : ServerSSM . _debug ( "confirmation %r" , apdu ) if self . state != AWAIT_RESPONSE : if _debug : ServerSSM . _debug ( " - warning: not expecting a response" ) if ( apdu . apduType == AbortPDU . pduType ) : if _debug : ServerSSM . _debug ( " - abort" ) self . set_state ( ABORTED ) self . response ( apdu ) return if ( apdu . apduType == SimpleAckPDU . pduType ) or ( apdu . apduType == ErrorPDU . pduType ) or ( apdu . apduType == RejectPDU . pduType ) : if _debug : ServerSSM . _debug ( " - simple ack, error, or reject" ) self . set_state ( COMPLETED ) self . response ( apdu ) return if ( apdu . apduType == ComplexAckPDU . pduType ) : if _debug : ServerSSM . _debug ( " - complex ack" ) self . set_segmentation_context ( apdu ) if ( not self . device_info ) or ( self . device_info . maxNpduLength is None ) : self . segmentSize = self . maxApduLengthAccepted else : self . segmentSize = min ( self . device_info . maxNpduLength , self . maxApduLengthAccepted ) if _debug : ServerSSM . _debug ( " - segment size: %r" , self . segmentSize ) if not apdu . pduData : self . segmentCount = 1 else : self . segmentCount , more = divmod ( len ( apdu . pduData ) , self . segmentSize ) if more : self . segmentCount += 1 if _debug : ServerSSM . _debug ( " - segment count: %r" , self . segmentCount ) if self . segmentCount > 1 : if _debug : ServerSSM . _debug ( " - segmentation required, %d segments" , self . segmentCount ) if self . segmentationSupported not in ( 'segmentedTransmit' , 'segmentedBoth' ) : if _debug : ServerSSM . _debug ( " - server can't send segmented responses" ) abort = self . abort ( AbortReason . segmentationNotSupported ) self . response ( abort ) return if not self . segmented_response_accepted : if _debug : ServerSSM . _debug ( " - client can't receive segmented responses" ) abort = self . abort ( AbortReason . segmentationNotSupported ) self . response ( abort ) return if ( self . maxSegmentsAccepted is not None ) and ( self . segmentCount > self . maxSegmentsAccepted ) : if _debug : ServerSSM . _debug ( " - client can't receive enough segments" ) abort = self . abort ( AbortReason . apduTooLong ) self . response ( abort ) return self . segmentRetryCount = 0 self . initialSequenceNumber = 0 self . actualWindowSize = None if self . segmentCount == 1 : self . response ( apdu ) self . set_state ( COMPLETED ) else : self . response ( self . get_segment ( 0 ) ) self . set_state ( SEGMENTED_RESPONSE , self . segmentTimeout ) else : raise RuntimeError ( "invalid APDU (4)" ) | This function is called when the application has provided a response and needs it to be sent to the client . |
13,053 | def process_task ( self ) : if _debug : ServerSSM . _debug ( "process_task" ) if self . state == SEGMENTED_REQUEST : self . segmented_request_timeout ( ) elif self . state == AWAIT_RESPONSE : self . await_response_timeout ( ) elif self . state == SEGMENTED_RESPONSE : self . segmented_response_timeout ( ) elif self . state == COMPLETED : pass elif self . state == ABORTED : pass else : if _debug : ServerSSM . _debug ( "invalid state" ) raise RuntimeError ( "invalid state" ) | This function is called when the client has failed to send all of the segments of a segmented request the application has taken too long to complete the request or the client failed to ack the segments of a segmented response . |
13,054 | def abort ( self , reason ) : if _debug : ServerSSM . _debug ( "abort %r" , reason ) self . set_state ( ABORTED ) return AbortPDU ( True , self . invokeID , reason ) | This function is called when the application would like to abort the transaction . There is no notification back to the application . |
13,055 | def await_response_timeout ( self ) : if _debug : ServerSSM . _debug ( "await_response_timeout" ) abort = self . abort ( AbortReason . serverTimeout ) self . request ( abort ) | This function is called when the application has taken too long to respond to a clients request . The client has probably long since given up . |
13,056 | def get_next_invoke_id ( self , addr ) : if _debug : StateMachineAccessPoint . _debug ( "get_next_invoke_id" ) initialID = self . nextInvokeID while 1 : invokeID = self . nextInvokeID self . nextInvokeID = ( self . nextInvokeID + 1 ) % 256 if initialID == self . nextInvokeID : raise RuntimeError ( "no available invoke ID" ) for tr in self . clientTransactions : if ( invokeID == tr . invokeID ) and ( addr == tr . pdu_address ) : break else : break return invokeID | Called by clients to get an unused invoke ID . |
13,057 | def sap_indication ( self , apdu ) : if _debug : StateMachineAccessPoint . _debug ( "sap_indication %r" , apdu ) if self . dccEnableDisable == 'enable' : if _debug : StateMachineAccessPoint . _debug ( " - communications enabled" ) elif self . dccEnableDisable == 'disable' : if _debug : StateMachineAccessPoint . _debug ( " - communications disabled" ) return elif self . dccEnableDisable == 'disableInitiation' : if _debug : StateMachineAccessPoint . _debug ( " - initiation disabled" ) if ( apdu . apduType == 1 ) and ( apdu . apduService == 0 ) : if _debug : StateMachineAccessPoint . _debug ( " - continue with I-Am" ) else : if _debug : StateMachineAccessPoint . _debug ( " - not an I-Am" ) return if isinstance ( apdu , UnconfirmedRequestPDU ) : self . request ( apdu ) elif isinstance ( apdu , ConfirmedRequestPDU ) : if apdu . apduInvokeID is None : apdu . apduInvokeID = self . get_next_invoke_id ( apdu . pduDestination ) else : for tr in self . clientTransactions : if ( apdu . apduInvokeID == tr . invokeID ) and ( apdu . pduDestination == tr . pdu_address ) : raise RuntimeError ( "invoke ID in use" ) if ( apdu . pduDestination . addrType != Address . localStationAddr ) and ( apdu . pduDestination . addrType != Address . remoteStationAddr ) : StateMachineAccessPoint . _warning ( "%s is not a local or remote station" , apdu . pduDestination ) tr = ClientSSM ( self , apdu . pduDestination ) if _debug : StateMachineAccessPoint . _debug ( " - client segmentation state machine: %r" , tr ) self . clientTransactions . append ( tr ) tr . indication ( apdu ) else : raise RuntimeError ( "invalid APDU (9)" ) | This function is called when the application is requesting a new transaction as a client . |
13,058 | def sap_confirmation ( self , apdu ) : if _debug : StateMachineAccessPoint . _debug ( "sap_confirmation %r" , apdu ) if isinstance ( apdu , SimpleAckPDU ) or isinstance ( apdu , ComplexAckPDU ) or isinstance ( apdu , ErrorPDU ) or isinstance ( apdu , RejectPDU ) or isinstance ( apdu , AbortPDU ) : for tr in self . serverTransactions : if ( apdu . apduInvokeID == tr . invokeID ) and ( apdu . pduDestination == tr . pdu_address ) : break else : return tr . confirmation ( apdu ) else : raise RuntimeError ( "invalid APDU (10)" ) | This function is called when the application is responding to a request the apdu may be a simple ack complex ack error reject or abort . |
13,059 | def add_peer ( self , peerAddr , networks = None ) : if _debug : BTR . _debug ( "add_peer %r networks=%r" , peerAddr , networks ) if peerAddr in self . peers : if not networks : networks = [ ] else : self . peers [ peerAddr ] . extend ( networks ) else : if not networks : networks = [ ] self . peers [ peerAddr ] = networks | Add a peer and optionally provide a list of the reachable networks . |
13,060 | def delete_peer ( self , peerAddr ) : if _debug : BTR . _debug ( "delete_peer %r" , peerAddr ) del self . peers [ peerAddr ] | Delete a peer . |
13,061 | def register ( self , addr , ttl ) : if ttl <= 0 : raise ValueError ( "time-to-live must be greater than zero" ) if isinstance ( addr , Address ) : self . bbmdAddress = addr else : self . bbmdAddress = Address ( addr ) self . bbmdTimeToLive = ttl self . install_task ( when = 0 ) | Initiate the process of registering with a BBMD . |
13,062 | def unregister ( self ) : pdu = RegisterForeignDevice ( 0 ) pdu . pduDestination = self . bbmdAddress self . request ( pdu ) self . registrationStatus = - 2 self . bbmdAddress = None self . bbmdTimeToLive = None | Drop the registration with a BBMD . |
13,063 | def process_task ( self ) : pdu = RegisterForeignDevice ( self . bbmdTimeToLive ) pdu . pduDestination = self . bbmdAddress self . request ( pdu ) | Called when the registration request should be sent to the BBMD . |
13,064 | def register_foreign_device ( self , addr , ttl ) : if _debug : BIPBBMD . _debug ( "register_foreign_device %r %r" , addr , ttl ) if isinstance ( addr , Address ) : pass elif isinstance ( addr , str ) : addr = Address ( addr ) else : raise TypeError ( "addr must be a string or an Address" ) for fdte in self . bbmdFDT : if addr == fdte . fdAddress : break else : fdte = FDTEntry ( ) fdte . fdAddress = addr self . bbmdFDT . append ( fdte ) fdte . fdTTL = ttl fdte . fdRemain = ttl + 5 return 0 | Add a foreign device to the FDT . |
13,065 | def encode_max_segments_accepted ( arg ) : if not arg : return 0 if arg > 64 : return 7 for i in range ( 6 , 0 , - 1 ) : if _max_segments_accepted_encoding [ i ] <= arg : return i raise ValueError ( "invalid max max segments accepted: %r" % ( arg , ) ) | Encode the maximum number of segments the device will accept Section 20 . 1 . 2 . 4 and if the device says it can only accept one segment it shouldn t say that it supports segmentation! |
13,066 | def encode_max_apdu_length_accepted ( arg ) : for i in range ( 5 , - 1 , - 1 ) : if ( arg >= _max_apdu_length_encoding [ i ] ) : return i raise ValueError ( "invalid max APDU length accepted: %r" % ( arg , ) ) | Return the encoding of the highest encodable value less than the value of the arg . |
13,067 | def encode ( self , pdu ) : if _debug : APCI . _debug ( "encode %r" , pdu ) PCI . update ( pdu , self ) if ( self . apduType == ConfirmedRequestPDU . pduType ) : buff = self . apduType << 4 if self . apduSeg : buff += 0x08 if self . apduMor : buff += 0x04 if self . apduSA : buff += 0x02 pdu . put ( buff ) pdu . put ( ( self . apduMaxSegs << 4 ) + self . apduMaxResp ) pdu . put ( self . apduInvokeID ) if self . apduSeg : pdu . put ( self . apduSeq ) pdu . put ( self . apduWin ) pdu . put ( self . apduService ) elif ( self . apduType == UnconfirmedRequestPDU . pduType ) : pdu . put ( self . apduType << 4 ) pdu . put ( self . apduService ) elif ( self . apduType == SimpleAckPDU . pduType ) : pdu . put ( self . apduType << 4 ) pdu . put ( self . apduInvokeID ) pdu . put ( self . apduService ) elif ( self . apduType == ComplexAckPDU . pduType ) : buff = self . apduType << 4 if self . apduSeg : buff += 0x08 if self . apduMor : buff += 0x04 pdu . put ( buff ) pdu . put ( self . apduInvokeID ) if self . apduSeg : pdu . put ( self . apduSeq ) pdu . put ( self . apduWin ) pdu . put ( self . apduService ) elif ( self . apduType == SegmentAckPDU . pduType ) : buff = self . apduType << 4 if self . apduNak : buff += 0x02 if self . apduSrv : buff += 0x01 pdu . put ( buff ) pdu . put ( self . apduInvokeID ) pdu . put ( self . apduSeq ) pdu . put ( self . apduWin ) elif ( self . apduType == ErrorPDU . pduType ) : pdu . put ( self . apduType << 4 ) pdu . put ( self . apduInvokeID ) pdu . put ( self . apduService ) elif ( self . apduType == RejectPDU . pduType ) : pdu . put ( self . apduType << 4 ) pdu . put ( self . apduInvokeID ) pdu . put ( self . apduAbortRejectReason ) elif ( self . apduType == AbortPDU . pduType ) : buff = self . apduType << 4 if self . apduSrv : buff += 0x01 pdu . put ( buff ) pdu . put ( self . apduInvokeID ) pdu . put ( self . apduAbortRejectReason ) else : raise ValueError ( "invalid APCI.apduType" ) | encode the contents of the APCI into the PDU . |
13,068 | def decode ( self , pdu ) : if _debug : APCI . _debug ( "decode %r" , pdu ) PCI . update ( self , pdu ) buff = pdu . get ( ) self . apduType = ( buff >> 4 ) & 0x0F if ( self . apduType == ConfirmedRequestPDU . pduType ) : self . apduSeg = ( ( buff & 0x08 ) != 0 ) self . apduMor = ( ( buff & 0x04 ) != 0 ) self . apduSA = ( ( buff & 0x02 ) != 0 ) buff = pdu . get ( ) self . apduMaxSegs = ( buff >> 4 ) & 0x07 self . apduMaxResp = buff & 0x0F self . apduInvokeID = pdu . get ( ) if self . apduSeg : self . apduSeq = pdu . get ( ) self . apduWin = pdu . get ( ) self . apduService = pdu . get ( ) self . pduData = pdu . pduData elif ( self . apduType == UnconfirmedRequestPDU . pduType ) : self . apduService = pdu . get ( ) self . pduData = pdu . pduData elif ( self . apduType == SimpleAckPDU . pduType ) : self . apduInvokeID = pdu . get ( ) self . apduService = pdu . get ( ) elif ( self . apduType == ComplexAckPDU . pduType ) : self . apduSeg = ( ( buff & 0x08 ) != 0 ) self . apduMor = ( ( buff & 0x04 ) != 0 ) self . apduInvokeID = pdu . get ( ) if self . apduSeg : self . apduSeq = pdu . get ( ) self . apduWin = pdu . get ( ) self . apduService = pdu . get ( ) self . pduData = pdu . pduData elif ( self . apduType == SegmentAckPDU . pduType ) : self . apduNak = ( ( buff & 0x02 ) != 0 ) self . apduSrv = ( ( buff & 0x01 ) != 0 ) self . apduInvokeID = pdu . get ( ) self . apduSeq = pdu . get ( ) self . apduWin = pdu . get ( ) elif ( self . apduType == ErrorPDU . pduType ) : self . apduInvokeID = pdu . get ( ) self . apduService = pdu . get ( ) self . pduData = pdu . pduData elif ( self . apduType == RejectPDU . pduType ) : self . apduInvokeID = pdu . get ( ) self . apduAbortRejectReason = pdu . get ( ) elif ( self . apduType == AbortPDU . pduType ) : self . apduSrv = ( ( buff & 0x01 ) != 0 ) self . apduInvokeID = pdu . get ( ) self . apduAbortRejectReason = pdu . get ( ) self . pduData = pdu . pduData else : raise DecodingError ( "invalid APDU type" ) | decode the contents of the PDU into the APCI . |
13,069 | def decode ( self , pdu ) : try : tag = pdu . get ( ) self . tagClass = ( tag >> 3 ) & 0x01 self . tagNumber = ( tag >> 4 ) if ( self . tagNumber == 0x0F ) : self . tagNumber = pdu . get ( ) self . tagLVT = tag & 0x07 if ( self . tagLVT == 5 ) : self . tagLVT = pdu . get ( ) if ( self . tagLVT == 254 ) : self . tagLVT = pdu . get_short ( ) elif ( self . tagLVT == 255 ) : self . tagLVT = pdu . get_long ( ) elif ( self . tagLVT == 6 ) : self . tagClass = Tag . openingTagClass self . tagLVT = 0 elif ( self . tagLVT == 7 ) : self . tagClass = Tag . closingTagClass self . tagLVT = 0 if ( self . tagClass == Tag . applicationTagClass ) and ( self . tagNumber == Tag . booleanAppTag ) : self . tagData = '' else : self . tagData = pdu . get_data ( self . tagLVT ) except DecodingError : raise InvalidTag ( "invalid tag encoding" ) | Decode a tag from the PDU . |
13,070 | def app_to_context ( self , context ) : if self . tagClass != Tag . applicationTagClass : raise ValueError ( "application tag required" ) if ( self . tagNumber == Tag . booleanAppTag ) : return ContextTag ( context , chr ( self . tagLVT ) ) else : return ContextTag ( context , self . tagData ) | Return a context encoded tag . |
13,071 | def context_to_app ( self , dataType ) : if self . tagClass != Tag . contextTagClass : raise ValueError ( "context tag required" ) if ( dataType == Tag . booleanAppTag ) : return Tag ( Tag . applicationTagClass , Tag . booleanAppTag , struct . unpack ( 'B' , self . tagData ) [ 0 ] , '' ) else : return ApplicationTag ( dataType , self . tagData ) | Return an application encoded tag . |
13,072 | def encode ( self , pdu ) : if _debug : BSLCI . _debug ( "encode %r" , pdu ) PCI . update ( pdu , self ) pdu . put ( self . bslciType ) pdu . put ( self . bslciFunction ) if ( self . bslciLength != len ( self . pduData ) + 4 ) : raise EncodingError ( "invalid BSLCI length" ) pdu . put_short ( self . bslciLength ) | encode the contents of the BSLCI into the PDU . |
13,073 | def decode ( self , pdu ) : if _debug : BSLCI . _debug ( "decode %r" , pdu ) PCI . update ( self , pdu ) self . bslciType = pdu . get ( ) if self . bslciType != 0x83 : raise DecodingError ( "invalid BSLCI type" ) self . bslciFunction = pdu . get ( ) self . bslciLength = pdu . get_short ( ) if ( self . bslciLength != len ( pdu . pduData ) + 4 ) : raise DecodingError ( "invalid BSLCI length" ) | decode the contents of the PDU into the BSLCI . |
13,074 | def ConsoleLogHandler ( loggerRef = '' , handler = None , level = logging . DEBUG , color = None ) : if isinstance ( loggerRef , logging . Logger ) : pass elif isinstance ( loggerRef , str ) : if not loggerRef : loggerRef = _log elif loggerRef not in logging . Logger . manager . loggerDict : raise RuntimeError ( "not a valid logger name: %r" % ( loggerRef , ) ) loggerRef = logging . getLogger ( loggerRef ) else : raise RuntimeError ( "not a valid logger reference: %r" % ( loggerRef , ) ) if hasattr ( loggerRef , 'globs' ) : loggerRef . globs [ '_debug' ] += 1 elif hasattr ( loggerRef . parent , 'globs' ) : loggerRef . parent . globs [ '_debug' ] += 1 if not handler : handler = logging . StreamHandler ( ) handler . setLevel ( level ) handler . setFormatter ( LoggingFormatter ( color ) ) loggerRef . addHandler ( handler ) loggerRef . setLevel ( level ) | Add a handler to stderr with our custom formatter to a logger . |
13,075 | def call_me ( iocb ) : if _debug : call_me . _debug ( "callback_function %r" , iocb ) print ( "call me, %r or %r" % ( iocb . ioResponse , iocb . ioError ) ) | When a controller completes the processing of a request the IOCB can contain one or more functions to be called . |
13,076 | def get_object_class ( object_type , vendor_id = 0 ) : if _debug : get_object_class . _debug ( "get_object_class %r vendor_id=%r" , object_type , vendor_id ) cls = registered_object_types . get ( ( object_type , vendor_id ) ) if _debug : get_object_class . _debug ( " - direct lookup: %s" , repr ( cls ) ) if ( not cls ) and vendor_id : cls = registered_object_types . get ( ( object_type , 0 ) ) if _debug : get_object_class . _debug ( " - default lookup: %s" , repr ( cls ) ) return cls | Return the class associated with an object type . |
13,077 | def _attr_to_property ( self , attr ) : prop = self . _properties . get ( attr ) if not prop : raise PropertyError ( attr ) return prop | Common routine to translate a python attribute name to a property name and return the appropriate property . |
13,078 | def add_property ( self , prop ) : if _debug : Object . _debug ( "add_property %r" , prop ) self . _properties = _copy ( self . _properties ) self . _properties [ prop . identifier ] = prop self . _values [ prop . identifier ] = prop . default | Add a property to an object . The property is an instance of a Property or one of its derived classes . Adding a property disconnects it from the collection of properties common to all of the objects of its class . |
13,079 | def delete_property ( self , prop ) : if _debug : Object . _debug ( "delete_property %r" , prop ) self . _properties = _copy ( self . _properties ) del self . _properties [ prop . identifier ] if prop . identifier in self . _values : del self . _values [ prop . identifier ] | Delete a property from an object . The property is an instance of a Property or one of its derived classes but only the property is relavent . Deleting a property disconnects it from the collection of properties common to all of the objects of its class . |
13,080 | def debug_contents ( self , indent = 1 , file = sys . stdout , _ids = None ) : klasses = list ( self . __class__ . __mro__ ) klasses . reverse ( ) previous_attrs = ( ) for c in klasses : attrs = getattr ( c , '_debug_contents' , ( ) ) if attrs is previous_attrs : continue for attr in attrs : file . write ( "%s%s = %s\n" % ( " " * indent , attr , getattr ( self , attr ) ) ) previous_attrs = attrs property_names = [ ] properties_seen = set ( ) for c in klasses : for prop in getattr ( c , 'properties' , [ ] ) : if prop . identifier not in properties_seen : property_names . append ( prop . identifier ) properties_seen . add ( prop . identifier ) for property_name in property_names : property_value = self . _values . get ( property_name , None ) if property_value is None : continue if hasattr ( property_value , "debug_contents" ) : file . write ( "%s%s\n" % ( " " * indent , property_name ) ) property_value . debug_contents ( indent + 1 , file , _ids ) else : file . write ( "%s%s = %r\n" % ( " " * indent , property_name , property_value ) ) | Print out interesting things about the object . |
13,081 | def encode ( self , pdu ) : if _debug : BVLCI . _debug ( "encode %s" , str ( pdu ) ) PCI . update ( pdu , self ) pdu . put ( self . bvlciType ) pdu . put ( self . bvlciFunction ) if ( self . bvlciLength != len ( self . pduData ) + 4 ) : raise EncodingError ( "invalid BVLCI length" ) pdu . put_short ( self . bvlciLength ) | encode the contents of the BVLCI into the PDU . |
13,082 | def decode ( self , pdu ) : if _debug : BVLCI . _debug ( "decode %s" , str ( pdu ) ) PCI . update ( self , pdu ) self . bvlciType = pdu . get ( ) if self . bvlciType != 0x81 : raise DecodingError ( "invalid BVLCI type" ) self . bvlciFunction = pdu . get ( ) self . bvlciLength = pdu . get_short ( ) if ( self . bvlciLength != len ( pdu . pduData ) + 4 ) : raise DecodingError ( "invalid BVLCI length" ) | decode the contents of the PDU into the BVLCI . |
13,083 | def indication ( self , * args , ** kwargs ) : if not self . current_terminal : raise RuntimeError ( "no active terminal" ) if not isinstance ( self . current_terminal , Server ) : raise RuntimeError ( "current terminal not a server" ) self . current_terminal . indication ( * args , ** kwargs ) | Downstream packet send to current terminal . |
13,084 | def confirmation ( self , * args , ** kwargs ) : if not self . current_terminal : raise RuntimeError ( "no active terminal" ) if not isinstance ( self . current_terminal , Client ) : raise RuntimeError ( "current terminal not a client" ) self . current_terminal . confirmation ( * args , ** kwargs ) | Upstream packet send to current terminal . |
13,085 | def do_ReadPropertyRequest ( self , apdu ) : if _debug : ReadWritePropertyServices . _debug ( "do_ReadPropertyRequest %r" , apdu ) objId = apdu . objectIdentifier if ( objId == ( 'device' , 4194303 ) ) and self . localDevice is not None : if _debug : ReadWritePropertyServices . _debug ( " - wildcard device identifier" ) objId = self . localDevice . objectIdentifier obj = self . get_object_id ( objId ) if _debug : ReadWritePropertyServices . _debug ( " - object: %r" , obj ) if not obj : raise ExecutionError ( errorClass = 'object' , errorCode = 'unknownObject' ) try : datatype = obj . get_datatype ( apdu . propertyIdentifier ) if _debug : ReadWritePropertyServices . _debug ( " - datatype: %r" , datatype ) value = obj . ReadProperty ( apdu . propertyIdentifier , apdu . propertyArrayIndex ) if _debug : ReadWritePropertyServices . _debug ( " - value: %r" , value ) if value is None : raise PropertyError ( apdu . propertyIdentifier ) if issubclass ( datatype , Atomic ) : value = datatype ( value ) elif issubclass ( datatype , Array ) and ( apdu . propertyArrayIndex is not None ) : if apdu . propertyArrayIndex == 0 : value = Unsigned ( value ) elif issubclass ( datatype . subtype , Atomic ) : value = datatype . subtype ( value ) elif not isinstance ( value , datatype . subtype ) : raise TypeError ( "invalid result datatype, expecting %r and got %r" % ( datatype . subtype . __name__ , type ( value ) . __name__ ) ) elif not isinstance ( value , datatype ) : raise TypeError ( "invalid result datatype, expecting %r and got %r" % ( datatype . __name__ , type ( value ) . __name__ ) ) if _debug : ReadWritePropertyServices . _debug ( " - encodeable value: %r" , value ) resp = ReadPropertyACK ( context = apdu ) resp . objectIdentifier = objId resp . propertyIdentifier = apdu . propertyIdentifier resp . propertyArrayIndex = apdu . propertyArrayIndex resp . propertyValue = Any ( ) resp . propertyValue . cast_in ( value ) if _debug : ReadWritePropertyServices . _debug ( " - resp: %r" , resp ) except PropertyError : raise ExecutionError ( errorClass = 'property' , errorCode = 'unknownProperty' ) self . response ( resp ) | Return the value of some property of one of our objects . |
13,086 | def do_WritePropertyRequest ( self , apdu ) : if _debug : ReadWritePropertyServices . _debug ( "do_WritePropertyRequest %r" , apdu ) obj = self . get_object_id ( apdu . objectIdentifier ) if _debug : ReadWritePropertyServices . _debug ( " - object: %r" , obj ) if not obj : raise ExecutionError ( errorClass = 'object' , errorCode = 'unknownObject' ) try : if obj . ReadProperty ( apdu . propertyIdentifier , apdu . propertyArrayIndex ) is None : raise PropertyError ( apdu . propertyIdentifier ) if apdu . propertyValue . is_application_class_null ( ) : datatype = Null else : datatype = obj . get_datatype ( apdu . propertyIdentifier ) if _debug : ReadWritePropertyServices . _debug ( " - datatype: %r" , datatype ) if issubclass ( datatype , Array ) and ( apdu . propertyArrayIndex is not None ) : if apdu . propertyArrayIndex == 0 : value = apdu . propertyValue . cast_out ( Unsigned ) else : value = apdu . propertyValue . cast_out ( datatype . subtype ) else : value = apdu . propertyValue . cast_out ( datatype ) if _debug : ReadWritePropertyServices . _debug ( " - value: %r" , value ) value = obj . WriteProperty ( apdu . propertyIdentifier , value , apdu . propertyArrayIndex , apdu . priority ) resp = SimpleAckPDU ( context = apdu ) if _debug : ReadWritePropertyServices . _debug ( " - resp: %r" , resp ) except PropertyError : raise ExecutionError ( errorClass = 'property' , errorCode = 'unknownProperty' ) self . response ( resp ) | Change the value of some property of one of our objects . |
13,087 | def do_ReadPropertyMultipleRequest ( self , apdu ) : if _debug : ReadWritePropertyMultipleServices . _debug ( "do_ReadPropertyMultipleRequest %r" , apdu ) resp = None read_access_result_list = [ ] for read_access_spec in apdu . listOfReadAccessSpecs : objectIdentifier = read_access_spec . objectIdentifier if _debug : ReadWritePropertyMultipleServices . _debug ( " - objectIdentifier: %r" , objectIdentifier ) if ( objectIdentifier == ( 'device' , 4194303 ) ) and self . localDevice is not None : if _debug : ReadWritePropertyMultipleServices . _debug ( " - wildcard device identifier" ) objectIdentifier = self . localDevice . objectIdentifier obj = self . get_object_id ( objectIdentifier ) if _debug : ReadWritePropertyMultipleServices . _debug ( " - object: %r" , obj ) read_access_result_element_list = [ ] for prop_reference in read_access_spec . listOfPropertyReferences : propertyIdentifier = prop_reference . propertyIdentifier if _debug : ReadWritePropertyMultipleServices . _debug ( " - propertyIdentifier: %r" , propertyIdentifier ) propertyArrayIndex = prop_reference . propertyArrayIndex if _debug : ReadWritePropertyMultipleServices . _debug ( " - propertyArrayIndex: %r" , propertyArrayIndex ) if propertyIdentifier in ( 'all' , 'required' , 'optional' ) : if not obj : read_result = ReadAccessResultElementChoice ( ) read_result . propertyAccessError = ErrorType ( errorClass = 'object' , errorCode = 'unknownObject' ) read_access_result_element = ReadAccessResultElement ( propertyIdentifier = propertyIdentifier , propertyArrayIndex = propertyArrayIndex , readResult = read_result , ) read_access_result_element_list . append ( read_access_result_element ) else : for propId , prop in obj . _properties . items ( ) : if _debug : ReadWritePropertyMultipleServices . _debug ( " - checking: %r %r" , propId , prop . optional ) if ( propertyIdentifier == 'all' ) : pass elif ( propertyIdentifier == 'required' ) and ( prop . optional ) : if _debug : ReadWritePropertyMultipleServices . _debug ( " - not a required property" ) continue elif ( propertyIdentifier == 'optional' ) and ( not prop . optional ) : if _debug : ReadWritePropertyMultipleServices . _debug ( " - not an optional property" ) continue read_access_result_element = read_property_to_result_element ( obj , propId , propertyArrayIndex ) if read_access_result_element . readResult . propertyAccessError and read_access_result_element . readResult . propertyAccessError . errorCode == 'unknownProperty' : continue read_access_result_element_list . append ( read_access_result_element ) else : read_access_result_element = read_property_to_result_element ( obj , propertyIdentifier , propertyArrayIndex ) read_access_result_element_list . append ( read_access_result_element ) read_access_result = ReadAccessResult ( objectIdentifier = objectIdentifier , listOfResults = read_access_result_element_list ) if _debug : ReadWritePropertyMultipleServices . _debug ( " - read_access_result: %r" , read_access_result ) read_access_result_list . append ( read_access_result ) if not resp : resp = ReadPropertyMultipleACK ( context = apdu ) resp . listOfReadAccessResults = read_access_result_list if _debug : ReadWritePropertyMultipleServices . _debug ( " - resp: %r" , resp ) self . response ( resp ) | Respond to a ReadPropertyMultiple Request . |
13,088 | def handle_write ( self ) : if _debug : UDPDirector . _debug ( "handle_write" ) try : pdu = self . request . get ( ) sent = self . socket . sendto ( pdu . pduData , pdu . pduDestination ) if _debug : UDPDirector . _debug ( " - sent %d octets to %s" , sent , pdu . pduDestination ) except socket . error , err : if _debug : UDPDirector . _debug ( " - socket error: %s" , err ) peer = self . peers . get ( pdu . pduDestination , None ) if peer : peer . handle_error ( err ) else : self . handle_error ( err ) | get a PDU from the queue and send it . |
13,089 | def indication ( self , pdu ) : if _debug : UDPDirector . _debug ( "indication %r" , pdu ) addr = pdu . pduDestination peer = self . peers . get ( addr , None ) if not peer : peer = self . actorClass ( self , addr ) peer . indication ( pdu ) | Client requests are queued for delivery . |
13,090 | def _response ( self , pdu ) : if _debug : UDPDirector . _debug ( "_response %r" , pdu ) addr = pdu . pduSource peer = self . peers . get ( addr , None ) if not peer : peer = self . actorClass ( self , addr ) peer . response ( pdu ) | Incoming datagrams are routed through an actor . |
13,091 | def subscriptions ( self ) : if _debug : ChangeOfValueServices . _debug ( "subscriptions" ) subscription_list = [ ] for obj , cov_detection in self . cov_detections . items ( ) : for cov in cov_detection . cov_subscriptions : subscription_list . append ( cov ) return subscription_list | Generator for the active subscriptions . |
13,092 | def bind ( * args ) : if _debug : bind . _debug ( "bind %r" , args ) if not args : for cid , client in client_map . items ( ) : if client . clientPeer : continue if not cid in server_map : raise RuntimeError ( "unmatched server {!r}" . format ( cid ) ) server = server_map [ cid ] if server . serverPeer : raise RuntimeError ( "server already bound %r" . format ( cid ) ) bind ( client , server ) for sid , server in server_map . items ( ) : if server . serverPeer : continue if not sid in client_map : raise RuntimeError ( "unmatched client {!r}" . format ( sid ) ) else : raise RuntimeError ( "mistery unbound server {!r}" . format ( sid ) ) for eid , element in element_map . items ( ) : if element . elementService : continue if not eid in service_map : raise RuntimeError ( "unmatched element {!r}" . format ( cid ) ) service = service_map [ eid ] if server . serverPeer : raise RuntimeError ( "service already bound {!r}" . format ( cid ) ) bind ( element , service ) for sid , service in service_map . items ( ) : if service . serviceElement : continue if not sid in element_map : raise RuntimeError ( "unmatched service {!r}" . format ( sid ) ) else : raise RuntimeError ( "mistery unbound service {!r}" . format ( sid ) ) for i in xrange ( len ( args ) - 1 ) : client = args [ i ] if _debug : bind . _debug ( " - client: %r" , client ) server = args [ i + 1 ] if _debug : bind . _debug ( " - server: %r" , server ) if isinstance ( client , Client ) and isinstance ( server , Server ) : client . clientPeer = server server . serverPeer = client elif isinstance ( client , ApplicationServiceElement ) and isinstance ( server , ServiceAccessPoint ) : client . elementService = server server . serviceElement = client else : raise TypeError ( "bind() requires a client and server" ) if _debug : bind . _debug ( " - bound" ) | bind a list of clients and servers together top down . |
13,093 | def encode ( self , pdu ) : if _debug : NPCI . _debug ( "encode %s" , repr ( pdu ) ) PCI . update ( pdu , self ) pdu . put ( self . npduVersion ) if self . npduNetMessage is not None : netLayerMessage = 0x80 else : netLayerMessage = 0x00 dnetPresent = 0x00 if self . npduDADR is not None : dnetPresent = 0x20 snetPresent = 0x00 if self . npduSADR is not None : snetPresent = 0x08 control = netLayerMessage | dnetPresent | snetPresent if self . pduExpectingReply : control |= 0x04 control |= ( self . pduNetworkPriority & 0x03 ) self . npduControl = control pdu . put ( control ) pdu . pduExpectingReply = self . pduExpectingReply pdu . pduNetworkPriority = self . pduNetworkPriority if dnetPresent : if self . npduDADR . addrType == Address . remoteStationAddr : pdu . put_short ( self . npduDADR . addrNet ) pdu . put ( self . npduDADR . addrLen ) pdu . put_data ( self . npduDADR . addrAddr ) elif self . npduDADR . addrType == Address . remoteBroadcastAddr : pdu . put_short ( self . npduDADR . addrNet ) pdu . put ( 0 ) elif self . npduDADR . addrType == Address . globalBroadcastAddr : pdu . put_short ( 0xFFFF ) pdu . put ( 0 ) if snetPresent : pdu . put_short ( self . npduSADR . addrNet ) pdu . put ( self . npduSADR . addrLen ) pdu . put_data ( self . npduSADR . addrAddr ) if dnetPresent : pdu . put ( self . npduHopCount ) if netLayerMessage : pdu . put ( self . npduNetMessage ) if ( self . npduNetMessage >= 0x80 ) and ( self . npduNetMessage <= 0xFF ) : pdu . put_short ( self . npduVendorID ) | encode the contents of the NPCI into the PDU . |
13,094 | def decode ( self , pdu ) : if _debug : NPCI . _debug ( "decode %s" , str ( pdu ) ) PCI . update ( self , pdu ) if len ( pdu . pduData ) < 2 : raise DecodingError ( "invalid length" ) self . npduVersion = pdu . get ( ) if ( self . npduVersion != 0x01 ) : raise DecodingError ( "only version 1 messages supported" ) self . npduControl = control = pdu . get ( ) netLayerMessage = control & 0x80 dnetPresent = control & 0x20 snetPresent = control & 0x08 self . pduExpectingReply = ( control & 0x04 ) != 0 self . pduNetworkPriority = control & 0x03 if dnetPresent : dnet = pdu . get_short ( ) dlen = pdu . get ( ) dadr = pdu . get_data ( dlen ) if dnet == 0xFFFF : self . npduDADR = GlobalBroadcast ( ) elif dlen == 0 : self . npduDADR = RemoteBroadcast ( dnet ) else : self . npduDADR = RemoteStation ( dnet , dadr ) if snetPresent : snet = pdu . get_short ( ) slen = pdu . get ( ) sadr = pdu . get_data ( slen ) if snet == 0xFFFF : raise DecodingError ( "SADR can't be a global broadcast" ) elif slen == 0 : raise DecodingError ( "SADR can't be a remote broadcast" ) self . npduSADR = RemoteStation ( snet , sadr ) if dnetPresent : self . npduHopCount = pdu . get ( ) if netLayerMessage : self . npduNetMessage = pdu . get ( ) if ( self . npduNetMessage >= 0x80 ) and ( self . npduNetMessage <= 0xFF ) : self . npduVendorID = pdu . get_short ( ) else : self . npduNetMessage = None | decode the contents of the PDU and put them into the NPDU . |
13,095 | def del_actor ( self , actor ) : if _debug : TCPClientDirector . _debug ( "del_actor %r" , actor ) del self . clients [ actor . peer ] if self . serviceElement : self . sap_request ( del_actor = actor ) if actor . peer in self . reconnect : connect_task = FunctionTask ( self . connect , actor . peer ) connect_task . install_task ( _time ( ) + self . reconnect [ actor . peer ] ) | Remove an actor when the socket is closed . |
13,096 | def indication ( self , pdu ) : if _debug : TCPClientDirector . _debug ( "indication %r" , pdu ) addr = pdu . pduDestination client = self . clients . get ( addr , None ) if not client : client = self . actorClass ( self , addr ) client . indication ( pdu ) | Direct this PDU to the appropriate server create a connection if one hasn t already been created . |
13,097 | def indication ( self , pdu ) : if _debug : TCPServerDirector . _debug ( "indication %r" , pdu ) addr = pdu . pduDestination server = self . servers . get ( addr , None ) if not server : raise RuntimeError ( "not a connected server" ) server . indication ( pdu ) | Direct this PDU to the appropriate server . |
13,098 | def indication ( self , pdu ) : if _debug : StreamToPacket . _debug ( "indication %r" , pdu ) for packet in self . packetize ( pdu , self . downstreamBuffer ) : self . request ( packet ) | Message going downstream . |
13,099 | def confirmation ( self , pdu ) : if _debug : StreamToPacket . _debug ( "StreamToPacket.confirmation %r" , pdu ) for packet in self . packetize ( pdu , self . upstreamBuffer ) : self . response ( packet ) | Message going upstream . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.