本文整理汇总了Python中pyndn.encoding.ProtobufTlv.encode方法的典型用法代码示例。如果您正苦于以下问题:Python ProtobufTlv.encode方法的具体用法?Python ProtobufTlv.encode怎么用?Python ProtobufTlv.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.encoding.ProtobufTlv
的用法示例。
在下文中一共展示了ProtobufTlv.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: controlTV
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def controlTV(self):
count = 0
for pir in self.getPirs():
if pir.status.getLastValue():
count += 1
if count >= 2:
# TODO: Send command interest to TV
self.log.info("turn on tv")
for cec in self.getCecs():
message = pb.CommandMessage()
message.destination = pb.TV
message.commands.append(pb.AS)
message.commands.append(pb.SLEEP)
message.commands.append(pb.PLAY)
encodedMessage = ProtobufTlv.encode(message)
interest = Interest(Name(cec.id).append(encodedMessage))
# self.face.makeCommandInterest(interest)
self.face.expressInterest(interest, self.onDataCec, self.onTimeoutCec)
elif count == 0:
# TODO: Send command interest to TV
self.log.info("turn off tv")
for cec in self.getCecs():
message = pb.CommandMessage()
message.destination = pb.TV
message.commands.append(pb.STANDBY)
encodedMessage = ProtobufTlv.encode(message)
interest = Interest(Name(cec.id).append(encodedMessage))
# self.face.makeCommandInterest(interest)
self.face.expressInterest(interest, self.onDataCec, self.onTimeoutCec)
示例2: main
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def main():
# Construct a sample FibEntry message using the structure in fib_entry_pb2
# which was produced by protoc.
message = fib_entry_pb2.FibEntryMessage()
message.fib_entry.name.component.append("ndn")
message.fib_entry.name.component.append("ucla")
nextHopRecord = message.fib_entry.next_hop_records.add()
nextHopRecord.face_id = 16
nextHopRecord.cost = 1
# Encode the Protobuf message object as TLV.
encoding = ProtobufTlv.encode(message)
decodedMessage = fib_entry_pb2.FibEntryMessage()
ProtobufTlv.decode(decodedMessage, encoding)
dump("Re-decoded FibEntry:")
# This should print the same values that we put in message above.
value = ""
for component in decodedMessage.fib_entry.name.component:
value += "/" + component
value += " nexthops = {"
for next_hop_record in decodedMessage.fib_entry.next_hop_records:
value += ("faceid=" + repr(next_hop_record.face_id)
+ " (cost=" + repr(next_hop_record.cost) + ")")
value += " }"
dump(value)
示例3: _sendCertificateRequest
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [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)
示例4: _updateCapabilities
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [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)
示例5: requestInsert
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def requestInsert(face, repoCommandPrefix, fetchName, onInsertStarted, onFailed,
startBlockId = None, endBlockId = None):
"""
Send a command interest for the repo to fetch the given fetchName and insert
it in the repo.
Since this calls expressInterest, your application must call face.processEvents.
:param Face face: The Face used to call makeCommandInterest and expressInterest.
:param Name repoCommandPrefix: The repo command prefix.
:param Name fetchName: The name to fetch. If startBlockId and endBlockId are
supplied, then the repo will request multiple segments by appending the
range of block IDs (segment numbers).
:param onInsertStarted: When the request insert command successfully returns,
this calls onInsertStarted().
:type onInsertStarted: function object
:param onFailed: If the command fails for any reason, this prints an error
and calls onFailed().
:type onFailed: function object
:param int startBlockId: (optional) The starting block ID (segment number)
to fetch.
:param int endBlockId: (optional) The end block ID (segment number)
to fetch.
"""
# repo_command_parameter_pb2 was produced by protoc.
parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
# Add the Name.
for i in range(fetchName.size()):
parameter.repo_command_parameter.name.component.append(
fetchName[i].getValue().toBytes())
# Add startBlockId and endBlockId if supplied.
if startBlockId != None:
parameter.repo_command_parameter.start_block_id = startBlockId
if endBlockId != None:
parameter.repo_command_parameter.end_block_id = endBlockId
# Create the command interest.
interest = Interest(Name(repoCommandPrefix).append("insert")
.append(Name.Component(ProtobufTlv.encode(parameter))))
face.makeCommandInterest(interest)
# Send the command interest and get the response or timeout.
def onData(interest, data):
# repo_command_response_pb2 was produced by protoc.
response = repo_command_response_pb2.RepoCommandResponseMessage()
try:
ProtobufTlv.decode(response, data.content)
except:
dump("Cannot decode the repo command response")
onFailed()
if response.repo_command_response.status_code == 100:
onInsertStarted()
else:
dump("Got repo command error code", response.repo_command_response.status_code)
onFailed()
def onTimeout(interest):
dump("Insert repo command timeout")
onFailed()
face.expressInterest(interest, onData, onTimeout)
示例6: _sendCertificateRequest
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [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.
"""
#TODO: GENERATE A NEW PUBLIC/PRIVATE PAIR INSTEAD OF COPYING
makeKey = False
try:
defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(keyIdentity)
newKeyName = defaultKey
except SecurityException:
defaultIdentity = self._keyChain.getDefaultIdentity()
defaultKey = self._identityStorage.getDefaultKeyNameForIdentity(defaultIdentity)
newKeyName = self._identityStorage.getNewKeyName(keyIdentity, True)
makeKey = True
self.log.debug("Found key: " + defaultKey.toUri()+ " renaming as: " + newKeyName.toUri())
keyType = self._identityStorage.getKeyType(defaultKey)
keyDer = self._identityStorage.getKey(defaultKey)
if makeKey:
try:
privateDer = self._identityManager.getPrivateKey(defaultKey)
except SecurityException:
# XXX: is recovery impossible?
pass
else:
try:
self._identityStorage.addKey(newKeyName, keyType, keyDer)
self._identityManager.addPublicKey(newKeyName, keyDer)
self._identityManager.addPrivateKey(newKeyName, privateDer)
except SecurityException:
# TODO: key shouldn't exist...
pass
message = CertificateRequestMessage()
message.command.keyType = keyType
message.command.keyBits = keyDer.toRawStr()
for component in range(newKeyName.size()):
message.command.keyName.components.append(newKeyName.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)
示例7: createCheckInterest
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def createCheckInterest(fullName, checkNum):
insertionName = Name("/repotest/repo/insert check")
commandParams = RepoCommandParameterMessage()
interestName = Name(fullName)
commandParams.repo_command_parameter.process_id = checkNum
for i in range(interestName.size()):
commandParams.repo_command_parameter.name.component.append(interestName.get(i).toEscapedString())
commandName = insertionName.append(ProtobufTlv.encode(commandParams))
interest = Interest(commandName)
return interest
示例8: createCheckInterest
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def createCheckInterest(self, fullName, checkNum):
insertionName = Name(self.repoPrefix).append('insert check')
commandParams = RepoCommandParameterMessage()
interestName = Name(fullName)
commandParams.repo_command_parameter.process_id = checkNum
for i in range(interestName.size()):
commandParams.repo_command_parameter.name.component.append(str(interestName.get(i).getValue()))
commandName = insertionName.append(ProtobufTlv.encode(commandParams))
interest = Interest(commandName)
return interest
示例9: createCommandInterest
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def createCommandInterest(prefix="/testlight/setRGB", color=(255,0,128)):
interestName = Name(prefix)
commandParams = LightCommandMessage()
messageColor = commandParams.command.pattern.colors.add()
messageColor.r = color[0]
messageColor.g = color[1]
messageColor.b = color[2]
commandName = interestName.append(ProtobufTlv.encode(commandParams))
interest = Interest(commandName)
interest.setInterestLifetimeMilliseconds(2000)
return interest
示例10: initiateContentStoreInsertion
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def initiateContentStoreInsertion(self, repoCommandPrefix, data):
fetchName = data.getName()
parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
# Add the Name.
for i in range(fetchName.size()):
parameter.repo_command_parameter.name.component.append(
fetchName[i].getValue().toBytes())
# Create the command interest.
interest = Interest(Name(repoCommandPrefix).append("insert")
.append(Name.Component(ProtobufTlv.encode(parameter))))
self.face.makeCommandInterest(interest)
self.face.expressInterest(interest, self.onRepoData, self.onRepoTimeout)
示例11: sendRepoInsertCommand
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def sendRepoInsertCommand(self, dataName):
self.log.debug('Sending insert command for {}'.format(dataName))
commandMessage = RepoCommandParameterMessage()
command = commandMessage.command
for component in dataName:
command.name.components.append(str(component.getValue()))
command.start_block_id = command.end_block_id = 0
commandComponent = ProtobufTlv.encode(commandMessage)
interestName = Name(self.repoPrefix).append('insert')
interestName.append(commandComponent)
interest = Interest(interestName)
interest.setInterestLifetimeMilliseconds(4000)
self.face.makeCommandInterest(interest)
self.face.expressInterest(interest, self.onDataReceived, self.onTimeout)
示例12: processFaceStatus
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def processFaceStatus(encodedFaceStatus, prefix, uri, face, enabled):
"""
This is called when all the segments are received to decode the
encodedFaceStatus as a TLV FaceStatus message. If the face ID exists for the
face URL, use it to call registerRoute(), otherwise send a
/localhost/nfd/faces/create command to create the face.
:param Blob encodedFaceStatus: The TLV-encoded FaceStatus.
:param Name prefix: The prefix name to register.
:param str uri: The remote URI in case we need to tell NFD to create a face.
:param Face face: The Face which is used to sign the command interest and
call expressInterest.
:param enabled: On success or error, set enabled[0] = False.
:type enabled: An array with one bool element
"""
if encodedFaceStatus.size() == 0:
# No result, so we need to tell NFD to create the face.
# Encode the ControlParameters.
message = \
control_parameters_pb2.ControlParametersTypes.ControlParametersMessage()
message.control_parameters.uri = uri
encodedControlParameters = ProtobufTlv.encode(message)
interest = Interest(Name("/localhost/nfd/faces/create"))
interest.getName().append(encodedControlParameters)
interest.setInterestLifetimeMilliseconds(10000)
def onData(localInterest, data):
processCreateFaceResponse(data.getContent(), prefix, face, enabled)
def onTimeout(localInterest):
enabled[0] = False
dump("Face create command timed out.")
# Sign and express the interest.
face.makeCommandInterest(interest)
face.expressInterest(interest, onData, onTimeout)
else:
decodedFaceStatus = face_status_pb2.FaceStatusMessage()
ProtobufTlv.decode(decodedFaceStatus, encodedFaceStatus)
faceId = decodedFaceStatus.face_status[0].face_id
dump("Found face ID ", faceId)
registerRoute(prefix, faceId, face, enabled)
示例13: stopRepoWatch
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def stopRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStopped, onFailed):
"""
Send a command interest for the repo to stop watching the given watchPrefix.
Since this calls expressInterest, your application must call face.processEvents.
:param Face face: The Face used to call makeCommandInterest and expressInterest.
:param Name repoCommandPrefix: The repo command prefix.
:param Name watchPrefix: The prefix that the repo will stop watching.
:param onRepoWatchStopped: When the stop watch command successfully returns,
this calls onRepoWatchStopped().
:type onRepoWatchStopped: function object
:param onFailed: If the command fails for any reason, this prints an error
and calls onFailed().
:type onFailed: function object
"""
# repo_command_parameter_pb2 was produced by protoc.
parameter = repo_command_parameter_pb2.RepoCommandParameterMessage()
for i in range(watchPrefix.size()):
parameter.repo_command_parameter.name.component.append(
watchPrefix[i].getValue().toBytes())
# Create the command interest.
interest = Interest(Name(repoCommandPrefix).append("watch").append("stop")
.append(Name.Component(ProtobufTlv.encode(parameter))))
face.makeCommandInterest(interest)
# Send the command interest and get the response or timeout.
def onData(interest, data):
# repo_command_response_pb2 was produced by protoc.
response = repo_command_response_pb2.RepoCommandResponseMessage()
try:
ProtobufTlv.decode(response, data.content)
except:
dump("Cannot decode the repo command response")
onFailed()
if response.repo_command_response.status_code == 101:
onRepoWatchStopped()
else:
dump("Got repo command error code", response.repo_command_response.status_code)
onFailed()
def onTimeout(interest):
dump("Stop repo watch command timeout")
onFailed()
face.expressInterest(interest, onData, onTimeout)
示例14: createInsertInterest
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def createInsertInterest(fullName):
# we have to do the versioning when we poke the repo
interestName = Name(fullName)
logger.debug('Creating insert interest for: '+interestName.toUri())
insertionName = Name("/repotest/repo/insert")
commandParams = RepoCommandParameterMessage()
for i in range(interestName.size()):
commandParams.repo_command_parameter.name.component.append(interestName.get(i).toEscapedString())
commandParams.repo_command_parameter.start_block_id = 0
commandParams.repo_command_parameter.end_block_id = 0
commandName = insertionName.append(ProtobufTlv.encode(commandParams))
interest = Interest(commandName)
return interest
示例15: _addDeviceToNetwork
# 需要导入模块: from pyndn.encoding import ProtobufTlv [as 别名]
# 或者: from pyndn.encoding.ProtobufTlv import encode [as 别名]
def _addDeviceToNetwork(self, serial, suffix, pin):
self.ui.alert("Sending pairing info to gateway...", False)
# we must encrypt this so no one can see the pin!
message = DevicePairingInfoMessage()
message.info.deviceSuffix = suffix
message.info.deviceSerial = serial
message.info.devicePin = pin
rawBytes = ProtobufTlv.encode(message)
encryptedBytes = self._identityManager.encryptForIdentity(rawBytes, self.prefix)
encodedBytes = base64.urlsafe_b64encode(str(encryptedBytes))
interestName = Name(self.prefix).append("addDevice").append(encodedBytes)
interest = Interest(interestName)
# todo: have the controller register this console as a listener
# and update it with pairing status
interest.setInterestLifetimeMilliseconds(5000)
self.face.makeCommandInterest(interest)
self.face.expressInterest(interest, self._onAddDeviceResponse, self._onAddDeviceTimeout)