本文整理汇总了Python中pyndn.encoding.ProtobufTlv类的典型用法代码示例。如果您正苦于以下问题:Python ProtobufTlv类的具体用法?Python ProtobufTlv怎么用?Python ProtobufTlv使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ProtobufTlv类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: processRegisterResponse
def processRegisterResponse(encodedControlResponse):
"""
This is called when the register route command responds to decode the
encodedControlResponse as a TLV ControlParametersResponse message
containing one ControlParameters. On success, print the ControlParameters
values which should be the same as requested.
:param Blob encodedControlResponse: The TLV-encoded ControlParametersResponse.
"""
decodedControlResponse = \
control_parameters_pb2.ControlParametersTypes.ControlParametersResponseMessage()
ProtobufTlv.decode(decodedControlResponse, encodedControlResponse)
controlResponse = decodedControlResponse.control_response
lowestErrorCode = 400
if controlResponse.status_code >= lowestErrorCode:
dump(
"Face create command got error, code " + str(controlResponse.status_code) +
": " + controlResponse.status_text)
return
if len(controlResponse.control_parameters) != 1:
dump(
"Face create command response does not have one ControlParameters")
return
# Success. Print the ControlParameters response.
controlParameters = controlResponse.control_parameters[0]
dump(
"Successful in name registration: ControlParameters(Name: " +
ProtobufTlv.toName(controlParameters.name.component).toUri() +
", FaceId: " + str(controlParameters.face_id) +
", Origin: " + str(controlParameters.origin) +
", Cost: " + str(controlParameters.cost) +
", Flags: " + str(controlParameters.flags) + ")")
开发者ID:,项目名称:,代码行数:34,代码来源:
示例2: _onConfigurationReceived
def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
# the interest we get here is signed by HMAC, let's verify it
self.tempPrefixId = prefixId # didn't get it from register because of the event loop
interestName = interest.getName()
replyData = Data(interestName)
if len(interestName) == len(prefix):
# this is a discovery request. Check the exclude to see if we should
# return our serial
serial = self.getSerial()
serialComponent = Name.Component(serial)
if not interest.getExclude().matches(serialComponent):
replyData.setContent(serial)
self.sendData(replyData, transport, False) # no point in signing
elif (self._hmacHandler.verifyInterest(interest)):
# we have a match! decode the network parameters
configComponent = interest.getName()[len(prefix)+1]
replyData.setContent('200')
self._hmacHandler.signData(replyData, keyName=self.prefix)
transport.send(replyData.wireEncode().buf())
environmentConfig = DeviceConfigurationMessage()
ProtobufTlv.decode(environmentConfig, configComponent.getValue())
networkPrefix = self._extractNameFromField(environmentConfig.configuration.networkPrefix)
controllerName = self._extractNameFromField(environmentConfig.configuration.controllerName)
controllerName = Name(networkPrefix).append(controllerName)
self._policyManager.setEnvironmentPrefix(networkPrefix)
self._policyManager.setTrustRootIdentity(controllerName)
self.deviceSuffix = self._extractNameFromField(environmentConfig.configuration.deviceSuffix)
self._configureIdentity = Name(networkPrefix).append(self.deviceSuffix)
self._sendCertificateRequest(self._configureIdentity)
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:33,代码来源:iot_node.py
示例3: main
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)
开发者ID:bboalimoe,项目名称:PyNDN2,代码行数:27,代码来源:test_encode_decode_fib_entry.py
示例4: printRibEntries
def printRibEntries(encodedMessage):
"""
This is called when all the segments are received to decode the
encodedMessage as repeated TLV RibEntry messages and display the values.
:param Blob encodedMessage: The repeated TLV-encoded RibEntry.
"""
ribEntryMessage = rib_entry_pb2.RibEntryMessage()
ProtobufTlv.decode(ribEntryMessage, encodedMessage)
dump("RIB:");
for ribEntry in ribEntryMessage.rib_entry:
line = ""
for component in ribEntry.name.component:
# component may be a bytes type, so use Blob to convert to str.
line += "/" + Blob(component, False).toRawStr()
# Show the routes.
for route in ribEntry.routes:
line += (" route={faceId=" + str(route.face_id) + " (origin=" +
str(route.origin) + " cost=" + str(route.cost))
if (route.flags & 1) != 0:
line += " ChildInherit"
if (route.flags & 2) != 0:
line += " Capture"
if route.HasField("expiration_period"):
line += " expirationPeriod=" + str(route.expiration_period)
line += ")}"
dump(line)
开发者ID:mjycom,项目名称:PyNDN2,代码行数:30,代码来源:test_list_rib.py
示例5: _onConfigurationReceived
def _onConfigurationReceived(self, prefix, interest, transport, prefixId):
# the interest we get here is signed by HMAC, let's verify it
self.tempPrefixId = prefixId # didn't get it from register because of the event loop
dataName = Name(interest.getName())
replyData = Data(dataName)
if (self._hmacHandler.verifyInterest(interest)):
# we have a match! decode the controller's name
configComponent = interest.getName().get(prefix.size())
replyData.setContent('200')
self._hmacHandler.signData(replyData, keyName=self.prefix)
transport.send(replyData.wireEncode().buf())
environmentConfig = DeviceConfigurationMessage()
ProtobufTlv.decode(environmentConfig, configComponent.getValue())
networkPrefix = self._extractNameFromField(environmentConfig.configuration.networkPrefix)
controllerName = self._extractNameFromField(environmentConfig.configuration.controllerName)
controllerName = Name(networkPrefix).append(controllerName)
self._policyManager.setEnvironmentPrefix(networkPrefix)
self._policyManager.setTrustRootIdentity(controllerName)
self.deviceSuffix = self._extractNameFromField(environmentConfig.configuration.deviceSuffix)
self._configureIdentity = Name(networkPrefix).append(self.deviceSuffix)
self._sendCertificateRequest(self._configureIdentity)
开发者ID:zhehaowang,项目名称:ndn-pi,代码行数:25,代码来源:iot_node.py
示例6: printFaceStatuses
def printFaceStatuses(encodedMessage):
"""
This is called when all the segments are received to decode the
encodedMessage repeated TLV FaceStatus messages and display the values.
:param Blob encodedMessage: The repeated TLV-encoded FaceStatus.
"""
faceStatusMessage = face_status_pb2.FaceStatusMessage()
ProtobufTlv.decode(faceStatusMessage, encodedMessage)
dump("Faces:");
for faceStatus in faceStatusMessage.face_status:
line = ""
# Format to look the same as "nfd-status -f".
line += (" faceid=" + str(faceStatus.face_id) +
" remote=" + faceStatus.uri +
" local=" + faceStatus.local_uri)
if faceStatus.HasField("expiration_period"):
# Convert milliseconds to seconds.
line += (" expires=" +
str(round(faceStatus.expiration_period / 1000.0)) + "s")
line += (" counters={" + "in={" + str(faceStatus.n_in_interests) +
"i " + str(faceStatus.n_in_datas) + "d " + str(faceStatus.n_in_bytes) + "B}" +
" out={" + str(faceStatus.n_out_interests) + "i "+ str(faceStatus.n_out_datas) +
"d " + str(faceStatus.n_out_bytes) + "B}" + "}" +
" " + ("local" if faceStatus.face_scope == 1 else "non-local") +
" " + ("permanent" if faceStatus.face_persistency == 2 else
("on-demand" if faceStatus.face_persistency == 1 else "persistent")) +
" " + ("multi-access" if faceStatus.link_type == 1 else "point-to-point"))
dump(line)
开发者ID:named-data,项目名称:PyNDN2,代码行数:31,代码来源:test_list_faces.py
示例7: processCreateFaceResponse
def processCreateFaceResponse(encodedControlResponse, prefix, face, enabled):
"""
This is called when the face create command responds to decode the
encodedControlResonse as a TLV ControlResponse message containing one
ControlParameters. Get the face ID and call registerRoute().
:param Blob encodedControlResponse: The TLV-encoded ControlResponse.
"""
decodedControlResponse = \
control_parameters_pb2.ControlParametersTypes.ControlParametersResponseMessage()
ProtobufTlv.decode(decodedControlResponse, encodedControlResponse)
controlResponse = decodedControlResponse.control_response
lowestErrorCode = 400
if controlResponse.status_code >= lowestErrorCode:
dump(
"Face create command got error, code " + str(controlResponse.status_code) +
": " + controlResponse.status_text)
enabled[0] = False
return
if len(controlResponse.control_parameters) != 1:
dump(
"Face create command response does not have one ControlParameters")
enabled[0] = False
return
faceId = controlResponse.control_parameters[0].face_id
dump("Created face ID " + str(faceId))
registerRoute(prefix, faceId, face, enabled)
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:30,代码来源:test_register_route.py
示例8: controlTV
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)
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:29,代码来源:consumer.py
示例9: onLightingCommand
def onLightingCommand(self, prefix, interest, transport, prefixId):
interestName = Name(interest.getName())
#d = Data(interest.getName().getPrefix(prefix.size()+1))
d = Data(interest.getName())
# get the command parameters from the name
try:
commandComponent = interest.getName().get(prefix.size())
commandParams = interest.getName().get(prefix.size()+1)
lightingCommand = LightCommandMessage()
ProtobufTlv.decode(lightingCommand, commandParams.getValue())
self.log.info("Command: " + commandComponent.toEscapedString())
requestedColor = lightingCommand.command.pattern.colors[0]
colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
self.log.info("Requested color: " + colorStr)
self.setPayloadColor(0, requestedColor)
self.sendLightPayload(1)
d.setContent("Gotcha: " + colorStr+ "\n")
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
d.getMetaInfo().setFinalBlockID(0)
self.signData(d)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
开发者ID:thecodemaiden,项目名称:nfd-timing,代码行数:27,代码来源:fixture.py
示例10: versionFromCommandMessage
def versionFromCommandMessage(self, component):
command = RepoCommandParameterMessage()
try:
ProtobufTlv.decode(command, component.getValue())
except Exception as e:
logger.warn(e)
# last component of name to insert is version
versionStr = command.repo_command_parameter.name.component[-1]
return versionStr
开发者ID:thecodemaiden,项目名称:nfd-timing,代码行数:11,代码来源:repo-event-publisher.py
示例11: onCecCommand
def onCecCommand(self, interest):
self.log.debug("Received CEC command")
# check command interest name
# verify command interest
message = pb.CommandMessage()
ProtobufTlv.decode(message, interest.getName().get(3).getValue())
self.loop.call_soon(self.processCommands, message)
data = Data(interest.getName())
data.setContent('ACK')
return data
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:11,代码来源:cec_tv.py
示例12: onCommandData
def onCommandData(interest, data):
global current_insertion #
global current_status
now = time.time()
# assume it's a command response
response = RepoCommandResponseMessage()
ProtobufTlv.decode(response, data.getContent())
current_status = response.repo_command_response.status_code
current_insertion = response.repo_command_response.process_id
logger.debug("Response status code: " + str(current_status) + ", process id: " + str(current_insertion) + ", insert #" + str(response.repo_command_response.insert_num))
开发者ID:thecodemaiden,项目名称:nfd-timing,代码行数:12,代码来源:repo-publisher.py
示例13: onRepoCommandResponse
def onRepoCommandResponse(interest, data):
# repo_command_response_pb2 was produced by protoc.
response = repo_command_response_pb2.RepoCommandResponseMessage()
try:
ProtobufTlv.decode(response, data.content)
except:
print("Cannot decode the repo command response")
if response.repo_command_response.status_code == 100:
if __debug__:
print("Insertion started")
else:
print("Got repo command error code", response.repo_command_response.status_code)
开发者ID:zhehaowang,项目名称:bms-node,代码行数:13,代码来源:bms_publisher_repo.py
示例14: printChannelStatuses
def printChannelStatuses(encodedMessage):
"""
This is called when all the segments are received to decode the
encodedMessage repeated TLV ChannelStatus messages and display the values.
:param Blob encodedMessage: The repeated TLV-encoded ChannelStatus.
"""
channelStatusMessage = channel_status_pb2.ChannelStatusMessage()
ProtobufTlv.decode(channelStatusMessage, encodedMessage)
dump("Channels:");
for channelStatus in channelStatusMessage.channel_status:
# Format to look the same as "nfd-status -c".
dump(" " + channelStatus.local_uri)
开发者ID:named-data,项目名称:PyNDN2,代码行数:14,代码来源:test_list_channels.py
示例15: onData
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()
开发者ID:named-data,项目名称:PyNDN2,代码行数:14,代码来源:basic_insertion.py
示例16: _beginPairing
def _beginPairing(self, encryptedMessage):
# base64 decode, decrypt, protobuf decode
responseCode = 202
try:
encryptedBytes = base64.urlsafe_b64decode(str(encryptedMessage.getValue()))
decryptedBytes = self._identityManager.decryptAsIdentity(encryptedBytes, self.prefix)
message = DevicePairingInfoMessage()
ProtobufTlv.decode(message, decryptedBytes)
except:
responseCode = 500
else:
info = message.info
self.loop.call_soon(self._addDeviceToNetwork, info.deviceSerial,
info.deviceSuffix, info.devicePin)
return responseCode
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:15,代码来源:iot_controller.py
示例17: _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)
开发者ID:RayneHwang,项目名称:ndn-pi,代码行数:32,代码来源:iot_node.py
示例18: _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)
开发者ID:remap,项目名称:ndn-flow,代码行数:32,代码来源:iot_node.py
示例19: onLightingCommand
def onLightingCommand(self, prefix, interest, transport, prefixId):
#print datetime.datetime.now()
self.receiveFile.write('{0:f}'.format(self.unix_time_now()) + '\n')
interestName = Name(interest.getName())
#interstname: /ndn/ucla.edu/sculptures/ai_bus/lights/setRGB/%83%0D%84%0B%87%09%89%01%04%8A%01%01%8B%01%01
#d: <pyndn.data.Data object at 0xb64825d0>
print "interstname", interestName.toUri()
d = Data(interest.getName())
# get the command parameters from the name
try:
commandComponent = interest.getName().get(prefix.size())
#print commandComponent.toEscapedString():setRGB
#print "prefix ",prefix.toUri():/ndn/ucla.edu/sculpture/ai_bus/lights
#print "get name",interest.getName().toUri()
commandParams = interest.getName().get(prefix.size()+1)
#print "commandParams ",commandParams:%83%0D%84%0B%87%09%89%01%04%8A%01%01%8B%01%01
lightingCommand = LightCommandMessage()
ProtobufTlv.decode(lightingCommand, commandParams.getValue())
#self.log.info("Command: " + commandComponent.toEscapedString())
requestedColor = lightingCommand.command.pattern.colors[0]
colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
#self.log.info("Requested color: " + colorStr)
self.setPayloadColor(0, requestedColor)
self.lightState = not self.lightState
if self.lightState:
print "Off"
else:
print "On"
#print requestedColor
self.sendLightPayload(1)
d.setContent("Gotcha: " + colorStr+ "\n")
except KeyboardInterrupt:
print "key interrupt"
sys.exit(1)
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
d.getMetaInfo().setFinalBlockID(0)
self.signData(d)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
开发者ID:mengchenpei,项目名称:Mu-lighting,代码行数:47,代码来源:fixture.py
示例20: requestInsert
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)
开发者ID:named-data,项目名称:PyNDN2,代码行数:59,代码来源:basic_insertion.py
注:本文中的pyndn.encoding.ProtobufTlv类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论