code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
broadcast_distribution_table = []
for bdte in self.bvlciBDT:
broadcast_distribution_table.append(str(bdte))
return key_value_contents(use_dict=use_dict, as_class=as_class,
key_values=(
('function', 'ReadBroadcastDistributionTableAck'),
('bdt', broadcast_distribution_table),
))
|
def bvlpdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 7.75111 | 7.244743 | 1.069894 |
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# save the content
use_dict.__setitem__('address', str(self.fdAddress))
use_dict.__setitem__('ttl', self.fdTTL)
use_dict.__setitem__('remaining', self.fdRemain)
# return what we built/updated
return use_dict
|
def bvlpdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 5.012882 | 5.058381 | 0.991005 |
return key_value_contents(use_dict=use_dict, as_class=as_class,
key_values=(
('function', 'RegisterForeignDevice'),
('ttl', self.bvlciTimeToLive),
))
|
def bvlpdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 10.978035 | 11.730503 | 0.935854 |
foreign_device_table = []
for fdte in self.bvlciFDT:
foreign_device_table.append(fdte.dict_contents(as_class=as_class))
return key_value_contents(use_dict=use_dict, as_class=as_class,
key_values=(
('function', 'ReadForeignDeviceTableAck'),
('foreign_device_table', foreign_device_table),
))
|
def bvlpdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 6.446597 | 6.287728 | 1.025267 |
return key_value_contents(use_dict=use_dict, as_class=as_class,
key_values=(
('function', 'DeleteForeignDeviceTableEntry'),
('address', str(self.bvlciAddress)),
))
|
def bvlpdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 11.040832 | 11.997783 | 0.920239 |
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# call the normal procedure
key_value_contents(use_dict=use_dict, as_class=as_class,
key_values=(
('function', 'DistributeBroadcastToNetwork'),
))
# this message has data
PDUData.dict_contents(self, use_dict=use_dict, as_class=as_class)
# return what we built/updated
return use_dict
|
def bvlpdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 5.856159 | 5.909836 | 0.990917 |
global server_address
# check the version
if (sys.version_info[:2] != (2, 5)):
sys.stderr.write("Python 2.5 only\n")
sys.exit(1)
# parse the command line arguments
parser = ArgumentParser(description=__doc__)
parser.add_argument(
"host", nargs='?',
help="address of host (default %r)" % (SERVER_HOST,),
default=SERVER_HOST,
)
parser.add_argument(
"port", nargs='?', type=int,
help="server port (default %r)" % (SERVER_PORT,),
default=SERVER_PORT,
)
args = parser.parse_args()
if _debug: _log.debug("initialization")
if _debug: _log.debug(" - args: %r", args)
# extract the server address and port
host = args.host
port = args.port
server_address = (host, port)
if _debug: _log.debug(" - server_address: %r", server_address)
# build the stack
this_console = ConsoleClient()
if _debug: _log.debug(" - this_console: %r", this_console)
this_middle_man = MiddleMan()
if _debug: _log.debug(" - this_middle_man: %r", this_middle_man)
this_director = TCPClientDirector()
if _debug: _log.debug(" - this_director: %r", this_director)
bind(this_console, this_middle_man, this_director)
bind(MiddleManASE(), this_director)
# create a task manager for scheduled functions
task_manager = TaskManager()
if _debug: _log.debug(" - task_manager: %r", task_manager)
# don't wait to connect
this_director.connect(server_address)
if _debug: _log.debug("running")
run()
|
def main()
|
Main function, called when run as an application.
| 2.415922 | 2.402681 | 1.005511 |
if _debug: TaskManager._debug("get_next_task")
# get the time
now = _time()
task = None
delta = None
if self.tasks:
# look at the first task
when, n, nxttask = self.tasks[0]
if when <= now:
# pull it off the list and mark that it's no longer scheduled
heappop(self.tasks)
task = nxttask
task.isScheduled = False
if self.tasks:
when, n, nxttask = self.tasks[0]
# peek at the next task, return how long to wait
delta = max(when - now, 0.0)
else:
delta = when - now
# return the task to run and how long to wait for the next one
return (task, delta)
|
def get_next_task(self)
|
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.
| 4.813307 | 4.634484 | 1.038585 |
global args, server_address
# parse the command line arguments
parser = ArgumentParser(description=__doc__)
parser.add_argument(
"host", nargs='?',
help="address of host (default %r)" % (SERVER_HOST,),
default=SERVER_HOST,
)
parser.add_argument(
"port", nargs='?', type=int,
help="server port (default %r)" % (SERVER_PORT,),
default=SERVER_PORT,
)
parser.add_argument(
"--hello", action="store_true",
default=False,
help="send a hello message",
)
parser.add_argument(
"--connect-timeout", nargs='?', type=int,
help="idle connection timeout",
default=CONNECT_TIMEOUT,
)
parser.add_argument(
"--idle-timeout", nargs='?', type=int,
help="idle connection timeout",
default=IDLE_TIMEOUT,
)
args = parser.parse_args()
if _debug: _log.debug("initialization")
if _debug: _log.debug(" - args: %r", args)
# extract the server address and port
host = args.host
port = args.port
server_address = (host, port)
if _debug: _log.debug(" - server_address: %r", server_address)
# build the stack
this_console = ConsoleClient()
if _debug: _log.debug(" - this_console: %r", this_console)
this_middle_man = MiddleMan()
if _debug: _log.debug(" - this_middle_man: %r", this_middle_man)
this_director = TCPClientDirector(
connect_timeout=args.connect_timeout,
idle_timeout=args.idle_timeout,
)
if _debug: _log.debug(" - this_director: %r", this_director)
bind(this_console, this_middle_man, this_director)
bind(MiddleManASE(), this_director)
# create a task manager for scheduled functions
task_manager = TaskManager()
if _debug: _log.debug(" - task_manager: %r", task_manager)
# don't wait to connect
deferred(this_director.connect, server_address)
# send hello maybe
if args.hello:
deferred(this_middle_man.indication, PDU(b'Hello, world!\n'))
if _debug: _log.debug("running")
run()
if _debug: _log.debug("fini")
|
def main()
|
Main function, called when run as an application.
| 2.350102 | 2.32704 | 1.00991 |
# unpack the date and pattern
year, month, day, day_of_week = date
year_p, month_p, day_p, day_of_week_p = date_pattern
# check the year
if year_p == 255:
# any year
pass
elif year != year_p:
# specific year
return False
# 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 day
if day_p == 255:
# any day
pass
elif day_p == 32:
# last day of the month
last_day = calendar.monthrange(year + 1900, month)[1]
if day != last_day:
return False
elif day_p == 33:
# odd days of the month
if (day % 2) == 0:
return False
elif day_p == 34:
# even days of the month
if (day % 2) == 1:
return False
elif day != day_p:
# specific day
return False
# check the day of week
if day_of_week_p == 255:
# any day of the week
pass
elif day_of_week != day_of_week_p:
# specific day of the week
return False
# all tests pass
return True
|
def match_date(date, date_pattern)
|
Match a specific date, a four-tuple with no special values, with a date
pattern, four-tuple possibly having special values.
| 1.622877 | 1.609134 | 1.008541 |
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)
|
def datetime_to_time(date, time)
|
Take the date and time 4-tuples and return the time in seconds since
the epoch as a floating point number.
| 3.926679 | 3.857166 | 1.018022 |
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")
# check the weekly schedule values
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")
# check the exception schedule values
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")
# check list of object property references
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")
# get the datatype of the property to be written
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")
# all good
self.reliability = 'noFaultDetected'
if _debug: LocalScheduleObject._debug(" - no fault detected")
except Exception as err:
if _debug: LocalScheduleObject._debug(" - exception: %r", err)
self.reliability = 'configurationError'
|
def _check_reliability(self, old_value=None, new_value=None)
|
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.
| 2.50637 | 2.515837 | 0.996237 |
if _debug: LocalScheduleInterpreter._debug("present_value_changed %s %s", old_value, new_value)
# if this hasn't been added to an application, there's nothing to do
if not self.sched_obj._app:
if _debug: LocalScheduleInterpreter._debug(" - no application")
return
# process the list of [device] object property [array index] references
obj_prop_refs = self.sched_obj.listOfObjectPropertyReferences
if not obj_prop_refs:
if _debug: LocalScheduleInterpreter._debug(" - no writes defined")
return
# primitive values just set the value part
new_value = new_value.value
# loop through the writes
for obj_prop_ref in obj_prop_refs:
if obj_prop_ref.deviceIdentifier:
if _debug: LocalScheduleInterpreter._debug(" - no externals")
continue
# get the object from the application
obj = self.sched_obj._app.get_object_id(obj_prop_ref.objectIdentifier)
if not obj:
if _debug: LocalScheduleInterpreter._debug(" - no object")
continue
# try to change the value
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)
|
def present_value_changed(self, old_value, new_value)
|
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.
| 3.464628 | 3.191019 | 1.085743 |
### humm...
instance_type = getattr(types, 'InstanceType', object)
# snapshot of counts
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)
# count the things that have changed
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()
]
# ready for the next time
self.type2count = type2count
self.type2all = type2all
fmt = "%-30s %-30s %6s %6s %6s\n"
self.stdout.write(fmt % ("Module", "Type", "Count", "dCount", "dRef"))
# sorted by count
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"))
# sorted by module and class
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")
|
def do_gc(self, args)
|
gc - print out garbage collection information
| 2.529018 | 2.443018 | 1.035202 |
args = args.split()
if _debug: ConsoleCmd._debug("do_bugin %r", args)
# get the logger name and logger
if args:
loggerName = args[0]
if loggerName in logging.Logger.manager.loggerDict:
logger = logging.getLogger(loggerName)
else:
logger = None
else:
loggerName = '__root__'
logger = logging.getLogger()
# add a logging handler
if not logger:
self.stdout.write("not a valid logger name\n")
elif loggerName in self.handlers:
self.stdout.write("%s already has a handler\n" % loggerName)
else:
handler = ConsoleLogHandler(logger)
self.handlers[loggerName] = handler
self.stdout.write("handler to %s added\n" % loggerName)
self.stdout.write("\n")
|
def do_bugin(self, args)
|
bugin [ <logger> ] - add a console logging handler to a logger
| 2.730195 | 2.471069 | 1.104864 |
args = args.split()
if _debug: ConsoleCmd._debug("do_bugout %r", args)
# get the logger name and logger
if args:
loggerName = args[0]
if loggerName in logging.Logger.manager.loggerDict:
logger = logging.getLogger(loggerName)
else:
logger = None
else:
loggerName = '__root__'
logger = logging.getLogger()
# remove the logging handler
if not logger:
self.stdout.write("not a valid logger name\n")
elif not loggerName in self.handlers:
self.stdout.write("no handler for %s\n" % loggerName)
else:
handler = self.handlers[loggerName]
del self.handlers[loggerName]
# see if this (or its parent) is a module level logger
if hasattr(logger, 'globs'):
logger.globs['_debug'] -= 1
elif hasattr(logger.parent, 'globs'):
logger.parent.globs['_debug'] -= 1
# remove it from the logger
logger.removeHandler(handler)
self.stdout.write("handler to %s removed\n" % loggerName)
self.stdout.write("\n")
|
def do_bugout(self, args)
|
bugout [ <logger> ] - remove a console logging handler from a logger
| 2.950707 | 2.686383 | 1.098394 |
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")
|
def do_buggers(self, args)
|
buggers - list the console logging handlers
| 2.777084 | 2.599287 | 1.068402 |
if _debug: ConsoleCmd._debug("do_EOF %r", args)
return self.do_exit(args)
|
def do_EOF(self, args)
|
Exit on system end of file character
| 4.15085 | 4.148689 | 1.000521 |
if _debug: ConsoleCmd._debug("do_shell %r", args)
os.system(args)
|
def do_shell(self, args)
|
Pass command to a system shell when line begins with '!
| 5.465648 | 6.480479 | 0.843402 |
if _debug: ConsoleCmd._debug("do_help %r", args)
# the only reason to define this method is for the help text in the doc string
cmd.Cmd.do_help(self, args)
|
def do_help(self, args)
|
Get help on commands
'help' or '?' with no arguments prints a list of commands for which help is available
'help <command>' or '? <command>' gives help on <command>
| 6.677097 | 8.126911 | 0.821603 |
cmd.Cmd.preloop(self) ## sets up command completion
try:
if readline:
readline.read_history_file(sys.argv[0] + ".history")
except Exception, err:
if not isinstance(err, IOError):
self.stdout.write("history error: %s\n" % err)
|
def preloop(self)
|
Initialization before prompting user for commands.
Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
| 4.816334 | 3.650217 | 1.319465 |
try:
if readline:
readline.write_history_file(sys.argv[0] + ".history")
except Exception, err:
if not isinstance(err, IOError):
self.stdout.write("history error: %s\n" % err)
# clean up command completion
cmd.Cmd.postloop(self)
if self.interactive:
self.stdout.write("Exiting...\n")
# tell the core we have stopped
core.deferred(core.stop)
|
def postloop(self)
|
Take care of any unfinished business.
Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
| 5.205504 | 4.928957 | 1.056107 |
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)
|
def confirmation(self, pdu)
|
Decode upstream PDUs and pass them up to the service access point.
| 6.962814 | 6.402108 | 1.087581 |
if _debug: NetworkAdapter._debug("process_npdu %r (net=%r)", npdu, self.adapterNet)
pdu = PDU(user_data=npdu.pduUserData)
npdu.encode(pdu)
self.request(pdu)
|
def process_npdu(self, npdu)
|
Encode NPDUs from the service access point and send them downstream.
| 6.749459 | 6.255702 | 1.078929 |
if _debug: NetworkServiceAccessPoint._debug("bind %r net=%r address=%r", server, net, address)
# make sure this hasn't already been called with this network
if net in self.adapters:
raise RuntimeError("already bound")
# create an adapter object, add it to our map
adapter = NetworkAdapter(self, net)
self.adapters[net] = adapter
if _debug: NetworkServiceAccessPoint._debug(" - adapters[%r]: %r", net, adapter)
# if the address was given, make it the "local" one
if address and not self.local_address:
self.local_adapter = adapter
self.local_address = address
# bind to the server
bind(adapter, server)
|
def bind(self, server, net=None, address=None)
|
Create a network adapter object and bind.
| 3.490864 | 3.41455 | 1.02235 |
if _debug: NetworkServiceAccessPoint._debug("add_router_references %r %r %r", snet, address, dnets)
# see if we have an adapter for the snet
if snet not in self.adapters:
raise RuntimeError("no adapter for network: %d" % (snet,))
# pass this along to the cache
self.router_info_cache.update_router_info(snet, address, dnets)
|
def add_router_references(self, snet, address, dnets)
|
Add/update references to routers.
| 4.000008 | 3.994411 | 1.001401 |
if _debug: NetworkServiceAccessPoint._debug("delete_router_references %r %r %r", snet, address, dnets)
# see if we have an adapter for the snet
if snet not in self.adapters:
raise RuntimeError("no adapter for network: %d" % (snet,))
# pass this along to the cache
self.router_info_cache.delete_router_info(snet, address, dnets)
|
def delete_router_references(self, snet, address=None, dnets=None)
|
Delete references to routers/networks.
| 3.918338 | 4.013268 | 0.976346 |
if _debug: abort._debug("abort %r", err)
# start with the server
if IOServer._highlander:
IOServer._highlander.abort(err)
# now do everything local
for controller in _local_controllers.values():
controller.abort(err)
|
def abort(err)
|
Abort everything, everywhere.
| 7.846667 | 6.715163 | 1.1685 |
addr, port = addr
return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask)
|
def pack_ip_addr(addr)
|
Given an IP address tuple like ('1.2.3.4', 47808) return the six-octet string
useful for a BACnet address.
| 5.834328 | 5.039857 | 1.157638 |
if isinstance(addr, bytearray):
addr = bytes(addr)
return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0])
|
def unpack_ip_addr(addr)
|
Given a six-octet BACnet address, return an IP address tuple.
| 2.64541 | 2.398845 | 1.102785 |
# translate the blob into hex
hex_str = binascii.hexlify(data)
# inject the separator if it was given
if sep:
hex_str = sep.join(hex_str[i:i+2] for i in range(0, len(hex_str), 2))
# return the result
return hex_str
|
def btox(data, sep='')
|
Return the hex encoding of a blob (string).
| 3.231711 | 2.808206 | 1.15081 |
# remove the non-hex characters
data = re.sub("[^0-9a-fA-F]", '', data)
# interpret the hex
return binascii.unhexlify(data)
|
def xtob(data, sep='')
|
Interpret the hex encoding of a blob (string).
| 4.678495 | 4.050767 | 1.154965 |
# make sure that _debug is defined
if not globs.has_key('_debug'):
raise RuntimeError("define _debug before creating a module logger")
# logger name is the module name
logger_name = globs['__name__']
# create a logger to be assigned to _log
logger = logging.getLogger(logger_name)
# put in a reference to the module globals
logger.globs = globs
# if this is a "root" logger add a default handler for warnings and up
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
|
def ModuleLogger(globs)
|
Create a module level logger.
To debug a module, create a _debug variable in the module, then use the
ModuleLogger function to create a "module level" logger. When a handler
is added to this logger or a child of this logger, the _debug variable will
be incremented.
All of the calls within functions or class methods within the module should
first check to see if _debug is set to prevent calls to formatter objects
that aren't necessary.
| 3.70875 | 3.603118 | 1.029317 |
# create a logger for this object
logger = logging.getLogger(obj.__module__ + '.' + obj.__name__)
# make it available to instances
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
|
def bacpypes_debugging(obj)
|
Function for attaching a debugging logger to a class or function.
| 3.900174 | 3.802228 | 1.02576 |
args = args.split()
if _debug: ReadPropertyConsoleCmd._debug("do_read %r", args)
try:
addr, obj_id, prop_id = args[:3]
obj_id = ObjectIdentifier(obj_id).value
datatype = get_datatype(obj_id[0], prop_id)
if not datatype:
raise ValueError("invalid property for object type")
# build a request
request = ReadPropertyRequest(
objectIdentifier=obj_id,
propertyIdentifier=prop_id,
)
request.pduDestination = Address(addr)
if len(args) == 4:
request.propertyArrayIndex = int(args[3])
if _debug: ReadPropertyConsoleCmd._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug: ReadPropertyConsoleCmd._debug(" - iocb: %r", iocb)
# give it to the application
deferred(this_application.request_io, iocb)
# wait for it to complete
iocb.wait()
# do something for success
if iocb.ioResponse:
apdu = iocb.ioResponse
# should be an ack
if not isinstance(apdu, ReadPropertyACK):
if _debug: ReadPropertyConsoleCmd._debug(" - not an ack")
return
# find the datatype
datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
if _debug: ReadPropertyConsoleCmd._debug(" - datatype: %r", datatype)
if not datatype:
raise TypeError("unknown 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: ReadPropertyConsoleCmd._debug(" - value: %r", value)
sys.stdout.write(str(value) + '\n')
if hasattr(value, 'debug_contents'):
value.debug_contents(file=sys.stdout)
sys.stdout.flush()
# do something for error/reject/abort
if iocb.ioError:
sys.stdout.write(str(iocb.ioError) + '\n')
except Exception, error:
ReadPropertyConsoleCmd._exception("exception: %r", error)
|
def do_read(self, args)
|
read <addr> <objid> <prop> [ <indx> ]
| 2.157121 | 2.104511 | 1.024999 |
args = args.split()
if _debug: ReadPropertyConsoleCmd._debug("do_rtn %r", args)
# provide the address and a list of network numbers
router_address = Address(args[0])
network_list = [int(arg) for arg in args[1:]]
# pass along to the service access point
this_application.nsap.add_router_references(None, router_address, network_list)
|
def do_rtn(self, args)
|
rtn <addr> <net> ...
| 7.278016 | 6.115298 | 1.190133 |
if _debug: Network._debug("add_node %r", node)
self.nodes.append(node)
node.lan = self
# update the node name
if not node.name:
node.name = '%s:%s' % (self.name, node.address)
|
def add_node(self, node)
|
Add a node to this network, let the node know which network it's on.
| 3.835943 | 3.390454 | 1.131395 |
if _debug: Network._debug("remove_node %r", node)
self.nodes.remove(node)
node.lan = None
|
def remove_node(self, node)
|
Remove a node from this network.
| 5.116685 | 4.268438 | 1.198725 |
if _debug: Network._debug("process_pdu(%s) %r", self.name, pdu)
# if there is a traffic log, call it with the network name and pdu
if self.traffic_log:
self.traffic_log(self.name, pdu)
# randomly drop a packet
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))
|
def process_pdu(self, pdu)
|
Process a PDU by sending a copy to each node as dictated by the
addressing and if a node is promiscuous.
| 2.590232 | 2.47271 | 1.047527 |
if _debug: Node._debug("bind %r", lan)
lan.add_node(self)
|
def bind(self, lan)
|
bind to a LAN.
| 6.719514 | 5.563639 | 1.207755 |
if _debug: Node._debug("indication(%s) %r", self.name, pdu)
# make sure we're connected
if not self.lan:
raise ConfigurationError("unbound node")
# if the pduSource is unset, fill in our address, otherwise
# leave it alone to allow for simulated spoofing
if pdu.pduSource is None:
pdu.pduSource = self.address
elif (not self.spoofing) and (pdu.pduSource != self.address):
raise RuntimeError("spoofing address conflict")
# actual network delivery is a zero-delay task
OneShotFunction(self.lan.process_pdu, pdu)
|
def indication(self, pdu)
|
Send a message.
| 7.698024 | 7.36905 | 1.044643 |
if _debug: Match._debug("Match %r %r", addr1, addr2)
if (addr2.addrType == Address.localBroadcastAddr):
# match any local station
return (addr1.addrType == Address.localStationAddr) or (addr1.addrType == Address.localBroadcastAddr)
elif (addr2.addrType == Address.localStationAddr):
# match a specific local station
return (addr1.addrType == Address.localStationAddr) and (addr1.addrAddr == addr2.addrAddr)
elif (addr2.addrType == Address.remoteBroadcastAddr):
# match any remote station or remote broadcast on a matching network
return ((addr1.addrType == Address.remoteStationAddr) or (addr1.addrType == Address.remoteBroadcastAddr)) \
and (addr1.addrNet == addr2.addrNet)
elif (addr2.addrType == Address.remoteStationAddr):
# match a specific remote station
return (addr1.addrType == Address.remoteStationAddr) and \
(addr1.addrNet == addr2.addrNet) and (addr1.addrAddr == addr2.addrAddr)
elif (addr2.addrType == Address.globalBroadcastAddr):
# match a global broadcast address
return (addr1.addrType == Address.globalBroadcastAddr)
else:
raise RuntimeError, "invalid match combination"
|
def Match(addr1, addr2)
|
Return true iff addr1 matches addr2.
| 1.842636 | 1.842261 | 1.000203 |
if _debug: Sequence._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
global _sequence_of_classes, _list_of_classes
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# loop through the elements
for element in self.sequenceElements:
value = getattr(self, element.name, None)
if value is None:
continue
if (element.klass in _sequence_of_classes) or (element.klass in _list_of_classes):
helper = element.klass(value)
mapped_value = helper.dict_contents(as_class=as_class)
elif issubclass(element.klass, Atomic):
mapped_value = value ### ambiguous
elif issubclass(element.klass, AnyAtomic):
mapped_value = value.value ### ambiguous
elif isinstance(value, element.klass):
mapped_value = value.dict_contents(as_class=as_class)
use_dict.__setitem__(element.name, mapped_value)
else:
continue
# update the dictionary being built
use_dict.__setitem__(element.name, mapped_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.
| 3.241054 | 3.197379 | 1.01366 |
if _debug: Choice._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()
# look for the chosen element
for element in self.choiceElements:
value = getattr(self, element.name, None)
if value is None:
continue
if issubclass(element.klass, Atomic):
mapped_value = value ### ambiguous
elif issubclass(element.klass, AnyAtomic):
mapped_value = value.value ### ambiguous
elif isinstance(value, element.klass):
mapped_value = value.dict_contents(as_class=as_class)
use_dict.__setitem__(element.name, mapped_value)
break
# 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.857975 | 3.78574 | 1.019081 |
if _debug: Any._debug("cast_in %r", element)
t = TagList()
if isinstance(element, Atomic):
tag = Tag()
element.encode(tag)
t.append(tag)
elif isinstance(element, AnyAtomic):
tag = Tag()
element.value.encode(tag)
t.append(tag)
else:
element.encode(t)
self.tagList.extend(t.tagList)
|
def cast_in(self, element)
|
encode the element into the internal tag list.
| 3.864747 | 3.276981 | 1.179362 |
if _debug: Any._debug("cast_out %r", klass)
global _sequence_of_classes, _list_of_classes
# check for a sequence element
if (klass in _sequence_of_classes) or (klass in _list_of_classes):
# build a sequence helper
helper = klass()
# make a copy of the tag list
t = TagList(self.tagList[:])
# let it decode itself
helper.decode(t)
# make sure everything was consumed
if len(t) != 0:
raise DecodingError("incomplete cast")
# return what was built
return helper.value
# check for an array element
elif klass in _array_of_classes:
# build a sequence helper
helper = klass()
# make a copy of the tag list
t = TagList(self.tagList[:])
# let it decode itself
helper.decode(t)
# make sure everything was consumed
if len(t) != 0:
raise DecodingError("incomplete cast")
# return what was built with Python list semantics
return helper.value[1:]
elif issubclass(klass, (Atomic, AnyAtomic)):
# make sure there's only one piece
if len(self.tagList) == 0:
raise DecodingError("missing cast component")
if len(self.tagList) > 1:
raise DecodingError("too many cast components")
if _debug: Any._debug(" - building helper: %r", klass)
# a helper cooperates between the atomic value and the tag
helper = klass(self.tagList[0])
# return the value
return helper.value
else:
if _debug: Any._debug(" - building value: %r", klass)
# build an element
value = klass()
# make a copy of the tag list
t = TagList(self.tagList[:])
# let it decode itself
value.decode(t)
# make sure everything was consumed
if len(t) != 0:
raise DecodingError("incomplete cast")
# return what was built
return value
|
def cast_out(self, klass)
|
Interpret the content as a particular class.
| 2.691764 | 2.717696 | 0.990458 |
if _debug: Any._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# result will be a list
rslt_list = []
# loop through the tags
for tag in self.tagList:
# build a tag thing
use_dict = as_class()
# save the pieces
use_dict.__setitem__('class', tag.tagClass)
use_dict.__setitem__('number', tag.tagNumber)
use_dict.__setitem__('lvt', tag.tagLVT)
### use_dict.__setitem__('data', '.'.join('%02X' % ord(c) for c in tag.tagData))
# add it to the list
rslt_list = use_dict
# return what we built
return rslt_list
|
def dict_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 4.294547 | 4.24547 | 1.01156 |
if _debug: SequenceOfAny._debug("cast_in %r", element)
# make sure it is a list
if not isinstance(element, List):
raise EncodingError("%r is not a list" % (element,))
t = TagList()
element.encode(t)
self.tagList.extend(t.tagList)
|
def cast_in(self, element)
|
encode the element into the internal tag list.
| 4.945879 | 3.973588 | 1.244689 |
if _debug: SequenceOfAny._debug("cast_out %r", klass)
# make sure it is a list
if not issubclass(klass, List):
raise DecodingError("%r is not a list" % (klass,))
# build a helper
helper = klass()
# make a copy of the tag list
t = TagList(self.tagList[:])
# let it decode itself
helper.decode(t)
# make sure everything was consumed
if len(t) != 0:
raise DecodingError("incomplete cast")
return helper.value
|
def cast_out(self, klass)
|
Interpret the content as a particular class.
| 4.509448 | 4.578175 | 0.984988 |
if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu)
# ignore this if there's no local device
if not self.localDevice:
if _debug: WhoIsIAmServices._debug(" - no local device")
return
# extract the parameters
low_limit = apdu.deviceInstanceRangeLowLimit
high_limit = apdu.deviceInstanceRangeHighLimit
# check for consistent parameters
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")
# see we should respond
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
# generate an I-Am
self.i_am(address=apdu.pduSource)
|
def do_WhoIsRequest(self, apdu)
|
Respond to a Who-Is request.
| 2.408095 | 2.3669 | 1.017405 |
if _debug: WhoIsIAmServices._debug("do_IAmRequest %r", apdu)
# check for required parameters
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")
# extract the device instance number
device_instance = apdu.iAmDeviceIdentifier[1]
if _debug: WhoIsIAmServices._debug(" - device_instance: %r", device_instance)
# extract the source address
device_address = apdu.pduSource
if _debug: WhoIsIAmServices._debug(" - device_address: %r", device_address)
|
def do_IAmRequest(self, apdu)
|
Respond to an I-Am request.
| 2.05258 | 2.002153 | 1.025186 |
if _debug: WhoHasIHaveServices._debug("do_WhoHasRequest, %r", apdu)
# ignore this if there's no local device
if not self.localDevice:
if _debug: WhoIsIAmServices._debug(" - no local device")
return
# if this has limits, check them like Who-Is
if apdu.limits is not None:
# extract the parameters
low_limit = apdu.limits.deviceInstanceRangeLowLimit
high_limit = apdu.limits.deviceInstanceRangeHighLimit
# check for consistent parameters
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")
# see we should respond
if (self.localDevice.objectIdentifier[1] < low_limit):
return
if (self.localDevice.objectIdentifier[1] > high_limit):
return
# find the object
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")
# maybe we don't have it
if not obj:
return
# send out the response
self.i_have(obj, address=apdu.pduSource)
|
def do_WhoHasRequest(self, apdu)
|
Respond to a Who-Has request.
| 3.009669 | 2.93339 | 1.026004 |
if _debug: WhoHasIHaveServices._debug("do_IHaveRequest %r", apdu)
# check for required parameters
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")
|
def do_IHaveRequest(self, apdu)
|
Respond to a I-Have request.
| 3.59642 | 3.320826 | 1.08299 |
if _debug: SSM._debug("set_state %r (%s) timer=%r", newState, SSM.transactionLabels[newState], timer)
# make sure we have a correct transition
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
# stop any current timer
self.stop_timer()
# make the change
self.state = newState
# if another timer should be started, start it
if timer:
self.start_timer(timer)
|
def set_state(self, newState, timer=0)
|
This function is called when the derived class wants to change state.
| 3.440347 | 3.45364 | 0.996151 |
if _debug: SSM._debug("set_segmentation_context %s", repr(apdu))
# set the context
self.segmentAPDU = apdu
|
def set_segmentation_context(self, apdu)
|
This function is called to set the segmentation context.
| 6.314577 | 5.758365 | 1.096592 |
if _debug: SSM._debug("get_segment %r", indx)
# check for no context
if not self.segmentAPDU:
raise RuntimeError("no segmentation context established")
# check for invalid segment number
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
# segmented response accepted?
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")
# maintain the the user data reference
segAPDU.pduUserData = self.segmentAPDU.pduUserData
# make sure the destination is set
segAPDU.pduDestination = self.pdu_address
# segmented message?
if (self.segmentCount != 1):
segAPDU.apduSeg = True
segAPDU.apduMor = (indx < (self.segmentCount - 1)) # more follows
segAPDU.apduSeq = indx % 256 # sequence number
# first segment sends proposed window size, rest get actual
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
# add the content
offset = indx * self.segmentSize
segAPDU.put_data( self.segmentAPDU.pduData[offset:offset+self.segmentSize] )
# success
return segAPDU
|
def get_segment(self, indx)
|
This function returns an APDU coorisponding to a particular
segment of a confirmed request or complex ack. The segmentAPDU
is the context.
| 3.062155 | 2.888825 | 1.06 |
if _debug: SSM._debug("append_segment %r", apdu)
# check for no context
if not self.segmentAPDU:
raise RuntimeError("no segmentation context established")
# append the data
self.segmentAPDU.put_data(apdu.pduData)
|
def append_segment(self, apdu)
|
This function appends the apdu content to the end of the current
APDU being built. The segmentAPDU is the context.
| 5.789835 | 4.407228 | 1.313713 |
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)
# send the message
self.ssmSAP.request(apdu)
# check for no more follows
if not apdu.apduMor:
self.sentAllSegments = True
break
|
def fill_window(self, seqNum)
|
This function sends all of the packets necessary to fill
out the segmentation window.
| 6.223747 | 5.778031 | 1.07714 |
if _debug: ClientSSM._debug("request %r", apdu)
# make sure it has a good source and destination
apdu.pduSource = None
apdu.pduDestination = self.pdu_address
# send it via the device
self.ssmSAP.request(apdu)
|
def request(self, apdu)
|
This function is called by client transaction functions when it wants
to send a message to the device.
| 5.998596 | 5.886343 | 1.01907 |
if _debug: ClientSSM._debug("indication %r", apdu)
# make sure we're getting confirmed requests
if (apdu.apduType != ConfirmedRequestPDU.pduType):
raise RuntimeError("invalid APDU (1)")
# save the request and set the segmentation context
self.set_segmentation_context(apdu)
# if the max apdu length of the server isn't known, assume that it
# is the same size as our own and will be the segment size
if (not self.device_info) or (self.device_info.maxApduLengthAccepted is None):
self.segmentSize = self.maxApduLengthAccepted
# if the max npdu length of the server isn't known, assume that it
# is the same as the max apdu length accepted
elif self.device_info.maxNpduLength is None:
self.segmentSize = self.device_info.maxApduLengthAccepted
# the segment size is the minimum of the size of the largest packet
# that can be delivered to the server and the largest it can accept
else:
self.segmentSize = min(self.device_info.maxNpduLength, self.device_info.maxApduLengthAccepted)
if _debug: ClientSSM._debug(" - segment size: %r", self.segmentSize)
# save the invoke ID
self.invokeID = apdu.apduInvokeID
if _debug: ClientSSM._debug(" - invoke ID: %r", self.invokeID)
# compute the segment count
if not apdu.pduData:
# always at least one segment
self.segmentCount = 1
else:
# split into chunks, maybe need one more
self.segmentCount, more = divmod(len(apdu.pduData), self.segmentSize)
if more:
self.segmentCount += 1
if _debug: ClientSSM._debug(" - segment count: %r", self.segmentCount)
# make sure we support segmented transmit if we need to
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
# make sure we dont exceed the number of segments in our request
# that the server said it was willing to accept
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
# send out the first segment (or the whole thing)
if self.segmentCount == 1:
# unsegmented
self.sentAllSegments = True
self.retryCount = 0
self.set_state(AWAIT_CONFIRMATION, self.apduTimeout)
else:
# segmented
self.sentAllSegments = False
self.retryCount = 0
self.segmentRetryCount = 0
self.initialSequenceNumber = 0
self.actualWindowSize = None # segment ack will set value
self.set_state(SEGMENTED_REQUEST, self.segmentTimeout)
# deliver to the device
self.request(self.get_segment(0))
|
def indication(self, apdu)
|
This function is called after the device has bound a new transaction
and wants to start the process rolling.
| 2.879993 | 2.87332 | 1.002322 |
if _debug: ClientSSM._debug("response %r", apdu)
# make sure it has a good source and destination
apdu.pduSource = self.pdu_address
apdu.pduDestination = None
# send it to the application
self.ssmSAP.sap_response(apdu)
|
def response(self, apdu)
|
This function is called by client transaction functions when they want
to send a message to the application.
| 5.942677 | 5.611321 | 1.059051 |
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")
|
def confirmation(self, apdu)
|
This function is called by the device for all upstream messages related
to the transaction.
| 2.977572 | 2.980419 | 0.999045 |
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
|
def process_task(self)
|
This function is called when something has taken too long.
| 3.245448 | 3.094634 | 1.048734 |
if _debug: ClientSSM._debug("abort %r", reason)
# change the state to aborted
self.set_state(ABORTED)
# build an abort PDU to return
abort_pdu = AbortPDU(False, self.invokeID, reason)
# return it
return abort_pdu
|
def abort(self, reason)
|
This function is called when the transaction should be aborted.
| 6.287745 | 5.772584 | 1.089243 |
if _debug: ClientSSM._debug("segmented_request %r", apdu)
# server is ready for the next segment
if apdu.apduType == SegmentAckPDU.pduType:
if _debug: ClientSSM._debug(" - segment ack")
# actual window size is provided by server
self.actualWindowSize = apdu.apduWin
# duplicate ack received?
if not self.in_window(apdu.apduSeq, self.initialSequenceNumber):
if _debug: ClientSSM._debug(" - not in window")
self.restart_timer(self.segmentTimeout)
# final ack received?
elif self.sentAllSegments:
if _debug: ClientSSM._debug(" - all done sending request")
self.set_state(AWAIT_CONFIRMATION, self.apduTimeout)
# more segments to send
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)
# simple ack
elif (apdu.apduType == SimpleAckPDU.pduType):
if _debug: ClientSSM._debug(" - simple ack")
if not self.sentAllSegments:
abort = self.abort(AbortReason.invalidApduInThisState)
self.request(abort) # send it to the device
self.response(abort) # send it to the application
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) # send it to the device
self.response(abort) # send it to the application
elif not apdu.apduSeg:
# ack is not segmented
self.set_state(COMPLETED)
self.response(apdu)
else:
# set the segmented response context
self.set_segmentation_context(apdu)
# minimum of what the server is proposing and this client proposes
self.actualWindowSize = min(apdu.apduWin, self.ssmSAP.proposedWindowSize)
self.lastSequenceNumber = 0
self.initialSequenceNumber = 0
self.set_state(SEGMENTED_CONFIRMATION, self.segmentTimeout)
# some kind of problem
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)")
|
def segmented_request(self, apdu)
|
This function is called when the client is sending a segmented request
and receives an apdu.
| 2.948271 | 2.941703 | 1.002233 |
if _debug: ServerSSM._debug("set_state %r (%s) timer=%r", newState, SSM.transactionLabels[newState], timer)
# do the regular state change
SSM.set_state(self, newState, timer)
# when completed or aborted, remove tracking
if (newState == COMPLETED) or (newState == ABORTED):
if _debug: ServerSSM._debug(" - remove from active transactions")
self.ssmSAP.serverTransactions.remove(self)
# release the device info
if self.device_info:
if _debug: ClientSSM._debug(" - release device information")
self.ssmSAP.deviceInfoCache.release(self.device_info)
|
def set_state(self, newState, timer=0)
|
This function is called when the client wants to change state.
| 4.71595 | 4.676692 | 1.008394 |
if _debug: ServerSSM._debug("request %r", apdu)
# make sure it has a good source and destination
apdu.pduSource = self.pdu_address
apdu.pduDestination = None
# send it via the device
self.ssmSAP.sap_request(apdu)
|
def request(self, apdu)
|
This function is called by transaction functions to send
to the application.
| 6.608263 | 6.745269 | 0.979689 |
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")
|
def indication(self, apdu)
|
This function is called for each downstream packet related to
the transaction.
| 2.406647 | 2.44877 | 0.982798 |
if _debug: ServerSSM._debug("confirmation %r", apdu)
# check to see we are in the correct state
if self.state != AWAIT_RESPONSE:
if _debug: ServerSSM._debug(" - warning: not expecting a response")
# abort response
if (apdu.apduType == AbortPDU.pduType):
if _debug: ServerSSM._debug(" - abort")
self.set_state(ABORTED)
# send the response to the device
self.response(apdu)
return
# simple response
if (apdu.apduType == SimpleAckPDU.pduType) or (apdu.apduType == ErrorPDU.pduType) or (apdu.apduType == RejectPDU.pduType):
if _debug: ServerSSM._debug(" - simple ack, error, or reject")
# transaction completed
self.set_state(COMPLETED)
# send the response to the device
self.response(apdu)
return
# complex ack
if (apdu.apduType == ComplexAckPDU.pduType):
if _debug: ServerSSM._debug(" - complex ack")
# save the response and set the segmentation context
self.set_segmentation_context(apdu)
# the segment size is the minimum of the size of the largest packet
# that can be delivered to the client and the largest it can accept
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)
# compute the segment count
if not apdu.pduData:
# always at least one segment
self.segmentCount = 1
else:
# split into chunks, maybe need one more
self.segmentCount, more = divmod(len(apdu.pduData), self.segmentSize)
if more:
self.segmentCount += 1
if _debug: ServerSSM._debug(" - segment count: %r", self.segmentCount)
# make sure we support segmented transmit if we need to
if self.segmentCount > 1:
if _debug: ServerSSM._debug(" - segmentation required, %d segments", self.segmentCount)
# make sure we support segmented transmit
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
# make sure client supports segmented receive
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
# make sure we dont exceed the number of segments in our response
# that the client said it was willing to accept in the request
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
# initialize the state
self.segmentRetryCount = 0
self.initialSequenceNumber = 0
self.actualWindowSize = None
# send out the first segment (or the whole thing)
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)")
|
def confirmation(self, apdu)
|
This function is called when the application has provided a response
and needs it to be sent to the client.
| 2.68991 | 2.679169 | 1.004009 |
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")
|
def process_task(self)
|
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.
| 2.937217 | 2.671393 | 1.099508 |
if _debug: ServerSSM._debug("abort %r", reason)
# change the state to aborted
self.set_state(ABORTED)
# return an abort APDU
return AbortPDU(True, self.invokeID, reason)
|
def abort(self, reason)
|
This function is called when the application would like to abort the
transaction. There is no notification back to the application.
| 7.68642 | 7.289598 | 1.054437 |
if _debug: ServerSSM._debug("await_response_timeout")
abort = self.abort(AbortReason.serverTimeout)
self.request(abort)
|
def await_response_timeout(self)
|
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.
| 14.724078 | 12.695827 | 1.159757 |
if _debug: StateMachineAccessPoint._debug("get_next_invoke_id")
initialID = self.nextInvokeID
while 1:
invokeID = self.nextInvokeID
self.nextInvokeID = (self.nextInvokeID + 1) % 256
# see if we've checked for them all
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
|
def get_next_invoke_id(self, addr)
|
Called by clients to get an unused invoke ID.
| 4.157831 | 3.891412 | 1.068463 |
if _debug: StateMachineAccessPoint._debug("confirmation %r", pdu)
# check device communication control
if self.dccEnableDisable == 'enable':
if _debug: StateMachineAccessPoint._debug(" - communications enabled")
elif self.dccEnableDisable == 'disable':
if (pdu.apduType == 0) and (pdu.apduService == 17):
if _debug: StateMachineAccessPoint._debug(" - continue with DCC request")
elif (pdu.apduType == 0) and (pdu.apduService == 20):
if _debug: StateMachineAccessPoint._debug(" - continue with reinitialize device")
elif (pdu.apduType == 1) and (pdu.apduService == 8):
if _debug: StateMachineAccessPoint._debug(" - continue with Who-Is")
else:
if _debug: StateMachineAccessPoint._debug(" - not a Who-Is, dropped")
return
elif self.dccEnableDisable == 'disableInitiation':
if _debug: StateMachineAccessPoint._debug(" - initiation disabled")
# make a more focused interpretation
atype = apdu_types.get(pdu.apduType)
if not atype:
StateMachineAccessPoint._warning(" - unknown apduType: %r", pdu.apduType)
return
# decode it
apdu = atype()
apdu.decode(pdu)
if _debug: StateMachineAccessPoint._debug(" - apdu: %r", apdu)
if isinstance(apdu, ConfirmedRequestPDU):
# find duplicates of this request
for tr in self.serverTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
break
else:
# build a server transaction
tr = ServerSSM(self, apdu.pduSource)
# add it to our transactions to track it
self.serverTransactions.append(tr)
# let it run with the apdu
tr.indication(apdu)
elif isinstance(apdu, UnconfirmedRequestPDU):
# deliver directly to the application
self.sap_request(apdu)
elif isinstance(apdu, SimpleAckPDU) \
or isinstance(apdu, ComplexAckPDU) \
or isinstance(apdu, ErrorPDU) \
or isinstance(apdu, RejectPDU):
# find the client transaction this is acking
for tr in self.clientTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
break
else:
return
# send the packet on to the transaction
tr.confirmation(apdu)
elif isinstance(apdu, AbortPDU):
# find the transaction being aborted
if apdu.apduSrv:
for tr in self.clientTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
break
else:
return
# send the packet on to the transaction
tr.confirmation(apdu)
else:
for tr in self.serverTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
break
else:
return
# send the packet on to the transaction
tr.indication(apdu)
elif isinstance(apdu, SegmentAckPDU):
# find the transaction being aborted
if apdu.apduSrv:
for tr in self.clientTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
break
else:
return
# send the packet on to the transaction
tr.confirmation(apdu)
else:
for tr in self.serverTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduSource == tr.pdu_address):
break
else:
return
# send the packet on to the transaction
tr.indication(apdu)
else:
raise RuntimeError("invalid APDU (8)")
|
def confirmation(self, pdu)
|
Packets coming up the stack are APDU's.
| 2.331836 | 2.318016 | 1.005962 |
if _debug: StateMachineAccessPoint._debug("sap_indication %r", apdu)
# check device communication control
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):
# deliver to the device
self.request(apdu)
elif isinstance(apdu, ConfirmedRequestPDU):
# make sure it has an invoke ID
if apdu.apduInvokeID is None:
apdu.apduInvokeID = self.get_next_invoke_id(apdu.pduDestination)
else:
# verify the invoke ID isn't already being used
for tr in self.clientTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduDestination == tr.pdu_address):
raise RuntimeError("invoke ID in use")
# warning for bogus requests
if (apdu.pduDestination.addrType != Address.localStationAddr) and (apdu.pduDestination.addrType != Address.remoteStationAddr):
StateMachineAccessPoint._warning("%s is not a local or remote station", apdu.pduDestination)
# create a client transaction state machine
tr = ClientSSM(self, apdu.pduDestination)
if _debug: StateMachineAccessPoint._debug(" - client segmentation state machine: %r", tr)
# add it to our transactions to track it
self.clientTransactions.append(tr)
# let it run
tr.indication(apdu)
else:
raise RuntimeError("invalid APDU (9)")
|
def sap_indication(self, apdu)
|
This function is called when the application is requesting
a new transaction as a client.
| 3.250745 | 3.279295 | 0.991294 |
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):
# find the appropriate server transaction
for tr in self.serverTransactions:
if (apdu.apduInvokeID == tr.invokeID) and (apdu.pduDestination == tr.pdu_address):
break
else:
return
# pass control to the transaction
tr.confirmation(apdu)
else:
raise RuntimeError("invalid APDU (10)")
|
def sap_confirmation(self, apdu)
|
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.
| 3.551795 | 3.245769 | 1.094285 |
if _debug: BTR._debug("add_peer %r networks=%r", peerAddr, networks)
# see if this is already a peer
if peerAddr in self.peers:
# add the (new?) reachable networks
if not networks:
networks = []
else:
self.peers[peerAddr].extend(networks)
else:
if not networks:
networks = []
# save the networks
self.peers[peerAddr] = networks
|
def add_peer(self, peerAddr, networks=None)
|
Add a peer and optionally provide a list of the reachable networks.
| 4.067688 | 3.739604 | 1.087732 |
if _debug: BTR._debug("delete_peer %r", peerAddr)
# get the peer networks
# networks = self.peers[peerAddr]
### send a control message upstream that these are no longer reachable
# now delete the peer
del self.peers[peerAddr]
|
def delete_peer(self, peerAddr)
|
Delete a peer.
| 11.038911 | 11.013946 | 1.002267 |
# a little error checking
if ttl <= 0:
raise ValueError("time-to-live must be greater than zero")
# save the BBMD address and time-to-live
if isinstance(addr, Address):
self.bbmdAddress = addr
else:
self.bbmdAddress = Address(addr)
self.bbmdTimeToLive = ttl
# install this task to run when it gets a chance
self.install_task(when=0)
|
def register(self, addr, ttl)
|
Initiate the process of registering with a BBMD.
| 5.845738 | 5.158562 | 1.133211 |
pdu = RegisterForeignDevice(0)
pdu.pduDestination = self.bbmdAddress
# send it downstream
self.request(pdu)
# change the status to unregistered
self.registrationStatus = -2
# clear the BBMD address and time-to-live
self.bbmdAddress = None
self.bbmdTimeToLive = None
|
def unregister(self)
|
Drop the registration with a BBMD.
| 7.442174 | 6.228415 | 1.194874 |
pdu = RegisterForeignDevice(self.bbmdTimeToLive)
pdu.pduDestination = self.bbmdAddress
# send it downstream
self.request(pdu)
|
def process_task(self)
|
Called when the registration request should be sent to the BBMD.
| 21.879667 | 13.651119 | 1.602775 |
if _debug: BIPBBMD._debug("register_foreign_device %r %r", addr, ttl)
# see if it is an address or make it one
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 success
return 0
|
def register_foreign_device(self, addr, ttl)
|
Add a foreign device to the FDT.
| 3.982941 | 3.817454 | 1.04335 |
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
# save the content
use_dict.__setitem__('dnet', self.rtDNET)
use_dict.__setitem__('port_id', self.rtPortID)
use_dict.__setitem__('port_info', self.rtPortInfo)
# 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.
| 5.347941 | 5.40172 | 0.990044 |
if not isinstance(arg, (int, long)) or isinstance(arg, bool):
return False
if (arg < cls._low_limit):
return False
if (cls._high_limit is not None) and (arg > cls._high_limit):
return False
return True
|
def is_valid(cls, arg)
|
Return True if arg is valid value for the class.
| 2.674475 | 2.559766 | 1.044812 |
return isinstance(arg, (int, long)) and (not isinstance(arg, bool))
|
def is_valid(cls, arg)
|
Return True if arg is valid value for the class.
| 5.533093 | 5.270431 | 1.049837 |
return (isinstance(arg, (int, long)) and (arg >= 0)) or \
isinstance(arg, str)
|
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.302624 | 4.475806 | 0.961307 |
objType, objInstance = self.value
if isinstance(objType, int):
pass
elif isinstance(objType, long):
objType = int(objType)
elif isinstance(objType, basestring):
# turn it back into an integer
objType = self.objectTypeClass()[objType]
else:
raise TypeError("invalid datatype for objType")
# pack the components together
return (objType, objInstance)
|
def get_tuple(self)
|
Return the unsigned integer tuple of the identifier.
| 5.48009 | 4.864864 | 1.126463 |
if _debug: FileServices._debug("do_AtomicReadFileRequest %r", apdu)
if (apdu.fileIdentifier[0] != 'file'):
raise ExecutionError('services', 'inconsistentObjectType')
# get the object
obj = self.get_object_id(apdu.fileIdentifier)
if _debug: FileServices._debug(" - object: %r", obj)
if not obj:
raise ExecutionError('object', 'unknownObject')
if apdu.accessMethod.recordAccess:
# check against the object
if obj.fileAccessMethod != 'recordAccess':
raise ExecutionError('services', 'invalidFileAccessMethod')
# simplify
record_access = apdu.accessMethod.recordAccess
# check for required parameters
if record_access.fileStartRecord is None:
raise MissingRequiredParameter("fileStartRecord required")
if record_access.requestedRecordCount is None:
raise MissingRequiredParameter("requestedRecordCount required")
### verify start is valid - double check this (empty files?)
if (record_access.fileStartRecord < 0) or \
(record_access.fileStartRecord >= len(obj)):
raise ExecutionError('services', 'invalidFileStartPosition')
# pass along to the object
end_of_file, record_data = obj.read_record(
record_access.fileStartRecord,
record_access.requestedRecordCount,
)
if _debug: FileServices._debug(" - record_data: %r", record_data)
# this is an ack
resp = AtomicReadFileACK(context=apdu,
endOfFile=end_of_file,
accessMethod=AtomicReadFileACKAccessMethodChoice(
recordAccess=AtomicReadFileACKAccessMethodRecordAccess(
fileStartRecord=record_access.fileStartRecord,
returnedRecordCount=len(record_data),
fileRecordData=record_data,
),
),
)
elif apdu.accessMethod.streamAccess:
# check against the object
if obj.fileAccessMethod != 'streamAccess':
raise ExecutionError('services', 'invalidFileAccessMethod')
# simplify
stream_access = apdu.accessMethod.streamAccess
# check for required parameters
if stream_access.fileStartPosition is None:
raise MissingRequiredParameter("fileStartPosition required")
if stream_access.requestedOctetCount is None:
raise MissingRequiredParameter("requestedOctetCount required")
### verify start is valid - double check this (empty files?)
if (stream_access.fileStartPosition < 0) or \
(stream_access.fileStartPosition >= len(obj)):
raise ExecutionError('services', 'invalidFileStartPosition')
# pass along to the object
end_of_file, record_data = obj.read_stream(
stream_access.fileStartPosition,
stream_access.requestedOctetCount,
)
if _debug: FileServices._debug(" - record_data: %r", record_data)
# this is an ack
resp = AtomicReadFileACK(context=apdu,
endOfFile=end_of_file,
accessMethod=AtomicReadFileACKAccessMethodChoice(
streamAccess=AtomicReadFileACKAccessMethodStreamAccess(
fileStartPosition=stream_access.fileStartPosition,
fileData=record_data,
),
),
)
if _debug: FileServices._debug(" - resp: %r", resp)
# return the result
self.response(resp)
|
def do_AtomicReadFileRequest(self, apdu)
|
Return one of our records.
| 2.25578 | 2.240681 | 1.006738 |
if _debug: FileServices._debug("do_AtomicWriteFileRequest %r", apdu)
if (apdu.fileIdentifier[0] != 'file'):
raise ExecutionError('services', 'inconsistentObjectType')
# get the object
obj = self.get_object_id(apdu.fileIdentifier)
if _debug: FileServices._debug(" - object: %r", obj)
if not obj:
raise ExecutionError('object', 'unknownObject')
if apdu.accessMethod.recordAccess:
# check against the object
if obj.fileAccessMethod != 'recordAccess':
raise ExecutionError('services', 'invalidFileAccessMethod')
# simplify
record_access = apdu.accessMethod.recordAccess
# check for required parameters
if record_access.fileStartRecord is None:
raise MissingRequiredParameter("fileStartRecord required")
if record_access.recordCount is None:
raise MissingRequiredParameter("recordCount required")
if record_access.fileRecordData is None:
raise MissingRequiredParameter("fileRecordData required")
# check for read-only
if obj.readOnly:
raise ExecutionError('services', 'fileAccessDenied')
# pass along to the object
start_record = obj.write_record(
record_access.fileStartRecord,
record_access.recordCount,
record_access.fileRecordData,
)
if _debug: FileServices._debug(" - start_record: %r", start_record)
# this is an ack
resp = AtomicWriteFileACK(context=apdu,
fileStartRecord=start_record,
)
elif apdu.accessMethod.streamAccess:
# check against the object
if obj.fileAccessMethod != 'streamAccess':
raise ExecutionError('services', 'invalidFileAccessMethod')
# simplify
stream_access = apdu.accessMethod.streamAccess
# check for required parameters
if stream_access.fileStartPosition is None:
raise MissingRequiredParameter("fileStartPosition required")
if stream_access.fileData is None:
raise MissingRequiredParameter("fileData required")
# check for read-only
if obj.readOnly:
raise ExecutionError('services', 'fileAccessDenied')
# pass along to the object
start_position = obj.write_stream(
stream_access.fileStartPosition,
stream_access.fileData,
)
if _debug: FileServices._debug(" - start_position: %r", start_position)
# this is an ack
resp = AtomicWriteFileACK(context=apdu,
fileStartPosition=start_position,
)
if _debug: FileServices._debug(" - resp: %r", resp)
# return the result
self.response(resp)
|
def do_AtomicWriteFileRequest(self, apdu)
|
Return one of our records.
| 2.211157 | 2.198491 | 1.005761 |
# unspecified
if not arg:
return 0
if arg > 64:
return 7
# the largest number not greater than the arg
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,))
|
def encode_max_segments_accepted(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!
| 6.072464 | 6.340312 | 0.957755 |
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,))
|
def encode_max_apdu_length_accepted(arg)
|
Return the encoding of the highest encodable value less than the
value of the arg.
| 4.319243 | 4.065002 | 1.062544 |
if _debug: APCI._debug("encode %r", pdu)
PCI.update(pdu, self)
if (self.apduType == ConfirmedRequestPDU.pduType):
# PDU type
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):
# PDU type
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):
# PDU type
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):
# PDU type
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")
|
def encode(self, pdu)
|
encode the contents of the APCI into the PDU.
| 1.736058 | 1.699066 | 1.021772 |
if _debug: APCI._debug("decode %r", pdu)
PCI.update(self, pdu)
# decode the first octet
buff = pdu.get()
# decode the APCI type
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")
|
def decode(self, pdu)
|
decode the contents of the PDU into the APCI.
| 1.875261 | 1.817302 | 1.031892 |
if _debug: APCI._debug("apci_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()
# copy the source and destination to make it easier to search
if self.pduSource:
use_dict.__setitem__('source', str(self.pduSource))
if self.pduDestination:
use_dict.__setitem__('destination', str(self.pduDestination))
# loop through the elements
for attr in APCI._debug_contents:
value = getattr(self, attr, None)
if value is None:
continue
if attr == 'apduType':
mapped_value = apdu_types[self.apduType].__name__
elif attr == 'apduService':
if self.apduType in (ConfirmedRequestPDU.pduType, SimpleAckPDU.pduType, ComplexAckPDU.pduType):
mapped_value = confirmed_request_types[self.apduService].__name__
elif (self.apduType == UnconfirmedRequestPDU.pduType):
mapped_value = unconfirmed_request_types[self.apduService].__name__
elif (self.apduType == ErrorPDU.pduType):
mapped_value = error_types[self.apduService].__name__
else:
mapped_value = value
# save the mapped value
use_dict.__setitem__(attr, mapped_value)
# return what we built/updated
return use_dict
|
def apci_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 2.52061 | 2.489692 | 1.012418 |
if _debug: APDU._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.apci_contents(use_dict=use_dict, as_class=as_class)
self.apdu_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.234995 | 3.175454 | 1.01875 |
if _debug: APCISequence._debug("apdu_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()
# set the function based on the class name
use_dict.__setitem__('function', self.__class__.__name__)
# fill in from the sequence contents
Sequence.dict_contents(self, use_dict=use_dict, as_class=as_class)
# return what we built/updated
return use_dict
|
def apdu_contents(self, use_dict=None, as_class=dict)
|
Return the contents of an object as a dict.
| 4.312726 | 3.918467 | 1.100616 |
if not isinstance(tdata, str):
raise TypeError("tag data must be str")
self.tagClass = tclass
self.tagNumber = tnum
self.tagLVT = tlvt
self.tagData = tdata
|
def set(self, tclass, tnum, tlvt=0, tdata='')
|
set the values of the tag.
| 2.963552 | 2.663656 | 1.112588 |
if not isinstance(tdata, str):
raise TypeError("tag data must be str")
self.tagClass = Tag.applicationTagClass
self.tagNumber = tnum
self.tagLVT = len(tdata)
self.tagData = tdata
|
def set_app_data(self, tnum, tdata)
|
set the values of the tag.
| 5.536669 | 4.708939 | 1.175779 |
try:
tag = pdu.get()
# extract the type
self.tagClass = (tag >> 3) & 0x01
# extract the tag number
self.tagNumber = (tag >> 4)
if (self.tagNumber == 0x0F):
self.tagNumber = pdu.get()
# extract the length
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
# application tagged boolean has no more data
if (self.tagClass == Tag.applicationTagClass) and (self.tagNumber == Tag.booleanAppTag):
# tagLVT contains value
self.tagData = ''
else:
# tagLVT contains length
self.tagData = pdu.get_data(self.tagLVT)
except DecodingError:
raise InvalidTag("invalid tag encoding")
|
def decode(self, pdu)
|
Decode a tag from the PDU.
| 2.953071 | 2.812047 | 1.05015 |
if self.tagClass != Tag.applicationTagClass:
raise ValueError("application tag required")
# application tagged boolean now has data
if (self.tagNumber == Tag.booleanAppTag):
return ContextTag(context, chr(self.tagLVT))
else:
return ContextTag(context, self.tagData)
|
def app_to_context(self, context)
|
Return a context encoded tag.
| 11.593847 | 9.113035 | 1.272227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.