Пример #1
0
class SongHandler:

    def __init__(self):

        self._device = "PC1"
        self._playPrefix = Name("/ndn/edu/ucla/remap/music/play")
	self.prefix = self._playPrefix.append(self._device)
        self._face = None
        self._loop = None

	self.thread = None
        
        self._keyChain = KeyChain()
        self._certificateName = self._keyChain.getDefaultCertificateName()

        self._repoCommandPrefix = "/example/repo/1"

	self.song = ""
	self.ftxt = ""
	self.ffreq = ""

	self.songList = ""
	self.mp = MusicPlayer()
	self.config = RawConfigParser()
	self.config.read('config.cfg')
	self.s = LightMessenger(self.config)

	self.q = Queue.Queue()
	

    def start(self):
        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop,"")
        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._face.registerPrefix(self.prefix, self.onPlayingCommand, self.onRegisterFailed)
	print "after register prefix"
        try:
            self._loop.run_forever()
        except KeyboardInterrupt:
            sys.exit()
        finally:
            self.stop()

    def stop(self):
        self._loop.close()        
        self._face.shutdown()
        sys.exit(1)

    def playFunction(self):

	    txt = open(self.ftxt)
	    print "open txt successfully",self.ftxt
	
		#collect the onset duration
	    osDur = [0.0]
	    freq = []
	    data = [float(line.split()[0])for line in txt]
	
	    for i in data:
	    	osDur.append(i)
	    txt.close()
	    txt = open(self.ffreq)
	    print "open txt successfully",self.ffreq
	    data = [float(line.split()[1])for line in txt]
	    print "dasfdaaaa"
	    for j in data:
		freq.append(j)
	    avefq = int(sum(freq)/len(freq))  
	    print avefq  	
	    txt.close()
	    g=(avefq-100)/10
	    r=avefq/30
	    b=(100-avefq)/10
	    startingColors = [int((15+r)/1.5),int((10+g)/1.5), int((10+b)/1.5)]
	    for i in range(0,3):
		if startingColors[i]<0:
			startingColors[i]=6
	    #startingColors = [5,5,5]
	    self.q.put(self.song+str("-music.mp3") )
	    print "MusicPlayer.isPlaying",MusicPlayer.isPlaying
	    if not MusicPlayer.isPlaying:
    	    	self.thread.start() 
		#MusicPlayer.isPlaying = True 
	      
	    self.s.start(osDur,startingColors)

    def getOnset(self):
	print "getonset"
	otxt = self.song+str("-o")
	print otxt
	g = GetFile(self._repoCommandPrefix, otxt, self._face, self.getFreq)
	g.oStream = open(self.song+str("-os.txt"),'wb')    
	g.start()

    def getFreq(self):
	print "getfreq"
	ftxt = self.song+str("-f")
	g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.playFunction)
	g.oStream = open(self.song+str("-freq.txt"),'wb')    
	g.start()

    def signData(self, data):
        data.setSignature(Sha256WithRsaSignature())
        

    def onPlayingCommand(self, prefix, interest, transport, prefixId):
	print "receive interest"
        interestName = Name(interest.getName())
        commandComponent = interest.getName().get(self.prefix.size())
        if commandComponent == Name.Component("stop"):
            pass
        if commandComponent == Name.Component("play"):
            pass
        else:
            songName = commandComponent.toEscapedString()
	    print songName
	    songList = []
	    songList = songName.split('%2C')
	    print "songlist and its len",songList,len(songList)
	    for i in songList:
		self.song = i
            	fmusic = i+str("-music.mp3") 
		self.ftxt = i + str("-os.txt")
		self.ffreq = i + str("-freq.txt")
		print "FMUSIC:",fmusic 
		  
	    	self.thread = threading.Thread(target = self.mp.play_music, args = (fmusic,songList,self.q,))
	    	self.thread.daemon = True
            	g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset)
		#g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.lightFunction)
            	g.oStream = open(fmusic,'wb')
            	g.start()
	   
		
	
	d = Data(interest.getName())
	d.setContent("start to play: " + songName + "\n")
	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())	

        
            
    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        self.stop()
Пример #2
0
class BaseNode(object):
    """
    This class contains methods/attributes common to both node and controller.
    
    """
    def __init__(self):
        """
        Initialize the network and security classes for the node
        """
        super(BaseNode, self).__init__()

        self._identityStorage = IotIdentityStorage()
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._policyManager = IotPolicyManager(self._identityStorage)

        # hopefully there is some private/public key pair available
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._registrationFailures = 0
        self._prepareLogging()

        self._setupComplete = False
        self._instanceSerial = None

        # waiting devices register this prefix and respond to discovery
        # or configuration interest
        self._hubPrefix = Name('/localhop/configure')

    def getSerial(self):
        """
         Since you may wish to run two nodes on a Raspberry Pi, each
         node will generate a unique serial number each time it starts up.
        """
        if self._instanceSerial is None:
            prefixLen = 4
            prefix = ''
            for i in range(prefixLen):
                prefix += (chr(random.randint(0,0xff)))
            suffix = self.getDeviceSerial().lstrip('0')
            self._instanceSerial = '-'.join([prefix.encode('hex'), suffix])
        return self._instanceSerial

##
# Logging
##
    def _prepareLogging(self):
        self.log = logging.getLogger(str(self.__class__))
        self.log.setLevel(logging.DEBUG)
        logFormat = "%(asctime)-15s %(name)-20s %(funcName)-20s (%(levelname)-8s):\n\t%(message)s"
        self._console = logging.StreamHandler()
        self._console.setFormatter(logging.Formatter(logFormat))
        self._console.setLevel(logging.INFO)
        # without this, a lot of ThreadsafeFace errors get swallowed up
        logging.getLogger("trollius").addHandler(self._console)
        self.log.addHandler(self._console)

    def setLogLevel(self, level):
        """
        Set the log level that will be output to standard error
        :param level: A log level constant defined in the logging module (e.g. logging.INFO) 
        """
        self._console.setLevel(level)

    def getLogger(self):
        """
        :return: The logger associated with this node
        :rtype: logging.Logger
        """
        return self.log

###
# Startup and shutdown
###
    def beforeLoopStart(self):
        """
        Called before the event loop starts.
        """
        pass

    def getDefaultCertificateName(self):
        try:
            certName = self._identityStorage.getDefaultCertificateNameForIdentity( 
                self._policyManager.getDeviceIdentity())
        except SecurityException:
            certName = self._keyChain.getDefaultCertificateName()

        return certName

    def start(self):
        """
        Begins the event loop. After this, the node's Face is set up and it can
        send/receive interests+data
        """
        self.log.info("Starting up")
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, '')
        self.face.setCommandSigningInfo(self._keyChain, self.getDefaultCertificateName())
        self._keyChain.setFace(self.face)

        self._isStopped = False
        self.face.stopWhen(lambda:self._isStopped)
        self.beforeLoopStart()
        
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            pass
        except Exception as e:
            self.log.exception(e, exc_info=True)
        finally:
            self._isStopped = True

    def stop(self):
        """
        Stops the node, taking it off the network
        """
        self.log.info("Shutting down")
        self._isStopped = True 
        
###
# Data handling
###
    def signData(self, data):
        """
        Sign the data with our network certificate
        :param pyndn.Data data: The data to sign
        """
        self._keyChain.sign(data, self.getDefaultCertificateName())

    def sendData(self, data, transport, sign=True):
        """
        Reply to an interest with a data packet, optionally signing it.
        :param pyndn.Data data: The response data packet
        :param pyndn.Transport transport: The transport to send the data through. This is 
            obtained from an incoming interest handler
        :param boolean sign: (optional, default=True) Whether the response must be signed. 
        """
        if sign:
            self.signData(data)
        transport.send(data.wireEncode().buf())

###
# 
# 
##
    def onRegisterFailed(self, prefix):
        """
        Called when the node cannot register its name with the forwarder
        :param pyndn.Name prefix: The network name that failed registration
        """
        if self._registrationFailures < 5:
            self._registrationFailures += 1
            self.log.warn("Could not register {}, retry: {}/{}".format(prefix.toUri(), self._registrationFailures, 5)) 
            self.face.registerPrefix(self.prefix, self._onCommandReceived, self.onRegisterFailed)
        else:
            self.log.critical("Could not register device prefix, ABORTING")
            self._isStopped = True

    def verificationFailed(self, dataOrInterest):
        """
        Called when verification of a data packet or command interest fails.
        :param pyndn.Data or pyndn.Interest: The packet that could not be verified
        """
        self.log.info("Received invalid" + dataOrInterest.getName().toUri())

    @staticmethod
    def getDeviceSerial():
        """
        Find and return the serial number of the Raspberry Pi. Provided in case
        you wish to distinguish data from nodes with the same name by serial.
        :return: The serial number extracted from device information in /proc/cpuinfo
        :rtype: str
        """
        with open('/proc/cpuinfo') as f:
            for line in f:
                if line.startswith('Serial'):
                    return line.split(':')[1].strip()
Пример #3
0
class RegisterSongList(object):
    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

        logging.basicConfig()
        '''#这些log是干嘛的myIP="192.168.1.1",lightIP="192.168.1.50",
        self.log = logging.getLogger("RegisterSongList")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        self.log.addHandler(sh)
        fh = logging.FileHandler("RegisterSongList.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)'''
        self.device = "PC3"
        self.deviceComponent = Name.Component(self.device)
        self.excludeDevice = None
        #self.songList = originalList

        #security?
        self.prefix = Name(prefix)
        self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True

    #self.payloadBuffer = []

    #self.kinetsender = KinetSender(myIP, playerIP,self.STRAND_SIZE*self.COLORS_PER_LIGHT)

    def start(self):
        print "reg start"
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, self.address)
        self.face.setCommandSigningInfo(self.keychain, self.certificateName)
        self.face.registerPrefix(self.prefix, self.onInterest,
                                 self.onRegisterFailed)
        self._isStopped = False
        self.face.stopWhen(lambda: self._isStopped)
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:

            sys.exit()
        finally:
            self.stop()

    def stop(self):
        self.loop.close()
        #self.kinetsender.stop = True
        #self.kinetsender.complete.wait()
        self.face.shutdown()
        self.face = None
        sys.exit(1)

    def signData(self, data):
        data.setSignature(Sha256WithRsaSignature())
        #self.keychain.sign(data,self.certificateName)

    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:", initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
        #initInterest = interest.getName()
        d = Data(interest.getName().append(self.deviceComponent))
        try:
            print "start to set data's content"

            currentString = ','.join(currentList)
            d.setContent("songList of " + self.device + ":" + currentString +
                         "\n")
            self.face.registerPrefix(self.changePrefix, self.onInterest,
                                     self.onRegisterFailed)

        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
        print d.getName().toUri()
        print d.getContent()

        self.stop()
        '''print"remove register"
        self.face.removeRegisteredPrefix(registeredPrefixId)
        time.sleep(30)
        #sleep 30s which means user cannot update the song list twice within 1 minutes
	print"register again"
        self.face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed)'''

    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        self.stop()
Пример #4
0
class RegisterSongList(object):


    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

	logging.basicConfig()        
	'''#这些log是干嘛的myIP="192.168.1.1",lightIP="192.168.1.50",
        self.log = logging.getLogger("RegisterSongList")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        self.log.addHandler(sh)
        fh = logging.FileHandler("RegisterSongList.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)'''
    	self.device = "PC3"
    	self.deviceComponent = Name.Component(self.device)
	self.excludeDevice = None
    	#self.songList = originalList

        #security?
        self.prefix = Name(prefix)
	self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True
  
        #self.payloadBuffer = []

        #self.kinetsender = KinetSender(myIP, playerIP,self.STRAND_SIZE*self.COLORS_PER_LIGHT)




    
    def start(self):
	print "reg start"
	self.loop = asyncio.get_event_loop()
	self.face = ThreadsafeFace(self.loop,self.address)
	self.face.setCommandSigningInfo(self.keychain,self.certificateName)
        self.face.registerPrefix(self.prefix,self.onInterest,self.onRegisterFailed)
        self._isStopped = False
        self.face.stopWhen(lambda:self._isStopped)
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:

            sys.exit()
        finally:
            self.stop()


    def stop(self):
        self.loop.close()
        #self.kinetsender.stop = True
        #self.kinetsender.complete.wait()         
        self.face.shutdown()
        self.face = None
        sys.exit(1)

    def signData(self,data):
	data.setSignature(Sha256WithRsaSignature())
	#self.keychain.sign(data,self.certificateName)

    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
	#initInterest = interest.getName()
	d = Data(interest.getName().append(self.deviceComponent))
	try:
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)	



	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()

	self.stop()
		
	'''print"remove register"
        self.face.removeRegisteredPrefix(registeredPrefixId)
        time.sleep(30)
        #sleep 30s which means user cannot update the song list twice within 1 minutes
	print"register again"
        self.face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed)'''

    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        self.stop()
Пример #5
0
class BaseNode(object):
    """
    This class contains methods/attributes common to both node and controller.
    
    """
    def __init__(self):
        """
        Initialize the network and security classes for the node
        """
        super(BaseNode, self).__init__()

        self._identityStorage = IotIdentityStorage()
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._policyManager = IotPolicyManager(self._identityStorage)

        # hopefully there is some private/public key pair available
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._registrationFailures = 0
        self._prepareLogging()

        self._setupComplete = False
        self._instanceSerial = None

        # waiting devices register this prefix and respond to discovery
        # or configuration interest
        self._hubPrefix = Name('/localhop/configure')

    def getSerial(self):
        """
         Since you may wish to run two nodes on a Raspberry Pi, each
         node will generate a unique serial number each time it starts up.
        """
        if self._instanceSerial is None:
            prefixLen = 4
            prefix = ''
            for i in range(prefixLen):
                prefix += (chr(random.randint(0, 0xff)))
            suffix = self.getDeviceSerial().lstrip('0')
            self._instanceSerial = '-'.join([prefix.encode('hex'), suffix])
        return self._instanceSerial

##
# Logging
##

    def _prepareLogging(self):
        self.log = logging.getLogger(str(self.__class__))
        self.log.setLevel(logging.DEBUG)
        logFormat = "%(asctime)-15s %(name)-20s %(funcName)-20s (%(levelname)-8s):\n\t%(message)s"
        self._console = logging.StreamHandler()
        self._console.setFormatter(logging.Formatter(logFormat))
        self._console.setLevel(logging.INFO)
        # without this, a lot of ThreadsafeFace errors get swallowed up
        logging.getLogger("trollius").addHandler(self._console)
        self.log.addHandler(self._console)

    def setLogLevel(self, level):
        """
        Set the log level that will be output to standard error
        :param level: A log level constant defined in the logging module (e.g. logging.INFO) 
        """
        self._console.setLevel(level)

    def getLogger(self):
        """
        :return: The logger associated with this node
        :rtype: logging.Logger
        """
        return self.log

###
# Startup and shutdown
###

    def beforeLoopStart(self):
        """
        Called before the event loop starts.
        """
        pass

    def getDefaultCertificateName(self):
        try:
            certName = self._identityStorage.getDefaultCertificateNameForIdentity(
                self._policyManager.getDeviceIdentity())
        except SecurityException:
            certName = self._keyChain.getDefaultCertificateName()

        return certName

    def start(self):
        """
        Begins the event loop. After this, the node's Face is set up and it can
        send/receive interests+data
        """
        self.log.info("Starting up")
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, '')
        self.face.setCommandSigningInfo(self._keyChain,
                                        self.getDefaultCertificateName())
        self._keyChain.setFace(self.face)

        self._isStopped = False
        self.face.stopWhen(lambda: self._isStopped)
        self.beforeLoopStart()

        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            pass
        except Exception as e:
            self.log.exception(e, exc_info=True)
        finally:
            self._isStopped = True

    def stop(self):
        """
        Stops the node, taking it off the network
        """
        self.log.info("Shutting down")
        self._isStopped = True

###
# Data handling
###

    def signData(self, data):
        """
        Sign the data with our network certificate
        :param pyndn.Data data: The data to sign
        """
        self._keyChain.sign(data, self.getDefaultCertificateName())

    def sendData(self, data, transport, sign=True):
        """
        Reply to an interest with a data packet, optionally signing it.
        :param pyndn.Data data: The response data packet
        :param pyndn.Transport transport: The transport to send the data through. This is 
            obtained from an incoming interest handler
        :param boolean sign: (optional, default=True) Whether the response must be signed. 
        """
        if sign:
            self.signData(data)
        transport.send(data.wireEncode().buf())

###
#
#
##

    def onRegisterFailed(self, prefix):
        """
        Called when the node cannot register its name with the forwarder
        :param pyndn.Name prefix: The network name that failed registration
        """
        if self._registrationFailures < 5:
            self._registrationFailures += 1
            self.log.warn("Could not register {}, retry: {}/{}".format(
                prefix.toUri(), self._registrationFailures, 5))
            self.face.registerPrefix(self.prefix, self._onCommandReceived,
                                     self.onRegisterFailed)
        else:
            self.log.critical("Could not register device prefix, ABORTING")
            self._isStopped = True

    def verificationFailed(self, dataOrInterest):
        """
        Called when verification of a data packet or command interest fails.
        :param pyndn.Data or pyndn.Interest: The packet that could not be verified
        """
        self.log.info("Received invalid" + dataOrInterest.getName().toUri())

    @staticmethod
    def getDeviceSerial():
        """
        Find and return the serial number of the Raspberry Pi. Provided in case
        you wish to distinguish data from nodes with the same name by serial.
        :return: The serial number extracted from device information in /proc/cpuinfo
        :rtype: str
        """
        with open('/proc/cpuinfo') as f:
            for line in f:
                if line.startswith('Serial'):
                    return line.split(':')[1].strip()
Пример #6
0
class SongHandler:

	def __init__(self):

		self._device = "PC1"
		self._playPrefix = Name("/ndn/edu/ucla/remap/music/play")
		self.prefix = self._playPrefix.append(self._device)
		
		self._face = None
		self._loop = None
	
		self._keyChain = KeyChain()
		self._certificateName = self._keyChain.getDefaultCertificateName()

		self._repoCommandPrefix = "/example/repo/1"

		self.mp = MusicPlayer()
		#self._getFiles = []
		
	def start(self):
		self._loop = asyncio.get_event_loop()
		self._face = ThreadsafeFace(self._loop,"")
		self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
		self._face.registerPrefix(self.prefix, self.onPlayingCommand, self.onRegisterFailed)
	
		try:
			self._loop.run_forever()
		except KeyboardInterrupt:
			sys.exit()
		finally:
			self.stop()

	def stop(self):
		self._loop.close()	
		self._face.shutdown()
		sys.exit(1)

	def getOnset(self, musicName):
		otxt = musicName + str("-o")
		print otxt
		g = GetFile(self._repoCommandPrefix, otxt, self._face, self.getFreq, musicName)
		g.oStream = open(musicName + str("-os.txt"), 'wb')
		g.start()
		
		#self._getFiles.append(g)

	def getFreq(self, musicName):
		ftxt = musicName + str("-f")
		print musicName, " get Freq called"
		g = GetFile(self._repoCommandPrefix, ftxt, self._face, self.mp.play_music, musicName, False)
		g.oStream = open(musicName + str("-freq.txt"),'wb')
		g.start()
		
		#self._getFiles.append(g)

	def signData(self, data):
		data.setSignature(Sha256WithRsaSignature())
	
	def onPlayingCommand(self, prefix, interest, transport, prefixId):
		
		interestName = Name(interest.getName())
		commandComponent = interest.getName().get(self.prefix.size())
		if commandComponent == Name.Component("stop"):
			pass
		if commandComponent == Name.Component("play"):
			pass
		else:
			songName = commandComponent.toEscapedString()
	    
		songList = []
		songList = songName.split('%2C')
	    
		for i in songList:
			fmusic = i + str("-music.mp3") 
			print "started getting music file", i
			
			g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset, i)
			
			g.oStream = open(fmusic,'wb')
			g.start()
			
			#self._getFiles.append(g)
			
		d = Data(interest.getName())
		d.setContent("start to play: " + songName + "\n")
		encodedData = d.wireEncode()
		transport.send(encodedData.toBuffer())	

	def onRegisterFailed(self, prefix):
		self.log.error("Could not register " + prefix.toUri())
		self.stop()
Пример #7
0
class LightController():
    shouldSign = False
    COLORS_PER_LIGHT = 3
    STRAND_SIZE = 50
    #mengchen: let's make the lighting lits only a half every time
    #HALF_STRAND_SIZE = 25
    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.DEBUG)
        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.prefix = Name(prefix)
        self.keychain = KeyChain()

        self.address = ""
        self._isStopped = True

        self.lightState = False
        #mengchen: let's make the lighting lits only a half every time
        #self.uphalf =  True
        self.HALF_STRAND_SIZE = 25       
        self.certificateName = self.keychain.getDefaultCertificateName()
        self.receiveFile = open('interestReceiveFile', 'w')

    def unix_time_now(self):
        epoch = datetime.datetime.utcfromtimestamp(0)
        delta = datetime.datetime.utcnow() - epoch
        return delta.total_seconds() * 1000.0
    
    # XXX: we should get a thread for this or something!
    def start(self):

        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, self.address)
        self.face.setCommandSigningInfo(self.keychain, self.certificateName)
        self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed)
        self._isStopped = False
        self.face.stopWhen(lambda:self._isStopped)
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:
            #self.stop()
            #print "key interrupt in run_forever"
            sys.exit()
        finally:
            #print "executing finally"
            self.stop()


    def stop(self):
        self.loop.close()
        self.kinetsender.stop = True
        #print "before wait"
        #self.kinetsender.complete.set
        #self.kinetsender.complete.wait()         
        self.face.shutdown()
        self.face = None
        #print "sys exit"
        self.receiveFile.close()
        sys.exit(1)

    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
       # if self.uphalf and not self.lightState:
        #    self.uphalf = False
         #   self.payloadBuffer[strand] = [int(color.r)&0xff, int(color.g)&0xff, int(color.b)&0xff]*self.HALF_STRAND_SIZE+[int(0)&0xff, int(0)&0xff, int(0)&0xff]*self.HALF_STRAND_SIZE
        #if not self.uphalf and self.lightState :
         #   self.uphalf = True
            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):
        #print datetime.datetime.now()
        self.receiveFile.write('{0:f}'.format(self.unix_time_now()) + '\n')
        interestName = Name(interest.getName())
        #interstname: /ndn/ucla.edu/sculptures/ai_bus/lights/setRGB/%83%0D%84%0B%87%09%89%01%04%8A%01%01%8B%01%01
        #d: <pyndn.data.Data object at 0xb64825d0>
        print "interstname", interestName.toUri()
        d = Data(interest.getName())
        # get the command parameters from the name
        try:
            commandComponent = interest.getName().get(prefix.size())
            #print commandComponent.toEscapedString():setRGB
            #print "prefix ",prefix.toUri():/ndn/ucla.edu/sculpture/ai_bus/lights
            #print "get name",interest.getName().toUri()
            commandParams = interest.getName().get(prefix.size()+1)
            #print "commandParams ",commandParams:%83%0D%84%0B%87%09%89%01%04%8A%01%01%8B%01%01

            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.lightState = not self.lightState
            if self.lightState:
                print "Off"
            else:
                print "On"
            
            #print requestedColor
            
            self.sendLightPayload(1)
            d.setContent("Gotcha: " + colorStr+ "\n")
        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        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())
        self.stop()

    def sendLightPayload(self, port):
        # print port
        # print self.payloadBuffer[port-1]
        self.kinetsender.setPayload(port, self.payloadBuffer[port-1])
class RepoPublisher:
    def __init__(self, repoPrefix, dataPrefix, dataSuffix, keychain=None):
        self.currentInsertion = -1
        self.currentStatus = -1
        self.face = None
        self.loop = None
        self.repoPrefix = Name(repoPrefix)
        self.dataName = Name(dataPrefix).append(dataSuffix)
        self.dataPrefix = Name(dataPrefix)

        if keychain is not None:
            self.keychain = keychain
        else:
            self.keychain = KeyChain()

        self.certificateName = self.keychain.getDefaultCertificateName()

        self.failureCount = 0
        self.successCount = 0

        self.processIdToVersion = {}

    def onRegisterFailed(self):
        logger.error("Could not register data publishing face!")
        self.stop()

    def versionFromCommandMessage(self, component):
        command = RepoCommandParameterMessage()
        try:
            ProtobufTlv.decode(command, component.getValue())
        except Exception as e:
            logger.warn(e)

        # last component of name to insert is version
        versionStr = command.repo_command_parameter.name.component[-1]

        return versionStr

    def stop(self):
        self.loop.close()
        self.face.shutdown()

    def onPublishInterest(self, prefix, interest, transport, pxID):
        '''
           For publishing face
        '''
        # just make up some data and return it
        interestName = interest.getName()
        logger.info("Interest for " + interestName.toUri())

        ## CURRENTLY ASSUMES THERE'S A VERSION+SEGMENT SUFFIX!
        dataName = Name(interestName)
        ts = (time.time())
        segmentId = 0
        #try:
        #   segmentId = interestName.get(-1).toSegment()
        #except:
            #logger.debug("Could not find segment id!")
            #dataName.appendSegment(segmentId)
        versionStr = str(interestName.get(-2).getValue())
        logger.debug('Publishing ' + versionStr + ' @ ' + str(ts))

        d = Data(dataName)
        content = "(" + str(ts) +  ") Data named " + dataName.toUri()
        d.setContent(content)
        d.getMetaInfo().setFinalBlockID(segmentId)
        d.getMetaInfo().setFreshnessPeriod(1000)
        self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()

        stats.insertDataForVersion(versionStr, {'publish_time': time.time()})
        transport.send(encodedData.toBuffer())
        #yield from asyncio.sleep()

    def generateVersionedName(self):
        fullName = Name(self.dataName)
        # currently we need to provide the version ourselves when we
        # poke the repo
        ts = int(time.time()*1000)
        fullName.appendVersion(int(ts))
        return fullName

    def onTimeout(self, prefix):
        logger.warn('Timeout waiting for '+prefix.toUri())

    
    def start(self):
        self.loop = asyncio.new_event_loop()
        self.face = ThreadsafeFace(self.loop, "")

        asyncio.set_event_loop(self.loop)
        self.face.setCommandSigningInfo(self.keychain, self.certificateName)
        self.face.registerPrefix(self.dataPrefix,self.onPublishInterest, self.onRegisterFailed)
        try:
            self.loop.call_soon(self.kickRepo)
            self.loop.run_forever()
        finally:
           self.stop() 


    def kickRepo(self):
        # command the repo to insert a new bit of data
        fullName = self.generateVersionedName()
        versionStr = str(fullName.get(-1).getValue())
        command = self.createInsertInterest(fullName)

        logger.debug('inserting: ' + versionStr)

        self.face.makeCommandInterest(command)
        def timeoutLoop(interest):
            logger.warn('Timed out on ' + interest.toUri())
            self.face.expressInterest(command, self.onCommandData, self.onTimeout)

        self.face.expressInterest(command, self.onCommandData, timeoutLoop)
        stats.insertDataForVersion(versionStr, {'insert_request':time.time()})

    def checkInsertion(self, versionStr, processID):
        fullName = Name(self.dataName).append(Name.fromEscapedString(versionStr))
        checkCommand = self.createCheckInterest(fullName, processID)
        self.face.makeCommandInterest(checkCommand)
        def timeoutLoop(interest):
            logger.warn('Timed out waiting on: '+interest.toUri())
            self.face.expressInterest(checkCommand, self.onCommandData, self.onTimeout)
        self.face.expressInterest(checkCommand, self.onCommandData, timeoutLoop)

    def createInsertInterest(self, fullName):
        '''
            For poking the repo
        '''
        # we have to do the versioning before we poke the repo
        interestName = Name(fullName)
        logger.debug('Creating insert interest for: '+interestName.toUri())
        
        insertionName = Name(self.repoPrefix).append('insert')
        commandParams = RepoCommandParameterMessage()

        for i in range(interestName.size()):
            commandParams.repo_command_parameter.name.component.append(interestName.get(i).getValue().toRawStr())

        commandParams.repo_command_parameter.start_block_id = 0
        commandParams.repo_command_parameter.end_block_id = 0

        commandName = insertionName.append(ProtobufTlv.encode(commandParams))
        interest = Interest(commandName)

        interest.setInterestLifetimeMilliseconds(2000)

        return interest

    def createCheckInterest(self, fullName, checkNum):
        insertionName = Name(self.repoPrefix).append('insert check')
        commandParams = RepoCommandParameterMessage()
        interestName = Name(fullName)

        commandParams.repo_command_parameter.process_id = checkNum
        for i in range(interestName.size()):
            commandParams.repo_command_parameter.name.component.append(str(interestName.get(i).getValue()))

        commandName = insertionName.append(ProtobufTlv.encode(commandParams))
        interest = Interest(commandName)

        return interest

    def onCommandData(self, interest, data):
        # assume it's a command response
        now = time.time()
        response = RepoCommandResponseMessage()
        ProtobufTlv.decode(response, data.getContent())


        self.currentStatus = response.repo_command_response.status_code
        self.currentInsertion =  response.repo_command_response.process_id
        logger.debug("Response status code: " + str(self.currentStatus) + ", process id: " + str(self.currentInsertion) + ", insert #" + str(response.repo_command_response.insert_num))

        command_idx = self.repoPrefix.size()
        # we also need to keep track of the mapping from version to processID for stats
        commandName = interest.getName().get(command_idx).getValue().toRawStr()
        if commandName == 'insert check':
            try:
                versionStr = self.processIdToVersion[self.currentInsertion]
                if self.currentStatus == 200:
                    stats.insertDataForVersion(versionStr, {'insert_complete': now})
                    self.loop.call_soon(self.kickRepo)
                elif self.currentStatus >= 400:
                    self.failureCount += 1
                    self.loop.call_soon(self.kickRepo)
                else:
                    self.loop.call_soon(self.checkInsertion, versionStr, self.currentInserion)
            except:
                logger.warn('Missing version for process ID {}'.format(self.currentInsertion))
        elif commandName == 'insert':
            if self.currentStatus == 100:
                versionStr = self.versionFromCommandMessage(interest.getName().get(command_idx+1))
                self.processIdToVersion[self.currentInsertion] = versionStr
                stats.insertDataForVersion(versionStr, {'insert_begin': now})
                self.loop.call_soon(self.checkInsertion, versionStr, self.currentInsertion)
            else:
                self.failureCount += 1
                self.loop.call_soon(self.kickRepo)
Пример #9
0
class RegisterSongList(object):
    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

        logging.basicConfig()
        self.device = "PC1"
        self.deviceComponent = Name.Component(self.device)
        self.excludeDevice = None

        self.prefix = Name(prefix)
        self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True

    def start(self):
        print "reg start"
        self.loop = asyncio.get_event_loop()
        self.face = ThreadsafeFace(self.loop, self.address)
        self.face.setCommandSigningInfo(self.keychain, self.certificateName)
        self.face.registerPrefix(self.prefix, self.onInterest,
                                 self.onRegisterFailed)
        self._isStopped = False
        self.face.stopWhen(lambda: self._isStopped)
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:

            sys.exit()
        finally:
            self.stop()

    def stop(self):
        self.loop.close()
        self.face.shutdown()
        self.face = None
        sys.exit(1)

    def signData(self, data):
        data.setSignature(Sha256WithRsaSignature())

    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:", initInterest.toUri()
        d = Data(interest.getName().append(self.deviceComponent))
        try:
            print "start to set data's content"

            currentString = ','.join(currentList)
            d.setContent("songList of " + self.device + ":" + currentString +
                         "\n")
            self.face.registerPrefix(self.changePrefix, self.onInterest,
                                     self.onRegisterFailed)

        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
        print d.getName().toUri()
        print d.getContent()

        self.loop.close()

        self.face.shutdown()
        self.face = None

    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        self.stop()
Пример #10
0
class RegisterSongList(object):


    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

	logging.basicConfig()        
    	self.device = "PC1"
    	self.deviceComponent = Name.Component(self.device)
	self.excludeDevice = None

        self.prefix = Name(prefix)
	self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True
  

    
    def start(self):
	print "reg start"
	self.loop = asyncio.get_event_loop()
	self.face = ThreadsafeFace(self.loop,self.address)
	self.face.setCommandSigningInfo(self.keychain,self.certificateName)
        self.face.registerPrefix(self.prefix,self.onInterest,self.onRegisterFailed)
        self._isStopped = False
        self.face.stopWhen(lambda:self._isStopped)
        try:
            self.loop.run_forever()
        except KeyboardInterrupt:

            sys.exit()
        finally:
            self.stop()


    def stop(self):
        self.loop.close()       
        self.face.shutdown()
        self.face = None
        sys.exit(1)

    def signData(self,data):
	data.setSignature(Sha256WithRsaSignature())


    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	try:
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)	



	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()

	self.loop.close()
     
        self.face.shutdown()
        self.face = None
		


    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        self.stop()
Пример #11
0
class SongHandler:
    def __init__(self):

        self._device = "PC1"
        self._playPrefix = Name("/ndn/edu/ucla/remap/music/play")
        self.prefix = self._playPrefix.append(self._device)

        self._face = None
        self._loop = None

        self._keyChain = KeyChain()
        self._certificateName = self._keyChain.getDefaultCertificateName()

        self._repoCommandPrefix = "/example/repo/1"

        self.mp = MusicPlayer()
        #self._getFiles = []

    def start(self):
        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop, "")
        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._face.registerPrefix(self.prefix, self.onPlayingCommand,
                                  self.onRegisterFailed)

        try:
            self._loop.run_forever()
        except KeyboardInterrupt:
            sys.exit()
        finally:
            self.stop()

    def stop(self):
        self._loop.close()
        self._face.shutdown()
        sys.exit(1)

    def getOnset(self, musicName):
        otxt = musicName + str("-o")
        print otxt
        g = GetFile(self._repoCommandPrefix, otxt, self._face, self.getFreq,
                    musicName)
        g.oStream = open(musicName + str("-os.txt"), 'wb')
        g.start()

        #self._getFiles.append(g)

    def getFreq(self, musicName):
        ftxt = musicName + str("-f")
        print musicName, " get Freq called"
        g = GetFile(self._repoCommandPrefix, ftxt, self._face,
                    self.mp.play_music, musicName, False)
        g.oStream = open(musicName + str("-freq.txt"), 'wb')
        g.start()

        #self._getFiles.append(g)

    def signData(self, data):
        data.setSignature(Sha256WithRsaSignature())

    def onPlayingCommand(self, prefix, interest, transport, prefixId):

        interestName = Name(interest.getName())
        commandComponent = interest.getName().get(self.prefix.size())
        if commandComponent == Name.Component("stop"):
            pass
        if commandComponent == Name.Component("play"):
            pass
        else:
            songName = commandComponent.toEscapedString()

        songList = []
        songList = songName.split('%2C')

        for i in songList:
            fmusic = i + str("-music.mp3")
            print "started getting music file", i

            g = GetFile(self._repoCommandPrefix, i, self._face, self.getOnset,
                        i)

            g.oStream = open(fmusic, 'wb')
            g.start()

            #self._getFiles.append(g)

        d = Data(interest.getName())
        d.setContent("start to play: " + songName + "\n")
        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())

    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        self.stop()