本文整理汇总了Python中pyndn.Interest.setInterestLifetimeMilliseconds方法的典型用法代码示例。如果您正苦于以下问题:Python Interest.setInterestLifetimeMilliseconds方法的具体用法?Python Interest.setInterestLifetimeMilliseconds怎么用?Python Interest.setInterestLifetimeMilliseconds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.Interest
的用法示例。
在下文中一共展示了Interest.setInterestLifetimeMilliseconds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _scanForUnconfiguredDevices
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def _scanForUnconfiguredDevices(self):
# unconfigured devices should register '/localhop/configure'
# we keep asking for unconfigured devices until we stop getting replies
foundDevices = []
self.ui.alert("Scanning for unconfigured devices...", False)
def onDeviceTimeout(interest):
# assume we're done - everyone is excluded
self.unconfiguredDevices = foundDevices
self.loop.call_soon(self._showConfigurationList)
def onDeviceResponse(interest, data):
updatedInterest = Interest(interest)
deviceSerial = str(data.getContent())
if len(deviceSerial) > 0:
foundDevices.append(deviceSerial)
updatedInterest.getExclude().appendComponent(Name.Component(deviceSerial))
# else ignore the malformed response
self.face.expressInterest(updatedInterest, onDeviceResponse, onDeviceTimeout)
interest = Interest(Name("/localhop/configure"))
interest.setInterestLifetimeMilliseconds(2000)
self.face.expressInterest(interest, onDeviceResponse, onDeviceTimeout)
示例2: requestCertificate
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def requestCertificate(self, keyIdentity):
"""
We compose a command interest with our public key info so the controller
can sign us a certificate that can be used with other nodes in the network.
Name format : /home/<device-category>/KEY/<device-id>/<key-id>/<publickey>/ID-CERT/<version-number>
"""
certificateRequestName = self._keyChain.getDefaultIdentity()
deviceIdComponent = certificateRequestName.get(-1)
keyIdComponent = keyIdentity.get(-1)
certificateRequestName = certificateRequestName
certificateRequestName.append("KEY")
#certificateRequestName.append(deviceIdComponent)
certificateRequestName.append(keyIdComponent)
key = self._identityManager.getPublicKey(keyIdentity)
keyInfo = {}
keyInfo["keyType"] = key.getKeyType()
keyInfo["keyDer"] = key.getKeyDer().toRawStr()
certificateRequestName.append(json.dumps(keyInfo, encoding="latin-1"))
certificateRequestName.append("ID-CERT")
certificateRequest = Interest(certificateRequestName)
certificateRequest.setInterestLifetimeMilliseconds(5000)
self._hmacHelper.signInterest(certificateRequest)
dump("Sending certificate request : ",certificateRequestName)
self.face.expressInterest(certificateRequest, self.onCertificateData, self.onTimeout)
示例3: main
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def main():
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
dataPrefix = "/home/test1/data"
repoDataPrefix = "/home/test1/data"
# Set up repo-ng, register prefix for repo-ng's fetch prefix
# Per configuration file in /usr/local/etc/ndn/repo-ng.conf
# memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd
#memCache = MemoryContentCache(face, 100000)
#memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound)
counter = Counter(face, repoDataPrefix)
interest = Interest(Name(dataPrefix))
interest.setChildSelector(1)
interest.setInterestLifetimeMilliseconds(defaultInterestLifetime)
face.expressInterest(interest, counter.onData, counter.onTimeout)
while True:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(1)
face.shutdown()
示例4: onHeartbeatTimeout
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def onHeartbeatTimeout(self, interest):
if self.incrementTimeoutCnt(interest.getName().toUri()):
print "Remove: " + interest.getName().toUri() + " because of consecutive timeout cnt exceeded"
else:
newInterest = Interest(interest.getName())
newInterest.setInterestLifetimeMilliseconds(4000)
self._face.expressInterest(newInterest, self.onHeartbeatData, self.onHeartbeatTimeout)
示例5: main
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def main():
# The default Face connects to the local NFD.
face = Face()
interest = Interest(Name("/localhost/nfd/rib/list"))
interest.setInterestLifetimeMilliseconds(4000)
dump("Express interest", interest.getName().toUri())
enabled = [True]
def onComplete(content):
enabled[0] = False
printRibEntries(content)
def onError(errorCode, message):
enabled[0] = False
dump(message)
SegmentFetcher.fetch(
face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError)
# Loop calling processEvents until a callback sets enabled[0] = False.
while enabled[0]:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
示例6: reissueInterest
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def reissueInterest(self):
BACKOFF_THRESHOLD = 10
if self.backoffCounter > BACKOFF_THRESHOLD:
self.TIMEOUT += 50
self.backoffCounter = 0
self.logger.debug('Backing off interval to ' + str(self.TIMEOUT))
if self.backoffCounter < -BACKOFF_THRESHOLD:
self.TIMEOUT -= 50
self.backoffCounter = 0
self.logger.debug('Reducing backoff interval to ' + str(self.TIMEOUT))
if self.nextIssue is not None:
now = time.clock()
if self.nextIssue > now:
pass
# time.sleep(self.nextIssue-now)
interest = Interest(Name(self.prefix))
interest.setInterestLifetimeMilliseconds(self.interestLifetime)
interest.setMustBeFresh(False)
if self.lastVersion is not None:
e = Exclude()
e.appendAny()
e.appendComponent(self.lastVersion)
interest.setExclude(e)
interest.setChildSelector(1) #rightmost == freshest
self.face.expressInterest(interest, self.onData, self.onTimeout)
self.nextIssue = time.clock()+self.TIMEOUT/2000
示例7: expressInterest
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def expressInterest(self, interestTemplate = None):
"""
Call expressInterest on this (or a parent's) Face where the interest
name is the name of this Namespace node. When the Data packet is
received this calls setData, so you should use a callback with
addOnContentSet. This uses ExponentialReExpress to re-express a timed-out
interest with longer lifetimes.
TODO: How to alert the application on a final interest timeout?
TODO: Replace this by a mechanism for requesting a Data object which is
more general than a Face network operation.
:raises RuntimeError: If a Face object has not been set for this or a
parent Namespace node.
:param Interest interestTemplate: (optional) The interest template for
expressInterest. If omitted, just use a default interest lifetime.
"""
face = self._getFace()
if face == None:
raise ValueError("A Face object has not been set for this or a parent.")
def onData(interest, data):
self[data.name].setData(data)
if interestTemplate == None:
interestTemplate = Interest()
interestTemplate.setInterestLifetimeMilliseconds(4000)
face.expressInterest(
self._name, interestTemplate, onData,
ExponentialReExpress.makeOnTimeout(face, onData, None))
示例8: _onData
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def _onData(self, interest, data):
"""
Process the incoming Chat data.
"""
# TODO: Check if this works in Python 3.
content = chatbuf_pb2.ChatMessage()
content.ParseFromString(data.getContent().toRawStr())
if self.getNowMilliseconds() - content.timestamp * 1000.0 < 120000.0:
# Use getattr because "from" is a reserved keyword.
name = getattr(content, "from")
prefix = data.getName().getPrefix(-2).toUri()
sessionNo = int(data.getName().get(-2).toEscapedString())
sequenceNo = int(data.getName().get(-1).toEscapedString())
nameAndSession = name + str(sessionNo)
l = 0
# Update roster.
while l < len(self._roster):
entry = self._roster[l]
tempName = entry[0:len(entry) - 10]
tempSessionNo = int(entry[len(entry) - 10:])
if (name != tempName and
content.type != chatbuf_pb2.ChatMessage.LEAVE):
l += 1
else:
if name == tempName and sessionNo > tempSessionNo:
self._roster[l] = nameAndSession
break
if l == len(self._roster):
self._roster.append(nameAndSession)
print(name + ": Join")
# Set the alive timeout using the Interest timeout mechanism.
# TODO: Are we sure using a "/local/timeout" interest is the best
# future call approach?
timeout = Interest(Name("/local/timeout"))
timeout.setInterestLifetimeMilliseconds(120000)
self._face.expressInterest(
timeout, self._dummyOnData,
self._makeAlive(sequenceNo, name, sessionNo, prefix))
# isRecoverySyncState_ was set by sendInterest.
# TODO: If isRecoverySyncState_ changed, this assumes that we won't get
# data from an interest sent before it changed.
# Use getattr because "from" is a reserved keyword.
if (content.type == chatbuf_pb2.ChatMessage.CHAT and
not self._isRecoverySyncState and
getattr(content, "from") != self._screenName):
print(getattr(content, "from") + ": " + content.data)
elif content.type == chatbuf_pb2.ChatMessage.LEAVE:
# leave message
try:
n = self._roster.index(nameAndSession)
if name != self._screenName:
self._roster.pop(n)
print(name + ": Leave")
except ValueError:
pass
示例9: main
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def main():
# Silence the warning from Interest wire encode.
Interest.setDefaultCanBePrefix(True)
# The default Face connects to the local NFD.
face = Face()
interest = Interest(Name("/localhost/nfd/faces/list"))
interest.setInterestLifetimeMilliseconds(4000)
dump("Express interest", interest.getName().toUri())
enabled = [True]
def onComplete(content):
enabled[0] = False
printFaceStatuses(content)
def onError(errorCode, message):
enabled[0] = False
dump(message)
SegmentFetcher.fetch(face, interest, None, onComplete, onError)
# Loop calling processEvents until a callback sets enabled[0] = False.
while enabled[0]:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
示例10: _sendCertificateRequest
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def _sendCertificateRequest(self, keyIdentity):
"""
We compose a command interest with our public key info so the controller
can sign us a certificate that can be used with other nodes in the network.
"""
try:
defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(keyIdentity)
except SecurityException:
defaultKey = self._identityManager.generateRSAKeyPairAsDefault(keyIdentity)
self.log.debug("Key name: " + defaultKey.toUri())
message = CertificateRequestMessage()
publicKey = self._identityManager.getPublicKey(defaultKey)
message.command.keyType = publicKey.getKeyType()
message.command.keyBits = publicKey.getKeyDer().toRawStr()
for component in range(defaultKey.size()):
message.command.keyName.components.append(defaultKey.get(component).toEscapedString())
paramComponent = ProtobufTlv.encode(message)
interestName = Name(self._policyManager.getTrustRootIdentity()).append("certificateRequest").append(paramComponent)
interest = Interest(interestName)
interest.setInterestLifetimeMilliseconds(10000) # takes a tick to verify and sign
self._hmacHandler.signInterest(interest, keyName=self.prefix)
self.log.info("Sending certificate request to controller")
self.log.debug("Certificate request: "+interest.getName().toUri())
self.face.expressInterest(interest, self._onCertificateReceived, self._onCertificateTimeout)
示例11: helper
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def helper(identityName, signerName):
try:
self._defaultIdentity = identityName
self._defaultCertificateName = self._identityManager.getDefaultCertificateNameForIdentity(self._defaultIdentity)
self._defaultKeyName = self._identityManager.getDefaultKeyNameForIdentity(identityName)
except SecurityException:
msg = "Identity " + identityName.toUri() + " in configuration does not exist. Please configure the device with this identity first."
if onSetupFailed:
onSetupFailed(msg)
return
if not self._defaultCertificateName:
msg = "Unable to get default certificate name for identity " + identityName.toUri() + ". Please configure the device with this identity first."
if onSetupFailed:
onSetupFailed(msg)
return
if not self._defaultKeyName:
msg = "Unable to get default key name for identity " + identityName.toUri() + ". Please configure the device with this identity first."
if onSetupFailed:
onSetupFailed(msg)
return
# Note we'll not be able to issue face commands before this point
self._face.setCommandSigningInfo(self._keyChain, self._defaultCertificateName)
# Serve our own certificate
self._certificateContentCache.registerPrefix(Name(self._defaultCertificateName).getPrefix(-1), self.onRegisterFailed)
self._certificateContentCache.add(self._keyChain.getCertificate(self._defaultCertificateName))
actualSignerName = self._keyChain.getCertificate(self._defaultCertificateName).getSignature().getKeyLocator().getKeyName()
if not signerName:
print "Deriving from " + actualSignerName.toUri() + " for controller name"
else:
if signerName and actualSignerName.toUri() != signerName.toUri():
msg = "Configuration signer names mismatch: expected " + signerName.toUri() + "; got " + actualSignerName.toUri()
print msg
if onSetupFailed:
onSetupFailed(msg)
self._controllerName = self.getIdentityNameFromCertName(actualSignerName)
print "Controller name: " + self._controllerName.toUri()
try:
self._controllerCertificate = self._keyChain.getCertificate(self._identityManager.getDefaultCertificateNameForIdentity(self._controllerName))
# TODO: this does not seem a good approach, implementation-wise and security implication
self._policyManager._certificateCache.insertCertificate(self._controllerCertificate)
if onSetupComplete:
onSetupComplete(Name(self._defaultCertificateName), self._keyChain)
except SecurityException as e:
print "don't have controller certificate " + actualSignerName.toUri() + " yet"
controllerCertInterest = Interest(Name(actualSignerName))
controllerCertInterest.setInterestLifetimeMilliseconds(4000)
controllerCertRetries = 3
self._face.expressInterest(controllerCertInterest,
lambda interest, data: self.onControllerCertData(interest, data, onSetupComplete, onSetupFailed),
lambda interest: self.onControllerCertTimeout(interest, onSetupComplete, onSetupFailed, controllerCertRetries))
return
示例12: startPublishingAggregation
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def startPublishingAggregation(self, params, childrenList, dataType, aggregationType):
if __debug__:
print('Start publishing for ' + dataType + '-' + aggregationType)
# aggregation calculating and publishing mechanism
publishingPrefix = Name(self._identityName).append(DATA_COMPONENT).append(dataType).append(AGGREGATION_COMPONENT).append(aggregationType)
self._dataQueue[dataType + aggregationType] = DataQueue(params, childrenList, publishingPrefix)
if len(childrenList.keys()) == 0:
# TODO: make start_time optional for leaf nodes
self._loop.call_later(int(params['producer_interval']), self.calculateAggregation, dataType, aggregationType, childrenList, int(params['start_time']), int(params['producer_interval']), publishingPrefix, True)
else:
# express interest for children who produce the same data and aggregation type
for childName in childrenList.keys():
name = Name(self._identityName).append(childName).append(DATA_COMPONENT).append(dataType).append(AGGREGATION_COMPONENT).append(aggregationType)
interest = Interest(name)
# if start_time is specified, we ask for data starting at start_time;
# if not, we ask for the right most child and go from there
if ('start_time' in childrenList[childName]):
endTime = int(childrenList[childName]['start_time']) + int(childrenList[childName]['producer_interval'])
interest.getName().append(str(childrenList[childName]['start_time'])).append(str(endTime))
else:
# TODO: For now we are playing with historical data, for each run we don't want to miss any data, thus we start with leftMost
interest.setChildSelector(0)
interest.setMustBeFresh(True)
interest.setInterestLifetimeMilliseconds(DEFAULT_INTEREST_LIFETIME)
if __debug__:
print(' Issue interest: ' + interest.getName().toUri())
self._face.expressInterest(interest, self.onData, self.onTimeout)
return
示例13: consume
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def consume(self, prefix, onVerified, onVerifyFailed, onTimeout):
"""
Consume data continuously under a given prefix, maintaining pipelineSize number of
interest in the pipeline
:param name: prefix to consume data under
:type name: Name
:param onData: onData(data) gets called after received data's onVerifyFailed
:type onData: function object
:param onVerifyFailed: onVerifyFailed(data) gets called if received data
cannot be verified
:type onVerifyFailed: function object
:param onTimeout: onTimeout(interest) gets called if a consumer interest times out
:type onTimeout: function object
"""
num = self._emptySlot
for i in range(0, num):
name = Name(prefix).append(str(self._currentSeqNumber))
interest = Interest(name)
# interest configuration / template?
interest.setInterestLifetimeMilliseconds(self._defaultInterestLifetime)
self._face.expressInterest(interest,
lambda i, d : self.onData(i, d, onVerified, onVerifyFailed, onTimeout),
lambda i: self.beforeReplyTimeout(i, onVerified, onVerifyFailed, onTimeout))
self._currentSeqNumber += 1
self._emptySlot -= 1
return
示例14: _updateCapabilities
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def _updateCapabilities(self):
"""
Send the controller a list of our commands.
"""
fullCommandName = Name(self._policyManager.getTrustRootIdentity()
).append('updateCapabilities')
capabilitiesMessage = UpdateCapabilitiesCommandMessage()
for command in self._commands:
commandName = Name(self.prefix).append(Name(command.suffix))
capability = capabilitiesMessage.capabilities.add()
for i in range(commandName.size()):
capability.commandPrefix.components.append(
str(commandName.get(i).getValue()))
for kw in command.keywords:
capability.keywords.append(kw)
capability.needsSignature = command.isSigned
encodedCapabilities = ProtobufTlv.encode(capabilitiesMessage)
fullCommandName.append(encodedCapabilities)
interest = Interest(fullCommandName)
interest.setInterestLifetimeMilliseconds(5000)
self.face.makeCommandInterest(interest)
signature = self._policyManager._extractSignature(interest)
self.log.info("Sending capabilities to controller")
self.face.expressInterest(interest, self._onCapabilitiesAck, self._onCapabilitiesTimeout)
# update twice a minute
self.loop.call_later(30, self._updateCapabilities)
示例15: consume
# 需要导入模块: from pyndn import Interest [as 别名]
# 或者: from pyndn.Interest import setInterestLifetimeMilliseconds [as 别名]
def consume(self, prefix, onVerified, onVerifyFailed, onTimeout):
"""
Consume data continuously under a given prefix, each time sending interest with
the last timestamp excluded
:param name: prefix to consume data under
:type name: Name
:param onData: onData(data) gets called after received data's onVerifyFailed
:type onData: function object
:param onVerifyFailed: onVerifyFailed(data) gets called if received data
cannot be verified
:type onVerifyFailed: function object
:param onTimeout: onTimeout(interest) gets called if a consumer interest times out
:type onTimeout: function object
"""
name = Name(prefix)
interest = Interest(name)
interest.setInterestLifetimeMilliseconds(self._defaultInterestLifetime)
if self._currentTimestamp:
exclude = Exclude()
exclude.appendAny()
exclude.appendComponent(Name.Component.fromVersion(self._currentTimestamp))
interest.setExclude(exclude)
self._face.expressInterest(interest,
lambda i, d : self.onData(i, d, onVerified, onVerifyFailed, onTimeout),
lambda i: self.beforeReplyTimeout(i, onVerified, onVerifyFailed, onTimeout))
return