当前位置: 首页>>代码示例>>Python>>正文


Python encoding.ProtobufTlv类代码示例

本文整理汇总了Python中pyndn.encoding.ProtobufTlv的典型用法代码示例。如果您正苦于以下问题:Python ProtobufTlv类的具体用法?Python ProtobufTlv怎么用?Python ProtobufTlv使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ProtobufTlv类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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


注:本文中的pyndn.encoding.ProtobufTlv类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。