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


Python Face.expressInterest方法代码示例

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


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

示例1: main

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    dataPrefix = "/home/test1/data"
    repoDataPrefix = "/home/test1/data"
    # Set up repo-ng, register prefix for repo-ng's fetch prefix
    # Per configuration file in /usr/local/etc/ndn/repo-ng.conf
    # memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd
    #memCache = MemoryContentCache(face, 100000)
    #memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound)

    counter = Counter(face, repoDataPrefix)

    interest = Interest(Name(dataPrefix))
    interest.setChildSelector(1)
    interest.setInterestLifetimeMilliseconds(defaultInterestLifetime)
    face.expressInterest(interest, counter.onData, counter.onTimeout)
    
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(1)
    face.shutdown()
开发者ID:zhehaowang,项目名称:ndn-pi,代码行数:28,代码来源:test_udp_multicast_consumer_outstanding.py

示例2: main

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
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()
开发者ID:named-data,项目名称:PyNDN2,代码行数:27,代码来源:test_echo_consumer.py

示例3: Consumer

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class Consumer(object):
    '''Hello World consumer'''

    def __init__(self, prefix):
        self.prefix = Name(prefix)
        self.outstanding = dict()
        self.isDone = False

        self.face = Face("127.0.0.1")


    def run(self):
        try:
            self._sendNextInterest(self.prefix)

            while not self.isDone:
                self.face.processEvents()
                time.sleep(0.01)

        except RuntimeError as e:
            print "ERROR: %s" %  e


    def _sendNextInterest(self, name):
        interest = Interest(name)
        uri = name.toUri()

        interest.setInterestLifetimeMilliseconds(4000)
        interest.setMustBeFresh(True)

        if uri not in self.outstanding:
            self.outstanding[uri] = 1

        self.face.expressInterest(interest, self._onData, self._onTimeout)
        print "Sent Interest for %s" % uri


    def _onData(self, interest, data):
        payload = data.getContent()
        name = data.getName()

        print "Received data: ", payload.toRawStr()
        del self.outstanding[name.toUri()]

        self.isDone = True


    def _onTimeout(self, interest):
        name = interest.getName()
        uri = name.toUri()

        print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri)
        self.outstanding[uri] += 1

        if self.outstanding[uri] <= 3:
            self._sendNextInterest(name)
        else:
            self.isDone = True
开发者ID:dibenede,项目名称:ndn-tutorial-gec21,代码行数:60,代码来源:hello_consumer.py

示例4: main

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
def main():
    if len(sys.argv) < 2:
        print("argv error: please input turnOn, turnOff or status")
        exit(1)
    else:
        cmd = sys.argv[1]

    loop = asyncio.get_event_loop()
    #face = ThreadsafeFace(loop, "localhost")
    face = Face("localhost")
    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    seed = HMACKey(0,0,"seed","seedName")

    # Try to fetch anything.
    name1 = Name("/home/sensor/LED/0/"+cmd+"/0/0")

    commandTokenName = '/home/sensor/LED/0/'+cmd+'/token/0'
    
    commandTokenKey = hmac.new(seed.getKey(), commandTokenName, sha256).digest()
    accessTokenName = '/home/sensor/LED/0/'+cmd+'/token/0/user/Tom/token/0'
    accessTokenKey = hmac.new(commandTokenKey, accessTokenName, sha256).digest()
    accessToken = HMACKey(0,0,accessTokenKey,accessTokenName)

    dump("seed.getKey() :",seed.getKey())
    dump("commandTokenName :",commandTokenName)
    dump("commandTokenKey :",base64.b64encode(commandTokenKey))
    dump("accessTokenName :",accessTokenName)
    dump("accessTokenKey :",base64.b64encode(accessTokenKey))

    
    interest = Interest(name1)
    interest.setInterestLifetimeMilliseconds(3000)
    a = AccessControlManager()
    a.signInterestWithHMACKey(interest,accessToken)
    dump("Express name ", interest.toUri())
    face.expressInterest(interest, counter.onData, counter.onTimeout)
    
    """
    name2 = Name("/home/sensor/LED/T0829374723/turnOff")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, 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(2)

    face.shutdown()
开发者ID:philoL,项目名称:NDN-HOME,代码行数:54,代码来源:test_led.py

示例5: main

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
def main():
    seg = 0
    if len(sys.argv) < 3:
        print("argv error: please input capture or capture with #seg")
        exit(1)
    elif len(sys.argv) == 2:
        cmd = sys.argv[1]
    else:
        cmd = sys.argv[1]
        seg = sys.argv[2]

    loop = asyncio.get_event_loop()
    #face = ThreadsafeFace(loop, "localhost")
    face = Face("localhost")
    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    seed = HMACKey(0,0,"seed","seedName")

    # Try to fetch anything.
    import time
    r = time.time()

    name1 = Name("/home/security/camera/0/"+cmd)
    name1.appendTimestamp(int(r))
    name1.appendSegment(int(seg))

    
    interest = Interest(name1)
    interest.setInterestLifetimeMilliseconds(3000)
    dump("Express name ", interest.toUri())
    face.expressInterest(interest, counter.onData, counter.onTimeout)
    
    """
    name2 = Name("/home/sensor/LED/T0829374723/turnOff")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, 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(2)

    face.shutdown()
开发者ID:philoL,项目名称:NDN-HOME,代码行数:48,代码来源:test_camera.py

示例6: main

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
def main():
    face = Face("localhost")
    
    counter = Counter()

    ignored, name = argv
    name = "/ndn/ucla.edu/bms/" + name
    name1 = Name(name)
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, 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()
开发者ID:remap,项目名称:BMS-REPO,代码行数:19,代码来源:client.py

示例7: Consumer

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class Consumer(object):
    '''Sends Interest, listens for data'''

    def __init__(self, name):
        self.name = Name(name)
        self.face = Face()
        self.isDone = False


    def run(self):
        try:
            interest = Interest(self.name)
            uri = self.name.toUri()

            interest.setInterestLifetimeMilliseconds(4000)
            interest.setMustBeFresh(True)

            self.face.expressInterest(interest, self._onData, self._onTimeout)

            while not self.isDone:
                self.face.processEvents()
                time.sleep(0.01)

            print "Sent Interest for %s" % uri

        except RuntimeError as e:
            print "ERROR: %s" % e


    def _onData(self, interest, data):
        payload = data.getContent()
        name = data.getName()

        print "Received data: %s\n" % payload.toRawStr()
        self.isDone = True


    def _onTimeout(self, interest):
        name = interest.getName()
        uri = name.toUri()

        print "TIMEOUT ", uri
        self.isDone = True
开发者ID:dibenede,项目名称:nfd-strategies,代码行数:45,代码来源:consumer.py

示例8: KDSPublisher

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class KDSPublisher(Thread):
    def  __init__(self, bld_root, keychain, cert_name, symkey, timestamp):
        Thread.__init__(self)
        self.bld_root = bld_root
        self.keychain = keychain
        self.cert_name = cert_name
        self.symkey = binascii.hexlify(symkey)
        self.timestamp = timestamp
        self.face = Face("localhost")

    def run(self):
        print 'KDS start'
        closure = Closure(self.bld_root, self.keychain, self.cert_name, self.symkey, self.timestamp)

        self.face.expressInterest(user_name, closure.onData, closure.onTimeout)

        while(closure.flag_terminate == 0):
            self.face.processEvents()
            time.sleep(0.01)

        print 'KDS stop'
开发者ID:wentaoshang,项目名称:ndn-sensor,代码行数:23,代码来源:kds.py

示例9: deviceListRequest

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
def deviceListRequest():
    
    loop = asyncio.get_event_loop()
    #face = ThreadsafeFace(loop, "localhost")
    face = Face("localhost")
    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    while True:
        username = raw_input('Login username: ')
        if not len(username)>0:
            print("Username can't be blank")
            continue
        else:
            break
    while True:
        password = raw_input("Login password: ")
        if not len(password)>0:
            print("Username can't be blank")
            continue
        else:
            break
        
    userHMACKey = HMACKey(0,0,password,"userHMACKey")
    
    interestName = Name("/home/controller/deviceList/user/"+username)
    interest = Interest(interestName)    

    a = AccessControlManager()
    a.signInterestWithHMACKey(interest,userHMACKey)
    dump("Express interst :",interest.toUri())
    face.expressInterest(interest,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(2)

    face.shutdown()
开发者ID:philoL,项目名称:NDN-HOME,代码行数:40,代码来源:manage_controller.py

示例10: TestFaceInterestMethods

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class TestFaceInterestMethods(ut.TestCase):
    def setUp(self):
        self.face = Face("aleph.ndn.ucla.edu")

    def tearDown(self):
        self.face.shutdown()

    def run_express_name_test(self, interestName, timeout=12):
        # returns the dataCallback and timeoutCallback mock objects so we can test timeout behavior
        # as well as a bool for if we timed out without timeoutCallback being called
        name = Name(interestName)
        dataCallback = Mock()
        timeoutCallback = Mock()
        self.face.expressInterest(name, dataCallback, timeoutCallback)
        
        def waitForCallbacks():
            while 1:
                self.face.processEvents()
                gevent.sleep()
                if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
                    break
        
        task = gevent.spawn(waitForCallbacks)
        task.join(timeout=10)

        return dataCallback, timeoutCallback



    def test_any_interest(self):
        uri = "/"
        (dataCallback, timeoutCallback) = self.run_express_name_test(uri)
        self.assertTrue(timeoutCallback.call_count == 0 , 'Timeout on expressed interest')
        
        # check that the callback was correct
        self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

        onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])

        #just check that the interest was returned correctly?
        callbackInterest = onDataArgs[0]
        self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name')
        
    # TODO: Replace this with a test that connects to a Face on localhost
    #def test_specific_interest(self):
    #    uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4"
    #    (dataCallback, timeoutCallback) = self.run_express_name_test(uri)
    #    self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest')
    #    
    #    # check that the callback was correct
    #    self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

    #    onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])

    #    #just check that the interest was returned correctly?
    #    callbackInterest = onDataArgs[0]
    #    self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name')

    def test_timeout(self):
        uri = "/test/timeout"
        (dataCallback, timeoutCallback) = self.run_express_name_test(uri)

        # we're expecting a timeout callback, and only 1
        self.assertTrue(dataCallback.call_count == 0, 'Data callback called for invalid interest')

        self.assertTrue(timeoutCallback.call_count == 1, 'Expected 1 timeout call, got ' + str(timeoutCallback.call_count))

        #check that the interest was returned correctly
        onTimeoutArgs = timeoutCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])

        #just check that the interest was returned correctly?
        callbackInterest = onTimeoutArgs[0]
        self.assertTrue(callbackInterest.getName().equals(Name(uri)), 'Interest returned on callback had different name')

    def test_remove_pending(self):
        name = Name("/ndn/edu/ucla/remap/")
        dataCallback = Mock()
        timeoutCallback = Mock()

        interestID = self.face.expressInterest(name, dataCallback, timeoutCallback)

        def removeInterestAndWait():
            self.face.removePendingInterest(interestID)
            while 1:
                self.face.processEvents()
                gevent.sleep()
                currentTime = time.clock()
                if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
                    break

        task = gevent.spawn(removeInterestAndWait)
        task.join(timeout=10)

        self.assertEqual(dataCallback.call_count, 0, 'Should not have called data callback after interest was removed')
        self.assertEqual(timeoutCallback.call_count, 0, 'Should not have called timeout callback after interest was removed')
开发者ID:bboalimoe,项目名称:PyNDN2,代码行数:97,代码来源:test_face_methods.py

示例11: TestFaceInterestMethods

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class TestFaceInterestMethods(ut.TestCase):
    def setUp(self):
        self.face = Face("localhost")

    def tearDown(self):
        self.face.shutdown()

    def run_express_name_test(self, interestName, timeout=12):
        # returns the dataCallback and timeoutCallback mock objects so we can test timeout behavior
        # as well as a bool for if we timed out without timeoutCallback being called
        name = Name(interestName)
        dataCallback = Mock()
        timeoutCallback = Mock()
        self.face.expressInterest(name, dataCallback, timeoutCallback)

        while True:
            self.face.processEvents()
            time.sleep(0.01)
            if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
                break

        return dataCallback, timeoutCallback

    def test_any_interest(self):
        uri = "/"
        (dataCallback, timeoutCallback) = self.run_express_name_test(uri)
        self.assertTrue(timeoutCallback.call_count == 0 , 'Timeout on expressed interest')

        # check that the callback was correct
        self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

        onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])

        #just check that the interest was returned correctly?
        callbackInterest = onDataArgs[0]
        self.assertTrue(callbackInterest.getName() == (Name(uri)), 'Interest returned on callback had different name')

    # TODO: Replace this with a test that connects to a Face on localhost
    #def test_specific_interest(self):
    #    uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4"
    #    (dataCallback, timeoutCallback) = self.run_express_name_test(uri)
    #    self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest')
    #
    #    # check that the callback was correct
    #    self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

    #    onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])

    #    #just check that the interest was returned correctly?
    #    callbackInterest = onDataArgs[0]
    #    self.assertTrue(callbackInterest.getName() == Name(uri), 'Interest returned on callback had different name')

    def test_timeout(self):
        uri = "/test/timeout"
        (dataCallback, timeoutCallback) = self.run_express_name_test(uri)

        # we're expecting a timeout callback, and only 1
        self.assertTrue(dataCallback.call_count == 0, 'Data callback called for invalid interest')

        self.assertTrue(timeoutCallback.call_count == 1, 'Expected 1 timeout call, got ' + str(timeoutCallback.call_count))

        #check that the interest was returned correctly
        onTimeoutArgs = timeoutCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])

        #just check that the interest was returned correctly?
        callbackInterest = onTimeoutArgs[0]
        self.assertTrue(callbackInterest.getName() == (Name(uri)), 'Interest returned on callback had different name')

    def test_remove_pending(self):
        name = Name("/ndn/edu/ucla/remap/")
        dataCallback = Mock()
        timeoutCallback = Mock()

        interestID = self.face.expressInterest(name, dataCallback, timeoutCallback)

        self.face.removePendingInterest(interestID)

        timeout = 10000
        startTime = getNowMilliseconds()
        while True:
            self.face.processEvents()
            time.sleep(0.01)
            if getNowMilliseconds() - startTime >= timeout:
                break
            if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
                break

        self.assertEqual(dataCallback.call_count, 0, 'Should not have called data callback after interest was removed')
        self.assertEqual(timeoutCallback.call_count, 0, 'Should not have called timeout callback after interest was removed')

    def test_max_ndn_packet_size(self):
        # Construct an interest whose encoding is one byte larger than getMaxNdnPacketSize.
        targetSize = Face.getMaxNdnPacketSize() + 1
        # Start with an interest which is almost the right size.
        interest = Interest()
        interest.getName().append(bytearray(targetSize))
        initialSize = interest.wireEncode().size()
        # Now replace the component with the desired size which trims off the extra encoding.
        interest.setName(
          (Name().append(bytearray(targetSize - (initialSize - targetSize)))))
#.........这里部分代码省略.........
开发者ID:mjycom,项目名称:PyNDN2,代码行数:103,代码来源:test_face_methods.py

示例12: TestFaceRegisterMethods

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class TestFaceRegisterMethods(ut.TestCase):
    def setUp(self):
        self.face_in = Face()
        self.face_out = Face()
        self.keyChain = KeyChain()

    def tearDown(self):
        self.face_in.shutdown()
        self.face_out.shutdown()

    def onInterestEffect(self, prefix, interest, transport, prefixID):
        data = Data(interest.getName())
        data.setContent("SUCCESS")
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
        encodedData = data.wireEncode()
        transport.send(encodedData.toBuffer())

    def test_register_prefix_response(self):
        # gotta sign it (WAT)
        prefixName = Name("/test")
        self.face_in.setCommandSigningInfo(self.keyChain,
                self.keyChain.getDefaultCertificateName())

        failedCallback = Mock()
        interestCallback = Mock(side_effect=self.onInterestEffect)

        self.face_in.registerPrefix(prefixName, interestCallback, failedCallback)
        server = gevent.spawn(self.face_process_events, self.face_in, [interestCallback, failedCallback], 'h')

        time.sleep(1) # give the 'server' time to register the interest

        # express an interest on another face
        dataCallback = Mock()
        timeoutCallback = Mock()

        # now express an interest on this new face, and see if onInterest is called
        interestName = prefixName.append("hello")
        self.face_out.expressInterest(interestName, dataCallback, timeoutCallback)

        client = gevent.spawn(self.face_process_events, self.face_out, [dataCallback, timeoutCallback], 'c')

        gevent.joinall([server, client], timeout=10)

        self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all')

        self.assertEqual(interestCallback.call_count, 1, 'Expected 1 onInterest callback, got '+str(interestCallback.call_count))

        self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

        onDataArgs = dataCallback.call_args[0]
        # check the message content
        data = onDataArgs[1]
        expectedBlob = Blob(bytearray("SUCCESS"))
        self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')

    def face_process_events(self, face, callbacks, name=None):
        # implemented as a 'greenlet': something like a thread, but semi-synchronous
        # callbacks should be a list
        done = False
        while not done:
            face.processEvents()
            gevent.sleep()
            for c in callbacks:

                if (c.call_count > 0):
                    done = True
开发者ID:mjycom,项目名称:PyNDN2,代码行数:68,代码来源:test_face_methods.py

示例13: Name

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
            fullName = Name(data_prefix).append(Name(data_part))

            # currently we need to provide the version ourselves when we
            # poke the repo
            ts = int(time.time()*1000)
            fullName.appendVersion(int(ts))
            command = createInsertInterest(fullName)

            versionStr = fullName.get(-1).toEscapedString()
            logger.debug('inserting: ' + versionStr)

            repo_face.makeCommandInterest(command)
            lastFailCount = failure.call_count
            lastSuccessCount = success.call_count

            repo_face.expressInterest(command, success, failure)
            insertTable.append({'version':versionStr, 'insert_request':time.time()})
            while success.call_count == lastSuccessCount and failure.call_count == lastFailCount:
                repo_face.processEvents()
                time.sleep(0.1)

            # only expecting to insert one segment (<1k) for each request         
            # check on the insert status
            # TODO: kick off a greenlet instead of setting global variable?
            if success.call_count > lastSuccessCount and current_insertion >= 0:
                lastFailCount = failure.call_count
                lastSuccessCount = success.call_count
                info = getInfoForVersion(versionStr)

                logger.debug("Checking on: " + str(current_insertion))
                if current_status == 100:
开发者ID:thecodemaiden,项目名称:nfd-timing,代码行数:33,代码来源:repo-publisher.py

示例14: Consumer

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class Consumer(object):
    '''Sends Interest, listens for data'''

    def __init__(self, prefix, pipeline, count):
        self.prefix = prefix
        self.pipeline = pipeline
        self.count = count
        self.nextSegment = 0
        self.outstanding = dict()
        self.isDone = False

        self.face = Face("127.0.0.1")

    def run(self):
        try:
            while self.nextSegment < self.pipeline:
                self._sendNextInterest(self.prefix)
                self.nextSegment += 1

            while not self.isDone:
                self.face.processEvents()
                time.sleep(0.01)

        except RuntimeError as e:
            print "ERROR: %s" % e



    def _onData(self, interest, data):
        payload = data.getContent()
        name = data.getName()

        print "Received data: %s\n" % payload.toRawStr()
        del self.outstanding[name.toUri()]

        if self.count == self.nextSegment or data.getMetaInfo().getFinalBlockID() == data.getName()[-1]:
            self.isDone = True
        else:
            self._sendNextInterest(self.prefix)
            self.nextSegment += 1


    def _sendNextInterest(self, name):
        self._sendNextInterestWithSegment(Name(name).appendSegment(self.nextSegment))


    def _sendNextInterestWithSegment(self, name):
        interest = Interest(name)
        uri = name.toUri()

        interest.setInterestLifetimeMilliseconds(4000)
        interest.setMustBeFresh(True)

        if name.toUri() not in self.outstanding:
            self.outstanding[name.toUri()] = 1

        self.face.expressInterest(interest, self._onData, self._onTimeout)
        print "Sent Interest for %s" % uri


    def _onTimeout(self, interest):
        name = interest.getName()
        uri = name.toUri()

        print "TIMEOUT #%d: segment #%s" % (self.outstanding[uri], name[-1].toNumber())
        self.outstanding[uri] += 1

        if self.outstanding[uri] <= 3:
            self._sendNextInterestWithSegment(name)
        else:
            self.isDone = True
开发者ID:dibenede,项目名称:ndn-tutorial-gec21,代码行数:73,代码来源:consumer.py

示例15: TestFaceRegisterMethods

# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import expressInterest [as 别名]
class TestFaceRegisterMethods(ut.TestCase):
    def setUp(self):
        self.face_in = Face()
        self.face_out = Face()
        self.keyChain = KeyChain()

    def tearDown(self):
        self.face_in.shutdown()
        self.face_out.shutdown()

    def test_register_prefix_response(self):
        prefixName = Name("/test")
        self.face_in.setCommandSigningInfo(self.keyChain,
                self.keyChain.getDefaultCertificateName())

        interestCallbackCount = [0]
        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())

        failedCallback = Mock()

        self.face_in.registerPrefix(prefixName, onInterest, failedCallback)
        # Give the 'server' time to register the interest.
        time.sleep(1)

        # express an interest on another face
        dataCallback = Mock()
        timeoutCallback = Mock()

        # now express an interest on this new face, and see if onInterest is called
        # Add the timestamp so it is unique and we don't get a cached response.
        interestName = prefixName.append("hello" + repr(time.time()))
        self.face_out.expressInterest(interestName, dataCallback, timeoutCallback)

        # Process events for the in and out faces.
        timeout = 10000
        startTime = getNowMilliseconds()
        while True:
            if getNowMilliseconds() - startTime >= timeout:
                break

            self.face_in.processEvents()
            self.face_out.processEvents()

            done = True
            if interestCallbackCount[0] == 0 and failedCallback.call_count == 0:
                # Still processing face_in.
                done = False
            if dataCallback.call_count == 0 and timeoutCallback.call_count == 0:
                # Still processing face_out.
                done = False

            if done:
                break
            time.sleep(0.01)


        self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all')

        self.assertEqual(interestCallbackCount[0], 1, 'Expected 1 onInterest callback, got '+str(interestCallbackCount[0]))

        self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

        onDataArgs = dataCallback.call_args[0]
        # check the message content
        data = onDataArgs[1]
        expectedBlob = Blob("SUCCESS")
        self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')
开发者ID:MAHIS,项目名称:PyNDN2,代码行数:75,代码来源:test_face_methods.py


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