from pyccn import CCN, Name, Interest, Closure from time import sleep worked = False class MyClosure(Closure): def upcall(self, kind, upcallInfo): global worked print("Got response") print(kind) print(upcallInfo) worked = True n = Name("ccnx:/ccnx/ping") i = Interest() closure = MyClosure() c = CCN() res = c.expressInterest(n, closure, i) print(res) #causes crashes c.run(10) print("Ha!") assert(worked)
class CcnxSocket(object): ''' A socket like handler for ccnx operations. Runs a simple event loop and handles set interest filter, send interest, and publish data. Current only one ccnx handle is used, we can use multiple handles if needed, but there is no such need as of now. ''' __logger = Logger.get_logger('CcnxSocket') def __init__(self, *args, **kwargs): ''' Creates a socket. As of now, we try to get the ccnx key from the default location ''' super(CcnxSocket, self).__init__() self.ccnx_key = CCN.getDefaultKey() self.ccnx_key_locator = pyccn.KeyLocator(self.ccnx_key) self.ccnx_handle = CCN() self.event_loop = CcnxLoop(self.ccnx_handle) def get_signed_info(self, freshness): ''' Get signed info to be included in the Content Object Args: freshness (int): the freshness of the Content Object in seconds Returns: a PyCCN.SignedInfo object ''' si = pyccn.SignedInfo() si.publisherPublicKeyDigest = self.ccnx_key.publicKeyID si.type = pyccn.CONTENT_DATA si.freshnessSeconds = freshness si.keyLocator = self.ccnx_key_locator return si def get_pyccn_name(self, name): '''Get a valid name for PyCCN. This is useful when the name string is encoded as unicode, as is the usual case in Python. However, PyCCN has problem handling unicode names, raising TypeError as a result. Args: name (str): the name string Returns: An ascii encoded name string ''' if isinstance(name, unicode): return Name(name.encode('ascii', 'ignore')) else: return Name(name) def publish_content(self, name, content, freshness = 5): '''Publish the data as a Content Object Args: name (str): the name string content (bytes): the data bytes Kwargs: freshness (int): the freshness in seconds for the Content Object ''' co = ContentObject() co.name = self.get_pyccn_name(name) co.content = content si = self.get_signed_info(freshness) co.signedInfo = si co.sign(self.ccnx_key) self.ccnx_handle.put(co) def send_interest(self, name, closure, template = None): '''Send Interest Args: name (str): the name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN for this Interest Kwargs: template (PyCCN.Interest): the template for the additional field to be carried in the Interest, such as ChildSelector, Lifetime, AnswerOrigin, etc.. ''' n = self.get_pyccn_name(name) self.ccnx_handle.expressInterest(n, closure, template) def register_prefix(self, prefix, closure): '''Register the prefix under which the user wishes to receive Interests Args: prefix (str): the prefix name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN when an Interest with such prefix comes ''' p = self.get_pyccn_name(prefix) self.ccnx_handle.setInterestFilter(p, closure) def start(self): '''Start the CcnxLoop ''' start_new_thread(self.event_loop.run, ()) def stop(self): '''Stop the CcnxLoop ''' self.event_loop.stop()
print for obj in tyzxObjects.values(): print obj.id, ":", obj.x, obj.y, obj.z, obj.localupdatetime if __name__ == "__main__": print "prefix", prefix processIncoming = ProcessIncoming() while (True): T = time.time() if T - lastdiscovertime > DISCOVER_INTEREST_PERIOD: interestDiscover.exclude = ExclusionFilter() interestDiscover.exclude.add_names( [Name([key]) for key in tyzxObjects.keys()]) interestDiscover.exclude.add_names( [Name([key]) for key in oldObjects]) ccn.expressInterest(interestDiscover.name, processIncoming, interestDiscover) lastdiscovertime = time.time() for obj in tyzxObjects.values(): if T - obj.lastinteresttime < UPDATE_INTEREST_PERIOD: continue interestUpdate.name = Name(prefix) interestUpdate.name += str(obj.id) interestUpdate.exclude = ExclusionFilter() interestUpdate.exclude.add_any() n = Name() n.components.append(versionFromTime(obj.time)) interestUpdate.exclude.add_name(n) interestUpdate.exclude.add_name(Name([last_version_marker])) interestUpdate.exclude.add_any() ccn.expressInterest(interestUpdate.name, processIncoming, interestUpdate)
class sequencer(Closure): #ensure singleton _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(sequencer, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, configFileName): self.appConfigFileName = configFileName self.loadConfigFile() self.handle = CCN() self.getApplicationKey() #nameCrypto self.state = NameCrypto.new_state() self.cryptoKey = NameCrypto.generate_application_key(self.cfg.fixtureKey, self.cfg.appName) def loadConfigFile(self): command = "import "+self.appConfigFileName+" as appCfg" exec(command) self.appCfg = appCfg; self.cfg = appCfg; def getApplicationKey(self): print("getting application key for "+self.appCfg.appName) key = Key() keyFile = self.appCfg.keyFile key.fromPEM(filename=keyFile) self.appKey = key self.key = key def start(self): print "starting "+self.cfg.appName #self.allWhite() #self.allBlack() #self.spazz() def spazz(self): for i in range(1,500000): self.allWhite() self.allBlack() def allWhite(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],255,255,255) def allBlack(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],0,0,0) def sendAllLights(self,r,g,b): for d in self.cfg.names: if d['name'] != "incandescent": self.buildAndSendInterest(d['name'],r,g,b) return def hx(self, inum): num = hex(inum)[2:] if (len(num) == 1): num = '0'+num #print num return str(num) def buildAndSendInterest(self,device,r,g,b): rx = self.hx(r) gx = self.hx(g) bx = self.hx(b) CLI = device+"/setRGB/"+rx+gx+bx #print CLI self.sendSignedInterest(CLI) def sendInterest(self,command): n = Name.Name(self.cfg.appPrefix) print("\nInterest espressing for "+str(n)) n += command i = Interest.Interest() print("Interest sending to "+str(n)) co = self.handle.get(n,i,20) if not not co: #if co is not empty, print result for debugging print("content: "+str(co.content)) pass def sendSignedInterest(self,command): fullURI = self.cfg.appPrefix + command #print fullURI i = Interest() #build keyLocator to append to interest for NameCrypto on upcall keyLoc = pyccn.KeyLocator(self.key) keyLocStr = _pyccn.dump_charbuf(keyLoc.ccn_data) nameAndKeyLoc = Name(str(fullURI)) #print("there are "+str(len(nameAndKeyLoc))+" components") nameAndKeyLoc += keyLocStr #print("there are "+str(len(nameAndKeyLoc))+" components after adding keyLocStr") t0 = time() authName = NameCrypto.authenticate_command(self.state, nameAndKeyLoc, self.cfg.appName, self.cryptoKey) t1 = time() #print "elapsed sign", t1-t0 #print authName.components t0 = time() co = self.handle.expressInterest(authName,self) t1 = time()
return pyccn.RESULT_OK senderclosure = SenderClosure() receiverclosure = ReceiverClosure() sender_handle = CCN() receiver_handle = CCN() #Looks like the CCNx API doesn't deliver messages #that we sent to ourselves, so we just push it sender_handle.setInterestFilter(n, senderclosure) #senderclosure.upcall(1, None) i = Interest() receiver_handle.expressInterest(n, receiverclosure, i) upcall_called = False print("Running loops") #So sender closure is called #sender_handle.run(500) #So receiver closure is called #receiver_handle.run(500) # New way of doing this event_loop = pyccn.EventLoop(sender_handle, receiver_handle) event_loop.run()
from pyccn import CCN, Name, Interest, Closure from time import sleep worked = False class MyClosure(Closure): def upcall(self, kind, upcallInfo): global worked print("Got response") print(kind) print(upcallInfo) worked = True n = Name("ccnx:/ccnx/ping") i = Interest() closure = MyClosure() c = CCN() res = c.expressInterest(n, closure, i) print(res) #causes crashes c.run(10) print("Ha!") assert (worked)
class sequencer(Closure): def __init__(self, configFileName): self.appConfigFileName = configFileName self.loadConfigFile() self.handle = CCN() self.getApplicationKey() #nameCrypto self.state = NameCrypto.new_state() self.cryptoKey = NameCrypto.generate_application_key(self.cfg.fixtureKey, self.cfg.appName) self.count = 0 def loadConfigFile(self): command = "import "+self.appConfigFileName+" as appCfg" exec(command) self.appCfg = appCfg; self.cfg = appCfg; def getApplicationKey(self): #print("getting application key for "+self.appCfg.appName) key = Key() keyFile = self.appCfg.keyFile key.fromPEM(filename=keyFile) self.appKey = key self.key = key def start(self): #print "starting "+self.cfg.appName self.startTime = time.time() #self.play() #self.send() #self.discoProfile() #self.disco() #self.mobileDisco() #self.discoArt() #self.allWhite() self.allBlack() #self.spazz() def spazz(self): for i in range(1,500000): self.allWhite() self.allBlack() def allWhite(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],255,255,255) def allBlack(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendArtInterest('incandescent',0,) def disco(self): print "fading..." for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] r = b = g = 0 #red for i in range(0,85): r=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): r=0 g=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): g=0 b=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],0,0,0) return def discoProfile(self): print "fading..." for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] r = b = g = 0 #red for i in range(0,85): r=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): r=0 g=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): g=0 b=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],0,0,0) print "DONE" self.sendSignedInterest("whatever/profileStop/000000") self.endTime = time.time() print "total time is ",(self.endTime - self.startTime) print "number of interests is ",self.count print "average time per interest is ",((self.endTime - self.startTime)/self.count) return def mobileDisco(self): print "fading around" for i in range(0,85): r = b = g = 0 #red for i in range(0,85): r=i self.sendValToAllLights(r*3,g*3,b*3) for i in range(0,85): r=0 g=i self.sendValToAllLights(r*3,g*3,b*3) for i in range(0,85): g=0 b=i self.sendValToAllLights(r*3,g*3,b*3) self.sendValToAllLights(0,0,0) self.sendValToAllLights(255,255,255) self.sendValToAllLights(0,0,0) self.sendValToAllLights(255,255,255) self.sendValToAllLights(0,0,0) sys.exit() def sendValToAllLights(self,r,g,b): for d in self.cfg.names: self.buildAndSendInterest(d['name'],r,g,b) def discoArt(self): print "fading..." for d in self.cfg.names: if d['name'] == "incandescent": print d['name'] r = b = g = 0 #red for i in range(0,250): r=i self.buildAndSendArtInterest(d['name'],r) self.discoArt() def hx(self, inum): num = hex(inum)[2:] if (len(num) == 1): num = '0'+num #print num return str(num) def buildAndSendInterest(self,device,r,g,b): #rx = hex(r)[2:] #gx = hex(g)[2:] #bx = hex(b)[2:] rx = self.hx(r) gx = self.hx(g) bx = self.hx(b) #CLI = self.cfg.interestPrefix+device+"/rgb-8bit-hex/"+rx+gx+bx CLI = device+"/setRGB/"+rx+gx+bx #print CLI self.sendSignedInterest(CLI) #living-room-right-wall/rgb-8bit-hex/d2741d #interestPrefix #ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-right-wall/rgb-8bit-hex/d2741d def buildAndSendArtInterest(self,device,r): rx = self.hx(r) #gx = hex(g)[2:] #bx = hex(b)[2:] #rx = self.hx(r) #CLI = self.cfg.interestPrefix+device+"/rgb-8bit-hex/"+rx+gx+bx CLI = device+"/setBrightness/"+rx #print CLI self.sendSignedInterest(CLI) #living-room-right-wall/rgb-8bit-hex/d2741d #interestPrefix #ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-right-wall/rgb-8bit-hex/d2741d def sendInterest(self,command): n = Name(self.cfg.appPrefix) print("\nInterest espressing for "+str(n)) n += command #fullURI = self.cfg.interestPrefix + command #print fullURI i = Interest.Interest() #n = Name.Name([fullURI]) #this does not parse correctly #n = Name.Name(fullURI) print("Interest sending to "+str(n)) co = self.handle.get(n,i,200) if not not co: #if co is not empty, print result for debugging print("content: "+str(co.content)) def sendSignedInterest(self,command): self.count = self.count +1 time.sleep(self.cfg.refreshInterval) fullURI = self.cfg.appPrefix + command #print fullURI i = Interest() #self.state = NameCrypto.new_state() #build keyLocator to append to interest for NameCrypto on upcall keyLoc = pyccn.KeyLocator(self.key) keyLocStr = _pyccn.dump_charbuf(keyLoc.ccn_data) nameAndKeyLoc = Name(str(fullURI)) #print("there are "+str(len(nameAndKeyLoc))+" components") nameAndKeyLoc += keyLocStr #print("there are "+str(len(nameAndKeyLoc))+" components after adding keyLocStr") #symmetric authName = NameCrypto.authenticate_command(self.state, nameAndKeyLoc, self.cfg.appName, self.cryptoKey) #asymmetric #authName = NameCrypto.authenticate_command_sig(self.state, nameAndKeyLoc, self.cfg.appName, self.key) #print authName.components co = self.handle.expressInterest(authName,self)
class CcnxSocket(object): ''' A socket like handler for ccnx operations. Runs a simple event loop and handles set interest filter, send interest, and publish data. Current only one ccnx handle is used, we can use multiple handles if needed, but there is no such need as of now. ''' __logger = Logger.get_logger('CcnxSocket') def __init__(self, *args, **kwargs): ''' Creates a socket. As of now, we try to get the ccnx key from the default location ''' super(CcnxSocket, self).__init__() self.ccnx_key = CCN.getDefaultKey() self.ccnx_key_locator = pyccn.KeyLocator(self.ccnx_key) self.ccnx_handle = CCN() self.event_loop = CcnxLoop(self.ccnx_handle) def get_signed_info(self, freshness): ''' Get signed info to be included in the Content Object Args: freshness (int): the freshness of the Content Object in seconds Returns: a PyCCN.SignedInfo object ''' si = pyccn.SignedInfo() si.publisherPublicKeyDigest = self.ccnx_key.publicKeyID si.type = pyccn.CONTENT_DATA si.freshnessSeconds = freshness si.keyLocator = self.ccnx_key_locator return si def get_pyccn_name(self, name): '''Get a valid name for PyCCN. This is useful when the name string is encoded as unicode, as is the usual case in Python. However, PyCCN has problem handling unicode names, raising TypeError as a result. Args: name (str): the name string Returns: An ascii encoded name string ''' if isinstance(name, unicode): return Name(name.encode('ascii', 'ignore')) else: return Name(name) def publish_content(self, name, content, freshness=5): '''Publish the data as a Content Object Args: name (str): the name string content (bytes): the data bytes Kwargs: freshness (int): the freshness in seconds for the Content Object ''' co = ContentObject() co.name = self.get_pyccn_name(name) co.content = content si = self.get_signed_info(freshness) co.signedInfo = si co.sign(self.ccnx_key) self.ccnx_handle.put(co) def send_interest(self, name, closure, template=None): '''Send Interest Args: name (str): the name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN for this Interest Kwargs: template (PyCCN.Interest): the template for the additional field to be carried in the Interest, such as ChildSelector, Lifetime, AnswerOrigin, etc.. ''' n = self.get_pyccn_name(name) self.ccnx_handle.expressInterest(n, closure, template) def register_prefix(self, prefix, closure): '''Register the prefix under which the user wishes to receive Interests Args: prefix (str): the prefix name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN when an Interest with such prefix comes ''' p = self.get_pyccn_name(prefix) self.ccnx_handle.setInterestFilter(p, closure) def start(self): '''Start the CcnxLoop ''' start_new_thread(self.event_loop.run, ()) def stop(self): '''Stop the CcnxLoop ''' self.event_loop.stop()
def printPresent(self): print for obj in tyzxObjects.values(): print obj.id,":", obj.x, obj.y, obj.z, obj.localupdatetime if __name__ == "__main__": print "prefix", prefix processIncoming = ProcessIncoming() while (True): T = time.time() if T-lastdiscovertime > DISCOVER_INTEREST_PERIOD: interestDiscover.exclude = ExclusionFilter() interestDiscover.exclude.add_names([Name([key]) for key in tyzxObjects.keys()]) interestDiscover.exclude.add_names([Name([key]) for key in oldObjects]) ccn.expressInterest(interestDiscover.name, processIncoming, interestDiscover) lastdiscovertime = time.time() for obj in tyzxObjects.values(): if T-obj.lastinteresttime < UPDATE_INTEREST_PERIOD: continue interestUpdate.name = Name(prefix) interestUpdate.name += str(obj.id) interestUpdate.exclude = ExclusionFilter() interestUpdate.exclude.add_any() n = Name() n.components.append(versionFromTime(obj.time)) interestUpdate.exclude.add_name(n) interestUpdate.exclude.add_name(Name([last_version_marker])) interestUpdate.exclude.add_any() ccn.expressInterest(interestUpdate.name, processIncoming, interestUpdate) obj.lastinteresttime = time.time()