code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if self.tagClass != Tag.contextTagClass:
raise ValueError("context tag required")
# context booleans have value in data
if (dataType == Tag.booleanAppTag):
return Tag(Tag.applicationTagClass, Tag.booleanAppTag, struct.unpack('B', self.tagData)[0], '')
else:
return ApplicationTag(dataType, self.tagData)
|
def context_to_app(self, dataType)
|
Return an application encoded tag.
| 7.852639 | 6.279261 | 1.250567 |
return (isinstance(arg, (int, long)) and (arg >= 0)) or \
isinstance(arg, basestring)
|
def is_valid(cls, arg)
|
Return True if arg is valid value for the class. If the string
value is wrong for the enumeration, the encoding will fail.
| 4.0998 | 4.213341 | 0.973052 |
if _debug: BSLCI._debug("encode %r", pdu)
# copy the basics
PCI.update(pdu, self)
pdu.put( self.bslciType ) # 0x83
pdu.put( self.bslciFunction )
if (self.bslciLength != len(self.pduData) + 4):
raise EncodingError("invalid BSLCI length")
pdu.put_short( self.bslciLength )
|
def encode(self, pdu)
|
encode the contents of the BSLCI into the PDU.
| 6.213017 | 4.688461 | 1.325172 |
if _debug: BSLCI._debug("decode %r", pdu)
# copy the basics
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")
|
def decode(self, pdu)
|
decode the contents of the PDU into the BSLCI.
| 4.021716 | 3.250911 | 1.237104 |
if isinstance(loggerRef, logging.Logger):
pass
elif isinstance(loggerRef, str):
# check for root
if not loggerRef:
loggerRef = _log
# check for a valid logger name
elif loggerRef not in logging.Logger.manager.loggerDict:
raise RuntimeError("not a valid logger name: %r" % (loggerRef,))
# get the logger
loggerRef = logging.getLogger(loggerRef)
else:
raise RuntimeError("not a valid logger reference: %r" % (loggerRef,))
# see if this (or its parent) is a module level logger
if hasattr(loggerRef, 'globs'):
loggerRef.globs['_debug'] += 1
elif hasattr(loggerRef.parent, 'globs'):
loggerRef.parent.globs['_debug'] += 1
# make a handler if one wasn't provided
if not handler:
handler = logging.StreamHandler()
handler.setLevel(level)
# use our formatter
handler.setFormatter(LoggingFormatter(color))
# add it to the logger
loggerRef.addHandler(handler)
# make sure the logger has at least this level
loggerRef.setLevel(level)
|
def ConsoleLogHandler(loggerRef='', handler=None, level=logging.DEBUG, color=None)
|
Add a handler to stderr with our custom formatter to a logger.
| 2.724094 | 2.724166 | 0.999974 |
if _debug: ArgumentParser._debug("parse_args")
# pass along to the parent class
result_args = _ArgumentParser.parse_args(self, *args, **kwargs)
# check to dump labels
if result_args.buggers:
loggers = sorted(logging.Logger.manager.loggerDict.keys())
for loggerName in loggers:
sys.stdout.write(loggerName + '\n')
sys.exit(0)
# check for debug
if result_args.debug is None:
# --debug not specified
result_args.debug = []
elif not result_args.debug:
# --debug, but no arguments
result_args.debug = ["__main__"]
# check for debugging from the environment
if BACPYPES_DEBUG:
result_args.debug.extend(BACPYPES_DEBUG.split())
if BACPYPES_COLOR:
result_args.color = True
# keep track of which files are going to be used
file_handlers = {}
# loop through the bug list
for i, debug_name in enumerate(result_args.debug):
color = (i % 6) + 2 if result_args.color else None
debug_specs = debug_name.split(':')
if len(debug_specs) == 1:
ConsoleLogHandler(debug_name, color=color)
else:
# the debugger name is just the first component
debug_name = debug_specs[0]
# if the file is already being used, use the already created handler
file_name = debug_specs[1]
if file_name in file_handlers:
handler = file_handlers[file_name]
else:
if len(debug_specs) >= 3:
maxBytes = int(debug_specs[2])
else:
maxBytes = BACPYPES_MAXBYTES
if len(debug_specs) >= 4:
backupCount = int(debug_specs[3])
else:
backupCount = BACPYPES_BACKUPCOUNT
# create a handler
handler = logging.handlers.RotatingFileHandler(
file_name, maxBytes=maxBytes, backupCount=backupCount,
)
handler.setLevel(logging.DEBUG)
# save it for more than one instance
file_handlers[file_name] = handler
# use this handler, no color
ConsoleLogHandler(debug_name, handler=handler)
# return what was parsed
return result_args
|
def parse_args(self, *args, **kwargs)
|
Parse the arguments as usual, then add default processing.
| 3.276862 | 3.22505 | 1.016066 |
if _debug: ConfigArgumentParser._debug("parse_args")
# pass along to the parent class
result_args = ArgumentParser.parse_args(self, *args, **kwargs)
# read in the configuration file
config = _ConfigParser()
config.read(result_args.ini)
if _debug: _log.debug(" - config: %r", config)
# check for BACpypes section
if not config.has_section('BACpypes'):
raise RuntimeError("INI file with BACpypes section required")
# convert the contents to an object
ini_obj = type('ini', (object,), dict(config.items('BACpypes')))
if _debug: _log.debug(" - ini_obj: %r", ini_obj)
# add the object to the parsed arguments
setattr(result_args, 'ini', ini_obj)
# return what was parsed
return result_args
|
def parse_args(self, *args, **kwargs)
|
Parse the arguments as usual, then add default processing.
| 3.247457 | 3.186011 | 1.019286 |
if _debug: read_property_to_any._debug("read_property_to_any %s %r %r", obj, propertyIdentifier, propertyArrayIndex)
# get the datatype
datatype = obj.get_datatype(propertyIdentifier)
if _debug: read_property_to_any._debug(" - datatype: %r", datatype)
if datatype is None:
raise ExecutionError(errorClass='property', errorCode='datatypeNotSupported')
# get the value
value = obj.ReadProperty(propertyIdentifier, propertyArrayIndex)
if _debug: read_property_to_any._debug(" - value: %r", value)
if value is None:
raise ExecutionError(errorClass='property', errorCode='unknownProperty')
# change atomic values into something encodeable
if issubclass(datatype, Atomic):
value = datatype(value)
elif issubclass(datatype, Array) and (propertyArrayIndex is not None):
if 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 %s and got %s" \
% (datatype.subtype.__name__, type(value).__name__))
elif not isinstance(value, datatype):
raise TypeError("invalid result datatype, expecting %s and got %s" \
% (datatype.__name__, type(value).__name__))
if _debug: read_property_to_any._debug(" - encodeable value: %r", value)
# encode the value
result = Any()
result.cast_in(value)
if _debug: read_property_to_any._debug(" - result: %r", result)
# return the object
return result
|
def read_property_to_any(obj, propertyIdentifier, propertyArrayIndex=None)
|
Read the specified property of the object, with the optional array index,
and cast the result into an Any object.
| 2.1168 | 2.09532 | 1.010251 |
if _debug: read_property_to_result_element._debug("read_property_to_result_element %s %r %r", obj, propertyIdentifier, propertyArrayIndex)
# save the result in the property value
read_result = ReadAccessResultElementChoice()
try:
if not obj:
raise ExecutionError(errorClass='object', errorCode='unknownObject')
read_result.propertyValue = read_property_to_any(obj, propertyIdentifier, propertyArrayIndex)
if _debug: read_property_to_result_element._debug(" - success")
except PropertyError as error:
if _debug: read_property_to_result_element._debug(" - error: %r", error)
read_result.propertyAccessError = ErrorType(errorClass='property', errorCode='unknownProperty')
except ExecutionError as error:
if _debug: read_property_to_result_element._debug(" - error: %r", error)
read_result.propertyAccessError = ErrorType(errorClass=error.errorClass, errorCode=error.errorCode)
# make an element for this value
read_access_result_element = ReadAccessResultElement(
propertyIdentifier=propertyIdentifier,
propertyArrayIndex=propertyArrayIndex,
readResult=read_result,
)
if _debug: read_property_to_result_element._debug(" - read_access_result_element: %r", read_access_result_element)
# fini
return read_access_result_element
|
def read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex=None)
|
Read the specified property of the object, with the optional array index,
and cast the result into an Any object.
| 2.280983 | 2.216104 | 1.029276 |
if _debug: run_once._debug("run_once")
global taskManager, deferredFns
# reference the task manager (a singleton)
taskManager = TaskManager()
try:
delta = 0.0
while delta == 0.0:
# get the next task
task, delta = taskManager.get_next_task()
if _debug: run_once._debug(" - task, delta: %r, %r", task, delta)
# if there is a task to process, do it
if task:
taskManager.process_task(task)
# check for deferred functions
while deferredFns:
# get a reference to the list
fnlist = deferredFns
deferredFns = []
# call the functions
for fn, args, kwargs in fnlist:
if _debug: run_once._debug(" - call: %r %r %r", fn, args, kwargs)
fn(*args, **kwargs)
# done with this list
del fnlist
except KeyboardInterrupt:
if _debug: run_once._info("keyboard interrupt")
except Exception as err:
if _debug: run_once._exception("an error has occurred: %s", err)
|
def run_once()
|
Make a pass through the scheduled tasks and deferred functions just
like the run() function but without the asyncore call (so there is no
socket IO actviity) and the timers.
| 2.890368 | 2.758178 | 1.047927 |
if _debug: call_me._debug("callback_function %r", iocb)
# it will be successful or have an error
print("call me, %r or %r" % (iocb.ioResponse, iocb.ioError))
|
def call_me(iocb)
|
When a controller completes the processing of a request,
the IOCB can contain one or more functions to be called.
| 9.12305 | 9.875283 | 0.923827 |
if _debug: get_object_class._debug("get_object_class %r vendor_id=%r", object_type, vendor_id)
# find the klass as given
cls = registered_object_types.get((object_type, vendor_id))
if _debug: get_object_class._debug(" - direct lookup: %s", repr(cls))
# if the class isn't found and the vendor id is non-zero, try the standard class for the type
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
|
def get_object_class(object_type, vendor_id=0)
|
Return the class associated with an object type.
| 2.790159 | 2.733656 | 1.020669 |
if _debug: get_datatype._debug("get_datatype %r %r vendor_id=%r", object_type, propid, vendor_id)
# get the related class
cls = get_object_class(object_type, vendor_id)
if not cls:
return None
# get the property
prop = cls._properties.get(propid)
if not prop:
return None
# return the datatype
return prop.datatype
|
def get_datatype(object_type, propid, vendor_id=0)
|
Return the datatype for the property of an object.
| 2.171729 | 2.064829 | 1.051772 |
# get the property
prop = self._properties.get(attr)
if not prop:
raise PropertyError(attr)
# found it
return prop
|
def _attr_to_property(self, attr)
|
Common routine to translate a python attribute name to a property name and
return the appropriate property.
| 5.867192 | 5.223841 | 1.123157 |
if _debug: Object._debug("add_property %r", prop)
# make a copy of the properties dictionary
self._properties = _copy(self._properties)
# save the property reference and default value (usually None)
self._properties[prop.identifier] = prop
self._values[prop.identifier] = prop.default
|
def add_property(self, prop)
|
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.
| 4.398416 | 5.002958 | 0.879163 |
if _debug: Object._debug("delete_property %r", prop)
# make a copy of the properties dictionary
self._properties = _copy(self._properties)
# delete the property from the dictionary and values
del self._properties[prop.identifier]
if prop.identifier in self._values:
del self._values[prop.identifier]
|
def delete_property(self, prop)
|
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.
| 3.493333 | 3.676293 | 0.950232 |
if _debug: Object._debug("get_datatype %r", propid)
# get the property
prop = self._properties.get(propid)
if not prop:
raise PropertyError(propid)
# return the datatype
return prop.datatype
|
def get_datatype(self, propid)
|
Return the datatype for the property of an object.
| 3.145231 | 3.002777 | 1.047441 |
if _debug: Object._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
klasses = list(self.__class__.__mro__)
klasses.reverse()
# build a list of property identifiers "bottom up"
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)
# extract the values
for property_name in property_names:
# get the value
property_value = self._properties.get(property_name).ReadProperty(self)
if property_value is None:
continue
# if the value has a way to convert it to a dict, use it
if hasattr(property_value, "dict_contents"):
property_value = property_value.dict_contents(as_class=as_class)
# save the value
use_dict.__setitem__(property_name, property_value)
# return what we built/updated
return use_dict
|
def _dict_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 2.934191 | 2.836943 | 1.034279 |
klasses = list(self.__class__.__mro__)
klasses.reverse()
# print special attributes "bottom up"
previous_attrs = ()
for c in klasses:
attrs = getattr(c, '_debug_contents', ())
# if we have seen this list already, move to the next class
if attrs is previous_attrs:
continue
for attr in attrs:
file.write("%s%s = %s\n" % (" " * indent, attr, getattr(self, attr)))
previous_attrs = attrs
# build a list of property identifiers "bottom up"
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)
# print out the values
for property_name in property_names:
property_value = self._values.get(property_name, None)
# printing out property values that are None is tedious
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))
|
def debug_contents(self, indent=1, file=sys.stdout, _ids=None)
|
Print out interesting things about the object.
| 2.745026 | 2.699568 | 1.016839 |
if _debug: BVLCI._debug("encode %s", str(pdu))
# copy the basics
PCI.update(pdu, self)
pdu.put( self.bvlciType ) # 0x81
pdu.put( self.bvlciFunction )
if (self.bvlciLength != len(self.pduData) + 4):
raise EncodingError("invalid BVLCI length")
pdu.put_short( self.bvlciLength )
|
def encode(self, pdu)
|
encode the contents of the BVLCI into the PDU.
| 5.747833 | 4.477915 | 1.283596 |
if _debug: BVLCI._debug("decode %s", str(pdu))
# copy the basics
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")
|
def decode(self, pdu)
|
decode the contents of the PDU into the BVLCI.
| 3.693666 | 3.095342 | 1.193298 |
if _debug: BVLCI._debug("bvlci_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# save the mapped value
use_dict.__setitem__('type', self.bvlciType)
use_dict.__setitem__('function', self.bvlciFunction)
use_dict.__setitem__('length', self.bvlciLength)
# return what we built/updated
return use_dict
|
def bvlci_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 2.897392 | 2.810002 | 1.0311 |
if _debug: BVLPDU._debug("dict_contents use_dict=%r as_class=%r key_values=%r", use_dict, as_class, key_values)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# call the superclasses
self.bvlci_contents(use_dict=use_dict, as_class=as_class)
self.bvlpdu_contents(use_dict=use_dict, as_class=as_class)
# return what we built/updated
return use_dict
|
def dict_contents(self, use_dict=None, as_class=dict, key_values=())
|
Return the contents of an object as a dict.
| 3.226978 | 3.179015 | 1.015087 |
self.pduUserData = pci.pduUserData
self.pduSource = pci.pduSource
self.pduDestination = pci.pduDestination
|
def update(self, pci)
|
Copy the PCI fields.
| 5.932032 | 5.469616 | 1.084543 |
if _debug: PCI._debug("pci_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# save the values
for k, v in (('user_data', self.pduUserData), ('source', self.pduSource), ('destination', self.pduDestination)):
if _debug: PCI._debug(" - %r: %r", k, v)
if v is None:
continue
if hasattr(v, 'dict_contents'):
v = v.dict_contents(as_class=as_class)
use_dict.__setitem__(k, v)
# return what we built/updated
return use_dict
|
def pci_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 2.98494 | 2.883353 | 1.035232 |
if _debug: PCI._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
return self.pci_contents(use_dict=use_dict, as_class=as_class)
|
def dict_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 3.041996 | 2.872226 | 1.059107 |
if _debug: PDUData._debug("pdudata_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# add the data if it is not None
v = self.pduData
if v is not None:
if isinstance(v, str):
v = btox(v)
elif hasattr(v, 'dict_contents'):
v = v.dict_contents(as_class=as_class)
use_dict.__setitem__('data', v)
# return what we built/updated
return use_dict
|
def pdudata_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 3.093217 | 3.035651 | 1.018963 |
if _debug: PDUData._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
return self.pdudata_contents(use_dict=use_dict, as_class=as_class)
|
def dict_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 3.003309 | 2.985795 | 1.005866 |
if _debug: PDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# call into the two base classes
self.pci_contents(use_dict=use_dict, as_class=as_class)
self.pdudata_contents(use_dict=use_dict, as_class=as_class)
# return what we built/updated
return use_dict
|
def dict_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 3.234223 | 3.214789 | 1.006045 |
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)
|
def indication(self, *args, **kwargs)
|
Downstream packet, send to current terminal.
| 4.235947 | 3.207228 | 1.32075 |
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)
|
def confirmation(self, *args, **kwargs)
|
Upstream packet, send to current terminal.
| 4.399369 | 3.429469 | 1.282814 |
if _debug: ReadWritePropertyServices._debug("do_ReadPropertyRequest %r", apdu)
# extract the object identifier
objId = apdu.objectIdentifier
# check for wildcard
if (objId == ('device', 4194303)) and self.localDevice is not None:
if _debug: ReadWritePropertyServices._debug(" - wildcard device identifier")
objId = self.localDevice.objectIdentifier
# get the object
obj = self.get_object_id(objId)
if _debug: ReadWritePropertyServices._debug(" - object: %r", obj)
if not obj:
raise ExecutionError(errorClass='object', errorCode='unknownObject')
try:
# get the datatype
datatype = obj.get_datatype(apdu.propertyIdentifier)
if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype)
# get the value
value = obj.ReadProperty(apdu.propertyIdentifier, apdu.propertyArrayIndex)
if _debug: ReadWritePropertyServices._debug(" - value: %r", value)
if value is None:
raise PropertyError(apdu.propertyIdentifier)
# change atomic values into something encodeable
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)
# this is a ReadProperty ack
resp = ReadPropertyACK(context=apdu)
resp.objectIdentifier = objId
resp.propertyIdentifier = apdu.propertyIdentifier
resp.propertyArrayIndex = apdu.propertyArrayIndex
# save the result in the property value
resp.propertyValue = Any()
resp.propertyValue.cast_in(value)
if _debug: ReadWritePropertyServices._debug(" - resp: %r", resp)
except PropertyError:
raise ExecutionError(errorClass='property', errorCode='unknownProperty')
# return the result
self.response(resp)
|
def do_ReadPropertyRequest(self, apdu)
|
Return the value of some property of one of our objects.
| 2.503238 | 2.498292 | 1.00198 |
if _debug: ReadWritePropertyServices._debug("do_WritePropertyRequest %r", apdu)
# get the object
obj = self.get_object_id(apdu.objectIdentifier)
if _debug: ReadWritePropertyServices._debug(" - object: %r", obj)
if not obj:
raise ExecutionError(errorClass='object', errorCode='unknownObject')
try:
# check if the property exists
if obj.ReadProperty(apdu.propertyIdentifier, apdu.propertyArrayIndex) is None:
raise PropertyError(apdu.propertyIdentifier)
# get the datatype, special case for null
if apdu.propertyValue.is_application_class_null():
datatype = Null
else:
datatype = obj.get_datatype(apdu.propertyIdentifier)
if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype)
# special case for array parts, others are managed by cast_out
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)
# change the value
value = obj.WriteProperty(apdu.propertyIdentifier, value, apdu.propertyArrayIndex, apdu.priority)
# success
resp = SimpleAckPDU(context=apdu)
if _debug: ReadWritePropertyServices._debug(" - resp: %r", resp)
except PropertyError:
raise ExecutionError(errorClass='property', errorCode='unknownProperty')
# return the result
self.response(resp)
|
def do_WritePropertyRequest(self, apdu)
|
Change the value of some property of one of our objects.
| 2.594011 | 2.550251 | 1.017159 |
if _debug: ReadWritePropertyMultipleServices._debug("do_ReadPropertyMultipleRequest %r", apdu)
# response is a list of read access results (or an error)
resp = None
read_access_result_list = []
# loop through the request
for read_access_spec in apdu.listOfReadAccessSpecs:
# get the object identifier
objectIdentifier = read_access_spec.objectIdentifier
if _debug: ReadWritePropertyMultipleServices._debug(" - objectIdentifier: %r", objectIdentifier)
# check for wildcard
if (objectIdentifier == ('device', 4194303)) and self.localDevice is not None:
if _debug: ReadWritePropertyMultipleServices._debug(" - wildcard device identifier")
objectIdentifier = self.localDevice.objectIdentifier
# get the object
obj = self.get_object_id(objectIdentifier)
if _debug: ReadWritePropertyMultipleServices._debug(" - object: %r", obj)
# build a list of result elements
read_access_result_element_list = []
# loop through the property references
for prop_reference in read_access_spec.listOfPropertyReferences:
# get the property identifier
propertyIdentifier = prop_reference.propertyIdentifier
if _debug: ReadWritePropertyMultipleServices._debug(" - propertyIdentifier: %r", propertyIdentifier)
# get the array index (optional)
propertyArrayIndex = prop_reference.propertyArrayIndex
if _debug: ReadWritePropertyMultipleServices._debug(" - propertyArrayIndex: %r", propertyArrayIndex)
# check for special property identifiers
if propertyIdentifier in ('all', 'required', 'optional'):
if not obj:
# build a property access error
read_result = ReadAccessResultElementChoice()
read_result.propertyAccessError = ErrorType(errorClass='object', errorCode='unknownObject')
# make an element for this error
read_access_result_element = ReadAccessResultElement(
propertyIdentifier=propertyIdentifier,
propertyArrayIndex=propertyArrayIndex,
readResult=read_result,
)
# add it to the list
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 the specific property
read_access_result_element = read_property_to_result_element(obj, propId, propertyArrayIndex)
# check for undefined property
if read_access_result_element.readResult.propertyAccessError \
and read_access_result_element.readResult.propertyAccessError.errorCode == 'unknownProperty':
continue
# add it to the list
read_access_result_element_list.append(read_access_result_element)
else:
# read the specific property
read_access_result_element = read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex)
# add it to the list
read_access_result_element_list.append(read_access_result_element)
# build a read access result
read_access_result = ReadAccessResult(
objectIdentifier=objectIdentifier,
listOfResults=read_access_result_element_list
)
if _debug: ReadWritePropertyMultipleServices._debug(" - read_access_result: %r", read_access_result)
# add it to the list
read_access_result_list.append(read_access_result)
# this is a ReadPropertyMultiple ack
if not resp:
resp = ReadPropertyMultipleACK(context=apdu)
resp.listOfReadAccessResults = read_access_result_list
if _debug: ReadWritePropertyMultipleServices._debug(" - resp: %r", resp)
# return the result
self.response(resp)
|
def do_ReadPropertyMultipleRequest(self, apdu)
|
Respond to a ReadPropertyMultiple Request.
| 2.142891 | 2.127549 | 1.007211 |
# unpack the date
year, month, day, day_of_week = date
last_day = calendar.monthrange(year + 1900, month)[1]
# unpack the date pattern octet string
weeknday_unpacked = [c for c in weeknday]
month_p, week_of_month_p, day_of_week_p = weeknday_unpacked
# check the month
if month_p == 255:
# any month
pass
elif month_p == 13:
# odd months
if (month % 2) == 0:
return False
elif month_p == 14:
# even months
if (month % 2) == 1:
return False
elif month != month_p:
# specific month
return False
# check the week of the month
if week_of_month_p == 255:
# any week
pass
elif week_of_month_p == 1:
# days numbered 1-7
if (day > 7):
return False
elif week_of_month_p == 2:
# days numbered 8-14
if (day < 8) or (day > 14):
return False
elif week_of_month_p == 3:
# days numbered 15-21
if (day < 15) or (day > 21):
return False
elif week_of_month_p == 4:
# days numbered 22-28
if (day < 22) or (day > 28):
return False
elif week_of_month_p == 5:
# days numbered 29-31
if (day < 29) or (day > 31):
return False
elif week_of_month_p == 6:
# last 7 days of this month
if (day < last_day - 6):
return False
elif week_of_month_p == 7:
# any of the 7 days prior to the last 7 days of this month
if (day < last_day - 13) or (day > last_day - 7):
return False
elif week_of_month_p == 8:
# any of the 7 days prior to the last 14 days of this month
if (day < last_day - 20) or (day > last_day - 14):
return False
elif week_of_month_p == 9:
# any of the 7 days prior to the last 21 days of this month
if (day < last_day - 27) or (day > last_day - 21):
return False
# check the day
if day_of_week_p == 255:
# any day
pass
elif day_of_week != day_of_week_p:
# specific day
return False
# all tests pass
return True
|
def match_weeknday(date, weeknday)
|
Match a specific date, a four-tuple with no special values, with a
BACnetWeekNDay, an octet string with three (unsigned) octets.
| 1.762909 | 1.730366 | 1.018808 |
if _debug: _log.debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# exception to the rule of returning a dict
return str(self)
|
def dict_contents(self, use_dict=None, as_class=None)
|
Return the contents of an object as a dict.
| 6.455437 | 5.7918 | 1.114582 |
_PCI.update(self, pci)
# now do the BACnet PCI fields
self.pduExpectingReply = pci.pduExpectingReply
self.pduNetworkPriority = pci.pduNetworkPriority
|
def update(self, pci)
|
Copy the PCI fields.
| 17.491055 | 12.192783 | 1.434542 |
if _debug: PCI._debug("pci_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# call the parent class
_PCI.pci_contents(self, use_dict=use_dict, as_class=as_class)
# save the values
use_dict.__setitem__('expectingReply', self.pduExpectingReply)
use_dict.__setitem__('networkPriority', self.pduNetworkPriority)
# return what we built/updated
return use_dict
|
def pci_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 3.670545 | 3.49716 | 1.049579 |
if _debug: UDPDirector._debug("add_actor %r", actor)
self.peers[actor.peer] = actor
# tell the ASE there is a new client
if self.serviceElement:
self.sap_request(add_actor=actor)
|
def add_actor(self, actor)
|
Add an actor when a new one is connected.
| 11.627625 | 10.622748 | 1.094597 |
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)
# get the peer
peer = self.peers.get(pdu.pduDestination, None)
if peer:
# let the actor handle the error
peer.handle_error(err)
else:
# let the director handle the error
self.handle_error(err)
|
def handle_write(self)
|
get a PDU from the queue and send it.
| 3.007163 | 2.664824 | 1.128466 |
if _debug: UDPDirector._debug("close_socket")
self.socket.close()
self.close()
self.socket = None
|
def close_socket(self)
|
Close the socket.
| 7.689502 | 6.801616 | 1.13054 |
if _debug: UDPDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the peer
peer = self.peers.get(addr, None)
if not peer:
peer = self.actorClass(self, addr)
# send the message
peer.indication(pdu)
|
def indication(self, pdu)
|
Client requests are queued for delivery.
| 4.454622 | 4.331716 | 1.028374 |
if _debug: UDPDirector._debug("_response %r", pdu)
# get the destination
addr = pdu.pduSource
# get the peer
peer = self.peers.get(addr, None)
if not peer:
peer = self.actorClass(self, addr)
# send the message
peer.response(pdu)
|
def _response(self, pdu)
|
Incoming datagrams are routed through an actor.
| 4.869496 | 4.34946 | 1.119563 |
if _debug: abort._debug("abort %r", err)
global local_controllers
# tell all the local controllers to abort
for controller in local_controllers.values():
controller.abort(err)
|
def abort(err)
|
Abort everything, everywhere.
| 5.906013 | 5.144073 | 1.14812 |
if _debug: ChangeOfValueServices._debug("subscriptions")
subscription_list = []
# loop through the object and detection list
for obj, cov_detection in self.cov_detections.items():
for cov in cov_detection.cov_subscriptions:
subscription_list.append(cov)
return subscription_list
|
def subscriptions(self)
|
Generator for the active subscriptions.
| 8.454744 | 8.018708 | 1.054377 |
if _debug: bind._debug("bind %r", args)
# generic bind is pairs of names
if not args:
# find unbound clients and bind them
for cid, client in client_map.items():
# skip those that are already bound
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)
# see if there are any unbound servers
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))
# find unbound application service elements and bind them
for eid, element in element_map.items():
# skip those that are already bound
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)
# see if there are any unbound services
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))
# go through the argument pairs
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)
# make sure we're binding clients and servers
if isinstance(client, Client) and isinstance(server, Server):
client.clientPeer = server
server.serverPeer = client
# we could be binding application clients and servers
elif isinstance(client, ApplicationServiceElement) and isinstance(server, ServiceAccessPoint):
client.elementService = server
server.serviceElement = client
# error
else:
raise TypeError("bind() requires a client and server")
if _debug: bind._debug(" - bound")
|
def bind(*args)
|
bind a list of clients and servers together, top down.
| 2.619715 | 2.48493 | 1.054241 |
if _debug: NPCI._debug("encode %s", repr(pdu))
PCI.update(pdu, self)
# only version 1 messages supported
pdu.put(self.npduVersion)
# build the flags
if self.npduNetMessage is not None:
netLayerMessage = 0x80
else:
netLayerMessage = 0x00
# map the destination address
dnetPresent = 0x00
if self.npduDADR is not None:
dnetPresent = 0x20
# map the source address
snetPresent = 0x00
if self.npduSADR is not None:
snetPresent = 0x08
# encode the control octet
control = netLayerMessage | dnetPresent | snetPresent
if self.pduExpectingReply:
control |= 0x04
control |= (self.pduNetworkPriority & 0x03)
self.npduControl = control
pdu.put(control)
# make sure expecting reply and priority get passed down
pdu.pduExpectingReply = self.pduExpectingReply
pdu.pduNetworkPriority = self.pduNetworkPriority
# encode the destination address
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)
# encode the source address
if snetPresent:
pdu.put_short(self.npduSADR.addrNet)
pdu.put(self.npduSADR.addrLen)
pdu.put_data(self.npduSADR.addrAddr)
# put the hop count
if dnetPresent:
pdu.put(self.npduHopCount)
# put the network layer message type (if present)
if netLayerMessage:
pdu.put(self.npduNetMessage)
# put the vendor ID
if (self.npduNetMessage >= 0x80) and (self.npduNetMessage <= 0xFF):
pdu.put_short(self.npduVendorID)
|
def encode(self, pdu)
|
encode the contents of the NPCI into the PDU.
| 2.654534 | 2.568104 | 1.033655 |
if _debug: NPCI._debug("decode %s", str(pdu))
PCI.update(self, pdu)
# check the length
if len(pdu.pduData) < 2:
raise DecodingError("invalid length")
# only version 1 messages supported
self.npduVersion = pdu.get()
if (self.npduVersion != 0x01):
raise DecodingError("only version 1 messages supported")
# decode the control octet
self.npduControl = control = pdu.get()
netLayerMessage = control & 0x80
dnetPresent = control & 0x20
snetPresent = control & 0x08
self.pduExpectingReply = (control & 0x04) != 0
self.pduNetworkPriority = control & 0x03
# extract the destination address
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)
# extract the source address
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)
# extract the hop count
if dnetPresent:
self.npduHopCount = pdu.get()
# extract the network layer message type (if present)
if netLayerMessage:
self.npduNetMessage = pdu.get()
if (self.npduNetMessage >= 0x80) and (self.npduNetMessage <= 0xFF):
# extract the vendor ID
self.npduVendorID = pdu.get_short()
else:
# application layer message
self.npduNetMessage = None
|
def decode(self, pdu)
|
decode the contents of the PDU and put them into the NPDU.
| 2.828317 | 2.718026 | 1.040578 |
if _debug: NPCI._debug("npci_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
if _debug: NPCI._debug(" - new use_dict")
use_dict = as_class()
# version and control are simple
use_dict.__setitem__('version', self.npduVersion)
use_dict.__setitem__('control', self.npduControl)
# dnet/dlen/dadr
if self.npduDADR is not None:
if self.npduDADR.addrType == Address.remoteStationAddr:
use_dict.__setitem__('dnet', self.npduDADR.addrNet)
use_dict.__setitem__('dlen', self.npduDADR.addrLen)
use_dict.__setitem__('dadr', btox(self.npduDADR.addrAddr or ''))
elif self.npduDADR.addrType == Address.remoteBroadcastAddr:
use_dict.__setitem__('dnet', self.npduDADR.addrNet)
use_dict.__setitem__('dlen', 0)
use_dict.__setitem__('dadr', '')
elif self.npduDADR.addrType == Address.globalBroadcastAddr:
use_dict.__setitem__('dnet', 0xFFFF)
use_dict.__setitem__('dlen', 0)
use_dict.__setitem__('dadr', '')
# snet/slen/sadr
if self.npduSADR is not None:
use_dict.__setitem__('snet', self.npduSADR.addrNet)
use_dict.__setitem__('slen', self.npduSADR.addrLen)
use_dict.__setitem__('sadr', btox(self.npduSADR.addrAddr or ''))
# hop count
if self.npduHopCount is not None:
use_dict.__setitem__('hop_count', self.npduHopCount)
# network layer message name decoded
if self.npduNetMessage is not None:
use_dict.__setitem__('net_message', self.npduNetMessage)
if self.npduVendorID is not None:
use_dict.__setitem__('vendor_id', self.npduVendorID)
# return what we built/updated
return use_dict
|
def npci_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 2.072403 | 2.063934 | 1.004104 |
if _debug: NPDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# call the parent classes
self.npci_contents(use_dict=use_dict, as_class=as_class)
self.npdu_contents(use_dict=use_dict, as_class=as_class)
# return what we built/updated
return use_dict
|
def dict_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 3.276841 | 3.198073 | 1.02463 |
if _debug: TCPClient._debug("handle_error %r", error)
# core does not take parameters
asyncore.dispatcher.handle_error(self)
|
def handle_error(self, error=None)
|
Trap for TCPClient errors, otherwise continue.
| 9.251533 | 7.035816 | 1.31492 |
if _debug: TCPClient._debug("indication %r", pdu)
self.request += pdu.pduData
|
def indication(self, pdu)
|
Requests are queued for delivery.
| 6.939078 | 6.182634 | 1.12235 |
if _debug: TCPClientActor._debug("handle_error %r", error)
# pass along to the director
if error is not None:
self.director.actor_error(self, error)
else:
TCPClient.handle_error(self)
|
def handle_error(self, error=None)
|
Trap for TCPClient errors, otherwise continue.
| 5.085216 | 4.313963 | 1.178781 |
if _debug: TCPClientDirector._debug("add_actor %r", actor)
self.clients[actor.peer] = actor
# tell the ASE there is a new client
if self.serviceElement:
self.sap_request(add_actor=actor)
|
def add_actor(self, actor)
|
Add an actor when a new one is connected.
| 10.100117 | 9.275175 | 1.088941 |
if _debug: TCPClientDirector._debug("del_actor %r", actor)
del self.clients[actor.peer]
# tell the ASE the client has gone away
if self.serviceElement:
self.sap_request(del_actor=actor)
# see if it should be reconnected
if actor.peer in self.reconnect:
connect_task = FunctionTask(self.connect, actor.peer)
connect_task.install_task(_time() + self.reconnect[actor.peer])
|
def del_actor(self, actor)
|
Remove an actor when the socket is closed.
| 6.600294 | 6.53094 | 1.010619 |
if _debug: TCPClientDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the client
client = self.clients.get(addr, None)
if not client:
client = self.actorClass(self, addr)
# send the message
client.indication(pdu)
|
def indication(self, pdu)
|
Direct this PDU to the appropriate server, create a
connection if one hasn't already been created.
| 4.199155 | 3.867687 | 1.085702 |
if _debug: TCPServer._debug("handle_error %r", error)
# core does not take parameters
asyncore.dispatcher.handle_error(self)
|
def handle_error(self, error=None)
|
Trap for TCPServer errors, otherwise continue.
| 9.475025 | 7.275069 | 1.302397 |
if _debug: TCPServer._debug("indication %r", pdu)
self.request += pdu.pduData
|
def indication(self, pdu)
|
Requests are queued for delivery.
| 7.224534 | 6.002101 | 1.203667 |
if _debug: TCPServerActor._debug("handle_error %r", error)
# pass along to the director
if error is not None:
self.director.actor_error(self, error)
else:
TCPServer.handle_error(self)
|
def handle_error(self, error=None)
|
Trap for TCPServer errors, otherwise continue.
| 5.093822 | 4.357595 | 1.168952 |
if _debug: TCPServerDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the server
server = self.servers.get(addr, None)
if not server:
raise RuntimeError("not a connected server")
# pass the indication to the actor
server.indication(pdu)
|
def indication(self, pdu)
|
Direct this PDU to the appropriate server.
| 4.341531 | 3.842777 | 1.12979 |
if _debug: StreamToPacket._debug("indication %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.downstreamBuffer):
self.request(packet)
|
def indication(self, pdu)
|
Message going downstream.
| 12.851388 | 11.008649 | 1.16739 |
if _debug: StreamToPacket._debug("StreamToPacket.confirmation %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.upstreamBuffer):
self.response(packet)
|
def confirmation(self, pdu)
|
Message going upstream.
| 17.161795 | 15.430937 | 1.112168 |
if _debug: IOCB._debug("add_callback(%d) %r %r %r", self.ioID, fn, args, kwargs)
# store it
self.ioCallback.append((fn, args, kwargs))
# already complete?
if self.ioComplete.isSet():
self.trigger()
|
def add_callback(self, fn, *args, **kwargs)
|
Pass a function to be called when IO is complete.
| 5.005694 | 4.483572 | 1.116452 |
if _debug: IOCB._debug("wait(%d) %r %r", self.ioID, args, kwargs)
# waiting from a non-daemon thread could be trouble
return self.ioComplete.wait(*args, **kwargs)
|
def wait(self, *args, **kwargs)
|
Wait for the completion event to be set.
| 10.634131 | 10.2225 | 1.040267 |
if _debug: IOCB._debug("trigger(%d)", self.ioID)
# if it's queued, remove it from its queue
if self.ioQueue:
if _debug: IOCB._debug(" - dequeue")
self.ioQueue.remove(self)
# if there's a timer, cancel it
if self.ioTimeout:
if _debug: IOCB._debug(" - cancel timeout")
self.ioTimeout.suspend_task()
# set the completion event
self.ioComplete.set()
if _debug: IOCB._debug(" - complete event set")
# make the callback(s)
for fn, args, kwargs in self.ioCallback:
if _debug: IOCB._debug(" - callback fn: %r %r %r", fn, args, kwargs)
fn(self, *args, **kwargs)
|
def trigger(self)
|
Set the completion event and make the callback(s).
| 3.102751 | 2.734805 | 1.134542 |
if _debug: IOCB._debug("complete(%d) %r", self.ioID, msg)
if self.ioController:
# pass to controller
self.ioController.complete_io(self, msg)
else:
# just fill in the data
self.ioState = COMPLETED
self.ioResponse = msg
self.trigger()
|
def complete(self, msg)
|
Called to complete a transaction, usually when ProcessIO has
shipped the IOCB off to some other thread or function.
| 5.971229 | 5.599998 | 1.066291 |
if _debug: IOCB._debug("abort(%d) %r", self.ioID, err)
if self.ioController:
# pass to controller
self.ioController.abort_io(self, err)
elif self.ioState < COMPLETED:
# just fill in the data
self.ioState = ABORTED
self.ioError = err
self.trigger()
|
def abort(self, err)
|
Called by a client to abort a transaction.
| 5.841137 | 6.041604 | 0.966819 |
if _debug: IOCB._debug("set_timeout(%d) %r err=%r", self.ioID, delay, err)
# if one has already been created, cancel it
if self.ioTimeout:
self.ioTimeout.suspend_task()
else:
self.ioTimeout = FunctionTask(self.abort, err)
# (re)schedule it
self.ioTimeout.install_task(delay=delay)
|
def set_timeout(self, delay, err=TimeoutError)
|
Called to set a transaction timer.
| 6.483742 | 6.346248 | 1.021665 |
if _debug: IOChainMixIn._debug("chain_callback %r", iocb)
# if we're not chained, there's no notification to do
if not self.ioChain:
return
# refer to the chained iocb
iocb = self.ioChain
try:
if _debug: IOChainMixIn._debug(" - decoding")
# let the derived class transform the data
self.decode()
if _debug: IOChainMixIn._debug(" - decode complete")
except:
# extract the error and abort
err = sys.exc_info()[1]
if _debug: IOChainMixIn._exception(" - decoding exception: %r", err)
iocb.ioState = ABORTED
iocb.ioError = err
# break the references
self.ioChain = None
iocb.ioController = None
# notify the client
iocb.trigger()
|
def chain_callback(self, iocb)
|
Callback when this iocb completes.
| 4.356617 | 4.170427 | 1.044645 |
if _debug: IOChainMixIn._debug("abort_io %r %r", iocb, err)
# make sure we're being notified of an abort request from
# the iocb we are chained from
if iocb is not self.ioChain:
raise RuntimeError("broken chain")
# call my own Abort(), which may forward it to a controller or
# be overridden by IOGroup
self.abort(err)
|
def abort_io(self, iocb, err)
|
Forward the abort downstream.
| 9.498775 | 8.956254 | 1.060574 |
if _debug: IOChainMixIn._debug("decode")
# refer to the chained iocb
iocb = self.ioChain
# if this has completed successfully, pass it up
if self.ioState == COMPLETED:
if _debug: IOChainMixIn._debug(" - completed: %r", self.ioResponse)
# change the state and transform the content
iocb.ioState = COMPLETED
iocb.ioResponse = self.ioResponse
# if this aborted, pass that up too
elif self.ioState == ABORTED:
if _debug: IOChainMixIn._debug(" - aborted: %r", self.ioError)
# change the state
iocb.ioState = ABORTED
iocb.ioError = self.ioError
else:
raise RuntimeError("invalid state: %d" % (self.ioState,))
|
def decode(self)
|
Hook to transform the response, called when this IOCB is
completed.
| 3.651417 | 3.277458 | 1.1141 |
if _debug: IOGroup._debug("add %r", iocb)
# add this to our members
self.ioMembers.append(iocb)
# assume all of our members have not completed yet
self.ioState = PENDING
self.ioComplete.clear()
# when this completes, call back to the group. If this
# has already completed, it will trigger
iocb.add_callback(self.group_callback)
|
def add(self, iocb)
|
Add an IOCB to the group, you can also add other groups.
| 7.591408 | 6.809819 | 1.114774 |
if _debug: IOGroup._debug("group_callback %r", iocb)
# check all the members
for iocb in self.ioMembers:
if not iocb.ioComplete.isSet():
if _debug: IOGroup._debug(" - waiting for child: %r", iocb)
break
else:
if _debug: IOGroup._debug(" - all children complete")
# everything complete
self.ioState = COMPLETED
self.trigger()
|
def group_callback(self, iocb)
|
Callback when a child iocb completes.
| 4.255557 | 3.811834 | 1.116407 |
if _debug: IOGroup._debug("abort %r", err)
# change the state to reflect that it was killed
self.ioState = ABORTED
self.ioError = err
# abort all the members
for iocb in self.ioMembers:
iocb.abort(err)
# notify the client
self.trigger()
|
def abort(self, err)
|
Called by a client to abort all of the member transactions.
When the last pending member is aborted the group callback
function will be called.
| 6.999706 | 7.251594 | 0.965264 |
if _debug: IOQueue._debug("put %r", iocb)
# requests should be pending before being queued
if iocb.ioState != PENDING:
raise RuntimeError("invalid state transition")
# save that it might have been empty
wasempty = not self.notempty.isSet()
# add the request to the end of the list of iocb's at same priority
priority = iocb.ioPriority
item = (priority, iocb)
self.queue.insert(bisect_left(self.queue, (priority+1,)), item)
# point the iocb back to this queue
iocb.ioQueue = self
# set the event, queue is no longer empty
self.notempty.set()
return wasempty
|
def put(self, iocb)
|
Add an IOCB to a queue. This is usually called by the function
that filters requests and passes them out to the correct processing
thread.
| 6.216546 | 5.931322 | 1.048088 |
if _debug: IOQueue._debug("get block=%r delay=%r", block, delay)
# if the queue is empty and we do not block return None
if not block and not self.notempty.isSet():
if _debug: IOQueue._debug(" - not blocking and empty")
return None
# wait for something to be in the queue
if delay:
self.notempty.wait(delay)
if not self.notempty.isSet():
return None
else:
self.notempty.wait()
# extract the first element
priority, iocb = self.queue[0]
del self.queue[0]
iocb.ioQueue = None
# if the queue is empty, clear the event
qlen = len(self.queue)
if not qlen:
self.notempty.clear()
# return the request
return iocb
|
def get(self, block=1, delay=None)
|
Get a request from a queue, optionally block until a request
is available.
| 3.36449 | 3.199707 | 1.051499 |
if _debug: IOQueue._debug("remove %r", iocb)
# remove the request from the queue
for i, item in enumerate(self.queue):
if iocb is item[1]:
if _debug: IOQueue._debug(" - found at %d", i)
del self.queue[i]
# if the queue is empty, clear the event
qlen = len(self.queue)
if not qlen:
self.notempty.clear()
# record the new length
# self.queuesize.Record( qlen, _time() )
break
else:
if _debug: IOQueue._debug(" - not found")
|
def remove(self, iocb)
|
Remove a control block from the queue, called if the request
is canceled/aborted.
| 3.531399 | 3.436404 | 1.027644 |
if _debug: IOQueue._debug("abort %r", err)
# send aborts to all of the members
try:
for iocb in self.queue:
iocb.ioQueue = None
iocb.abort(err)
# flush the queue
self.queue = []
# the queue is now empty, clear the event
self.notempty.clear()
except ValueError:
pass
|
def abort(self, err)
|
Abort all of the control blocks in the queue.
| 5.729544 | 5.147729 | 1.113023 |
if _debug: IOController._debug("request_io %r", iocb)
# check that the parameter is an IOCB
if not isinstance(iocb, IOCB):
raise TypeError("IOCB expected")
# bind the iocb to this controller
iocb.ioController = self
try:
# hopefully there won't be an error
err = None
# change the state
iocb.ioState = PENDING
# let derived class figure out how to process this
self.process_io(iocb)
except:
# extract the error
err = sys.exc_info()[1]
# if there was an error, abort the request
if err:
self.abort_io(iocb, err)
|
def request_io(self, iocb)
|
Called by a client to start processing a request.
| 3.814138 | 3.840822 | 0.993053 |
if _debug: IOController._debug("active_io %r", iocb)
# requests should be idle or pending before coming active
if (iocb.ioState != IDLE) and (iocb.ioState != PENDING):
raise RuntimeError("invalid state transition (currently %d)" % (iocb.ioState,))
# change the state
iocb.ioState = ACTIVE
|
def active_io(self, iocb)
|
Called by a handler to notify the controller that a request is
being processed.
| 5.254677 | 5.101017 | 1.030123 |
if _debug: IOController._debug("complete_io %r %r", iocb, msg)
# if it completed, leave it alone
if iocb.ioState == COMPLETED:
pass
# if it already aborted, leave it alone
elif iocb.ioState == ABORTED:
pass
else:
# change the state
iocb.ioState = COMPLETED
iocb.ioResponse = msg
# notify the client
iocb.trigger()
|
def complete_io(self, iocb, msg)
|
Called by a handler to return data to the client.
| 3.366897 | 3.431339 | 0.98122 |
if _debug: IOController._debug("abort_io %r %r", iocb, err)
# if it completed, leave it alone
if iocb.ioState == COMPLETED:
pass
# if it already aborted, leave it alone
elif iocb.ioState == ABORTED:
pass
else:
# change the state
iocb.ioState = ABORTED
iocb.ioError = err
# notify the client
iocb.trigger()
|
def abort_io(self, iocb, err)
|
Called by a handler or a client to abort a transaction.
| 3.036853 | 2.985604 | 1.017165 |
if _debug: IOQController._debug("abort %r", err)
if (self.state == CTRL_IDLE):
if _debug: IOQController._debug(" - idle")
return
while True:
iocb = self.ioQueue.get(block=0)
if not iocb:
break
if _debug: IOQController._debug(" - iocb: %r", iocb)
# change the state
iocb.ioState = ABORTED
iocb.ioError = err
# notify the client
iocb.trigger()
if (self.state != CTRL_IDLE):
if _debug: IOQController._debug(" - busy after aborts")
|
def abort(self, err)
|
Abort all pending requests.
| 3.512784 | 3.477415 | 1.010171 |
if _debug: IOQController._debug("request_io %r", iocb)
# bind the iocb to this controller
iocb.ioController = self
# if we're busy, queue it
if (self.state != CTRL_IDLE):
if _debug: IOQController._debug(" - busy, request queued, active_iocb: %r", self.active_iocb)
iocb.ioState = PENDING
self.ioQueue.put(iocb)
return
try:
# hopefully there won't be an error
err = None
# let derived class figure out how to process this
self.process_io(iocb)
except:
# extract the error
err = sys.exc_info()[1]
if _debug: IOQController._debug(" - process_io() exception: %r", err)
# if there was an error, abort the request
if err:
if _debug: IOQController._debug(" - aborting")
self.abort_io(iocb, err)
|
def request_io(self, iocb)
|
Called by a client to start processing a request.
| 3.574353 | 3.571377 | 1.000833 |
if _debug: IOQController._debug("active_io %r", iocb)
# base class work first, setting iocb state and timer data
IOController.active_io(self, iocb)
# change our state
self.state = CTRL_ACTIVE
_statelog.debug("%s %s %s" % (_strftime(), self.name, "active"))
# keep track of the iocb
self.active_iocb = iocb
|
def active_io(self, iocb)
|
Called by a handler to notify the controller that a request is
being processed.
| 6.816389 | 7.117367 | 0.957712 |
if _debug: IOQController._debug("complete_io %r %r", iocb, msg)
# check to see if it is completing the active one
if iocb is not self.active_iocb:
raise RuntimeError("not the current iocb")
# normal completion
IOController.complete_io(self, iocb, msg)
# no longer an active iocb
self.active_iocb = None
# check to see if we should wait a bit
if self.wait_time:
# change our state
self.state = CTRL_WAITING
_statelog.debug("%s %s %s" % (_strftime(), self.name, "waiting"))
# schedule a call in the future
task = FunctionTask(IOQController._wait_trigger, self)
task.install_task(delta=self.wait_time)
else:
# change our state
self.state = CTRL_IDLE
_statelog.debug("%s %s %s" % (_strftime(), self.name, "idle"))
# look for more to do
deferred(IOQController._trigger, self)
|
def complete_io(self, iocb, msg)
|
Called by a handler to return data to the client.
| 4.11878 | 4.181983 | 0.984887 |
if _debug: IOQController._debug("abort_io %r %r", iocb, err)
# normal abort
IOController.abort_io(self, iocb, err)
# check to see if it is completing the active one
if iocb is not self.active_iocb:
if _debug: IOQController._debug(" - not current iocb")
return
# no longer an active iocb
self.active_iocb = None
# change our state
self.state = CTRL_IDLE
_statelog.debug("%s %s %s" % (_strftime(), self.name, "idle"))
# look for more to do
deferred(IOQController._trigger, self)
|
def abort_io(self, iocb, err)
|
Called by a handler or a client to abort a transaction.
| 4.93282 | 5.034335 | 0.979836 |
if _debug: IOQController._debug("_trigger")
# if we are busy, do nothing
if self.state != CTRL_IDLE:
if _debug: IOQController._debug(" - not idle")
return
# if there is nothing to do, return
if not self.ioQueue.queue:
if _debug: IOQController._debug(" - empty queue")
return
# get the next iocb
iocb = self.ioQueue.get()
try:
# hopefully there won't be an error
err = None
# let derived class figure out how to process this
self.process_io(iocb)
except:
# extract the error
err = sys.exc_info()[1]
# if there was an error, abort the request
if err:
self.abort_io(iocb, err)
# if we're idle, call again
if self.state == CTRL_IDLE:
deferred(IOQController._trigger, self)
|
def _trigger(self)
|
Called to launch the next request in the queue.
| 3.879428 | 3.738599 | 1.037669 |
if _debug: IOQController._debug("_wait_trigger")
# make sure we are waiting
if (self.state != CTRL_WAITING):
raise RuntimeError("not waiting")
# change our state
self.state = CTRL_IDLE
_statelog.debug("%s %s %s" % (_strftime(), self.name, "idle"))
# look for more to do
IOQController._trigger(self)
|
def _wait_trigger(self)
|
Called to launch the next request in the queue.
| 7.165403 | 6.781047 | 1.056681 |
if _debug: DeviceToDeviceServerService._debug("process_npdu %r", npdu)
# broadcast messages go to peers
if npdu.pduDestination.addrType == Address.localBroadcastAddr:
destList = self.connections.keys()
else:
if npdu.pduDestination not in self.connections:
if _debug: DeviceToDeviceServerService._debug(" - not a connected client")
return
destList = [npdu.pduDestination]
if _debug: DeviceToDeviceServerService._debug(" - destList: %r", destList)
for dest in destList:
# make device-to-device APDU
xpdu = DeviceToDeviceAPDU(npdu)
xpdu.pduDestination = dest
# send it down to the multiplexer
self.service_request(xpdu)
|
def process_npdu(self, npdu)
|
encode NPDUs from the service access point and send them downstream.
| 3.203841 | 3.078776 | 1.040622 |
if _debug: DeviceToDeviceClientService._debug("process_npdu %r", npdu)
# broadcast messages go to everyone
if npdu.pduDestination.addrType == Address.localBroadcastAddr:
destList = self.connections.keys()
else:
conn = self.connections.get(npdu.pduDestination, None)
if not conn:
if _debug: DeviceToDeviceClientService._debug(" - not a connected client")
# start a connection attempt
conn = self.connect(npdu.pduDestination)
if not conn.connected:
# keep a reference to this npdu to send after the ack comes back
conn.pendingNPDU.append(npdu)
return
destList = [npdu.pduDestination]
if _debug: DeviceToDeviceClientService._debug(" - destList: %r", destList)
for dest in destList:
# make device-to-device APDU
xpdu = DeviceToDeviceAPDU(npdu)
xpdu.pduDestination = dest
# send it down to the multiplexer
self.service_request(xpdu)
|
def process_npdu(self, npdu)
|
encode NPDUs from the service access point and send them downstream.
| 3.563863 | 3.443845 | 1.03485 |
if _debug: DeviceToDeviceClientService._debug("connect %r", addr)
# make a connection
conn = ConnectionState(addr)
self.multiplexer.connections[addr] = conn
# associate with this service, but it is not connected until the ack comes back
conn.service = self
# keep a list of pending NPDU objects until the ack comes back
conn.pendingNPDU = []
# build a service request
request = ServiceRequest(DEVICE_TO_DEVICE_SERVICE_ID)
request.pduDestination = addr
# send it
self.service_request(request)
# return the connection object
return conn
|
def connect(self, addr)
|
Initiate a connection request to the device.
| 5.611013 | 5.458119 | 1.028012 |
if _debug: RouterToRouterService._debug("process_npdu %r", npdu)
# encode the npdu as if it was about to be delivered to the network
pdu = PDU()
npdu.encode(pdu)
if _debug: RouterToRouterService._debug(" - pdu: %r", pdu)
# broadcast messages go to everyone
if pdu.pduDestination.addrType == Address.localBroadcastAddr:
destList = self.connections.keys()
else:
conn = self.connections.get(pdu.pduDestination, None)
if not conn:
if _debug: RouterToRouterService._debug(" - not a connected client")
# start a connection attempt
conn = self.connect(pdu.pduDestination)
if not conn.connected:
# keep a reference to this pdu to send after the ack comes back
conn.pendingNPDU.append(pdu)
return
destList = [pdu.pduDestination]
if _debug: RouterToRouterService._debug(" - destList: %r", destList)
for dest in destList:
# make a router-to-router NPDU
xpdu = RouterToRouterNPDU(pdu)
xpdu.pduDestination = dest
# send it to the multiplexer
self.service_request(xpdu)
|
def process_npdu(self, npdu)
|
encode NPDUs from the service access point and send them downstream.
| 3.281201 | 3.219163 | 1.019271 |
if _debug: RouterToRouterService._debug("connect %r", addr)
# make a connection
conn = ConnectionState(addr)
self.multiplexer.connections[addr] = conn
# associate with this service, but it is not connected until the ack comes back
conn.service = self
# keep a list of pending NPDU objects until the ack comes back
conn.pendingNPDU = []
# build a service request
request = ServiceRequest(ROUTER_TO_ROUTER_SERVICE_ID)
request.pduDestination = addr
# send it
self.service_request(request)
# return the connection object
return conn
|
def connect(self, addr)
|
Initiate a connection request to the peer router.
| 5.41112 | 5.241286 | 1.032403 |
if _debug: ProxyServiceNetworkAdapter._debug("process_npdu %r", npdu)
# encode the npdu as if it was about to be delivered to the network
pdu = PDU()
npdu.encode(pdu)
if _debug: ProxyServiceNetworkAdapter._debug(" - pdu: %r", pdu)
# broadcast messages go to peers
if pdu.pduDestination.addrType == Address.localBroadcastAddr:
xpdu = ServerToProxyBroadcastNPDU(pdu)
else:
xpdu = ServerToProxyUnicastNPDU(pdu.pduDestination, pdu)
# the connection has the correct address
xpdu.pduDestination = self.conn.address
# send it down to the multiplexer
self.conn.service.service_request(xpdu)
|
def process_npdu(self, npdu)
|
encode NPDUs from the network service access point and send them to the proxy.
| 4.231828 | 4.052933 | 1.04414 |
if _debug: ProxyServiceNetworkAdapter._debug("service_confirmation %r", bslpdu)
# build a PDU
pdu = NPDU(bslpdu.pduData)
# the source is from the original source, not the proxy itself
pdu.pduSource = bslpdu.bslciAddress
# if the proxy received a broadcast, send it upstream as a broadcast
if isinstance(bslpdu, ProxyToServerBroadcastNPDU):
pdu.pduDestination = LocalBroadcast()
if _debug: ProxyServiceNetworkAdapter._debug(" - pdu: %r", pdu)
# decode it, the nework layer needs NPDUs
npdu = NPDU()
npdu.decode(pdu)
if _debug: ProxyServiceNetworkAdapter._debug(" - npdu: %r", npdu)
# send it to the service access point for processing
self.adapterSAP.process_npdu(self, npdu)
|
def service_confirmation(self, bslpdu)
|
Receive packets forwarded by the proxy and send them upstream to the network service access point.
| 4.807927 | 4.364803 | 1.101522 |
if _debug: ProxyServerService._debug("service_confirmation %r %r", conn, bslpdu)
# make sure there is an adapter for it - or something went wrong
if not getattr(conn, 'proxyAdapter', None):
raise RuntimeError("service confirmation received but no adapter for it")
# forward along
conn.proxyAdapter.service_confirmation(bslpdu)
|
def service_confirmation(self, conn, bslpdu)
|
Receive packets forwarded by the proxy and redirect them to the proxy network adapter.
| 5.429121 | 4.931058 | 1.101005 |
if _debug: ProxyClientService._debug("connect addr=%r", addr)
# if the address was provided, use it
if addr:
self.address = addr
else:
addr = self.address
# if the user was provided, save it
if userinfo:
self.userinfo = userinfo
# make a connection
conn = ConnectionState(addr)
self.multiplexer.connections[addr] = conn
if _debug: ProxyClientService._debug(" - conn: %r", conn)
# associate with this service, but it is not connected until the ack comes back
conn.service = self
# keep a list of pending BSLPDU objects until the ack comes back
conn.pendingBSLPDU = []
# build a service request
request = ServiceRequest(PROXY_SERVICE_ID)
request.pduDestination = addr
# send it
self.service_request(request)
# return the connection object
return conn
|
def connect(self, addr=None, userinfo=None)
|
Initiate a connection request to the device.
| 4.567074 | 4.431694 | 1.030548 |
amount += self.spellpower
amount <<= self.controller.spellpower_double
return amount
|
def get_spell_damage(self, amount: int) -> int
|
Returns the amount of damage \a amount will do, taking
SPELLPOWER and SPELLPOWER_DOUBLE into account.
| 31.815878 | 10.478359 | 3.036342 |
if self.spells_cost_health and card.type == CardType.SPELL:
return self.hero.health > card.cost
return self.mana >= card.cost
|
def can_pay_cost(self, card)
|
Returns whether the player can pay the resource cost of a card.
| 7.193671 | 6.399209 | 1.12415 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.