Beispiel #1
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "memoria.ndn.ucla.edu")

    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    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)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
Beispiel #2
0
def main():
    loop = asyncio.get_event_loop()
    # Connect to the demo host at memoria.ndn.ucla.edu .
    face = ThreadsafeFace(loop, "128.97.98.8")

    # Counter will stop the ioService after callbacks for all expressInterest.
    counter = Counter(loop, 3)

    # Try to fetch anything.
    name1 = Name("/")
    dump("Express name ", name1.toUri())
    # These call to exressIinterest is thread safe because face is a ThreadsafeFace.
    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)

    # Run until the Counter calls stop().
    loop.run_forever()
    face.shutdown()
def main():
    # Params parsing
    parser = argparse.ArgumentParser(
        description=
        'bms gateway node to Parse or follow Cascade Datahub log and publish to MiniNdn.'
    )
    parser.add_argument('filename', help='datahub log file')
    parser.add_argument('-f',
                        dest='follow',
                        action='store_true',
                        help='follow (tail -f) the log file')
    parser.add_argument('--namespace',
                        default='/ndn/nist/bms',
                        help='root of ndn name, no trailing slash')

    parser.add_argument('--image',
                        dest='image',
                        default='../simulator/res/floor2.jpg',
                        help='the floor plan to publish')
    parser.add_argument('--location',
                        dest='location',
                        default='../simulator/res/locations.txt',
                        help='the floor plan to publish')

    args = parser.parse_args()

    # Setup logging
    logger = Logger()
    logger.prepareLogging()

    # Face, KeyChain, memoryContentCache and asio event loop initialization
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop)

    keyChain = KeyChain(IdentityManager(BasicIdentityStorage()))
    # For the gateway publisher, we create one identity for it to sign nfd command interests
    certificateName = keyChain.createIdentityAndCertificate(
        Name("/ndn/nist/gateway"))
    face.setCommandSigningInfo(keyChain, certificateName)
    cache = MemoryContentCache(face)

    dataPublisher = DataPublisher(face, keyChain, loop, cache, args.namespace,
                                  args.image, args.location)
    cache.registerPrefix(Name(args.namespace), dataPublisher.onRegisterFailed,
                         dataPublisher.onDataNotFound)
    loop.run_until_complete(dataPublisher.publishFloorImage())

    if args.follow:
        #asyncio.async(loop.run_in_executor(executor, followfile, args.filename, args.namespace, cache))
        loop.run_until_complete(dataPublisher.followfile(args.filename))
    else:
        loop.run_until_complete(dataPublisher.readfile(args.filename))

    loop.run_forever()
    face.shutdown()
def main():
    # Params parsing
    parser = argparse.ArgumentParser(
        description=
        'bms gateway node to Parse or follow Cascade Datahub log and publish to MiniNdn.'
    )
    parser.add_argument('filename', help='datahub log file')
    parser.add_argument('-f',
                        dest='follow',
                        action='store_true',
                        help='follow (tail -f) the log file')
    parser.add_argument('--namespace',
                        default='/ndn/edu/ucla/remap/bms',
                        help='root of ndn name, no trailing slash')
    args = parser.parse_args()

    # Setup logging
    logger = Logger()
    logger.prepareLogging()

    # Face, KeyChain, memoryContentCache and asio event loop initialization
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "128.97.98.7")

    keyChain = KeyChain(
        IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage()))
    # For the gateway publisher, we create one identity for it to sign nfd command interests
    #certificateName = keyChain.createIdentityAndCertificate(Name("/ndn/bms/gateway-publisher"))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    print "Using certificate name " + keyChain.getDefaultCertificateName(
    ).toUri()
    cache = MemoryContentCache(face)

    dataPublisher = DataPublisher(face, keyChain, loop, cache, args.namespace)
    cache.registerPrefix(Name(args.namespace), dataPublisher.onRegisterFailed,
                         dataPublisher.onDataNotFound)

    # Parse csv to decide the mapping between sensor JSON -> <NDN name, data type>
    dataPublisher.populateSensorNDNDictFromCSV(
        'bms-sensor-data-types-sanitized.csv')

    loop.call_later(dataPublisher._restartInterval, dataPublisher.checkAlive)
    if args.follow:
        #asyncio.async(loop.run_in_executor(executor, followfile, args.filename, args.namespace, cache))
        loop.run_until_complete(dataPublisher.followfile(args.filename))
    else:
        loop.run_until_complete(dataPublisher.readfile(args.filename))

    loop.run_forever()
    face.shutdown()
Beispiel #5
0
class NdnClient:
    def __init__(self,localhub_ip):
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, localhub_ip)
         
    def request(self,req,callback,content= None, mustbefresh= False):
        baseName = ndn.Name(req)
        interest = ndn.Interest(ndn.Name(baseName))
        interest.setMustBeFresh(mustbefresh)
        self.callback = callback
        if content != None:
         interest.setContent(content)
        self.face.expressInterest(interest, self._onData, self._onTimeout)
        self.loop.run_forever()
    
    def _onData(self, interest, data):
        self.callback(data.content)
        self.loop.stop()
    def destroy(self):
        self.face.shutdown()
    def _onTimeout(self, interest):
        print >> "request timeout">> interest.name.toUri()
Beispiel #6
0
    def _onInterest(self, prefix, interest, *k):
        print >> sys.stderr, "<< PyNDN %s" % interest.name

        content = "PyNDN LINE #%d\n" % self.counter
        self.counter += 1

        data = ndn.Data(interest.getName())

        meta = ndn.MetaInfo()
        meta.setFreshnessPeriod(5000)
        data.setMetaInfo(meta)

        data.setContent(content)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        self.face.putData(data)

    def _onRegisterFailed(self, prefix):
        print >> sys.stderr, "<< PyNDN: failed to register prefix"


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, None)
    server = Server(face)

    loop.run_forever()
    face.shutdown()
Beispiel #7
0
class Flask():
    def __init__(self, host):
        self.__name__ = __name__
        self.keyChain = KeyChain()
        self.isDone = False
        self.counter = 0
        loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(loop, host)
        self.a = {}
        self.methods = {}

    def route(self, uri, methods):
        prefix = uri
        if bool(re.search('<(.*)>', prefix)):
            self.baseName = ndn.Name(
                re.sub('<(.*)>', methods[0] + '/<data>', prefix))
        else:
            self.baseName = ndn.Name(prefix + "/" + methods[0])
        self.methods[self.baseName.toUri()] = methods[0]
        return self.dec

    def onInterest(self, prefix, interest, *k):
        print >> sys.stderr, "<< PyNDN %s" % interest.name

        intrestUri = interest.name.toUri()
        prefixUri = prefix.toUri()

        parameters = ''
        if intrestUri != prefixUri:
            parameters = intrestUri[len(prefixUri) + 1:]
            print
            prefixUri += "/%3Cdata%3E"

        d = self.a[prefixUri]
        if self.methods[prefixUri] == "POST":
            content = json.dumps(
                d(interest.getContent().toRawStr().decode('string_escape')))
        else:
            if parameters:
                content = json.dumps(d(parameters))
            else:
                content = json.dumps(d())

        self.counter += 1
        data = ndn.Data(interest.getName())

        meta = ndn.MetaInfo()
        meta.setFreshnessPeriod(5000)
        data.setMetaInfo(meta)

        data.setContent(content)
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        self.face.putData(data)

    def _onRegisterFailed(self, prefix):
        print >> sys.stderr, "<< PyNDN: failed to register prefix"

    def run(self):
        root = logging.getLogger()
        root.setLevel(logging.DEBUG)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        root.addHandler(ch)
        loop = asyncio.get_event_loop()
        server = Server(self.face)

        loop.run_forever()
        self.face.shutdown()

    def dec(self, func):
        self.a[self.baseName.toUri()] = func
        self.face.registerPrefix(
            self.baseName,
            self.onInterest,
            self._onRegisterFailed,
        )