本文整理汇总了Python中pyndn.Interest类的典型用法代码示例。如果您正苦于以下问题:Python Interest类的具体用法?Python Interest怎么用?Python Interest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Interest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: startTrustSchemaUpdate
def startTrustSchemaUpdate(self, appPrefix, onUpdateSuccess = None, onUpdateFailed = None):
"""
Starts trust schema update for under an application prefix: initial
interest asks for the rightMostChild, and later interests are sent
with previous version excluded. Each verified trust schema will trigger
onUpdateSuccess and update the ConfigPolicyManager for the keyChain
in this instance, and unverified ones will trigger onUpdateFailed.
The keyChain and trust anchor should be set up using setupDefaultIdentityAndRoot
before calling this method.
:param appPrefix: the prefix to ask trust schema for. (interest name: /<prefix>/_schema)
:type appPrefix: Name
:param onUpdateSuccess: (optional) onUpdateSuccess(trustSchemaStr, isInitial) is
called when update succeeds
:type onUpdateSuccess: function object
:param onUpdateFailed: (optional) onUpdateFailed(msg) is called when update fails
:type onUpdateFailed: function object
"""
namespace = appPrefix.toUri()
if namespace in self._trustSchemas:
if self._trustSchemas[namespace]["following"] == True:
print "Already following trust schema under this namespace!"
return
self._trustSchemas[namespace]["following"] = True
else:
self._trustSchemas[namespace] = {"following": True, "version": 0, "is-initial": True}
initialInterest = Interest(Name(namespace).append("_schema"))
initialInterest.setChildSelector(1)
self._face.expressInterest(initialInterest,
lambda interest, data: self.onTrustSchemaData(interest, data, onUpdateSuccess, onUpdateFailed),
lambda interest: self.onTrustSchemaTimeout(interest, onUpdateSuccess, onUpdateFailed))
return
示例2: startPublishingAggregation
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
示例3: _onData
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
示例4: test_find_by_interest
def test_find_by_interest(self):
self.anchorContainer.insert("group1", self.certificatePath1, 400.0)
interest = Interest(self.identity1.getName())
self.assertTrue(self.anchorContainer.find(interest) != None)
interest1 = Interest(self.identity1.getName().getPrefix(-1))
self.assertTrue(self.anchorContainer.find(interest1) != None)
interest2 = Interest(Name(self.identity1.getName()).appendVersion(1))
self.assertTrue(self.anchorContainer.find(interest2) == None)
certificate3 = self.fixture.addCertificate(
self.identity1.getDefaultKey(), "3")
certificate4 = self.fixture.addCertificate(
self.identity1.getDefaultKey(), "4")
certificate5 = self.fixture.addCertificate(
self.identity1.getDefaultKey(), "5")
certificate3Copy = CertificateV2(certificate3)
self.anchorContainer.insert("group2", certificate3Copy)
self.anchorContainer.insert("group3", certificate4)
self.anchorContainer.insert("group4", certificate5)
interest3 = Interest(certificate3.getKeyName())
foundCertificate = self.anchorContainer.find(interest3)
self.assertTrue(foundCertificate != None)
self.assertTrue(interest3.getName().isPrefixOf(foundCertificate.getName()))
self.assertTrue(certificate3.getName().equals(foundCertificate.getName()))
interest3.getExclude().appendComponent(
certificate3.getName().get(CertificateV2.ISSUER_ID_OFFSET))
foundCertificate = self.anchorContainer.find(interest3)
self.assertTrue(foundCertificate != None)
self.assertTrue(interest3.getName().isPrefixOf(foundCertificate.getName()))
self.assertTrue(not foundCertificate.getName().equals(certificate3.getName()))
示例5: consume
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
示例6: main
def main():
# Silence the warning from Interest wire encode.
Interest.setDefaultCanBePrefix(True)
loop = asyncio.get_event_loop()
face = ThreadsafeFace(loop, "memoria.ndn.ucla.edu")
# Counter will stop the ioService after callbacks for all expressInterest.
counter = Counter(loop, 3)
# Try to fetch anything.
name1 = Name("/")
dump("Express name ", name1.toUri())
# These call to exressIinterest is thread safe because face is a ThreadsafeFace.
face.expressInterest(name1, counter.onData, counter.onTimeout)
# Try to fetch using a known name.
name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
dump("Express name ", name2.toUri())
face.expressInterest(name2, counter.onData, counter.onTimeout)
# Expect this to time out.
name3 = Name("/test/timeout")
dump("Express name ", name3.toUri())
face.expressInterest(name3, counter.onData, counter.onTimeout)
# Run until the Counter calls stop().
loop.run_forever()
face.shutdown()
示例7: helper
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
示例8: _scanForUnconfiguredDevices
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)
示例9: TestInterestDump
class TestInterestDump(ut.TestCase):
def setUp(self):
self.referenceInterest = Interest()
self.referenceInterest.wireDecode(codedInterest)
def test_dump(self):
# see if the dump format is the same as we expect
decodedDump = dumpInterest(self.referenceInterest)
self.assertEqual(initialDump, decodedDump, 'Initial dump does not have expected format')
def test_redecode(self):
# check that we encode and decode correctly
encoding = self.referenceInterest.wireEncode()
reDecodedInterest = Interest()
reDecodedInterest.wireDecode(encoding)
redecodedDump = dumpInterest(reDecodedInterest)
self.assertEqual(initialDump, redecodedDump, 'Re-decoded interest does not match original')
def test_create_fresh(self):
freshInterest = createFreshInterest()
freshDump = dumpInterest(freshInterest)
self.assertTrue(interestDumpsEqual(initialDump, freshDump), 'Fresh interest does not match original')
reDecodedFreshInterest = Interest()
reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
reDecodedFreshDump = dumpInterest(reDecodedFreshInterest)
self.assertTrue(interestDumpsEqual(freshDump, reDecodedFreshDump), 'Redecoded fresh interest does not match original')
示例10: requestCertificate
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)
示例11: main
def main():
# Silence the warning from Interest wire encode.
Interest.setDefaultCanBePrefix(True)
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
counter = Counter()
if sys.version_info[0] <= 2:
word = raw_input("Enter a word to echo: ")
else:
word = input("Enter a word to echo: ")
name = Name("/testecho")
name.append(word)
dump("Express name ", name.toUri())
face.expressInterest(name, counter.onData, counter.onTimeout)
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例12: _updateCapabilities
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)
示例13: expressInterest
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))
示例14: _sendCertificateRequest
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)
示例15: main
def main():
# 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, 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)