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()) publishIntervalMs = 1000.0 stream = Namespace("/ndn/eb/stream/run/28/annotations", keyChain) handler = GeneralizedObjectStreamHandler(stream) dump("Register prefix", stream.name) # Set the face and register to receive Interests. stream.setFace(face, lambda prefixName: dump("Register failed for prefix", prefixName)) # Loop, producing a new object every publishIntervalMs milliseconds (and # also calling processEvents()). previousPublishMs = 0 while True: now = Common.getNowMilliseconds() if now >= previousPublishMs + publishIntervalMs: dump("Preparing data for sequence", handler.getProducedSequenceNumber() + 1) handler.addObject( Blob("Payload " + str(handler.getProducedSequenceNumber() + 1)), "application/json") previousPublishMs = now 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(): # 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)
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()
def main(): face = Face("localhost") identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain( IdentityManager(identityStorage, privateKeyStorage), None) keyChain.setFace(face) # Initialize the storage. keyName = Name("/testname/DSK-reposerver") 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) echo = RepoServer(keyChain, certificateName) prefix = Name("/ndn/ucla.edu/bms") dump("Register prefix", prefix.toUri()) face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed) 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) face.shutdown()
class Consumer(object): '''Hello World consumer''' def __init__(self, gatewayprefix, newprefix, chatroom): self.gatewayprefix = Name(gatewayprefix) self.newprefix = str(Name(newprefix)) self.chatroom = str(Name(chatroom)) self.parameter = self.newprefix + "|" + self.chatroom self.outstanding = dict() self.isDone = False self.face = Face("127.0.0.1") def run(self): os.system("nlsrc advertise " + self.newprefix) os.system("nlsrc advertise " + self.chatroom) try: self._sendNextInterest(self.gatewayprefix) 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.setApplicationParameters(self.parameter) 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 print interest def _onData(self, interest, data): payload = data.getContent() name = data.getName() print "Received response from gateway: ", 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] <= 1000: self._sendNextInterest(name) else: self.isDone = True
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()
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)
class TestRegistrationCallbacks(ut.TestCase): def setUp(self): self.face = Face() keyChain = KeyChain() self.face.setCommandSigningInfo( keyChain, keyChain.getDefaultCertificateName()) def tearDown(self): self.face.shutdown() def test_registration_callbacks(self): onRegisterFailed = Mock() onRegisterSuccess = Mock() self.face.registerPrefix( Name("/test/register/callbacks"), None, onRegisterFailed, onRegisterSuccess) while True: self.face.processEvents() time.sleep(0.01) if (onRegisterSuccess.call_count > 0 or onRegisterFailed.call_count > 0): break self.assertEqual( onRegisterSuccess.call_count, 1, "Expected 1 onRegisterSuccess callback, got " + str(onRegisterSuccess.call_count))
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)
class PacketIn(object): '''PacketIn message is an interest for inquiring unknown prefix ''' def __init__(self): self.keyChain = KeyChain() self.isDone = False self.ofmsg = OFMSG() self.outstanding = dict() #a dictionary to keep track of outstanding Interests and retransmissions. #self.face = Face("127.0.0.1") self.face = Face() self.nodeid = OSCommand.getnodeid() def run(self, unknown_prefix="/abcd/dfgh/tcd"): try: self._sendPacketinInterest(unknown_prefix) while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print("ERROR: %s" % e) return self.isDone def _sendPacketinInterest(self,unknown_prefix): interest = self.ofmsg.create_packetin_msg_interest(unknown_prefix, self.nodeid) uri = interest.getName().toUri() if uri not in self.outstanding: self.outstanding[uri] = 1 self.face.expressInterest(interest, self._onData, self._onTimeout) print("######### Sent <<<PacketIn>>> Interest #########\n {0} \n".format(uri)) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print("Received <<<<FlowMod data>>>>from Controller ") self.nodeid = OSCommand.getnodeid() # add this item to flow table. FlowModDataList = NdnFlowTable.parse_FlowMod_Data(payload) # print(FlowModDataList) NdnFlowTable.updatendnflowtable(FlowModDataList,self.nodeid) print(NdnFlowTable) 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 self.isDone = True
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)
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()
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()
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()
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
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face connects to the local NFD. face = Face() interest = Interest(Name("/localhost/nfd/faces/list")) interest.setInterestLifetimeMilliseconds(4000) dump("Express interest", interest.getName().toUri()) enabled = [True] def onComplete(content): enabled[0] = False printFaceStatuses(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)
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()
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 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()
def main(): # 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 video name: ") #else: # word = input("Enter a video name: ") name = Name("/kebapp/video/video") #name.append(word) dump("Express name ", name.toUri()) interest = Interest(name) #interest.setInterestLifeTimeMilliseconds(30000) interest.setInterestLifetimeMilliseconds(30000) face.expressInterest(interest, counter.onData, counter.onTimeout) #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 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()
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(): face = Face("aleph.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(): # 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, SegmentFetcher.DontVerifySegment, 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)
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") self.start_time = 0 start_time = time.time() 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): self.start_time = time.time() interest = Interest(name) uri = name.toUri() interest.setInterestLifetimeMilliseconds(9000) interest.setMustBeFresh(False) 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: ", len(payload.toRawStr()) # print "Processing data: " time.sleep(2) del self.outstanding[name.toUri()] self.isDone = True elapsed_time = time.time() - self.start_time print elapsed_time 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
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(): # 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()
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)
class FaceModMsg(object): '''FlowRemoved message is an interest send once, no need response ''' def __init__(self): self.keyChain = KeyChain() self.ofmsg = OFMSG() self.face = Face() def run(self,facemod_suffix): try: self._sendFaceModInterest(facemod_suffix) n=0 while n<200: self.face.processEvents() time.sleep(0.01) n+=1 except RuntimeError as e: print("ERROR: %s" % e) return True def _sendFaceModInterest(self,facemod_suffix): interest = self.ofmsg.create_facemod_msg_interest(facemod_suffix) uri = interest.getName().toUri() self.face.expressInterest(interest, self._onData, self._onTimeout) print("--------Sent <<<FaceMod>>> Msg for \n %s" % uri) def _onData(self, interest, data): pass def _onTimeout(self, interest): pass
class Consumer(object): def __init__(self): self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") self.nameInput = '/umobile/pull' def run(self): try: self._sendNextInterest(Name(self.nameInput)) 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() dataName = data.getName() dataName_size = dataName.size() print "Received data name: ", dataName.toUri() print "Received data: ", payload.toRawStr() 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 def onRegisterFailed(self, prefix): print "Register failed for prefix", prefix.toUri() self.isDone = True
def cert_server_thread(): face = Face() CertServer(face) 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)
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
def main(): """ Call requestInsert and register a prefix so that ProduceSegments will answer interests from the repo to send the data packets. This assumes that repo-ng is already running (e.g. `sudo ndn-repo-ng`). """ repoCommandPrefix = Name("/localhost/repo1") repoDataPrefix = Name("/NIST/library/mainroom/ESP32ID001") nowMilliseconds = int(time.time() * 1000.0) fetchPrefix = Name(repoDataPrefix).append( Name.Component.fromNumber(nowMilliseconds)) # 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()) # Register the prefix and send the repo insert command at the same time. startBlockId = 0 endBlockId = 1 enabled = [True] def onFinished(): dump("All data was inserted.") enabled[0] = False produceSegments = ProduceSegments(keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId, onFinished) dump("Register prefix", fetchPrefix.toUri()) def onRegisterFailed(prefix): dump("Register failed for prefix", prefix.toUri()) enabled[0] = False face.registerPrefix(fetchPrefix, produceSegments.onInterest, onRegisterFailed) time.sleep(0.2) def onInsertStarted(): dump("Insert started for", fetchPrefix.toUri()) def onFailed(): enabled[0] = False requestInsert(face, repoCommandPrefix, fetchPrefix, 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()
class Consumer(object): def __init__(self): Prefix1 = '/umobile/notification/push' self.configPrefix = Name(Prefix1) self.outstanding = dict() self.isDone = False self.keyChain = KeyChain() self.face = Face("127.0.0.1") def run(self): try: self.face.setCommandSigningInfo(self.keyChain, \ self.keyChain.getDefaultCertificateName()) self.face.registerPrefix(self.configPrefix, self.onInterest, self.onRegisterFailed) print "Registering listening prefix : " + self.configPrefix.toUri() while not self.isDone: self.face.processEvents() time.sleep(0.01) except RuntimeError as e: print "ERROR: %s" % e def onInterest(self, prefix, interest, face, interestFilterId, filter): interestName = interest.getName() ### Extract Data content from Interest name interest_name_components = interestName.toUri().split("/") Data_content = interest_name_components[interest_name_components.index("push") + 1] print 'Received Data: %s' %Data_content data = Data(interestName) data.setContent("ACK") hourMilliseconds = 600 * 1000 data.getMetaInfo().setFreshnessPeriod(hourMilliseconds) self.keyChain.sign(data, self.keyChain.getDefaultCertificateName()) face.send(data.wireEncode().toBuffer()) print "Sending ACK" 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 def onRegisterFailed(self, prefix): print "Register failed for prefix", prefix.toUri() self.isDone = True
class Consumer(object): '''Register chat prefix to gateway router to advertise''' 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") def run(self): try: self._sendNextInterest(self.host) 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.setApplicationParameters(self.prefixesToSend) 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 Chat Prefixes to host " + str(self.host) def _onData(self, interest, data): payload = data.getContent() name = data.getName() print str(self.host) + " recieved prefixes" del self.outstanding[name.toUri()] os.system("nfdc cs erase " + str(name)) 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] <= 1000: self._sendNextInterest(name) else: self.isDone = True
def main(): if len(sys.argv) < 2: print("usage: python3 client-app.py {good/bad}") quit() #Interest.setDefaultCanBePrefix(True) with open("shared/system-info.json") as f: user_data = json.load(f) face = Face() counter = Counter() name = Name("/ndn-ss/austin") req_name = "/example/test" sym_key = base64.b64decode(user_data['austin']['sym_key']) iv, ct, tag = sym_encrypt(sym_key, req_name) enc_req_name = base64.b64encode(iv).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(ct).decode('ascii') name.append(enc_req_name) enc_req_name = base64.b64encode(tag).decode('ascii') name.append(enc_req_name) priv_key = user_data['austin']['priv_key'] priv_key = base64.b64decode(priv_key) priv_key = load_priv_key(priv_key) sig =\ base64.b64encode(priv_key.sign(bytes("austin",'utf-8'))).decode('ascii') bad_sig =\ base64.b64encode(priv_key.sign(bytes("abstin",'utf-8'))).decode('ascii') i = Interest() i.setMustBeFresh(True) i.setInterestLifetimeMilliseconds(0) #face.expressInterest(name,counter.onData,counter.onTimeout) if sys.argv[1] == "good": name.append(sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) elif sys.argv[1] == "bad": name.append(bad_sig) face.expressInterest(name, i, counter.onData, counter.onTimeout) else: print("c") while counter.rec == 1: face.processEvents() time.sleep(0.1) face.expressInterest(name, i, counter.onData, counter.onTimeout)
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()
def run(self): face = Face() # Use the system default key chain and certificate name to sign commands. face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed) print "Registering prefix %s" % self.prefix.toUri() while not self.isDone: face.processEvents() time.sleep(0.01)
def main(): """ Call requestInsert and register a prefix so that ProduceSegments will answer interests from the repo to send the data packets. This assumes that repo-ng is already running (e.g. `sudo ndn-repo-ng`). """ repoCommandPrefix = Name("/example/repo/1") repoDataPrefix = Name("/example/data/1") nowMilliseconds = int(time.time() * 1000.0) fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(nowMilliseconds) # 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()) # Register the prefix and send the repo insert command at the same time. startBlockId = 0 endBlockId = 1 enabled = [True] def onFinished(): dump("All data was inserted.") enabled[0] = False produceSegments = ProduceSegments( keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId, onFinished) dump("Register prefix", fetchPrefix.toUri()) def onRegisterFailed(prefix): dump("Register failed for prefix", prefix.toUri()) enabled[0] = False face.registerPrefix( fetchPrefix, produceSegments.onInterest, onRegisterFailed) def onInsertStarted(): dump("Insert started for", fetchPrefix.toUri()) def onFailed(): enabled[0] = False requestInsert( face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed, startBlockId, endBlockId) # 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()
def main(): """ Call startRepoWatch and register a prefix so that SendSegments will answer interests from the repo to send data packets for the watched prefix. When all the data is sent (or an error), call stopRepoWatch. This assumes that repo-ng is already running (e.g. `sudo ndn-repo-ng`). """ repoCommandPrefix = Name("/example/repo/1") repoDataPrefix = Name("/example/data/1") nowMilliseconds = int(time.time() * 1000.0) watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion( nowMilliseconds) # 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()) # Register the prefix and start the repo watch at the same time. enabled = [True] def onFinishedSending(): stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled) sendSegments = SendSegments( keyChain, keyChain.getDefaultCertificateName(), onFinishedSending) def onRegisterFailed(prefix): dump("Register failed for prefix", prefix.toUri()) enabled[0] = False dump("Register prefix", watchPrefix.toUri()) face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed) def onRepoWatchStarted(): dump("Watch started for", watchPrefix.toUri()) def onStartFailed(): dump("startRepoWatch failed.") stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled) startRepoWatch( face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed) # Run until someone sets enabled[0] = False. enabled[0] = True 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()
def main(): face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() certificateName = keyChain.getDefaultCertificateName() face.setCommandSigningInfo(keyChain, certificateName) test = DiscoveryTest(face, keyChain, certificateName) test.start() 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) face.shutdown()
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()
def run(self, namespace): # The default Face will connect using a Unix socket face = Face() prefix = Name(namespace) # Use the system default key chain and certificate name to sign commands. face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed) print "Registering prefix", prefix.toUri() while True: face.processEvents() time.sleep(0.01)
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()
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
def main(): prefix = Name("/nfd/edu/ucla/remap/test") # Route to aleph.ndn.ucla.edu. Have to use the canonical name with an IP # address and port. uri = "udp4://128.97.98.7:6363" # The default Face connects to the local NFD. face = Face() # Use the system default key chain and certificate name to sign commands. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Create the /localhost/nfd/faces/query command interest, including the # FaceQueryFilter. Construct the FaceQueryFilter using the structure in # face_query_filter_pb2 which was produced by protoc. message = face_query_filter_pb2.FaceQueryFilterMessage() filter = message.face_query_filter.add() filter.uri = uri encodedFilter = ProtobufTlv.encode(message) interest = Interest(Name("/localhost/nfd/faces/query")) interest.getName().append(encodedFilter) enabled = [True] def onComplete(content): processFaceStatus(content, prefix, uri, face, enabled) def onError(errorCode, message): enabled[0] = False dump(message) SegmentFetcher.fetch( face, interest, SegmentFetcher.DontVerifySegment, 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)
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. keyChain = KeyChain() face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. echo = Echo(keyChain, keyChain.getDefaultCertificateName()) 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()
def run(self, namespace): # Create a connection to the local forwarder over a Unix socket face = Face() prefix = Name(namespace) # Use the system default key chain and certificate name to sign commands. face.setCommandSigningInfo(self.keyChain, \ self.keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign Data packets. face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed) print "Registering prefix", prefix.toUri() # Run the event loop forever. Use a short sleep to # prevent the Producer from using 100% of the CPU. while not self.isDone: face.processEvents() time.sleep(0.01)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() groupName = Name("/Prefix/READ") userName = Name("/U") userKeyName = Name("/U/Key") contentPrefix = Name("/Prefix/SAMPLE") contentName = Name(contentPrefix).append("Content") keyChain = createVerifyKeyChain() # Imitate test_consumer from the PyNDN integration tests. databaseFilePath = "test.db" try: os.remove(databaseFilePath) except OSError: pass namespace = Namespace(contentName) namespace.setFace(face) handler = NacConsumerHandler( namespace, keyChain, groupName, userName, Sqlite3ConsumerDb(databaseFilePath)) fixtureUserDKeyBlob = Blob(FIXTURE_USER_D_KEY) handler.addDecryptionKey(userKeyName, fixtureUserDKeyBlob) enabled = [True] def onContentSet(namespace, contentNamespace, callbackId): if contentNamespace == namespace: dump("Got segmented content", contentNamespace.content.toRawStr()) enabled[0] = False namespace.addOnContentSet(onContentSet) segmentStream = SegmentStream(namespace) SegmentedContent(segmentStream) segmentStream.start() 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)
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'
def main(): face = Face("memoria.ndn.ucla.edu") page = Namespace("/ndn/edu/ucla/remap/demo/ndn-js-test/named-data.net/project/ndn-ar2011.html/%FDT%F7n%9E") page.setFace(face) enabled = [True] def onContentSet(namespace, contentNamespace, callbackId): if contentNamespace == namespace: dump("Got segmented content size", contentNamespace.content.size()) enabled[0] = False page.addOnContentSet(onContentSet) segmentStream = SegmentStream(page) SegmentedContent(segmentStream) segmentStream.start() # 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)
def run(self, prefix): self.keyChain = KeyChain() self.consoleThread = ConsoleThread() self.consoleThread.start() # The default Face will connect using a Unix socket face = Face() prefix = Name(prefix) # Use the system default key chain and certificate name to sign commands. face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName()) # Also use the default certificate name to sign data packets. face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed) print "Registering prefix", prefix.toUri() while not self.isDone: face.processEvents() time.sleep(0.01)
def main(): # The default Face will connect using a Unix socket, or to "localhost". face = Face() (keyChain, certificateName) = createKeyChain() face.setCommandSigningInfo(keyChain, certificateName) userKeyName = Name("/U/Key") contentPrefix = Name("/Prefix/SAMPLE") testProducer = TestProducer( contentPrefix, userKeyName, keyChain, certificateName) prefix = Name("/Prefix") dump("Register prefix", prefix.toUri()) face.registerPrefix( prefix, testProducer.onInterest, testProducer.onRegisterFailed) while testProducer._enabled: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
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: '******'t be blank") continue else: break while True: password = raw_input("Login password: "******"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()
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)
def main(): # Uncomment these lines to print ChronoSync debug messages. # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout)) # logging.getLogger('').setLevel(logging.INFO) screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap" hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ") if hubPrefix == "": hubPrefix = defaultHubPrefix defaultChatRoom = "ndnchat" chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ") if chatRoom == "": chatRoom = defaultChatRoom host = "localhost" print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"") # Set up the key chain. face = Face(host) identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), NoVerifyPolicyManager()) keyChain.setFace(face) 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) face.setCommandSigningInfo(keyChain, certificateName) chat = Chat( screenName, chatRoom, Name(hubPrefix), face, keyChain, certificateName) # The main loop to process Chat while checking stdin to send a message. print("Enter your chat message. To quit, enter \"leave\" or \"exit\".") while True: # Set timeout to 0 for an immediate check. isReady, _, _ = select.select([sys.stdin], [], [], 0) if len(isReady) != 0: input = promptAndInput("") if input == "leave" or input == "exit": # We will send the leave message below. break chat.sendMessage(input) face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01) # The user entered the command to leave. chat.leave() # Wait a little bit to allow other applications to fetch the leave message. startTime = Chat.getNowMilliseconds() while True: if Chat.getNowMilliseconds() - startTime >= 1000.0: break face.processEvents() time.sleep(0.01)
class LightController(): shouldSign = False COLORS_PER_LIGHT = 3 STRAND_SIZE = 50 def __init__(self, nStrands=1, myIP="192.168.1.1", lightIP="192.168.1.50", prefix="/testlight"): self.log = logging.getLogger("LightController") self.log.setLevel(logging.DEBUG) sh = logging.StreamHandler() sh.setLevel(logging.WARNING) self.log.addHandler(sh) fh = logging.FileHandler("LightController.log") fh.setLevel(logging.INFO) self.log.addHandler(fh) self.payloadBuffer = [[0]*self.STRAND_SIZE*self.COLORS_PER_LIGHT for n in range(nStrands)] self.kinetsender = KinetSender(myIP, lightIP, nStrands, self.STRAND_SIZE*self.COLORS_PER_LIGHT) self.registerFailed = False self.done = False self.prefix = Name(prefix) self.keychain = KeyChain() self.certificateName = self.keychain.getDefaultCertificateName() # XXX: we should get a thread for this or something! def start(self): self.face = Face() self.face.setCommandSigningInfo(self.keychain, self.certificateName) self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed) while self.face is not None: self.face.processEvents() if self.registerFailed: self.stop() break #time.sleep(0.001) def stop(self): self.kinetsender.stop = True self.kinetsender.complete.wait() self.face.shutdown() self.face = None def signData(self, data): if LightController.shouldSign: self.keychain.sign(data, self.certificateName) else: data.setSignature(Sha256WithRsaSignature()) def setPayloadColor(self, strand, color): # will expand this to allow the repeats, etc self.payloadBuffer[strand] = [int(color.r)&0xff, int(color.g)&0xff, int(color.b)&0xff]*self.STRAND_SIZE 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()) def onRegisterFailed(self, prefix): self.log.error("Could not register " + prefix.toUri()) print "Register failed!" self.registerFailed = True def sendLightPayload(self, port): self.kinetsender.setPayload(port, self.payloadBuffer[port-1])