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


Python Data.wireEncode方法代码示例

本文整理汇总了Python中pyndn.Data.wireEncode方法的典型用法代码示例。如果您正苦于以下问题:Python Data.wireEncode方法的具体用法?Python Data.wireEncode怎么用?Python Data.wireEncode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyndn.Data的用法示例。


在下文中一共展示了Data.wireEncode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: onInterest

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	
		  
        try:
	    if(initInterest == self.listPrefix):
	    
		print "initial db,start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent(currentString)
		encodedData = d.wireEncode()
		transport.send(encodedData.toBuffer())
		print d.getName().toUri()
		print d.getContent()
		
		
		
            else:
		self.excludeDevice = initInterest.get(self.listPrefix.size())
		excDevice = self.excludeDevice.toEscapedString()
		if(excDevice != str("exc")+self.device):
			print "not init db,start to set data's content"
                
			currentString = ','.join(currentList)
			d.setContent(currentString)
			encodedData = d.wireEncode()
			transport.send(encodedData.toBuffer())
			print d.getName().toUri()
			print d.getContent()
			
		else:
			
			print"controller has exclude me, I have to remove register!!!!!!!"
                	self.face.removeRegisteredPrefix(registeredPrefixId)
			print"register again"
                	self.face.registerPrefix(self.listPrefix,self.onInterest,self.onRegisterFailed)
    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)
开发者ID:mengchenpei,项目名称:Mu-lighting,代码行数:51,代码来源:storage2.py

示例2: onPublishInterest

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def onPublishInterest(self, prefix, interest, transport, pxID):
        '''
           For publishing face
        '''
        # just make up some data and return it
        interestName = interest.getName()
        logger.info("Interest for " + interestName.toUri())

        ## CURRENTLY ASSUMES THERE'S A VERSION+SEGMENT SUFFIX!
        dataName = Name(interestName)
        ts = (time.time())
        segmentId = 0
        #try:
        #   segmentId = interestName.get(-1).toSegment()
        #except:
            #logger.debug("Could not find segment id!")
            #dataName.appendSegment(segmentId)
        versionStr = str(interestName.get(-2).getValue())
        logger.debug('Publishing ' + versionStr + ' @ ' + str(ts))

        d = Data(dataName)
        content = "(" + str(ts) +  ") Data named " + dataName.toUri()
        d.setContent(content)
        d.getMetaInfo().setFinalBlockID(segmentId)
        d.getMetaInfo().setFreshnessPeriod(1000)
        self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()

        stats.insertDataForVersion(versionStr, {'publish_time': time.time()})
        transport.send(encodedData.toBuffer())
开发者ID:thecodemaiden,项目名称:nfd-timing,代码行数:33,代码来源:repo-event-publisher.py

示例3: publishData

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def publishData(self):
        timestamp = time.time()
        info = {''}
        if self._pir == None:
            cpu_use = ps.cpu_percent()
            users = [u.name for u in ps.users()]
            nProcesses = len(ps.pids())
            memUse = ps.virtual_memory().percent
            swapUse = ps.swap_memory().percent

            info = {'count': self._count, 'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses,
                    'memory_usage':memUse, 'swap_usage':swapUse}
        else:
            info = {'count': self._count, 'pir_bool': self._pir.read()}
        self._count += 1
        
        dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp)))
        dataOut.setContent(json.dumps(info))
        dataOut.getMetaInfo().setFreshnessPeriod(10000)
        self.signData(dataOut)

        #self._dataCache.add(dataOut)
        # instead of adding data to content cache, we put data to nfd anyway
        self.send(dataOut.wireEncode().buf())
        print('data name: ' + dataOut.getName().toUri() + '; content: ' + str(info))

        # repeat every 1 seconds
        self.loop.call_later(1, self.publishData)
开发者ID:zhehaowang,项目名称:ndn-pi,代码行数:30,代码来源:publisher.py

示例4: onInterest

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	try:
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)	



	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()

	self.loop.close()
     
        self.face.shutdown()
        self.face = None
开发者ID:mengchenpei,项目名称:Mu-lighting,代码行数:36,代码来源:PC1.py

示例5: onInterest

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
 def onInterest(prefix, interest, transport, prefixID):
     interestCallbackCount[0] += 1
     data = Data(interest.getName())
     data.setContent("SUCCESS")
     self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
     encodedData = data.wireEncode()
     transport.send(encodedData.toBuffer())
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:9,代码来源:test_face_methods.py

示例6: _onConfigurationReceived

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    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,代码行数:35,代码来源:iot_node.py

示例7: onLightingCommand

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    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,代码行数:29,代码来源:fixture.py

示例8: onDataInterest

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
def onDataInterest(prefix, interest, transport, pxID):
    '''
       For publishing face
    '''
    # just make up some data and return it
    interestName = interest.getName()
    logger.info("Interest for " + interestName.toUri())

    ## CURRENTLY ASSUMES THERE'S A VERSION/SEGMENT SUFFIX!
    dataName = Name(interestName.getPrefix(-1))
    ts = (time.time())
    segmentId = 0
    try:
       segmentId = interestName().get(-1).toSegment()
    except:
        logger.debug("Could not find segment id!")
    dataName.appendSegment(segmentId)

    versionStr = interestName.get(-2).getValue().toRawStr()
    logger.debug('publishing ' + versionStr)
    info = getInfoForVersion(versionStr)

    d = Data(dataName)
    content = "(" + str(ts) +  ") Data named " + dataName.toUri()
    d.setContent(content)
    d.getMetaInfo().setFinalBlockID(segmentId)
    keychain.sign(d, certName)

    encodedData = d.wireEncode()
    now = time.time()

    if info is not None:
        info['publish_time'] = now
    transport.send(encodedData.toBuffer())
开发者ID:thecodemaiden,项目名称:nfd-timing,代码行数:36,代码来源:repo-publisher.py

示例9: _onConfigurationReceived

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    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,代码行数:27,代码来源:iot_node.py

示例10: wrap_content

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def wrap_content(self, name, content, key=None, key_locator=None):
        """
        @param name - name of the data
        @param content - data to be wrapped
        @param key - key used to sign the data
        @return the content object created
        wraps the given name and content into a content object
        """
        co = Data(Name(name))
        co.setContent(content)
        co.getMetaInfo().setFreshnessPeriod(5000)
        co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])

        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        identityManager = IdentityManager(identityStorage, privateKeyStorage)
        keyChain = KeyChain(identityManager, None)

        # Initialize the storage.
        keyName = Name("/ndn/bms/DSK-default")
        certificateName = keyName.getSubName(0, keyName.size() - 1).append(
                "KEY").append(keyName[-1]).append("ID-CERT").append("0")
        identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
        privateKeyStorage.setKeyPairForKeyName(keyName, DEFAULT_PUBLIC_KEY_DER, 
                DEFAULT_PRIVATE_KEY_DER)

        keyChain.sign(co, certificateName)

        _data = co.wireEncode()

        return _data.toRawStr()
开发者ID:remap,项目名称:BMS-REPO,代码行数:33,代码来源:repo.py

示例11: onPlayingCommand

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
	def onPlayingCommand(self, prefix, interest, transport, prefixId):
		
		interestName = Name(interest.getName())
		commandComponent = interest.getName().get(self.prefix.size())
		if commandComponent == Name.Component("stop"):
			pass
		if commandComponent == Name.Component("play"):
			pass
		else:
			songName = commandComponent.toEscapedString()
	    
		songList = []
		songList = songName.split('%2C')
	    
		for i in songList:
			fmusic = i + str("-music.mp3") 
			print "started getting music file", i
			
			g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset, i)
			
			g.oStream = open(fmusic,'wb')
			g.start()
			
			#self._getFiles.append(g)
			
		d = Data(interest.getName())
		d.setContent("start to play: " + songName + "\n")
		encodedData = d.wireEncode()
		transport.send(encodedData.toBuffer())	
开发者ID:mengchenpei,项目名称:Mu-lighting,代码行数:31,代码来源:Music+player.py

示例12: handleDataInterests

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def handleDataInterests(self, prefix, interest, transport, prefixId):
        # TODO: verification
        
        # we match the components to the name, and any '_' components
        # are discarded. Then we run a MongoDB query and append the
        # object id to allow for excludes

        chosenSchema = (s for s in self.schemaList 
                if s.dbPrefix.match(prefix)).next()

        interestName = interest.getName()
        responseName = Name(interestName)
        nameFields = chosenSchema.matchNameToSchema(interestName)
        self.log.info("Data requested with params:\n\t{}".format(nameFields))
        allResults = []
        segment = 0
        try:
            segmentComponent = interest.getName()[-4]
            segment = segmentComponent.toSegment()
        except RuntimeError:
            pass
        
        (startPos, results) = self._segmentResponseData(nameFields, segment)
        for result in results:
            dataId = result[u'_id']
            self.log.debug("Found object {}".format(dataId))
            allResults.append(result)

        #responseName.append(str(dataId))
        totalCount = results.count(False)
        responseObject = {'count':totalCount, 'skip':startPos, 'results':allResults}
        responseData = Data(responseName)
        resultEncoded = BSON.encode(responseObject)
        responseData.setContent(resultEncoded)
        transport.send(responseData.wireEncode().buf())
开发者ID:thecodemaiden,项目名称:ndn-repo-3,代码行数:37,代码来源:repo.py

示例13: onPlayingCommand

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def onPlayingCommand(self, prefix, interest, transport, prefixId):
	print "receive interest"
        interestName = Name(interest.getName())
        commandComponent = interest.getName().get(self.prefix.size())
        if commandComponent == Name.Component("stop"):
            pass
        if commandComponent == Name.Component("play"):
            pass
        else:
            songName = commandComponent.toEscapedString()
	    print songName
	    songList = []
	    songList = songName.split('%2C')
	    print "songlist and its len",songList,len(songList)
	    for i in songList:
		self.song = i
            	fmusic = i+str("-music.mp3") 
		self.ftxt = i + str("-os.txt")
		self.ffreq = i + str("-freq.txt")
		print "FMUSIC:",fmusic 
		  
	    	self.thread = threading.Thread(target = self.mp.play_music, args = (fmusic,songList,self.q,))
	    	self.thread.daemon = True
            	g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset)
		#g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.lightFunction)
            	g.oStream = open(fmusic,'wb')
            	g.start()
	   
		
	
	d = Data(interest.getName())
	d.setContent("start to play: " + songName + "\n")
	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())	
开发者ID:mengchenpei,项目名称:Mu-lighting,代码行数:36,代码来源:p.py

示例14: test_encode_decode

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def test_encode_decode(self):
        data = Data()
        data.wireDecode(codedData)
        data.setContent(data.getContent())
        encoding = data.wireEncode()

        reDecodedData = Data()
        reDecodedData.wireDecode(encoding)
        self.assertEqual(dumpData(reDecodedData), initialDump, 'Re-decoded data does not match original dump')
开发者ID:bboalimoe,项目名称:PyNDN2,代码行数:11,代码来源:test_data_methods.py

示例15: onInterest

# 需要导入模块: from pyndn import Data [as 别名]
# 或者: from pyndn.Data import wireEncode [as 别名]
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        self._responseCount += 1

        # Make and sign a Data packet.
        data = Data(interest.getName())
        content = "Echo " + interest.getName().toUri()
        data.setContent(content)
        self._keyChain.sign(data, self._certificateName)
        encodedData = data.wireEncode()

        dump("Sent content", content)
        transport.send(encodedData.toBuffer())
开发者ID:bboalimoe,项目名称:PyNDN2,代码行数:14,代码来源:test_publish_async_ndnx.py


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