Example #1
0
    def __init__(self):

        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()
        self.face = Face("127.0.0.1")
        self.nameInput = '/umobile/pull'
Example #2
0
    def __init__(self, data_size, verbose=False):
        # create a KeyChain for signing data packets
        self._key_chain = KeyChain()
        self._is_done = False
        self._num_interests = 0
        #  self._keyChain.createIdentityV2(Name("/ndn/identity"))

        # host data at the local forwarder
        self._face = Face()

        # immutable byte array to use as data
        self._byte_array = bytes(data_size)

        # the number of bytes contained in each data packet
        self._data_size = data_size

        # the verbosity of diagnostic information
        self._verbose = verbose

        # keep track of if the first interest has been recieved (for timing)
        self._is_first_interst = True

        # keep track of various performance metrics:
        self._interests_satisfied = 0
        self._interests_recieved = 0
        self._data_sent = 0
        self._elapsed_time = {}
        self._initial_time = {}
        self._final_time = {}

        print("Producer instance created.")
Example #3
0
def get_mpd_ndn(url):
    """ Module to download the MPD from the URL and save it to file"""
    print 'Entered get mpd ndn'
    face = Face("server.simpleNDN.ch-geni-net.geni.case.edu")
    counter = Counter()
    s = time.clock()
    try:
        name = Name(url)
        face.expressInterest(name, counter.onData, counter.onTimeout)
        while counter._callbackCount < 1:
            face.processEvents()
        # Try to fetch using a known name.
        name = Name(url + Version)
        dump("Express name ", name.toUri())
        interest = Interest(name)
        interest.setInterestLifetimeMilliseconds(1000)
        SegmentFetcher.fetch(face, interest, None, counter.onComplete,
                             counter.onError)
    except:
        config_dash.LOG.error("Unable to download MPD file NDN error")
        return None
    while counter._callbackCount < 2:
        face.processEvents()
    print("time taken to copy all segments:" + str(time.clock() - s))
    mpd_data = Content
    mpd_file = url.split('/')[-1]
    mpd_file_handle = open(mpd_file, 'w')
    print mpd_file_handle
    mpd_file_handle.write(mpd_data)
    mpd_file_handle.close()
    config_dash.LOG.info("Downloaded the MPD file {}".format(mpd_file))
    return mpd_file
Example #4
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    #print("key1")
    #keyChain = KeyChain()
    #print("key2")
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    identityName = Name("TestProducer")
    certificateName = keyChain.createIdentityAndCertificate(identityName)
    keyChain.getIdentityManager().setDefaultIdentity(identityName)

    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    ubicdn = UbiCDN(keyChain, certificateName)
    prefix = Name("/ubicdn/video")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, ubicdn.onInterest, ubicdn.onRegisterFailed)

    while 1:
        #while ubicdn._responseCount < 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()
Example #5
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    face = Face("memoria.ndn.ucla.edu")

    counter = Counter()

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDU%8D%9DM")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    while counter._callbackCount < 3:
        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()
def main():

    # silence the warning from interest wire encode
    Interest.setDefaultCanBePrefix(True)

    # set up a face that connects to the remote forwarder
    udp_connection_info = UdpTransport.ConnectionInfo("10.10.1.1", 6363)
    udp_transport = UdpTransport()
    face = Face(udp_transport, udp_connection_info)

    counter = Counter()

    # try to fetch from provided name
    name_text = input("Enter a name to request content from: ")
    name = Name(name_text)
    dump("Express name", name.toUri())

    interest = Interest(name)
    interest.setMustBeFresh(False)
    face.expressInterest(interest, counter.onData, counter.onTimeout,
                         counter.onNetworkNack)

    while counter._callbackCount < 1:
        face.processEvents()

        # don't use 100% of the CPU
        time.sleep(0.01)

    face.shutdown()
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ")
    else:
        userPrefixUri = input("Enter your user prefix (e.g. /a): ")
    if userPrefixUri == "":
        dump("You must enter a user prefix")
        return

    syncPrefixUri = "/sync"
    nUserPrefixes = 2
    maxPublishedSequenceNo = 3

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    producer = Producer(face, keyChain, Name(syncPrefixUri), userPrefixUri,
                        nUserPrefixes, maxPublishedSequenceNo)

    # The main event loop.
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #8
0
 def init_network(self, prefix):
     self.prefix = prefix
     self.face = Face()
     self.keychain = KeyChain()
     self.face.setCommandSigningInfo(
         self.keychain, self.keychain.getDefaultCertificateName())
     self.face.registerPrefix(self.prefix, None, self.on_register_failed)
Example #9
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(
        0,
        keyName.size() - 1).append("KEY").append(
            keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA,
                           Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                           DEFAULT_RSA_PUBLIC_KEY_DER,
                                           DEFAULT_RSA_PRIVATE_KEY_DER)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 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()
Example #10
0
    def __init__(self, HostName, prefixesToSend):
        self.host = Name(HostName)
        self.outstanding = dict()
        self.prefixesToSend = prefixesToSend
        self.isDone = False

        self.face = Face("127.0.0.1")
Example #11
0
def main():
    async def face_loop():
        nonlocal face, repo
        while repo.running:
            face.processEvents()
            await asyncio.sleep(0.001)

    config = get_yaml()
    logging.info(config)

    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    # storage = LevelDBStorage(config['db_config']['leveldb']['dir'])
    storage = MongoDBStorage(config['db_config']['mongodb']['db'],
                             config['db_config']['mongodb']['collection'])
    read_handle = ReadHandle(face, keychain, storage)
    write_handle = WriteCommandHandle(face, keychain, storage, read_handle)
    delete_handle = DeleteCommandHandle(face, keychain, storage)
    tcp_bulk_insert_handle = TcpBulkInsertHandle(
        storage, read_handle, config['tcp_bulk_insert']['addr'],
        config['tcp_bulk_insert']['port'])

    repo = Repo(Name(config['repo_config']['repo_name']), face, storage,
                read_handle, write_handle, delete_handle,
                tcp_bulk_insert_handle)

    repo.listen()  # my nfd is broken...

    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(face_loop())
    finally:
        event_loop.close()
Example #12
0
    def start(self, osDur, startingColors):
        self.loop = asyncio.get_event_loop()
        self.lightFace = Face(self.lightAddress)
        self.lightFace.setCommandSigningInfo(self.keychain,
                                             self.certificateName)

        asyncio.Task(self.issueLightingCommand(osDur, startingColors))
Example #13
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    prefix = Name("/icear-server/result/example-data/2/deeplab")
    prefixNamespace = Namespace(prefix)
    prefixNamespace.setFace(face)

    enabled = [True]
    img = [None]

    def onGeneralizedObject(contentMetaInfo, obj):
        data = obj.toBytes()
        dump("Got generalized object, content-type",
             contentMetaInfo.getContentType(), ":", repr(data))
        print(len(data))
        enabled[0] = False
        img[0] = data

    goh = GeneralizedObjectHandler(onGeneralizedObject)
    prefixNamespace.setHandler(goh).objectNeeded()

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    image = Image.open(io.BytesIO(img[0]))
    image.show()
Example #14
0
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())

    async def face_loop():
        nonlocal face
        while True:
            face.processEvents()
            await asyncio.sleep(0.001)

    parser = argparse.ArgumentParser(description='segmented insert client')
    parser.add_argument('-r', '--repo_name',
                        required=True, help='Name of repo')
    parser.add_argument('-p', '--process_id',
                        required=True, help="Process ID")
    args = parser.parse_args()

    logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    client = CommandChecker(face, keychain)
    event_loop = asyncio.get_event_loop()
    event_loop.create_task(face_loop())
    event_loop.run_until_complete(client.check_delete(args.repo_name, int(args.process_id)))
Example #15
0
def main():
    if len(sys.argv) < 2:
        print("Usage:", sys.argv[0], "command-prefix", file=sys.stderr)
        return -1
    else:
        command_prefix = sys.argv[1]

    logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    event_loop = asyncio.get_event_loop()
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    server = Server(face, command_prefix)

    async def face_loop():
        nonlocal face, server
        while server.running:
            face.processEvents()
            await asyncio.sleep(0.01)

    try:
        event_loop.run_until_complete(face_loop())
    finally:
        event_loop.close()
Example #16
0
def main():
    if len(argv) < 3:
        dump("Usage:", argv[0], "<repo-command-prefix> <fetch-prefix>")
        return

    repoCommandPrefix = Name(argv[1])
    repoDataPrefix = Name(argv[2])

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    enabled = [True]

    def onInsertStarted():
        # nonlocal enabled
        dump("Insert started for", repoDataPrefix.toUri())
        enabled[0] = False

    def onFailed():
        # nonlocal enabled
        enabled[0] = False

    requestInsert(face, repoCommandPrefix, repoDataPrefix, onInsertStarted,
                  onFailed)

    # Run until all the data is sent.
    while enabled[0]:
        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()
Example #17
0
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()

    memberName = Name("/first/user")
    memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6"))

    memberKeyChain = KeyChain("pib-memory:", "tpm-memory:")
    memberKeyChain.importSafeBag(SafeBag
      (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False),
       Blob(MEMBER_PUBLIC_KEY, False)))
    # TODO: Use a real Validator.
    decryptor = DecryptorV2(
      memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(),
      ValidatorNull(), memberKeyChain, face)

    contentPrefix = Name("/testname/content")
    contentNamespace = Namespace(contentPrefix)
    contentNamespace.setFace(face)
    contentNamespace.setDecryptor(decryptor)

    enabled = [True]
    def onSegmentedObject(objectNamespace):
        dump("Got segmented content", objectNamespace.obj.toRawStr())
        enabled[0] = False
    SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded()

    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    objectPrefix = Namespace("/ndn/eb/run/28/description", keyChain)

    dump("Register prefix", objectPrefix.name)
    # Set the face and register to receive Interests.
    objectPrefix.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    dump("Preparing data for", objectPrefix.name)
    GeneralizedObjectHandler().setObject(objectPrefix,
                                         Blob("EB run #28. Ham and oats"),
                                         "text/html")

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #19
0
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()

    prefix = Namespace("/ndn/test/status")
    prefix.setFace(face)

    enabled = [True]

    # This is called to print the content after it is re-assembled from segments.
    def onGeneralizedObject(contentMetaInfo, objectNamespace):
        dump("Got generalized object", objectNamespace.name, ", content-type",
             contentMetaInfo.contentType, ":", str(objectNamespace.obj))
        enabled[0] = False

    handler = GeneralizedObjectHandler(prefix, onGeneralizedObject)
    # Allow one component after the prefix for the <version>.
    handler.setNComponentsAfterObjectNamespace(1)
    # In objectNeeded, set mustBeFresh == true so we avoid expired cached data.
    prefix.objectNeeded(True)

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #20
0
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    running = True
    img = None

    interest = Interest(Name("/icear-server/result/example-data/2/deeplab"))
    interest.mustBeFresh = True

    def on_data(_, data):
        # type: (Interest, Data) -> None
        nonlocal running, img
        print(data.name.toUri())
        print(data.content.toBytes())
        running = False
        if data.metaInfo.type == ContentType.NACK:
            print("NACK")
        else:
            img = data.content.toBytes()

    face.expressInterest(interest, on_data)

    while running:
        face.processEvents()
        time.sleep(0.01)

    face.shutdown()

    if img:
        image = Image.open(io.BytesIO(img))
        image.show()
Example #21
0
    def __init__(self, namePrefix):
        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()
        self.face = Face("127.0.0.1")
        self.configPrefix = Name(namePrefix)
        self.script_path = os.path.abspath(
            __file__)  # i.e. /path/to/dir/foobar.py
        self.script_dir = os.path.split(
            self.script_path)[0]  #i.e. /path/to/dir/
        self.interestLifetime = 800000
        #self.Datamessage_size = 1999000
        self.Datamessage_size = 19990000
        folder_name = "SC_repository/"
        rel_path = os.path.join(self.script_dir, folder_name)
        prefix_startDE = "/picasso/start_de/"
        self.prefix_startDE = Name(prefix_startDE)
        self.prefix_deployService = '/picasso/service_deployment_push/'
        self.json_server_Spec_default = {  # This is only an skeleton
            'par': {  #  service parameters
                'serviceName': 'nameOfService',
                'imageName': 'NameOfImageToIstantiateService',
                'imageSize': 'sizeOfImage',
                'maxConReq': 'maxNumConcurrentRequestsThatAnIntanceCanHandle',
                'startUpTime': 'timeToInstatiateService'
            },
            'QoS': {  #QoS parameters expected from the service
                'responseTime': 'resposeTimeExpectedFromService',
                'availability': 'availabilityExpectedFromService',
                'numConReq': 'numConcurrentRequestsToBeHandledByService'
            }
        }

        if not os.path.exists(rel_path):
            os.makedirs(rel_path)
Example #22
0
def main():
    # Connect to the demo host at memoria.ndn.ucla.edu .
    face = Face("128.97.98.8")

    counter = Counter()

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    face.expressInterest(name1, counter.onData, counter.onTimeout)

    # Try to fetch using a known name.
    name2 = Name("/ndn/edu/ucla/remap/demo/ndn-js-test/hello.txt/%FDX%DC5%1F")
    dump("Express name ", name2.toUri())
    face.expressInterest(name2, counter.onData, counter.onTimeout)

    # Expect this to time out.
    name3 = Name("/test/timeout")
    dump("Express name ", name3.toUri())
    face.expressInterest(name3, counter.onData, counter.onTimeout)

    while counter._callbackCount < 3:
        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()
Example #23
0
def main():
    face = Face()
    current_nbr = 1
    max_nbr = 10
    PGI = 5

    f = open('measurements/app_measurments.txt','a')    
    f.seek(0)
    f.truncate()
    
    cow = 0
    v = 0
    counter = Counter(f, face)
    while current_nbr <= max_nbr:
        name = Name("farm1/cows")
        name.append("1")
        name.append("mvmnt")        
        name.appendSegment(v)
        interest = Interest(name)                
        counter._callbackCount = 0
        f.write('\n'+str(datetime.now().strftime('%X.%f')))
        face.expressInterest(interest, counter.onData, counter.onTimeout)
        
        while counter._callbackCount < 1 :
            face.processEvents()
            time.sleep(0.01)

        time.sleep(PGI)
        current_nbr+=1
        v+=1

    face.shutdown()
    f.close()
Example #24
0
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.identityManager = IdentityManager(self.identityStorage,
                self.privateKeyStorage)
        self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf')

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        keyName = Name(self.identityName).append('ksk-1416010123')
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER)
        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER))

        cert = self.identityManager.selfSign(keyName)
        self.identityStorage.setDefaultKeyNameForIdentity(keyName)
        self.identityManager.addCertificateAsDefault(cert)

        self.keyChain = KeyChain(self.identityManager, self.policyManager)
        self.keyName = keyName

        self.face = Face()
Example #25
0
    def __init__(self, producerName, namePrefix):
        self.configPrefix = Name(namePrefix)
        prefix_pullService = "/picasso/pull_Service/"
        self.prefix_pullService = Name(prefix_pullService)
        self.Datamessage_size = 2000000  #20MB --> Max Size from modified NDN
        self.window = 1
        self.producerName = producerName
        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()
        self.face = Face("127.0.0.1")
        self.script_path = os.path.abspath(
            __file__)  # i.e. /path/to/dir/foobar.py
        self.script_dir = os.path.split(
            self.script_path)[0]  #i.e. /path/to/dir/
        self.interestLifetime = 12000000
        self.num_deployedContainer = 0
        self.lastChunk_window = 0
        self.lastChunk_sent = 0

        folder_name = "SEG_repository/"
        self.repo_path = os.path.join(self.script_dir, folder_name)
        if not os.path.exists(self.repo_path):
            os.makedirs(self.repo_path)

        folder_name = "Migration_cost/"
        self.timestamp_path = os.path.join(self.script_dir, folder_name)
        if not os.path.exists(self.timestamp_path):
            os.makedirs(self.timestamp_path)
Example #26
0
 def __init__(self, prefix):
     self.prefix = Name(prefix)
     self.outstanding = dict()
     self.isDone = False
     self.face = Face("127.0.0.1")
     self.start_time = 0
     start_time = time.time()
Example #27
0
def main():
    # The default Face connects to the local NFD.
    face = Face()

    interest = Interest(Name("/localhost/nfd/rib/list"))
    interest.setInterestLifetimeMilliseconds(4000)
    dump("Express interest", interest.getName().toUri())

    enabled = [True]

    def onComplete(content):
        enabled[0] = False
        printRibEntries(content)

    def onError(errorCode, message):
        enabled[0] = False
        dump(message)

    SegmentFetcher.fetch(face, interest, None, onComplete, onError)

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()

        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #28
0
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()
    def run(self):
        # The default Face connects to the local NFD.
        face = Face()

        interest = Interest(Name("/localhost/nfd/faces/channels"))
        interest.setInterestLifetimeMilliseconds(4000)
        self.dump("Express interest", interest.getName().toUri())

        enabled = [True]

        def onComplete(content):
            enabled[0] = False
            self.printChannelStatuses(content)

        def onError(errorCode, message):
            enabled[0] = False
            self.dump(message)

        SegmentFetcher.fetch(face, interest, None, onComplete, onError)

        # Loop calling processEvents until a callback sets enabled[0] = False.
        while enabled[0]:
            face.processEvents()

            # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
            time.sleep(0.01)
        # print('==================run Channels_status_getter finished===================')
        face.shutdown()
        return (self.total_result)
Example #30
0
async def main():

    # Set up face
    async def face_loop():
        nonlocal face, running
        while running:
            face.processEvents()
            await asyncio.sleep(0.001)

    face = Face()
    running = True
    face_event = event_loop.create_task(face_loop())

    # register prefix in local NFD with it own name: /local_manager/building_1/camera_1
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    prefix_id = face.registerPrefix(Name(VIDEO_STREAM_NAME), None, on_register_failed)
    filter_id = face.setInterestFilter(Name(VIDEO_STREAM_NAME), on_interest)
    print('Registered prefix ID {}'.format(prefix_id))
    print('Registered filter ID {}'.format(filter_id))

    cap = cv2.VideoCapture(0)

    # Capture a video every second
    while True:
        cur_time = await capture_video_chunk(duration=1, cap=cap)
        prepare_packets(cur_time=cur_time, keychain=keychain)
        remove_outdated_data(cur_time)

    cap.release()
    cv2.destroyAllWindows()

    running = False
    await face_event