repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
JoelBender/bacpypes | py25/bacpypes/service/device.py | WhoHasIHaveServices.do_WhoHasRequest | def do_WhoHasRequest(self, apdu):
"""Respond to a Who-Has request."""
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) | python | def do_WhoHasRequest(self, apdu):
"""Respond to a Who-Has request."""
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",
")",
":",
"if",
"_debug",
":",
"WhoHasIHaveServices",
".",
"_debug",
"(",
"\"do_WhoHasRequest, %r\"",
",",
"apdu",
")",
"# ignore this if there's no local device",
"if",
"not",
"self",
".",
"localDevice",
":",
"... | Respond to a Who-Has request. | [
"Respond",
"to",
"a",
"Who",
"-",
"Has",
"request",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/device.py#L170-L214 | train | 201,900 |
JoelBender/bacpypes | py25/bacpypes/service/device.py | WhoHasIHaveServices.do_IHaveRequest | def do_IHaveRequest(self, apdu):
"""Respond to a I-Have request."""
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") | python | def do_IHaveRequest(self, apdu):
"""Respond to a I-Have request."""
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",
")",
":",
"if",
"_debug",
":",
"WhoHasIHaveServices",
".",
"_debug",
"(",
"\"do_IHaveRequest %r\"",
",",
"apdu",
")",
"# check for required parameters",
"if",
"apdu",
".",
"deviceIdentifier",
"is",
"None",
":",
... | Respond to a I-Have request. | [
"Respond",
"to",
"a",
"I",
"-",
"Have",
"request",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/device.py#L240-L250 | train | 201,901 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | SSM.set_state | def set_state(self, newState, timer=0):
"""This function is called when the derived class wants to change state."""
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) | python | def set_state(self, newState, timer=0):
"""This function is called when the derived class wants to change state."""
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",
")",
":",
"if",
"_debug",
":",
"SSM",
".",
"_debug",
"(",
"\"set_state %r (%s) timer=%r\"",
",",
"newState",
",",
"SSM",
".",
"transactionLabels",
"[",
"newState",
"]",
",",
"timer",... | This function is called when the derived class wants to change state. | [
"This",
"function",
"is",
"called",
"when",
"the",
"derived",
"class",
"wants",
"to",
"change",
"state",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L121-L139 | train | 201,902 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | SSM.set_segmentation_context | def set_segmentation_context(self, apdu):
"""This function is called to set the segmentation context."""
if _debug: SSM._debug("set_segmentation_context %s", repr(apdu))
# set the context
self.segmentAPDU = apdu | python | def set_segmentation_context(self, apdu):
"""This function is called to set the segmentation context."""
if _debug: SSM._debug("set_segmentation_context %s", repr(apdu))
# set the context
self.segmentAPDU = apdu | [
"def",
"set_segmentation_context",
"(",
"self",
",",
"apdu",
")",
":",
"if",
"_debug",
":",
"SSM",
".",
"_debug",
"(",
"\"set_segmentation_context %s\"",
",",
"repr",
"(",
"apdu",
")",
")",
"# set the context",
"self",
".",
"segmentAPDU",
"=",
"apdu"
] | This function is called to set the segmentation context. | [
"This",
"function",
"is",
"called",
"to",
"set",
"the",
"segmentation",
"context",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L141-L146 | train | 201,903 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | SSM.get_segment | 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."""
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 | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"SSM",
".",
"_debug",
"(",
"\"get_segment %r\"",
",",
"indx",
")",
"# check for no context",
"if",
"not",
"self",
".",
"segmentAPDU",
":",
"raise",
"RuntimeError",
"(",
"\"no segm... | This function returns an APDU coorisponding to a particular
segment of a confirmed request or complex ack. The segmentAPDU
is the context. | [
"This",
"function",
"returns",
"an",
"APDU",
"coorisponding",
"to",
"a",
"particular",
"segment",
"of",
"a",
"confirmed",
"request",
"or",
"complex",
"ack",
".",
"The",
"segmentAPDU",
"is",
"the",
"context",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L148-L210 | train | 201,904 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | SSM.append_segment | 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."""
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) | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"SSM",
".",
"_debug",
"(",
"\"append_segment %r\"",
",",
"apdu",
")",
"# check for no context",
"if",
"not",
"self",
".",
"segmentAPDU",
":",
"raise",
"RuntimeError",
"(",
"\"n... | This function appends the apdu content to the end of the current
APDU being built. The segmentAPDU is the context. | [
"This",
"function",
"appends",
"the",
"apdu",
"content",
"to",
"the",
"end",
"of",
"the",
"current",
"APDU",
"being",
"built",
".",
"The",
"segmentAPDU",
"is",
"the",
"context",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L212-L222 | train | 201,905 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | SSM.fill_window | def fill_window(self, seqNum):
"""This function sends all of the packets necessary to fill
out the segmentation window."""
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 | python | def fill_window(self, seqNum):
"""This function sends all of the packets necessary to fill
out the segmentation window."""
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",
")",
":",
"if",
"_debug",
":",
"SSM",
".",
"_debug",
"(",
"\"fill_window %r\"",
",",
"seqNum",
")",
"if",
"_debug",
":",
"SSM",
".",
"_debug",
"(",
"\" - actualWindowSize: %r\"",
",",
"self",
".",
"actua... | This function sends all of the packets necessary to fill
out the segmentation window. | [
"This",
"function",
"sends",
"all",
"of",
"the",
"packets",
"necessary",
"to",
"fill",
"out",
"the",
"segmentation",
"window",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L232-L247 | train | 201,906 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.request | def request(self, apdu):
"""This function is called by client transaction functions when it wants
to send a message to the device."""
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) | python | def request(self, apdu):
"""This function is called by client transaction functions when it wants
to send a message to the device."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"request %r\"",
",",
"apdu",
")",
"# make sure it has a good source and destination",
"apdu",
".",
"pduSource",
"=",
"None",
"apdu",
".",
"pduDestinatio... | This function is called by client transaction functions when it wants
to send a message to the device. | [
"This",
"function",
"is",
"called",
"by",
"client",
"transaction",
"functions",
"when",
"it",
"wants",
"to",
"send",
"a",
"message",
"to",
"the",
"device",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L286-L296 | train | 201,907 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.indication | def indication(self, apdu):
"""This function is called after the device has bound a new transaction
and wants to start the process rolling."""
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)) | python | def indication(self, apdu):
"""This function is called after the device has bound a new transaction
and wants to start the process rolling."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"apdu",
")",
"# make sure we're getting confirmed requests",
"if",
"(",
"apdu",
".",
"apduType",
"!=",
"ConfirmedRequestPDU",
... | This function is called after the device has bound a new transaction
and wants to start the process rolling. | [
"This",
"function",
"is",
"called",
"after",
"the",
"device",
"has",
"bound",
"a",
"new",
"transaction",
"and",
"wants",
"to",
"start",
"the",
"process",
"rolling",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L298-L388 | train | 201,908 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.response | def response(self, apdu):
"""This function is called by client transaction functions when they want
to send a message to the application."""
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) | python | def response(self, apdu):
"""This function is called by client transaction functions when they want
to send a message to the application."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"response %r\"",
",",
"apdu",
")",
"# make sure it has a good source and destination",
"apdu",
".",
"pduSource",
"=",
"self",
".",
"pdu_address",
"apdu... | This function is called by client transaction functions when they want
to send a message to the application. | [
"This",
"function",
"is",
"called",
"by",
"client",
"transaction",
"functions",
"when",
"they",
"want",
"to",
"send",
"a",
"message",
"to",
"the",
"application",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L390-L400 | train | 201,909 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.confirmation | def confirmation(self, apdu):
"""This function is called by the device for all upstream messages related
to the transaction."""
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") | python | def confirmation(self, apdu):
"""This function is called by the device for all upstream messages related
to the transaction."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"confirmation %r\"",
",",
"apdu",
")",
"if",
"self",
".",
"state",
"==",
"SEGMENTED_REQUEST",
":",
"self",
".",
"segmented_request",
"(",
"ap... | This function is called by the device for all upstream messages related
to the transaction. | [
"This",
"function",
"is",
"called",
"by",
"the",
"device",
"for",
"all",
"upstream",
"messages",
"related",
"to",
"the",
"transaction",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L402-L414 | train | 201,910 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.process_task | def process_task(self):
"""This function is called when something has taken too long."""
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 | python | def process_task(self):
"""This function is called when something has taken too long."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"process_task\"",
")",
"if",
"self",
".",
"state",
"==",
"SEGMENTED_REQUEST",
":",
"self",
".",
"segmented_request_timeout",
"(",
")",
"elif",
"self",
".",
... | This function is called when something has taken too long. | [
"This",
"function",
"is",
"called",
"when",
"something",
"has",
"taken",
"too",
"long",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L416-L433 | train | 201,911 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.abort | def abort(self, reason):
"""This function is called when the transaction should be aborted."""
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 | python | def abort(self, reason):
"""This function is called when the transaction should be aborted."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"abort %r\"",
",",
"reason",
")",
"# change the state to aborted",
"self",
".",
"set_state",
"(",
"ABORTED",
")",
"# build an abort PDU to return",
"abo... | This function is called when the transaction should be aborted. | [
"This",
"function",
"is",
"called",
"when",
"the",
"transaction",
"should",
"be",
"aborted",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L435-L446 | train | 201,912 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ClientSSM.segmented_request | def segmented_request(self, apdu):
"""This function is called when the client is sending a segmented request
and receives an apdu."""
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)") | python | def segmented_request(self, apdu):
"""This function is called when the client is sending a segmented request
and receives an apdu."""
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",
")",
":",
"if",
"_debug",
":",
"ClientSSM",
".",
"_debug",
"(",
"\"segmented_request %r\"",
",",
"apdu",
")",
"# server is ready for the next segment",
"if",
"apdu",
".",
"apduType",
"==",
"SegmentAckPDU",
".",... | This function is called when the client is sending a segmented request
and receives an apdu. | [
"This",
"function",
"is",
"called",
"when",
"the",
"client",
"is",
"sending",
"a",
"segmented",
"request",
"and",
"receives",
"an",
"apdu",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L448-L523 | train | 201,913 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.set_state | def set_state(self, newState, timer=0):
"""This function is called when the client wants to change state."""
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) | python | def set_state(self, newState, timer=0):
"""This function is called when the client wants to change state."""
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",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"set_state %r (%s) timer=%r\"",
",",
"newState",
",",
"SSM",
".",
"transactionLabels",
"[",
"newState",
"]",
",",
"t... | This function is called when the client wants to change state. | [
"This",
"function",
"is",
"called",
"when",
"the",
"client",
"wants",
"to",
"change",
"state",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L703-L718 | train | 201,914 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.request | def request(self, apdu):
"""This function is called by transaction functions to send
to the application."""
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) | python | def request(self, apdu):
"""This function is called by transaction functions to send
to the application."""
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",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"request %r\"",
",",
"apdu",
")",
"# make sure it has a good source and destination",
"apdu",
".",
"pduSource",
"=",
"self",
".",
"pdu_address",
"apdu",... | This function is called by transaction functions to send
to the application. | [
"This",
"function",
"is",
"called",
"by",
"transaction",
"functions",
"to",
"send",
"to",
"the",
"application",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L720-L730 | train | 201,915 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.indication | def indication(self, apdu):
"""This function is called for each downstream packet related to
the transaction."""
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") | python | def indication(self, apdu):
"""This function is called for each downstream packet related to
the transaction."""
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",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"apdu",
")",
"if",
"self",
".",
"state",
"==",
"IDLE",
":",
"self",
".",
"idle",
"(",
"apdu",
")",
"elif",
"self"... | This function is called for each downstream packet related to
the transaction. | [
"This",
"function",
"is",
"called",
"for",
"each",
"downstream",
"packet",
"related",
"to",
"the",
"transaction",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L732-L746 | train | 201,916 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.confirmation | def confirmation(self, apdu):
"""This function is called when the application has provided a response
and needs it to be sent to the client."""
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)") | python | def confirmation(self, apdu):
"""This function is called when the application has provided a response
and needs it to be sent to the client."""
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",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"confirmation %r\"",
",",
"apdu",
")",
"# check to see we are in the correct state",
"if",
"self",
".",
"state",
"!=",
"AWAIT_RESPONSE",
":",
"if",... | This function is called when the application has provided a response
and needs it to be sent to the client. | [
"This",
"function",
"is",
"called",
"when",
"the",
"application",
"has",
"provided",
"a",
"response",
"and",
"needs",
"it",
"to",
"be",
"sent",
"to",
"the",
"client",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L760-L856 | train | 201,917 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.process_task | 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."""
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") | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"process_task\"",
")",
"if",
"self",
".",
"state",
"==",
"SEGMENTED_REQUEST",
":",
"self",
".",
"segmented_request_timeout",
"(",
")",
"elif",
"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. | [
"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",
"t... | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L858-L877 | train | 201,918 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.abort | 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."""
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) | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"abort %r\"",
",",
"reason",
")",
"# change the state to aborted",
"self",
".",
"set_state",
"(",
"ABORTED",
")",
"# return an abort APDU",
"return",
... | This function is called when the application would like to abort the
transaction. There is no notification back to the application. | [
"This",
"function",
"is",
"called",
"when",
"the",
"application",
"would",
"like",
"to",
"abort",
"the",
"transaction",
".",
"There",
"is",
"no",
"notification",
"back",
"to",
"the",
"application",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L879-L888 | train | 201,919 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | ServerSSM.await_response_timeout | 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."""
if _debug: ServerSSM._debug("await_response_timeout")
abort = self.abort(AbortReason.serverTimeout)
self.request(abort) | python | 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."""
if _debug: ServerSSM._debug("await_response_timeout")
abort = self.abort(AbortReason.serverTimeout)
self.request(abort) | [
"def",
"await_response_timeout",
"(",
"self",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"await_response_timeout\"",
")",
"abort",
"=",
"self",
".",
"abort",
"(",
"AbortReason",
".",
"serverTimeout",
")",
"self",
".",
"request",
"(",
"... | 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. | [
"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",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L1071-L1078 | train | 201,920 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | StateMachineAccessPoint.get_next_invoke_id | def get_next_invoke_id(self, addr):
"""Called by clients to get an unused invoke ID."""
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 | python | def get_next_invoke_id(self, addr):
"""Called by clients to get an unused invoke ID."""
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",
")",
":",
"if",
"_debug",
":",
"StateMachineAccessPoint",
".",
"_debug",
"(",
"\"get_next_invoke_id\"",
")",
"initialID",
"=",
"self",
".",
"nextInvokeID",
"while",
"1",
":",
"invokeID",
"=",
"self",
".",
... | Called by clients to get an unused invoke ID. | [
"Called",
"by",
"clients",
"to",
"get",
"an",
"unused",
"invoke",
"ID",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L1173-L1192 | train | 201,921 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | StateMachineAccessPoint.sap_indication | def sap_indication(self, apdu):
"""This function is called when the application is requesting
a new transaction as a client."""
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)") | python | def sap_indication(self, apdu):
"""This function is called when the application is requesting
a new transaction as a client."""
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",
")",
":",
"if",
"_debug",
":",
"StateMachineAccessPoint",
".",
"_debug",
"(",
"\"sap_indication %r\"",
",",
"apdu",
")",
"# check device communication control",
"if",
"self",
".",
"dccEnableDisable",
"==",
"'enable'... | This function is called when the application is requesting
a new transaction as a client. | [
"This",
"function",
"is",
"called",
"when",
"the",
"application",
"is",
"requesting",
"a",
"new",
"transaction",
"as",
"a",
"client",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L1304-L1355 | train | 201,922 |
JoelBender/bacpypes | py25/bacpypes/appservice.py | StateMachineAccessPoint.sap_confirmation | 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."""
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)") | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"StateMachineAccessPoint",
".",
"_debug",
"(",
"\"sap_confirmation %r\"",
",",
"apdu",
")",
"if",
"isinstance",
"(",
"apdu",
",",
"SimpleAckPDU",
")",
"or",
"isinstance",
"(",
... | 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. | [
"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",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/appservice.py#L1357-L1378 | train | 201,923 |
JoelBender/bacpypes | py25/bacpypes/bvllservice.py | BTR.add_peer | def add_peer(self, peerAddr, networks=None):
"""Add a peer and optionally provide a list of the reachable networks."""
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 | python | def add_peer(self, peerAddr, networks=None):
"""Add a peer and optionally provide a list of the reachable networks."""
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",
")",
":",
"if",
"_debug",
":",
"BTR",
".",
"_debug",
"(",
"\"add_peer %r networks=%r\"",
",",
"peerAddr",
",",
"networks",
")",
"# see if this is already a peer",
"if",
"peerAddr",
... | Add a peer and optionally provide a list of the reachable networks. | [
"Add",
"a",
"peer",
"and",
"optionally",
"provide",
"a",
"list",
"of",
"the",
"reachable",
"networks",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvllservice.py#L233-L249 | train | 201,924 |
JoelBender/bacpypes | py25/bacpypes/bvllservice.py | BTR.delete_peer | def delete_peer(self, peerAddr):
"""Delete a peer."""
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] | python | def delete_peer(self, peerAddr):
"""Delete a peer."""
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",
")",
":",
"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 l... | Delete a peer. | [
"Delete",
"a",
"peer",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvllservice.py#L253-L263 | train | 201,925 |
JoelBender/bacpypes | py25/bacpypes/bvllservice.py | BIPForeign.register | def register(self, addr, ttl):
"""Initiate the process of registering with a BBMD."""
# 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) | python | def register(self, addr, ttl):
"""Initiate the process of registering with a BBMD."""
# 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",
")",
":",
"# 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",
... | Initiate the process of registering with a BBMD. | [
"Initiate",
"the",
"process",
"of",
"registering",
"with",
"a",
"BBMD",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvllservice.py#L635-L649 | train | 201,926 |
JoelBender/bacpypes | py25/bacpypes/bvllservice.py | BIPForeign.unregister | def unregister(self):
"""Drop the registration with a BBMD."""
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 | python | def unregister(self):
"""Drop the registration with a BBMD."""
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",
")",
":",
"pdu",
"=",
"RegisterForeignDevice",
"(",
"0",
")",
"pdu",
".",
"pduDestination",
"=",
"self",
".",
"bbmdAddress",
"# send it downstream",
"self",
".",
"request",
"(",
"pdu",
")",
"# change the status to unregistered",
... | Drop the registration with a BBMD. | [
"Drop",
"the",
"registration",
"with",
"a",
"BBMD",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvllservice.py#L651-L664 | train | 201,927 |
JoelBender/bacpypes | py25/bacpypes/bvllservice.py | BIPForeign.process_task | def process_task(self):
"""Called when the registration request should be sent to the BBMD."""
pdu = RegisterForeignDevice(self.bbmdTimeToLive)
pdu.pduDestination = self.bbmdAddress
# send it downstream
self.request(pdu) | python | def process_task(self):
"""Called when the registration request should be sent to the BBMD."""
pdu = RegisterForeignDevice(self.bbmdTimeToLive)
pdu.pduDestination = self.bbmdAddress
# send it downstream
self.request(pdu) | [
"def",
"process_task",
"(",
"self",
")",
":",
"pdu",
"=",
"RegisterForeignDevice",
"(",
"self",
".",
"bbmdTimeToLive",
")",
"pdu",
".",
"pduDestination",
"=",
"self",
".",
"bbmdAddress",
"# send it downstream",
"self",
".",
"request",
"(",
"pdu",
")"
] | Called when the registration request should be sent to the BBMD. | [
"Called",
"when",
"the",
"registration",
"request",
"should",
"be",
"sent",
"to",
"the",
"BBMD",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvllservice.py#L666-L672 | train | 201,928 |
JoelBender/bacpypes | py25/bacpypes/bvllservice.py | BIPBBMD.register_foreign_device | def register_foreign_device(self, addr, ttl):
"""Add a foreign device to the FDT."""
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 | python | def register_foreign_device(self, addr, ttl):
"""Add a foreign device to the FDT."""
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",
")",
":",
"if",
"_debug",
":",
"BIPBBMD",
".",
"_debug",
"(",
"\"register_foreign_device %r %r\"",
",",
"addr",
",",
"ttl",
")",
"# see if it is an address or make it one",
"if",
"isinstance",
... | Add a foreign device to the FDT. | [
"Add",
"a",
"foreign",
"device",
"to",
"the",
"FDT",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvllservice.py#L911-L935 | train | 201,929 |
JoelBender/bacpypes | py25/bacpypes/apdu.py | encode_max_segments_accepted | 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!"""
# 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,)) | python | 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!"""
# 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",
")",
":",
"# 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",
... | 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! | [
"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"... | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/apdu.py#L63-L79 | train | 201,930 |
JoelBender/bacpypes | py25/bacpypes/apdu.py | encode_max_apdu_length_accepted | def encode_max_apdu_length_accepted(arg):
"""Return the encoding of the highest encodable value less than the
value of the arg."""
for i in range(5, -1, -1):
if (arg >= _max_apdu_length_encoding[i]):
return i
raise ValueError("invalid max APDU length accepted: %r" % (arg,)) | python | def encode_max_apdu_length_accepted(arg):
"""Return the encoding of the highest encodable value less than the
value of the arg."""
for i in range(5, -1, -1):
if (arg >= _max_apdu_length_encoding[i]):
return i
raise ValueError("invalid max APDU length accepted: %r" % (arg,)) | [
"def",
"encode_max_apdu_length_accepted",
"(",
"arg",
")",
":",
"for",
"i",
"in",
"range",
"(",
"5",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"(",
"arg",
">=",
"_max_apdu_length_encoding",
"[",
"i",
"]",
")",
":",
"return",
"i",
"raise",
"ValueE... | Return the encoding of the highest encodable value less than the
value of the arg. | [
"Return",
"the",
"encoding",
"of",
"the",
"highest",
"encodable",
"value",
"less",
"than",
"the",
"value",
"of",
"the",
"arg",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/apdu.py#L93-L100 | train | 201,931 |
JoelBender/bacpypes | py25/bacpypes/apdu.py | APCI.encode | def encode(self, pdu):
"""encode the contents of the APCI into the PDU."""
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") | python | def encode(self, pdu):
"""encode the contents of the APCI into the PDU."""
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",
")",
":",
"if",
"_debug",
":",
"APCI",
".",
"_debug",
"(",
"\"encode %r\"",
",",
"pdu",
")",
"PCI",
".",
"update",
"(",
"pdu",
",",
"self",
")",
"if",
"(",
"self",
".",
"apduType",
"==",
"ConfirmedRequestPDU"... | encode the contents of the APCI into the PDU. | [
"encode",
"the",
"contents",
"of",
"the",
"APCI",
"into",
"the",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/apdu.py#L173-L251 | train | 201,932 |
JoelBender/bacpypes | py25/bacpypes/apdu.py | APCI.decode | def decode(self, pdu):
"""decode the contents of the PDU into the APCI."""
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") | python | def decode(self, pdu):
"""decode the contents of the PDU into the APCI."""
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",
")",
":",
"if",
"_debug",
":",
"APCI",
".",
"_debug",
"(",
"\"decode %r\"",
",",
"pdu",
")",
"PCI",
".",
"update",
"(",
"self",
",",
"pdu",
")",
"# decode the first octet",
"buff",
"=",
"pdu",
".",
"get",
"("... | decode the contents of the PDU into the APCI. | [
"decode",
"the",
"contents",
"of",
"the",
"PDU",
"into",
"the",
"APCI",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/apdu.py#L253-L320 | train | 201,933 |
JoelBender/bacpypes | py25/bacpypes/primitivedata.py | Tag.decode | def decode(self, pdu):
"""Decode a tag from the PDU."""
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") | python | def decode(self, pdu):
"""Decode a tag from the PDU."""
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",
")",
":",
"try",
":",
"tag",
"=",
"pdu",
".",
"get",
"(",
")",
"# extract the type",
"self",
".",
"tagClass",
"=",
"(",
"tag",
">>",
"3",
")",
"&",
"0x01",
"# extract the tag number",
"self",
".",
"tagNumber",
... | Decode a tag from the PDU. | [
"Decode",
"a",
"tag",
"from",
"the",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/primitivedata.py#L137-L173 | train | 201,934 |
JoelBender/bacpypes | py25/bacpypes/primitivedata.py | Tag.app_to_context | def app_to_context(self, context):
"""Return a context encoded tag."""
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) | python | def app_to_context(self, context):
"""Return a context encoded tag."""
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",
")",
":",
"if",
"self",
".",
"tagClass",
"!=",
"Tag",
".",
"applicationTagClass",
":",
"raise",
"ValueError",
"(",
"\"application tag required\"",
")",
"# application tagged boolean now has data",
"if",
"(",
"sel... | Return a context encoded tag. | [
"Return",
"a",
"context",
"encoded",
"tag",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/primitivedata.py#L175-L184 | train | 201,935 |
JoelBender/bacpypes | py25/bacpypes/primitivedata.py | Tag.context_to_app | def context_to_app(self, dataType):
"""Return an application encoded tag."""
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) | python | def context_to_app(self, dataType):
"""Return an application encoded tag."""
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",
")",
":",
"if",
"self",
".",
"tagClass",
"!=",
"Tag",
".",
"contextTagClass",
":",
"raise",
"ValueError",
"(",
"\"context tag required\"",
")",
"# context booleans have value in data",
"if",
"(",
"dataType",
"... | Return an application encoded tag. | [
"Return",
"an",
"application",
"encoded",
"tag",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/primitivedata.py#L186-L195 | train | 201,936 |
JoelBender/bacpypes | py25/bacpypes/bsll.py | BSLCI.encode | def encode(self, pdu):
"""encode the contents of the BSLCI into the PDU."""
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 ) | python | def encode(self, pdu):
"""encode the contents of the BSLCI into the PDU."""
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",
")",
":",
"if",
"_debug",
":",
"BSLCI",
".",
"_debug",
"(",
"\"encode %r\"",
",",
"pdu",
")",
"# copy the basics",
"PCI",
".",
"update",
"(",
"pdu",
",",
"self",
")",
"pdu",
".",
"put",
"(",
"self",
".",
"b... | encode the contents of the BSLCI into the PDU. | [
"encode",
"the",
"contents",
"of",
"the",
"BSLCI",
"into",
"the",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bsll.py#L108-L121 | train | 201,937 |
JoelBender/bacpypes | py25/bacpypes/bsll.py | BSLCI.decode | def decode(self, pdu):
"""decode the contents of the PDU into the BSLCI."""
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") | python | def decode(self, pdu):
"""decode the contents of the PDU into the BSLCI."""
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",
")",
":",
"if",
"_debug",
":",
"BSLCI",
".",
"_debug",
"(",
"\"decode %r\"",
",",
"pdu",
")",
"# copy the basics",
"PCI",
".",
"update",
"(",
"self",
",",
"pdu",
")",
"self",
".",
"bslciType",
"=",
"pdu",
"."... | decode the contents of the PDU into the BSLCI. | [
"decode",
"the",
"contents",
"of",
"the",
"PDU",
"into",
"the",
"BSLCI",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bsll.py#L123-L138 | train | 201,938 |
JoelBender/bacpypes | py25/bacpypes/consolelogging.py | ConsoleLogHandler | def ConsoleLogHandler(loggerRef='', handler=None, level=logging.DEBUG, color=None):
"""Add a handler to stderr with our custom formatter to a logger."""
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) | python | def ConsoleLogHandler(loggerRef='', handler=None, level=logging.DEBUG, color=None):
"""Add a handler to stderr with our custom formatter to a logger."""
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",
")",
":",
"if",
"isinstance",
"(",
"loggerRef",
",",
"logging",
".",
"Logger",
")",
":",
"pass"... | Add a handler to stderr with our custom formatter to a logger. | [
"Add",
"a",
"handler",
"to",
"stderr",
"with",
"our",
"custom",
"formatter",
"to",
"a",
"logger",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/consolelogging.py#L38-L76 | train | 201,939 |
JoelBender/bacpypes | samples/Tutorial/ControllerAndIOCB.py | call_me | def call_me(iocb):
"""
When a controller completes the processing of a request,
the IOCB can contain one or more functions to be called.
"""
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)) | python | def call_me(iocb):
"""
When a controller completes the processing of a request,
the IOCB can contain one or more functions to be called.
"""
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",
")",
":",
"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",
",",
... | When a controller completes the processing of a request,
the IOCB can contain one or more functions to be called. | [
"When",
"a",
"controller",
"completes",
"the",
"processing",
"of",
"a",
"request",
"the",
"IOCB",
"can",
"contain",
"one",
"or",
"more",
"functions",
"to",
"be",
"called",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/samples/Tutorial/ControllerAndIOCB.py#L35-L43 | train | 201,940 |
JoelBender/bacpypes | py34/bacpypes/object.py | get_object_class | def get_object_class(object_type, vendor_id=0):
"""Return the class associated with an object type."""
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 | python | def get_object_class(object_type, vendor_id=0):
"""Return the class associated with an object type."""
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",
")",
":",
"if",
"_debug",
":",
"get_object_class",
".",
"_debug",
"(",
"\"get_object_class %r vendor_id=%r\"",
",",
"object_type",
",",
"vendor_id",
")",
"# find the klass as given",
"cls",
"... | Return the class associated with an object type. | [
"Return",
"the",
"class",
"associated",
"with",
"an",
"object",
"type",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/object.py#L109-L122 | train | 201,941 |
JoelBender/bacpypes | py25/bacpypes/object.py | Object._attr_to_property | def _attr_to_property(self, attr):
"""Common routine to translate a python attribute name to a property name and
return the appropriate property."""
# get the property
prop = self._properties.get(attr)
if not prop:
raise PropertyError(attr)
# found it
return prop | python | def _attr_to_property(self, attr):
"""Common routine to translate a python attribute name to a property name and
return the appropriate property."""
# get the property
prop = self._properties.get(attr)
if not prop:
raise PropertyError(attr)
# found it
return prop | [
"def",
"_attr_to_property",
"(",
"self",
",",
"attr",
")",
":",
"# get the property",
"prop",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"attr",
")",
"if",
"not",
"prop",
":",
"raise",
"PropertyError",
"(",
"attr",
")",
"# found it",
"return",
"prop... | Common routine to translate a python attribute name to a property name and
return the appropriate property. | [
"Common",
"routine",
"to",
"translate",
"a",
"python",
"attribute",
"name",
"to",
"a",
"property",
"name",
"and",
"return",
"the",
"appropriate",
"property",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/object.py#L509-L519 | train | 201,942 |
JoelBender/bacpypes | py25/bacpypes/object.py | Object.add_property | 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."""
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 | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"Object",
".",
"_debug",
"(",
"\"add_property %r\"",
",",
"prop",
")",
"# make a copy of the properties dictionary",
"self",
".",
"_properties",
"=",
"_copy",
"(",
"self",
".",
"_p... | 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. | [
"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",
"... | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/object.py#L547-L559 | train | 201,943 |
JoelBender/bacpypes | py25/bacpypes/object.py | Object.delete_property | 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."""
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] | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"Object",
".",
"_debug",
"(",
"\"delete_property %r\"",
",",
"prop",
")",
"# make a copy of the properties dictionary",
"self",
".",
"_properties",
"=",
"_copy",
"(",
"self",
".",... | 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. | [
"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",
... | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/object.py#L561-L574 | train | 201,944 |
JoelBender/bacpypes | py25/bacpypes/object.py | Object.debug_contents | def debug_contents(self, indent=1, file=sys.stdout, _ids=None):
"""Print out interesting things about the object."""
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)) | python | def debug_contents(self, indent=1, file=sys.stdout, _ids=None):
"""Print out interesting things about the object."""
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",
")",
":",
"klasses",
"=",
"list",
"(",
"self",
".",
"__class__",
".",
"__mro__",
")",
"klasses",
".",
"reverse",
"(",
"... | Print out interesting things about the object. | [
"Print",
"out",
"interesting",
"things",
"about",
"the",
"object",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/object.py#L647-L686 | train | 201,945 |
JoelBender/bacpypes | py25/bacpypes/bvll.py | BVLCI.encode | def encode(self, pdu):
"""encode the contents of the BVLCI into the PDU."""
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 ) | python | def encode(self, pdu):
"""encode the contents of the BVLCI into the PDU."""
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",
")",
":",
"if",
"_debug",
":",
"BVLCI",
".",
"_debug",
"(",
"\"encode %s\"",
",",
"str",
"(",
"pdu",
")",
")",
"# copy the basics",
"PCI",
".",
"update",
"(",
"pdu",
",",
"self",
")",
"pdu",
".",
"put",
"("... | encode the contents of the BVLCI into the PDU. | [
"encode",
"the",
"contents",
"of",
"the",
"BVLCI",
"into",
"the",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvll.py#L57-L70 | train | 201,946 |
JoelBender/bacpypes | py25/bacpypes/bvll.py | BVLCI.decode | def decode(self, pdu):
"""decode the contents of the PDU into the BVLCI."""
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") | python | def decode(self, pdu):
"""decode the contents of the PDU into the BVLCI."""
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",
")",
":",
"if",
"_debug",
":",
"BVLCI",
".",
"_debug",
"(",
"\"decode %s\"",
",",
"str",
"(",
"pdu",
")",
")",
"# copy the basics",
"PCI",
".",
"update",
"(",
"self",
",",
"pdu",
")",
"self",
".",
"bvlciType"... | decode the contents of the PDU into the BVLCI. | [
"decode",
"the",
"contents",
"of",
"the",
"PDU",
"into",
"the",
"BVLCI",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bvll.py#L72-L87 | train | 201,947 |
JoelBender/bacpypes | py25/bacpypes/comm.py | Switch.indication | def indication(self, *args, **kwargs):
"""Downstream packet, send to current terminal."""
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) | python | def indication(self, *args, **kwargs):
"""Downstream packet, send to current terminal."""
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",
")",
":",
"if",
"not",
"self",
".",
"current_terminal",
":",
"raise",
"RuntimeError",
"(",
"\"no active terminal\"",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"current_ter... | Downstream packet, send to current terminal. | [
"Downstream",
"packet",
"send",
"to",
"current",
"terminal",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/comm.py#L472-L479 | train | 201,948 |
JoelBender/bacpypes | py25/bacpypes/comm.py | Switch.confirmation | def confirmation(self, *args, **kwargs):
"""Upstream packet, send to current terminal."""
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) | python | def confirmation(self, *args, **kwargs):
"""Upstream packet, send to current terminal."""
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",
")",
":",
"if",
"not",
"self",
".",
"current_terminal",
":",
"raise",
"RuntimeError",
"(",
"\"no active terminal\"",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"current_t... | Upstream packet, send to current terminal. | [
"Upstream",
"packet",
"send",
"to",
"current",
"terminal",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/comm.py#L481-L488 | train | 201,949 |
JoelBender/bacpypes | py25/bacpypes/service/object.py | ReadWritePropertyServices.do_ReadPropertyRequest | def do_ReadPropertyRequest(self, apdu):
"""Return the value of some property of one of our objects."""
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) | python | def do_ReadPropertyRequest(self, apdu):
"""Return the value of some property of one of our objects."""
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",
")",
":",
"if",
"_debug",
":",
"ReadWritePropertyServices",
".",
"_debug",
"(",
"\"do_ReadPropertyRequest %r\"",
",",
"apdu",
")",
"# extract the object identifier",
"objId",
"=",
"apdu",
".",
"objectIdentifie... | Return the value of some property of one of our objects. | [
"Return",
"the",
"value",
"of",
"some",
"property",
"of",
"one",
"of",
"our",
"objects",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/object.py#L33-L94 | train | 201,950 |
JoelBender/bacpypes | py25/bacpypes/service/object.py | ReadWritePropertyServices.do_WritePropertyRequest | def do_WritePropertyRequest(self, apdu):
"""Change the value of some property of one of our objects."""
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) | python | def do_WritePropertyRequest(self, apdu):
"""Change the value of some property of one of our objects."""
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",
")",
":",
"if",
"_debug",
":",
"ReadWritePropertyServices",
".",
"_debug",
"(",
"\"do_WritePropertyRequest %r\"",
",",
"apdu",
")",
"# get the object",
"obj",
"=",
"self",
".",
"get_object_id",
"(",
"apdu... | Change the value of some property of one of our objects. | [
"Change",
"the",
"value",
"of",
"some",
"property",
"of",
"one",
"of",
"our",
"objects",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/object.py#L96-L139 | train | 201,951 |
JoelBender/bacpypes | py25/bacpypes/service/object.py | ReadWritePropertyMultipleServices.do_ReadPropertyMultipleRequest | def do_ReadPropertyMultipleRequest(self, apdu):
"""Respond to a ReadPropertyMultiple Request."""
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) | python | def do_ReadPropertyMultipleRequest(self, apdu):
"""Respond to a ReadPropertyMultiple Request."""
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",
")",
":",
"if",
"_debug",
":",
"ReadWritePropertyMultipleServices",
".",
"_debug",
"(",
"\"do_ReadPropertyMultipleRequest %r\"",
",",
"apdu",
")",
"# response is a list of read access results (or an error)",
"... | Respond to a ReadPropertyMultiple Request. | [
"Respond",
"to",
"a",
"ReadPropertyMultiple",
"Request",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/object.py#L238-L338 | train | 201,952 |
JoelBender/bacpypes | py25/bacpypes/udp.py | UDPDirector.handle_write | def handle_write(self):
"""get a PDU from the queue and send it."""
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) | python | def handle_write(self):
"""get a PDU from the queue and send it."""
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",
")",
":",
"if",
"_debug",
":",
"UDPDirector",
".",
"_debug",
"(",
"\"handle_write\"",
")",
"try",
":",
"pdu",
"=",
"self",
".",
"request",
".",
"get",
"(",
")",
"sent",
"=",
"self",
".",
"socket",
".",
"sendto",
"(... | get a PDU from the queue and send it. | [
"get",
"a",
"PDU",
"from",
"the",
"queue",
"and",
"send",
"it",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/udp.py#L229-L249 | train | 201,953 |
JoelBender/bacpypes | py25/bacpypes/udp.py | UDPDirector.indication | def indication(self, pdu):
"""Client requests are queued for delivery."""
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) | python | def indication(self, pdu):
"""Client requests are queued for delivery."""
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",
")",
":",
"if",
"_debug",
":",
"UDPDirector",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"pdu",
")",
"# get the destination",
"addr",
"=",
"pdu",
".",
"pduDestination",
"# get the peer",
"peer",
"=",
"self",
"... | Client requests are queued for delivery. | [
"Client",
"requests",
"are",
"queued",
"for",
"delivery",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/udp.py#L270-L283 | train | 201,954 |
JoelBender/bacpypes | py25/bacpypes/udp.py | UDPDirector._response | def _response(self, pdu):
"""Incoming datagrams are routed through an actor."""
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) | python | def _response(self, pdu):
"""Incoming datagrams are routed through an actor."""
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",
")",
":",
"if",
"_debug",
":",
"UDPDirector",
".",
"_debug",
"(",
"\"_response %r\"",
",",
"pdu",
")",
"# get the destination",
"addr",
"=",
"pdu",
".",
"pduSource",
"# get the peer",
"peer",
"=",
"self",
".",
"... | Incoming datagrams are routed through an actor. | [
"Incoming",
"datagrams",
"are",
"routed",
"through",
"an",
"actor",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/udp.py#L285-L298 | train | 201,955 |
JoelBender/bacpypes | py25/bacpypes/service/cov.py | ChangeOfValueServices.subscriptions | def subscriptions(self):
"""Generator for the active subscriptions."""
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 | python | def subscriptions(self):
"""Generator for the active subscriptions."""
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",
")",
":",
"if",
"_debug",
":",
"ChangeOfValueServices",
".",
"_debug",
"(",
"\"subscriptions\"",
")",
"subscription_list",
"=",
"[",
"]",
"# loop through the object and detection list",
"for",
"obj",
",",
"cov_detection",
"in",
"... | Generator for the active subscriptions. | [
"Generator",
"for",
"the",
"active",
"subscriptions",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/service/cov.py#L623-L634 | train | 201,956 |
JoelBender/bacpypes | py27/bacpypes/comm.py | bind | def bind(*args):
"""bind a list of clients and servers together, top down."""
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") | python | def bind(*args):
"""bind a list of clients and servers together, top down."""
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",
")",
":",
"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"... | bind a list of clients and servers together, top down. | [
"bind",
"a",
"list",
"of",
"clients",
"and",
"servers",
"together",
"top",
"down",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py27/bacpypes/comm.py#L613-L690 | train | 201,957 |
JoelBender/bacpypes | py25/bacpypes/npdu.py | NPCI.encode | def encode(self, pdu):
"""encode the contents of the NPCI into the PDU."""
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) | python | def encode(self, pdu):
"""encode the contents of the NPCI into the PDU."""
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",
")",
":",
"if",
"_debug",
":",
"NPCI",
".",
"_debug",
"(",
"\"encode %s\"",
",",
"repr",
"(",
"pdu",
")",
")",
"PCI",
".",
"update",
"(",
"pdu",
",",
"self",
")",
"# only version 1 messages supported",
"pdu",
"... | encode the contents of the NPCI into the PDU. | [
"encode",
"the",
"contents",
"of",
"the",
"NPCI",
"into",
"the",
"PDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/npdu.py#L75-L140 | train | 201,958 |
JoelBender/bacpypes | py25/bacpypes/npdu.py | NPCI.decode | def decode(self, pdu):
"""decode the contents of the PDU and put them into the NPDU."""
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 | python | def decode(self, pdu):
"""decode the contents of the PDU and put them into the NPDU."""
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",
")",
":",
"if",
"_debug",
":",
"NPCI",
".",
"_debug",
"(",
"\"decode %s\"",
",",
"str",
"(",
"pdu",
")",
")",
"PCI",
".",
"update",
"(",
"self",
",",
"pdu",
")",
"# check the length",
"if",
"len",
"(",
"pdu... | decode the contents of the PDU and put them into the NPDU. | [
"decode",
"the",
"contents",
"of",
"the",
"PDU",
"and",
"put",
"them",
"into",
"the",
"NPDU",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/npdu.py#L142-L203 | train | 201,959 |
JoelBender/bacpypes | py25/bacpypes/tcp.py | TCPClientDirector.del_actor | def del_actor(self, actor):
"""Remove an actor when the socket is closed."""
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]) | python | def del_actor(self, actor):
"""Remove an actor when the socket is closed."""
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",
")",
":",
"if",
"_debug",
":",
"TCPClientDirector",
".",
"_debug",
"(",
"\"del_actor %r\"",
",",
"actor",
")",
"del",
"self",
".",
"clients",
"[",
"actor",
".",
"peer",
"]",
"# tell the ASE the client has gone awa... | Remove an actor when the socket is closed. | [
"Remove",
"an",
"actor",
"when",
"the",
"socket",
"is",
"closed",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/tcp.py#L386-L399 | train | 201,960 |
JoelBender/bacpypes | py25/bacpypes/tcp.py | TCPClientDirector.indication | def indication(self, pdu):
"""Direct this PDU to the appropriate server, create a
connection if one hasn't already been created."""
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) | python | def indication(self, pdu):
"""Direct this PDU to the appropriate server, create a
connection if one hasn't already been created."""
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",
")",
":",
"if",
"_debug",
":",
"TCPClientDirector",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"pdu",
")",
"# get the destination",
"addr",
"=",
"pdu",
".",
"pduDestination",
"# get the client",
"client",
"=",
"... | Direct this PDU to the appropriate server, create a
connection if one hasn't already been created. | [
"Direct",
"this",
"PDU",
"to",
"the",
"appropriate",
"server",
"create",
"a",
"connection",
"if",
"one",
"hasn",
"t",
"already",
"been",
"created",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/tcp.py#L437-L451 | train | 201,961 |
JoelBender/bacpypes | py25/bacpypes/tcp.py | TCPServerDirector.indication | def indication(self, pdu):
"""Direct this PDU to the appropriate server."""
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) | python | def indication(self, pdu):
"""Direct this PDU to the appropriate server."""
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",
")",
":",
"if",
"_debug",
":",
"TCPServerDirector",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"pdu",
")",
"# get the destination",
"addr",
"=",
"pdu",
".",
"pduDestination",
"# get the server",
"server",
"=",
"... | Direct this PDU to the appropriate server. | [
"Direct",
"this",
"PDU",
"to",
"the",
"appropriate",
"server",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/tcp.py#L777-L790 | train | 201,962 |
JoelBender/bacpypes | py25/bacpypes/tcp.py | StreamToPacket.indication | def indication(self, pdu):
"""Message going downstream."""
if _debug: StreamToPacket._debug("indication %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.downstreamBuffer):
self.request(packet) | python | def indication(self, pdu):
"""Message going downstream."""
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",
")",
":",
"if",
"_debug",
":",
"StreamToPacket",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"pdu",
")",
"# hack it up into chunks",
"for",
"packet",
"in",
"self",
".",
"packetize",
"(",
"pdu",
",",
"self",
"... | Message going downstream. | [
"Message",
"going",
"downstream",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/tcp.py#L847-L853 | train | 201,963 |
JoelBender/bacpypes | py25/bacpypes/tcp.py | StreamToPacket.confirmation | def confirmation(self, pdu):
"""Message going upstream."""
if _debug: StreamToPacket._debug("StreamToPacket.confirmation %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.upstreamBuffer):
self.response(packet) | python | def confirmation(self, pdu):
"""Message going upstream."""
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",
")",
":",
"if",
"_debug",
":",
"StreamToPacket",
".",
"_debug",
"(",
"\"StreamToPacket.confirmation %r\"",
",",
"pdu",
")",
"# hack it up into chunks",
"for",
"packet",
"in",
"self",
".",
"packetize",
"(",
"pdu",
... | Message going upstream. | [
"Message",
"going",
"upstream",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/tcp.py#L855-L861 | train | 201,964 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOCB.add_callback | def add_callback(self, fn, *args, **kwargs):
"""Pass a function to be called when IO is complete."""
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() | python | def add_callback(self, fn, *args, **kwargs):
"""Pass a function to be called when IO is complete."""
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",
")",
":",
"if",
"_debug",
":",
"IOCB",
".",
"_debug",
"(",
"\"add_callback(%d) %r %r %r\"",
",",
"self",
".",
"ioID",
",",
"fn",
",",
"args",
",",
"kwargs",
")"... | Pass a function to be called when IO is complete. | [
"Pass",
"a",
"function",
"to",
"be",
"called",
"when",
"IO",
"is",
"complete",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L132-L141 | train | 201,965 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOCB.wait | def wait(self, *args, **kwargs):
"""Wait for the completion event to be set."""
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) | python | def wait(self, *args, **kwargs):
"""Wait for the completion event to be set."""
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",
")",
":",
"if",
"_debug",
":",
"IOCB",
".",
"_debug",
"(",
"\"wait(%d) %r %r\"",
",",
"self",
".",
"ioID",
",",
"args",
",",
"kwargs",
")",
"# waiting from a non-daemon thread could be ... | Wait for the completion event to be set. | [
"Wait",
"for",
"the",
"completion",
"event",
"to",
"be",
"set",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L143-L148 | train | 201,966 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOCB.complete | def complete(self, msg):
"""Called to complete a transaction, usually when ProcessIO has
shipped the IOCB off to some other thread or function."""
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() | python | def complete(self, msg):
"""Called to complete a transaction, usually when ProcessIO has
shipped the IOCB off to some other thread or function."""
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",
")",
":",
"if",
"_debug",
":",
"IOCB",
".",
"_debug",
"(",
"\"complete(%d) %r\"",
",",
"self",
".",
"ioID",
",",
"msg",
")",
"if",
"self",
".",
"ioController",
":",
"# pass to controller",
"self",
".",
"ioContr... | Called to complete a transaction, usually when ProcessIO has
shipped the IOCB off to some other thread or function. | [
"Called",
"to",
"complete",
"a",
"transaction",
"usually",
"when",
"ProcessIO",
"has",
"shipped",
"the",
"IOCB",
"off",
"to",
"some",
"other",
"thread",
"or",
"function",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L173-L185 | train | 201,967 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOCB.abort | def abort(self, err):
"""Called by a client to abort a transaction."""
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() | python | def abort(self, err):
"""Called by a client to abort a transaction."""
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",
")",
":",
"if",
"_debug",
":",
"IOCB",
".",
"_debug",
"(",
"\"abort(%d) %r\"",
",",
"self",
".",
"ioID",
",",
"err",
")",
"if",
"self",
".",
"ioController",
":",
"# pass to controller",
"self",
".",
"ioController"... | Called by a client to abort a transaction. | [
"Called",
"by",
"a",
"client",
"to",
"abort",
"a",
"transaction",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L187-L198 | train | 201,968 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOCB.set_timeout | def set_timeout(self, delay, err=TimeoutError):
"""Called to set a transaction timer."""
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) | python | def set_timeout(self, delay, err=TimeoutError):
"""Called to set a transaction timer."""
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",
")",
":",
"if",
"_debug",
":",
"IOCB",
".",
"_debug",
"(",
"\"set_timeout(%d) %r err=%r\"",
",",
"self",
".",
"ioID",
",",
"delay",
",",
"err",
")",
"# if one has already been ... | Called to set a transaction timer. | [
"Called",
"to",
"set",
"a",
"transaction",
"timer",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L200-L211 | train | 201,969 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOChainMixIn.chain_callback | def chain_callback(self, iocb):
"""Callback when this iocb completes."""
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() | python | def chain_callback(self, iocb):
"""Callback when this iocb completes."""
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",
")",
":",
"if",
"_debug",
":",
"IOChainMixIn",
".",
"_debug",
"(",
"\"chain_callback %r\"",
",",
"iocb",
")",
"# if we're not chained, there's no notification to do",
"if",
"not",
"self",
".",
"ioChain",
":",
"ret... | Callback when this iocb completes. | [
"Callback",
"when",
"this",
"iocb",
"completes",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L265-L296 | train | 201,970 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOChainMixIn.abort_io | def abort_io(self, iocb, err):
"""Forward the abort downstream."""
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) | python | def abort_io(self, iocb, err):
"""Forward the abort downstream."""
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",
")",
":",
"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... | Forward the abort downstream. | [
"Forward",
"the",
"abort",
"downstream",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L298-L309 | train | 201,971 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOChainMixIn.decode | def decode(self):
"""Hook to transform the response, called when this IOCB is
completed."""
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,)) | python | def decode(self):
"""Hook to transform the response, called when this IOCB is
completed."""
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",
")",
":",
"if",
"_debug",
":",
"IOChainMixIn",
".",
"_debug",
"(",
"\"decode\"",
")",
"# refer to the chained iocb",
"iocb",
"=",
"self",
".",
"ioChain",
"# if this has completed successfully, pass it up",
"if",
"self",
".",
"ioState",
... | Hook to transform the response, called when this IOCB is
completed. | [
"Hook",
"to",
"transform",
"the",
"response",
"called",
"when",
"this",
"IOCB",
"is",
"completed",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L318-L343 | train | 201,972 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOGroup.add | def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
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) | python | def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
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",
")",
":",
"if",
"_debug",
":",
"IOGroup",
".",
"_debug",
"(",
"\"add %r\"",
",",
"iocb",
")",
"# add this to our members",
"self",
".",
"ioMembers",
".",
"append",
"(",
"iocb",
")",
"# assume all of our members have not ... | Add an IOCB to the group, you can also add other groups. | [
"Add",
"an",
"IOCB",
"to",
"the",
"group",
"you",
"can",
"also",
"add",
"other",
"groups",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L385-L398 | train | 201,973 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOGroup.group_callback | def group_callback(self, iocb):
"""Callback when a child iocb completes."""
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() | python | def group_callback(self, iocb):
"""Callback when a child iocb completes."""
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",
")",
":",
"if",
"_debug",
":",
"IOGroup",
".",
"_debug",
"(",
"\"group_callback %r\"",
",",
"iocb",
")",
"# check all the members",
"for",
"iocb",
"in",
"self",
".",
"ioMembers",
":",
"if",
"not",
"iocb",
... | Callback when a child iocb completes. | [
"Callback",
"when",
"a",
"child",
"iocb",
"completes",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L400-L413 | train | 201,974 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOGroup.abort | 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."""
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() | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"IOGroup",
".",
"_debug",
"(",
"\"abort %r\"",
",",
"err",
")",
"# change the state to reflect that it was killed",
"self",
".",
"ioState",
"=",
"ABORTED",
"self",
".",
"ioError",
"=",
"... | 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. | [
"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",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L415-L430 | train | 201,975 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOQueue.put | 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."""
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 | python | 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."""
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",
")",
":",
"if",
"_debug",
":",
"IOQueue",
".",
"_debug",
"(",
"\"put %r\"",
",",
"iocb",
")",
"# requests should be pending before being queued",
"if",
"iocb",
".",
"ioState",
"!=",
"PENDING",
":",
"raise",
"RuntimeError... | 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. | [
"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",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L448-L472 | train | 201,976 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOQueue.get | def get(self, block=1, delay=None):
"""Get a request from a queue, optionally block until a request
is available."""
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 | python | def get(self, block=1, delay=None):
"""Get a request from a queue, optionally block until a request
is available."""
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",
")",
":",
"if",
"_debug",
":",
"IOQueue",
".",
"_debug",
"(",
"\"get block=%r delay=%r\"",
",",
"block",
",",
"delay",
")",
"# if the queue is empty and we do not block return None",
... | Get a request from a queue, optionally block until a request
is available. | [
"Get",
"a",
"request",
"from",
"a",
"queue",
"optionally",
"block",
"until",
"a",
"request",
"is",
"available",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L474-L503 | train | 201,977 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOQueue.abort | def abort(self, err):
"""Abort all of the control blocks in the queue."""
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 | python | def abort(self, err):
"""Abort all of the control blocks in the queue."""
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",
")",
":",
"if",
"_debug",
":",
"IOQueue",
".",
"_debug",
"(",
"\"abort %r\"",
",",
"err",
")",
"# send aborts to all of the members",
"try",
":",
"for",
"iocb",
"in",
"self",
".",
"queue",
":",
"iocb",
".",
"ioQue... | Abort all of the control blocks in the queue. | [
"Abort",
"all",
"of",
"the",
"control",
"blocks",
"in",
"the",
"queue",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L527-L543 | train | 201,978 |
JoelBender/bacpypes | py25/bacpypes/iocb.py | IOQController.abort | def abort(self, err):
"""Abort all pending requests."""
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") | python | def abort(self, err):
"""Abort all pending requests."""
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",
")",
":",
"if",
"_debug",
":",
"IOQController",
".",
"_debug",
"(",
"\"abort %r\"",
",",
"err",
")",
"if",
"(",
"self",
".",
"state",
"==",
"CTRL_IDLE",
")",
":",
"if",
"_debug",
":",
"IOQController",
".",
"_d... | Abort all pending requests. | [
"Abort",
"all",
"pending",
"requests",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L674-L696 | train | 201,979 |
JoelBender/bacpypes | py25/bacpypes/bsllservice.py | RouterToRouterService.connect | def connect(self, addr):
"""Initiate a connection request to the peer router."""
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 | python | def connect(self, addr):
"""Initiate a connection request to the peer router."""
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",
")",
":",
"if",
"_debug",
":",
"RouterToRouterService",
".",
"_debug",
"(",
"\"connect %r\"",
",",
"addr",
")",
"# make a connection",
"conn",
"=",
"ConnectionState",
"(",
"addr",
")",
"self",
".",
"multiplexer",
"... | Initiate a connection request to the peer router. | [
"Initiate",
"a",
"connection",
"request",
"to",
"the",
"peer",
"router",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bsllservice.py#L1041-L1063 | train | 201,980 |
JoelBender/bacpypes | py25/bacpypes/bsllservice.py | ProxyServiceNetworkAdapter.process_npdu | def process_npdu(self, npdu):
"""encode NPDUs from the network service access point and send them to the proxy."""
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) | python | def process_npdu(self, npdu):
"""encode NPDUs from the network service access point and send them to the proxy."""
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",
")",
":",
"if",
"_debug",
":",
"ProxyServiceNetworkAdapter",
".",
"_debug",
"(",
"\"process_npdu %r\"",
",",
"npdu",
")",
"# encode the npdu as if it was about to be delivered to the network",
"pdu",
"=",
"PDU",
"(",
")... | encode NPDUs from the network service access point and send them to the proxy. | [
"encode",
"NPDUs",
"from",
"the",
"network",
"service",
"access",
"point",
"and",
"send",
"them",
"to",
"the",
"proxy",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bsllservice.py#L1129-L1148 | train | 201,981 |
JoelBender/bacpypes | py25/bacpypes/bsllservice.py | ProxyServiceNetworkAdapter.service_confirmation | def service_confirmation(self, bslpdu):
"""Receive packets forwarded by the proxy and send them upstream to the network service access point."""
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) | python | def service_confirmation(self, bslpdu):
"""Receive packets forwarded by the proxy and send them upstream to the network service access point."""
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",
")",
":",
"if",
"_debug",
":",
"ProxyServiceNetworkAdapter",
".",
"_debug",
"(",
"\"service_confirmation %r\"",
",",
"bslpdu",
")",
"# build a PDU",
"pdu",
"=",
"NPDU",
"(",
"bslpdu",
".",
"pduData",
")"... | Receive packets forwarded by the proxy and send them upstream to the network service access point. | [
"Receive",
"packets",
"forwarded",
"by",
"the",
"proxy",
"and",
"send",
"them",
"upstream",
"to",
"the",
"network",
"service",
"access",
"point",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bsllservice.py#L1150-L1171 | train | 201,982 |
JoelBender/bacpypes | py25/bacpypes/bsllservice.py | ProxyServerService.service_confirmation | def service_confirmation(self, conn, bslpdu):
"""Receive packets forwarded by the proxy and redirect them to the proxy network adapter."""
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) | python | def service_confirmation(self, conn, bslpdu):
"""Receive packets forwarded by the proxy and redirect them to the proxy network adapter."""
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",
")",
":",
"if",
"_debug",
":",
"ProxyServerService",
".",
"_debug",
"(",
"\"service_confirmation %r %r\"",
",",
"conn",
",",
"bslpdu",
")",
"# make sure there is an adapter for it - or something wen... | Receive packets forwarded by the proxy and redirect them to the proxy network adapter. | [
"Receive",
"packets",
"forwarded",
"by",
"the",
"proxy",
"and",
"redirect",
"them",
"to",
"the",
"proxy",
"network",
"adapter",
"."
] | 4111b8604a16fa2b7f80d8104a43b9f3e28dfc78 | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/bsllservice.py#L1209-L1218 | train | 201,983 |
jleclanche/fireplace | fireplace/player.py | Player.get_spell_damage | def get_spell_damage(self, amount: int) -> int:
"""
Returns the amount of damage \a amount will do, taking
SPELLPOWER and SPELLPOWER_DOUBLE into account.
"""
amount += self.spellpower
amount <<= self.controller.spellpower_double
return amount | python | def get_spell_damage(self, amount: int) -> int:
"""
Returns the amount of damage \a amount will do, taking
SPELLPOWER and SPELLPOWER_DOUBLE into account.
"""
amount += self.spellpower
amount <<= self.controller.spellpower_double
return amount | [
"def",
"get_spell_damage",
"(",
"self",
",",
"amount",
":",
"int",
")",
"->",
"int",
":",
"amount",
"+=",
"self",
".",
"spellpower",
"amount",
"<<=",
"self",
".",
"controller",
".",
"spellpower_double",
"return",
"amount"
] | Returns the amount of damage \a amount will do, taking
SPELLPOWER and SPELLPOWER_DOUBLE into account. | [
"Returns",
"the",
"amount",
"of",
"damage",
"\\",
"a",
"amount",
"will",
"do",
"taking",
"SPELLPOWER",
"and",
"SPELLPOWER_DOUBLE",
"into",
"account",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/player.py#L168-L175 | train | 201,984 |
jleclanche/fireplace | fireplace/player.py | Player.can_pay_cost | def can_pay_cost(self, card):
"""
Returns whether the player can pay the resource cost of a card.
"""
if self.spells_cost_health and card.type == CardType.SPELL:
return self.hero.health > card.cost
return self.mana >= card.cost | python | def can_pay_cost(self, card):
"""
Returns whether the player can pay the resource cost of a card.
"""
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",
")",
":",
"if",
"self",
".",
"spells_cost_health",
"and",
"card",
".",
"type",
"==",
"CardType",
".",
"SPELL",
":",
"return",
"self",
".",
"hero",
".",
"health",
">",
"card",
".",
"cost",
"return",
"self... | Returns whether the player can pay the resource cost of a card. | [
"Returns",
"whether",
"the",
"player",
"can",
"pay",
"the",
"resource",
"cost",
"of",
"a",
"card",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/player.py#L184-L190 | train | 201,985 |
jleclanche/fireplace | fireplace/player.py | Player.pay_cost | def pay_cost(self, source, amount: int) -> int:
"""
Make player pay \a amount mana.
Returns how much mana is spent, after temporary mana adjustments.
"""
if self.spells_cost_health and source.type == CardType.SPELL:
self.log("%s spells cost %i health", self, amount)
self.game.queue_actions(self, [Hit(self.hero, amount)])
return amount
if self.temp_mana:
# Coin, Innervate etc
used_temp = min(self.temp_mana, amount)
amount -= used_temp
self.temp_mana -= used_temp
self.log("%s pays %i mana", self, amount)
self.used_mana += amount
return amount | python | def pay_cost(self, source, amount: int) -> int:
"""
Make player pay \a amount mana.
Returns how much mana is spent, after temporary mana adjustments.
"""
if self.spells_cost_health and source.type == CardType.SPELL:
self.log("%s spells cost %i health", self, amount)
self.game.queue_actions(self, [Hit(self.hero, amount)])
return amount
if self.temp_mana:
# Coin, Innervate etc
used_temp = min(self.temp_mana, amount)
amount -= used_temp
self.temp_mana -= used_temp
self.log("%s pays %i mana", self, amount)
self.used_mana += amount
return amount | [
"def",
"pay_cost",
"(",
"self",
",",
"source",
",",
"amount",
":",
"int",
")",
"->",
"int",
":",
"if",
"self",
".",
"spells_cost_health",
"and",
"source",
".",
"type",
"==",
"CardType",
".",
"SPELL",
":",
"self",
".",
"log",
"(",
"\"%s spells cost %i hea... | Make player pay \a amount mana.
Returns how much mana is spent, after temporary mana adjustments. | [
"Make",
"player",
"pay",
"\\",
"a",
"amount",
"mana",
".",
"Returns",
"how",
"much",
"mana",
"is",
"spent",
"after",
"temporary",
"mana",
"adjustments",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/player.py#L192-L208 | train | 201,986 |
jleclanche/fireplace | fireplace/player.py | Player.summon | def summon(self, card):
"""
Puts \a card in the PLAY zone
"""
if isinstance(card, str):
card = self.card(card, zone=Zone.PLAY)
self.game.cheat_action(self, [Summon(self, card)])
return card | python | def summon(self, card):
"""
Puts \a card in the PLAY zone
"""
if isinstance(card, str):
card = self.card(card, zone=Zone.PLAY)
self.game.cheat_action(self, [Summon(self, card)])
return card | [
"def",
"summon",
"(",
"self",
",",
"card",
")",
":",
"if",
"isinstance",
"(",
"card",
",",
"str",
")",
":",
"card",
"=",
"self",
".",
"card",
"(",
"card",
",",
"zone",
"=",
"Zone",
".",
"PLAY",
")",
"self",
".",
"game",
".",
"cheat_action",
"(",
... | Puts \a card in the PLAY zone | [
"Puts",
"\\",
"a",
"card",
"in",
"the",
"PLAY",
"zone"
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/player.py#L256-L263 | train | 201,987 |
jleclanche/fireplace | fireplace/entity.py | BaseEntity.get_damage | def get_damage(self, amount: int, target) -> int:
"""
Override to modify the damage dealt to a target from the given amount.
"""
if target.immune:
self.log("%r is immune to %s for %i damage", target, self, amount)
return 0
return amount | python | def get_damage(self, amount: int, target) -> int:
"""
Override to modify the damage dealt to a target from the given amount.
"""
if target.immune:
self.log("%r is immune to %s for %i damage", target, self, amount)
return 0
return amount | [
"def",
"get_damage",
"(",
"self",
",",
"amount",
":",
"int",
",",
"target",
")",
"->",
"int",
":",
"if",
"target",
".",
"immune",
":",
"self",
".",
"log",
"(",
"\"%r is immune to %s for %i damage\"",
",",
"target",
",",
"self",
",",
"amount",
")",
"retur... | Override to modify the damage dealt to a target from the given amount. | [
"Override",
"to",
"modify",
"the",
"damage",
"dealt",
"to",
"a",
"target",
"from",
"the",
"given",
"amount",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/entity.py#L79-L86 | train | 201,988 |
jleclanche/fireplace | fireplace/actions.py | Action.then | def then(self, *args):
"""
Create a callback containing an action queue, called upon the
action's trigger with the action's arguments available.
"""
ret = self.__class__(*self._args, **self._kwargs)
ret.callback = args
ret.times = self.times
return ret | python | def then(self, *args):
"""
Create a callback containing an action queue, called upon the
action's trigger with the action's arguments available.
"""
ret = self.__class__(*self._args, **self._kwargs)
ret.callback = args
ret.times = self.times
return ret | [
"def",
"then",
"(",
"self",
",",
"*",
"args",
")",
":",
"ret",
"=",
"self",
".",
"__class__",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")",
"ret",
".",
"callback",
"=",
"args",
"ret",
".",
"times",
"=",
"self",
"."... | Create a callback containing an action queue, called upon the
action's trigger with the action's arguments available. | [
"Create",
"a",
"callback",
"containing",
"an",
"action",
"queue",
"called",
"upon",
"the",
"action",
"s",
"trigger",
"with",
"the",
"action",
"s",
"arguments",
"available",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/actions.py#L121-L129 | train | 201,989 |
jleclanche/fireplace | fireplace/utils.py | random_draft | def random_draft(card_class: CardClass, exclude=[]):
"""
Return a deck of 30 random cards for the \a card_class
"""
from . import cards
from .deck import Deck
deck = []
collection = []
# hero = card_class.default_hero
for card in cards.db.keys():
if card in exclude:
continue
cls = cards.db[card]
if not cls.collectible:
continue
if cls.type == CardType.HERO:
# Heroes are collectible...
continue
if cls.card_class and cls.card_class not in [card_class, CardClass.NEUTRAL]:
# Play with more possibilities
continue
collection.append(cls)
while len(deck) < Deck.MAX_CARDS:
card = random.choice(collection)
if deck.count(card.id) < card.max_count_in_deck:
deck.append(card.id)
return deck | python | def random_draft(card_class: CardClass, exclude=[]):
"""
Return a deck of 30 random cards for the \a card_class
"""
from . import cards
from .deck import Deck
deck = []
collection = []
# hero = card_class.default_hero
for card in cards.db.keys():
if card in exclude:
continue
cls = cards.db[card]
if not cls.collectible:
continue
if cls.type == CardType.HERO:
# Heroes are collectible...
continue
if cls.card_class and cls.card_class not in [card_class, CardClass.NEUTRAL]:
# Play with more possibilities
continue
collection.append(cls)
while len(deck) < Deck.MAX_CARDS:
card = random.choice(collection)
if deck.count(card.id) < card.max_count_in_deck:
deck.append(card.id)
return deck | [
"def",
"random_draft",
"(",
"card_class",
":",
"CardClass",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"from",
".",
"import",
"cards",
"from",
".",
"deck",
"import",
"Deck",
"deck",
"=",
"[",
"]",
"collection",
"=",
"[",
"]",
"# hero = card_class.default_her... | Return a deck of 30 random cards for the \a card_class | [
"Return",
"a",
"deck",
"of",
"30",
"random",
"cards",
"for",
"the",
"\\",
"a",
"card_class"
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/utils.py#L66-L96 | train | 201,990 |
jleclanche/fireplace | fireplace/utils.py | get_script_definition | def get_script_definition(id):
"""
Find and return the script definition for card \a id
"""
for cardset in CARD_SETS:
module = import_module("fireplace.cards.%s" % (cardset))
if hasattr(module, id):
return getattr(module, id) | python | def get_script_definition(id):
"""
Find and return the script definition for card \a id
"""
for cardset in CARD_SETS:
module = import_module("fireplace.cards.%s" % (cardset))
if hasattr(module, id):
return getattr(module, id) | [
"def",
"get_script_definition",
"(",
"id",
")",
":",
"for",
"cardset",
"in",
"CARD_SETS",
":",
"module",
"=",
"import_module",
"(",
"\"fireplace.cards.%s\"",
"%",
"(",
"cardset",
")",
")",
"if",
"hasattr",
"(",
"module",
",",
"id",
")",
":",
"return",
"get... | Find and return the script definition for card \a id | [
"Find",
"and",
"return",
"the",
"script",
"definition",
"for",
"card",
"\\",
"a",
"id"
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/utils.py#L103-L110 | train | 201,991 |
jleclanche/fireplace | fireplace/game.py | BaseGame.check_for_end_game | def check_for_end_game(self):
"""
Check if one or more player is currently losing.
End the game if they are.
"""
gameover = False
for player in self.players:
if player.playstate in (PlayState.CONCEDED, PlayState.DISCONNECTED):
player.playstate = PlayState.LOSING
if player.playstate == PlayState.LOSING:
gameover = True
if gameover:
if self.players[0].playstate == self.players[1].playstate:
for player in self.players:
player.playstate = PlayState.TIED
else:
for player in self.players:
if player.playstate == PlayState.LOSING:
player.playstate = PlayState.LOST
else:
player.playstate = PlayState.WON
self.state = State.COMPLETE
self.manager.step(self.next_step, Step.FINAL_WRAPUP)
self.manager.step(self.next_step, Step.FINAL_GAMEOVER)
self.manager.step(self.next_step) | python | def check_for_end_game(self):
"""
Check if one or more player is currently losing.
End the game if they are.
"""
gameover = False
for player in self.players:
if player.playstate in (PlayState.CONCEDED, PlayState.DISCONNECTED):
player.playstate = PlayState.LOSING
if player.playstate == PlayState.LOSING:
gameover = True
if gameover:
if self.players[0].playstate == self.players[1].playstate:
for player in self.players:
player.playstate = PlayState.TIED
else:
for player in self.players:
if player.playstate == PlayState.LOSING:
player.playstate = PlayState.LOST
else:
player.playstate = PlayState.WON
self.state = State.COMPLETE
self.manager.step(self.next_step, Step.FINAL_WRAPUP)
self.manager.step(self.next_step, Step.FINAL_GAMEOVER)
self.manager.step(self.next_step) | [
"def",
"check_for_end_game",
"(",
"self",
")",
":",
"gameover",
"=",
"False",
"for",
"player",
"in",
"self",
".",
"players",
":",
"if",
"player",
".",
"playstate",
"in",
"(",
"PlayState",
".",
"CONCEDED",
",",
"PlayState",
".",
"DISCONNECTED",
")",
":",
... | Check if one or more player is currently losing.
End the game if they are. | [
"Check",
"if",
"one",
"or",
"more",
"player",
"is",
"currently",
"losing",
".",
"End",
"the",
"game",
"if",
"they",
"are",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/game.py#L166-L191 | train | 201,992 |
jleclanche/fireplace | fireplace/game.py | BaseGame.queue_actions | def queue_actions(self, source, actions, event_args=None):
"""
Queue a list of \a actions for processing from \a source.
Triggers an aura refresh afterwards.
"""
source.event_args = event_args
ret = self.trigger_actions(source, actions)
source.event_args = None
return ret | python | def queue_actions(self, source, actions, event_args=None):
"""
Queue a list of \a actions for processing from \a source.
Triggers an aura refresh afterwards.
"""
source.event_args = event_args
ret = self.trigger_actions(source, actions)
source.event_args = None
return ret | [
"def",
"queue_actions",
"(",
"self",
",",
"source",
",",
"actions",
",",
"event_args",
"=",
"None",
")",
":",
"source",
".",
"event_args",
"=",
"event_args",
"ret",
"=",
"self",
".",
"trigger_actions",
"(",
"source",
",",
"actions",
")",
"source",
".",
"... | Queue a list of \a actions for processing from \a source.
Triggers an aura refresh afterwards. | [
"Queue",
"a",
"list",
"of",
"\\",
"a",
"actions",
"for",
"processing",
"from",
"\\",
"a",
"source",
".",
"Triggers",
"an",
"aura",
"refresh",
"afterwards",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/game.py#L193-L201 | train | 201,993 |
jleclanche/fireplace | fireplace/game.py | BaseGame.trigger_actions | def trigger_actions(self, source, actions):
"""
Performs a list of `actions` from `source`.
This should seldom be called directly - use `queue_actions` instead.
"""
ret = []
for action in actions:
if isinstance(action, EventListener):
# Queuing an EventListener registers it as a one-time event
# This allows registering events from eg. play actions
self.log("Registering event listener %r on %r", action, self)
action.once = True
# FIXME: Figure out a cleaner way to get the event listener target
if source.type == CardType.SPELL:
listener = source.controller
else:
listener = source
listener._events.append(action)
else:
ret.append(action.trigger(source))
return ret | python | def trigger_actions(self, source, actions):
"""
Performs a list of `actions` from `source`.
This should seldom be called directly - use `queue_actions` instead.
"""
ret = []
for action in actions:
if isinstance(action, EventListener):
# Queuing an EventListener registers it as a one-time event
# This allows registering events from eg. play actions
self.log("Registering event listener %r on %r", action, self)
action.once = True
# FIXME: Figure out a cleaner way to get the event listener target
if source.type == CardType.SPELL:
listener = source.controller
else:
listener = source
listener._events.append(action)
else:
ret.append(action.trigger(source))
return ret | [
"def",
"trigger_actions",
"(",
"self",
",",
"source",
",",
"actions",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"action",
"in",
"actions",
":",
"if",
"isinstance",
"(",
"action",
",",
"EventListener",
")",
":",
"# Queuing an EventListener registers it as a one-time... | Performs a list of `actions` from `source`.
This should seldom be called directly - use `queue_actions` instead. | [
"Performs",
"a",
"list",
"of",
"actions",
"from",
"source",
".",
"This",
"should",
"seldom",
"be",
"called",
"directly",
"-",
"use",
"queue_actions",
"instead",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/game.py#L203-L223 | train | 201,994 |
jleclanche/fireplace | fireplace/dsl/evaluator.py | Evaluator.evaluate | def evaluate(self, source):
"""
Evaluates the board state from `source` and returns an iterable of
Actions as a result.
"""
ret = self.check(source)
if self._neg:
ret = not ret
if ret:
if self._if:
return self._if
elif self._else:
return self._else | python | def evaluate(self, source):
"""
Evaluates the board state from `source` and returns an iterable of
Actions as a result.
"""
ret = self.check(source)
if self._neg:
ret = not ret
if ret:
if self._if:
return self._if
elif self._else:
return self._else | [
"def",
"evaluate",
"(",
"self",
",",
"source",
")",
":",
"ret",
"=",
"self",
".",
"check",
"(",
"source",
")",
"if",
"self",
".",
"_neg",
":",
"ret",
"=",
"not",
"ret",
"if",
"ret",
":",
"if",
"self",
".",
"_if",
":",
"return",
"self",
".",
"_i... | Evaluates the board state from `source` and returns an iterable of
Actions as a result. | [
"Evaluates",
"the",
"board",
"state",
"from",
"source",
"and",
"returns",
"an",
"iterable",
"of",
"Actions",
"as",
"a",
"result",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/dsl/evaluator.py#L38-L50 | train | 201,995 |
jleclanche/fireplace | fireplace/dsl/evaluator.py | Evaluator.trigger | def trigger(self, source):
"""
Triggers all actions meant to trigger on the board state from `source`.
"""
actions = self.evaluate(source)
if actions:
if not hasattr(actions, "__iter__"):
actions = (actions, )
source.game.trigger_actions(source, actions) | python | def trigger(self, source):
"""
Triggers all actions meant to trigger on the board state from `source`.
"""
actions = self.evaluate(source)
if actions:
if not hasattr(actions, "__iter__"):
actions = (actions, )
source.game.trigger_actions(source, actions) | [
"def",
"trigger",
"(",
"self",
",",
"source",
")",
":",
"actions",
"=",
"self",
".",
"evaluate",
"(",
"source",
")",
"if",
"actions",
":",
"if",
"not",
"hasattr",
"(",
"actions",
",",
"\"__iter__\"",
")",
":",
"actions",
"=",
"(",
"actions",
",",
")"... | Triggers all actions meant to trigger on the board state from `source`. | [
"Triggers",
"all",
"actions",
"meant",
"to",
"trigger",
"on",
"the",
"board",
"state",
"from",
"source",
"."
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/dsl/evaluator.py#L52-L60 | train | 201,996 |
jleclanche/fireplace | fireplace/dsl/copy.py | Copy.copy | def copy(self, source, entity):
"""
Return a copy of \a entity
"""
log.info("Creating a copy of %r", entity)
return source.controller.card(entity.id, source) | python | def copy(self, source, entity):
"""
Return a copy of \a entity
"""
log.info("Creating a copy of %r", entity)
return source.controller.card(entity.id, source) | [
"def",
"copy",
"(",
"self",
",",
"source",
",",
"entity",
")",
":",
"log",
".",
"info",
"(",
"\"Creating a copy of %r\"",
",",
"entity",
")",
"return",
"source",
".",
"controller",
".",
"card",
"(",
"entity",
".",
"id",
",",
"source",
")"
] | Return a copy of \a entity | [
"Return",
"a",
"copy",
"of",
"\\",
"a",
"entity"
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/dsl/copy.py#L15-L20 | train | 201,997 |
jleclanche/fireplace | fireplace/dsl/random_picker.py | RandomCardPicker.find_cards | def find_cards(self, source=None, **filters):
"""
Generate a card pool with all cards matching specified filters
"""
if not filters:
new_filters = self.filters.copy()
else:
new_filters = filters.copy()
for k, v in new_filters.items():
if isinstance(v, LazyValue):
new_filters[k] = v.evaluate(source)
from .. import cards
return cards.filter(**new_filters) | python | def find_cards(self, source=None, **filters):
"""
Generate a card pool with all cards matching specified filters
"""
if not filters:
new_filters = self.filters.copy()
else:
new_filters = filters.copy()
for k, v in new_filters.items():
if isinstance(v, LazyValue):
new_filters[k] = v.evaluate(source)
from .. import cards
return cards.filter(**new_filters) | [
"def",
"find_cards",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"if",
"not",
"filters",
":",
"new_filters",
"=",
"self",
".",
"filters",
".",
"copy",
"(",
")",
"else",
":",
"new_filters",
"=",
"filters",
".",
"copy",... | Generate a card pool with all cards matching specified filters | [
"Generate",
"a",
"card",
"pool",
"with",
"all",
"cards",
"matching",
"specified",
"filters"
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/dsl/random_picker.py#L52-L66 | train | 201,998 |
jleclanche/fireplace | fireplace/dsl/random_picker.py | RandomCardPicker.evaluate | def evaluate(self, source, cards=None) -> str:
"""
This picks from a single combined card pool without replacement,
weighting each filtered set of cards against the total
"""
from ..utils import weighted_card_choice
if cards:
# Use specific card list if given
self.weights = [1]
card_sets = [list(cards)]
elif not self.weightedfilters:
# Use global filters if no weighted filter sets given
self.weights = [1]
card_sets = [self.find_cards(source)]
else:
# Otherwise find cards for each set of filters
# add the global filters to each set of filters
wf = [{**x, **self.filters} for x in self.weightedfilters]
card_sets = [self.find_cards(source, **x) for x in wf]
# get weighted sample of card pools
return weighted_card_choice(source, self.weights, card_sets, self.count) | python | def evaluate(self, source, cards=None) -> str:
"""
This picks from a single combined card pool without replacement,
weighting each filtered set of cards against the total
"""
from ..utils import weighted_card_choice
if cards:
# Use specific card list if given
self.weights = [1]
card_sets = [list(cards)]
elif not self.weightedfilters:
# Use global filters if no weighted filter sets given
self.weights = [1]
card_sets = [self.find_cards(source)]
else:
# Otherwise find cards for each set of filters
# add the global filters to each set of filters
wf = [{**x, **self.filters} for x in self.weightedfilters]
card_sets = [self.find_cards(source, **x) for x in wf]
# get weighted sample of card pools
return weighted_card_choice(source, self.weights, card_sets, self.count) | [
"def",
"evaluate",
"(",
"self",
",",
"source",
",",
"cards",
"=",
"None",
")",
"->",
"str",
":",
"from",
".",
".",
"utils",
"import",
"weighted_card_choice",
"if",
"cards",
":",
"# Use specific card list if given",
"self",
".",
"weights",
"=",
"[",
"1",
"]... | This picks from a single combined card pool without replacement,
weighting each filtered set of cards against the total | [
"This",
"picks",
"from",
"a",
"single",
"combined",
"card",
"pool",
"without",
"replacement",
"weighting",
"each",
"filtered",
"set",
"of",
"cards",
"against",
"the",
"total"
] | d0fc0e97e185c0210de86631be20638659c0609e | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/dsl/random_picker.py#L68-L90 | train | 201,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.