コード例 #1
0
ファイル: archive.py プロジェクト: sibosop/sibcommon
 def putArchive(self,choices):
   if Specs().s['doArchive']:
     try:
       Debug().p ("doing archive")
       tmpFile="%s/%s"%(Specs().s['tmpdir'],"tarFiles")
       cdir=self.cache
       textName=cdir+"/"+Specs().s['archiveTextName']
       cf=open(textName,"w")
       cf.write("%s\n"%choices[0])
       cf.write("%s\n"%choices[1])
       cf.close()
       afiles=glob.glob("%s/*.jpg"%cdir)
       tfiles=glob.glob("%s/*.lkp"%cdir)
       tf = open(tmpFile,"w")
       for file in afiles:
         Debug().p ("writing %s to %s"%(file,tmpFile))
         fb = os.path.basename(file)
         tf.write("%s\n"%fb)
       for file in tfiles:
         Debug().p("writing %s to %s"%(file,tmpFile))
         fb = os.path.basename(file)
         tf.write("%s\n"%fb)
       tf.close()
       cmd = ["tar","-czf",self.adir+"/"+str(uuid.uuid4())+".tgz","-C",cdir,"-T",tmpFile]
       Debug().p("cmd %s"%cmd)
       subprocess.check_output(cmd)
     except subprocess.CalledProcessError, e:
       print "Error %s"%(e)
コード例 #2
0
ファイル: musicPlayer.py プロジェクト: sibosop/sibcommon
 def run(self):
     print("%s starting" % self.name)
     self.setRunning(SoundFile().testBumpCollection())
     loop = Specs().s['musicLoop']
     while self.isRunning():
         if self.checkMsg():
             continue
         entry = SoundFile().getSoundEntry()
         Debug().p("player choosing %s" % entry)
         count = 0
         if self.musicBlocks[Hosts().getLocalHost()].mute:
             Debug().p("%s local %s mute so ignoring" %
                       (self.name, Hosts().getLocalHost()))
         else:
             for t in SoundTrackManager().eventThreads:
                 choice = random.choice(entry)
                 Debug().p("sending  %s request to %s" % (choice, t.name))
                 t.setCurrentSound(choice)
         for ip in self.musicBlocks.keys():
             if Hosts().isLocalHost(ip):
                 Debug().p("%s: ignoring %s" % (self.name, ip))
                 continue
             if self.musicBlocks[ip].mute:
                 Debug().p("%s: ignoring muted %s %s" %
                           (self.name, ip, self.musicBlocks[ip].mute))
                 continue
             try:
                 url = "http://" + ip + ":8080"
                 Debug().p("%s: url: %s" % (self.name, url))
                 cmd = {'cmd': "Sound", 'args': choice}
                 req = urllib2.Request(url, json.dumps(cmd),
                                       {'Content-Type': 'application/json'})
                 timeout = 1
                 f = urllib2.urlopen(req, None, timeout)
                 test = f.read()
                 Debug().p("%s: got response:%s" % (self.name, test))
             except urllib2.URLError as ve:
                 Debug().p("%s: got URLError %s on ip:%s" %
                           (self.name, ve, ip))
                 continue
             except Exception as e:
                 print("%s got exception %s" % (self.name, e))
                 continue
         self.waitTime = random.randint(Specs().s['minChange'],
                                        Specs().s['maxChange'])
         Debug().p("next change: %d" % self.waitTime)
         #Debug().p("number busy channels %d"%n
         if SoundFile().testBumpCollection() is False:
             print "waiting for channels to be done"
             n = pygame.mixer.get_busy()
             while n != 0:
                 n = pygame.mixer.get_busy()
                 print "number busy channels", n
                 if self.checkMsg():
                     continue
             if loop:
                 SoundFile().setCurrentCollection(self.collection)
             else:
                 self.SetRunning(false)
     self.doExit()
コード例 #3
0
 def run(self):
   stime = time.time()
   while SoundFile().testBumpCollection():
     try:
       #print (self.name,"time",time.time(),"stime",stime)
       if time.time() > stime:
         entry = SoundFile().getSoundEntry()
         Debug().p ("player choosing %s "%entry)
         count = 0
         for t in self.tList:
           choice = entry[count]
           count += 1
           if count == len(entry):
             count = 0
           Debug().p ("sending %s to %s"%(choice,t.name))
           t.setCurrentSound(choice)
         offset = random.randint(Specs().s['minChange'],Specs().s['maxChange'])
         stime = time.time() + offset
         Debug().p ("next change: %d"%offset)
         n = pygame.mixer.get_busy()
         Debug().p ("number busy channels %d"%n)
       time.sleep(1)
     except Exception as e:
       print("player error: "+repr(e))
       os._exit(3)
   for t in self.tList:
     t.stop()
   self.done = True
コード例 #4
0
ファイル: pulser.py プロジェクト: sibosop/garden
    def __init__(self):
        super(Pulser, self).__init__()
        self.name = "Pulser"
        self.pulseTime = None
        self.running = True
        self.threads = gardenTrack.TrackManager().eventThreads

        if "pulseTime" in Specs().s.keys():
            self.pulseTime = Specs().s["pulseTime"]
コード例 #5
0
 def __init__(self):
     self.name = "Words"
     wordList = Specs().s['wordList']
     wordDir = Specs().specDir
     self.lines = []
     for w in wordList:
         f = open(wordDir + "/" + w, "r")
         for l in f.read().split('\n'):
             self.lines.append(l)
コード例 #6
0
 def __init__(self):
     self.name = "Panel"
     self.ser = None
     brightness = Specs().s['panelBrightness']
     contrast = Specs().s['panelContrast']
     if self.hasPanel():
         self.ser = serial.Serial('/dev/ttyUSB0', 9600)
         self.ser.write(bytearray([0xfe, 0x53, brightness]))
         self.ser.write(bytearray([0xfe, 0x52, contrast]))
コード例 #7
0
ファイル: archive.py プロジェクト: sibosop/sibcommon
 def reset(self):
   self.cache = mkpath("%s/archiveCache"%(Specs().s['tmpdir']))
   self.adir=Specs().s["archiveDir"]
   Debug().p("archive dir %s"%self.adir)
   self.archives = []
   for a in glob.glob(self.adir+"/*.tgz"):
     #Debug().p("a: %s"%a)
     self.archives.append(a)
   self.randList = random.sample(range(len(self.archives)),len(self.archives))
   self.randListIndex = 0
コード例 #8
0
ファイル: imageHandler.py プロジェクト: sibosop/sibcommon
    def run(self):
        print("%s starting" % self.name)
        afiles = []
        (minTime, maxTime) = Specs().s["displayTimeRange"]
        lastImageDir = ""
        imageIndex = 0
        splash = Specs().s['splashImg']
        print("displaying f:%s" % splash)
        Display().image(splash)
        ts = None
        while True:
            Watchdog().feed(self)
            try:
                path = self.queue.get(timeout=ts)
            except Queue.Empty:
                path = lastImageDir

            if path == "__stop__":
                print("%s is stopping" % self.name)
                break

            print("%s: path %s lastImageDir %s" %
                  (self.name, path, lastImageDir))
            if path != lastImageDir:
                print("%s reseting imageIndex" % self.name)
                imageIndex = 0
                lastImageDir = path
                if len(afiles) == 0:
                    print("empty image file. waiting")
                    ts = 1
                    continue
            afiles = glob.glob(path + "/*.jpg")
            numFiles = len(afiles)
            if numFiles == 0:
                print("%s directory empty!!" % self.name)
                print("displaying f:%s" % splash)
                Display().image(splash)
                ts = 1
                continue
            print("imageIndex %d len afiles %d" % (imageIndex, numFiles))
            if imageIndex >= numFiles:
                print("resetting imageIndex")
                imageIndex = 0
            f = afiles[imageIndex]
            imageIndex += 1
            print("displaying f:%s" % f)
            if Display().image(f) == False:
                print "skipping bad images:%s" % f
                ts = .1
                continue
            ts = (random.random() * (maxTime - minTime)) + minTime
            print("next display %f" % ts)
コード例 #9
0
    def run(self):
        print("%s starting" % self.name)
        ts = None
        cs = None
        while self.isRunning():
            Debug().p("%s: timeout %s" % (self.name, ts))
            try:
                test = self.queue.get(timeout=ts)
                if type(test) is str:
                    if test == "__stop__":
                        print("%s stopping" % self.name)
                        break
                    if test == "__halt__":
                        Debug().p("%s: halting" % self.name)
                        ts = None
                        continue
            except Queue.Empty:
                test = cs
            cs = test
            file = ""
            file = cs['name']
            #path = rootDir + '/' + file
            Debug().p("%s: playing: %s" % (self.name, file))
            #sound = pygame.mixer.Sound(file=buffers[file])
            factor = self.getFactor(cs)
            sound = None
            nsound = speedx(SoundTrackManager().buffers[file], factor)
            if nsound is not None:
                sound = nsound
            else:
                sound = SoundTrackManager().buffers[file]
            v = random.uniform(Specs().s['soundMinVol'],
                               Specs().s['soundMaxVol'])
            self.setPanRatio()
            lVol = v * self.lRatio
            rVol = v * self.rRatio
            Debug().p("%s: lVol %f rVol %f lRatio %f rRatio %f" %
                      (self.name, lVol, rVol, self.lRatio, self.rRatio))
            event = {}
            event['vol'] = v
            event['factor'] = factor
            event['file'] = file
            Debug().p("Sound baseTime:%d" % SoundFile().baseTime)
            event['time'] = time.time() - SoundFile().baseTime
            self.playList['events'].append(event)
            playSound(sound, lVol, rVol)
            ts = random.randint(Specs().s['eventMin'],
                                Specs().s['eventMax']) / 1000.0

        print("%s exiting" % self.name)
コード例 #10
0
 def __init__(self):
   self.timeout = 2
   default = Specs().s['host_defaults']
   hosts = Specs().s['hosts']
   self.hosts = []
   for h in hosts:
     host = {}
     for k in default.keys():
       host[k] = default[k]
     for k in h.keys():
       host[k] = h[k]
     self.hosts.append(host)
   self.localHost = None
   self.findLocalHost()
コード例 #11
0
ファイル: netextc.py プロジェクト: MrCont/PySpice
 def import_file(self, filename):
     with open(filename, "r") as netfile:
         header = netfile.readline()
         if (not header.startswith(Specs.header())):
             #DA DEFINIRE UN CUSTOM ERROR
             raise EOFError
         else:
             #pick the number of nodes of the circuit (to not count them)
             self.n_nodes = int(header.replace(Specs.header(), ""))
             juice = netfile.readlines()
             for line in juice[:-1]:
                 com = Component()
                 com.from_fileline(line)
                 self.components.append(com)
コード例 #12
0
    def makeBuffers(self):
        Debug().p("%s: makeBuffers" % self.name)

        for c in Specs().s['collections']:
            for l in Specs().s[c]:
                Debug().p("c: %s l: %s" % (c, l))
                for f in Specs().s[l['list']]:
                    Debug().p("f: %s" % f['name'])
                    if f['name'] in self.buffers:
                        Debug().p("%s: skipping existing fname %s" %
                                  (self.name, f['name']))
                    else:
                        path = self.rootDir + '/' + f['name']
                        buffer = pygame.mixer.Sound(file=path)
                        self.buffers[f['name']] = buffer
コード例 #13
0
 def __init__(self):
     self.listMutex = threading.Lock()
     self.maxEvents = 2
     self.collections = {}
     self.currentCollection = None
     self.baseTime = time.time()
     self.index = 0
     self.timeout = 0
     self.rootDir = ""
     self.index = 0
     for k in Specs().s['collections']:
         self.collections[k] = []
         for d in Specs().s[k]:
             self.collections[k].append(d)
             Debug().p("key: %s collection %s" % (k, d))
コード例 #14
0
ファイル: watchdog.py プロジェクト: sibosop/sibcommon
 def __init__(self):
     super(Watchdog, self).__init__()
     self.wdLock = threading.Lock()
     self.name = "WatchDog"
     self.tlist = {}
     self.timeoutInterval = Specs().s['watchdogTimeout']
     self.queue = Queue.Queue()
コード例 #15
0
 def hasPanel(self):
     path = Specs().s['panelDev']
     if os.path.exists(path):
         print("%s Located usb serial device at %s" % (self.name, path))
         return True
     print("%s No usb serial device at %s" % (self.name, path))
     return False
コード例 #16
0
ファイル: textSpeaker.py プロジェクト: sibosop/sibcommon
def makeSpeakFile(line, language=''):
    rval = None
    if language == '':
        language = 'en-us'
    Debug().p("make speak file:" + line + " lang:" + str(language))
    try:
        fnameRoot = "%s/%s" % (Specs().s['tmpdir'], re.sub('\W+', '_', line))
        if internetOn() and language != "es":
            Debug().p("speak: internet on using gTTS")
            Debug().p("playText line:" + line)
            fname = fnameRoot + ".mp3"
            Debug().p("speak:" + fname)
            tts1 = gTTS(text=line, lang=language)
            Debug().p("tts1:%s" % tts1)
            tts1.save(fname)
            Debug().p("speak:" + fname)
            sound = AudioSegment.from_mp3(fname)
            os.unlink(fname)
            fname = fnameRoot + ".wav"
            Debug().p("speak:" + fname)
            sound.export(fname, format="wav")
            rval = fname
        else:
            print("speak: internet off using espeak")
            fname = fnameRoot + ".wav"
            Debug().p("speak:" + fname)
            os.system("espeak -w " + fname + " '" + line + "'")
            rval = fname
        convertSampleRate(rval)
    except Exception as e:
        print("speak error: " + str(e))
        rval = None
    return rval
コード例 #17
0
 def __init__(self):
     self.name = "Poem"
     random.seed()
     poemDir = 'POEMDATA'
     self.minLineTime = Specs().s['minLineTime']
     self.candidates = []
     self.candidates = glob.glob(poemDir + "/*/*/*.txt")
コード例 #18
0
ファイル: googleSearch.py プロジェクト: sibosop/sibcommon
 def __init__(self):
     self.creds = {}
     lines = open(Specs().s['credFile']).read().split('\n')
     for l in lines:
         vars = l.split("=")
         if len(vars) == 2:
             self.creds[vars[0]] = vars[1]
     for k in self.creds.keys():
         Debug().p("key: %s value %s" % (k, self.creds[k]))
コード例 #19
0
ファイル: midiHandler.py プロジェクト: sibosop/sibcommon
 def __init__(self):
   super(MidiHandler,self).__init__()
   spec = Specs().s
   self.midiSpec = Hosts().getLocalAttr('midi')
   mido.set_backend(self.midiSpec['backend']) 
   self.name = "MidiHandler"
   self.running = True
   self.queue = Queue.Queue()
   self.portHandlers = []
コード例 #20
0
 def getSoundEntry(self):
     cur = self.collections[self.currentCollection][self.index]
     keys = Specs().s[cur['list']]
     Debug().p("collection-list %s - %s number of keys %d" %
               (cur['name'], cur['list'], len(keys)))
     done = False
     choices = 0
     numChoices = Specs().s['maxEvents']
     Debug().p("collection: %s number of choices: %d max Events: %d" %
               (cur['name'], self.maxEvents, numChoices))
     rval = []
     while len(rval) < numChoices:
         choice = random.randint(0, len(keys) - 1)
         Debug().p("rval %s" % rval)
         if keys[choice]['name'] in rval:
             continue
         rval.append(keys[choice])
     return rval
コード例 #21
0
 def __init__(self):
     super(iAltar, self).__init__()
     self.name = "iAltarPlayer"
     print("starting: %s" % self.name)
     self.searchType = Specs().s['defaultSearchType']
     print("%s: default search type: %s" % (self.name, self.searchType))
     Watchdog().add(self)
     if Hosts().getLocalAttr("hasServer"):
         Server().register({'Search': self.setSearchType})
     self.queue = Queue.Queue()
コード例 #22
0
    def getFactor(self, cs):
        Debug().p("getFactor on: %s" % cs)

        rval = 1.0
        if 'tuning' in cs.keys() and cs['tuning'] in Specs().s['tunings'].keys(
        ):
            ts = SoundTrackManager().tunings[cs['tuning']]
            tc = random.choice(ts)
            oc = random.choice(SoundTrackManager().octaves)
            Debug().p("tc: %f oc: %f" % (tc, oc))
            rval = tc * oc
        else:
            Debug().p("default tuning for cs: %s" % cs)
            speedChangeMax = Specs().s['speedChangeMax']
            speedChangeMin = Specs().s['speedChangeMin']
            rval = ((speedChangeMax - speedChangeMin) *
                    random.random()) + speedChangeMin

        Debug().p("factor: %d" % rval)
        return rval
コード例 #23
0
 def __init__(self,
              config,
              openstack_spec,
              config_plugin,
              factory,
              notifier=None):
     # the base config never changes for a given NFVbench instance
     self.base_config = config
     # this is the running config, updated at every run()
     self.config = None
     self.config_plugin = config_plugin
     self.factory = factory
     self.notifier = notifier
     self.cred = credentials.Credentials(config.openrc_file, None, False) \
         if config.openrc_file else None
     self.chain_runner = None
     self.specs = Specs()
     self.specs.set_openstack_spec(openstack_spec)
     self.vni_ports = []
     sys.stdout.flush()
コード例 #24
0
 def sendPhrase(self,ip,text):
   lang = random.choice(Specs().s['langList'])
   phr = Hosts().getAttr(ip,'phrase')
   args = {}
   args["phrase"] = text
   if phr['voice']:
     args["phraseData"] = makeSpeakData("%s %s"%(text[0],text[1]),lang)
   else:
     args["phraseData"] = "" 
   cmd = { 'cmd' : "Phrase", 'args' : args}
   Debug().p("%s: ip %s sending %s"%(self.name,ip,args['phrase'])) 
   Hosts().sendToHost(ip,cmd)
コード例 #25
0
    def __init__(self, rootDir):
        self.rootDir = rootDir
        self.buffers = {}
        self.currentSound = {'file': ""}
        self.octaves = [0.25, 0.5, 1.0, 2.0, 4.0]
        self.ecount = 0
        self.name = "SoundTrackManager"
        self.eventThreads = []
        self.makeBuffers()
        if Hosts().getLocalAttr("hasServer"):
            Server().register({
                "Sound": self.doSound,
                "HaltSound": self.doHalt
            })

        self.changeNumSoundThreads(Specs().s['numMusicThreads'])
        self.tunings = {}
        for k in Specs().s['tunings'].keys():
            self.tunings[k] = []
            for t in Specs().s['tunings'][k]:
                num, den = t.split("/")
                self.tunings[k].append(float(num) / float(den))
コード例 #26
0
ファイル: display.py プロジェクト: sibosop/sibcommon
 def __init__(self):
     self.screen = None
     self.myFont = None
     self.FilterDot = True
     self.name = "Display"
     pygame.mouse.set_visible(False)
     self.lineLen = Specs().s['lineLen']
     isRaspberry = True
     if Specs().s['noHosts']:
         fontSize = Specs().s["fontSize"]
         isRasberry = Specs().s['hostType'] == "raspberry"
     else:
         fontSize = Hosts().getLocalAttr('fontSize')
         isRaspberry = Hosts().getLocalAttr("hostType") == "raspberry"
     if isRaspberry:
         self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
     else:
         self.screen = pygame.display.set_mode([800, 480])
     fontFile = Specs().s['fontFile']
     Debug().p("%s: setting font to %s size %d" %
               (self.name, fontFile, fontSize))
     self.myFont = pygame.font.Font("%s/%s" % ("speclib", fontFile),
                                    fontSize)
     print("display image setup done")
コード例 #27
0
ファイル: gardenSoundFile.py プロジェクト: sibosop/garden
def setup():
    global currentCollection
    global collections
    global timeout
    global rootDir
    currentCollection = ""

    for d in Specs().s['collections']:
        collections.append(d)

    if debug: print(collections)
    currentCollection = collections.pop(0)
    if debug: print("currentCollection:", currentCollection['name'])

    timeout = time.time() + currentCollection['time']
コード例 #28
0
 def sendToWordServer(ip,cmd): 
   Debug().p("send to word server")
   rval = True
   port = Specs().s['wordServerPort']
   try:
     #url = "http://"+ip + ":" + str(port) + "/"+cmd
     url = "http://%s:%d/%s"%(ip,port,cmd)
     Debug().p("send to word server: %s"%url)
     req = urllib2.Request(url)
     f = urllib2.urlopen(req,None,self.timeout)
     rval = f.read()
     Debug().p("got response: %s"%rval)  
   except Exception as e:
     print("host send error: %s"%str(e))
     rval = jsonStatus("408")
   return rval
コード例 #29
0
ファイル: nanoPlayer.py プロジェクト: sibosop/sibcommon
 def __init__(self,device):
   self.name = "%sPlayer"%device['id']
   self.desc = Specs().s[device['id']]
   iph = MidiPortHandler(device["inPort"],device['outPort'])
   iph.rtRegister("control_change",self.control_change)
   iph.rtRegister("sysex",self.sysex)
   MidiHandler().addPortHandler(iph)
   self.outport = iph.oport
   self.controlMap = []
   for i in range(0,128):
     self.controlMap.append(self.findEvent(i,self.desc['controls']))
   self.controlBlocks = [-1] * 8
   self.playerIps = []
   for h in Hosts().getHosts():
     if h['nanoId'] != -1:
       self.controlBlocks[h['nanoId']] = ControlBlock(h['ip'])
       Debug().p("%s added nano id %d for host %s"%(self.name,h['nanoId'],h['ip']))
     music = h['music']
     if music['enabled'] and music['player']:
       Debug().p("%s added added music player host %s"%(self.name,h['ip']))
       self.playerIps.append(h['ip'])
   
       
   self.register("slider", self.doSlider)
   self.register("pot", self.doPot)
   self.register("solo", self.doSolo)
   self.register("start", self.doStart)
   self.register("stop", self.doStop)
   self.register("begin", self.doBegin)
   self.register("end", self.doEnd)
   self.register("record", self.doRecord)
   self.register("cycle", self.doCycle)
   self.register("mute", self.doMute)
   self.register("prevTrack", self.doPrevTrack)
   self.register("nextTrack", self.doNextTrack)
   self.register("setMark", self.doSetMark)
   self.register("prevMark", self.doPrevMark)
   self.register("nextMark", self.doNextMark)
   self.register("recordSelect", self.doRecordSelect)
   self.register("recordSelect", self.doRecordSelect)
   self.setupState = "RequestSceneData"
   self.scene = None
   
   self.sendSysex(NanoPlayer.sceneReq)
   ThreadMgr().start(VolumeThread())  
   self.curVol = getVolume()
   self.soundList = []
コード例 #30
0
ファイル: display.py プロジェクト: sibosop/sibcommon
    def image(self, img):
        try:
            image = pygame.image.load(img)
        except:
            print("Display can't render " + img)
            splash = "%s" % (Specs().s['splashImg'])
            image = pygame.image.load(splash)
            return False
        ws = self.screen.get_width()
        hs = self.screen.get_height()
        rs = float(ws) / float(hs)
        wi = image.get_width()
        hi = image.get_height()
        ri = float(wi) / float(hi)
        dw = 0
        dh = 0
        if wi < (ws / 2) and hi < (hs / 2):
            print("doing half scale:" + img)
            simage = pygame.transform.scale2x(image)
        else:
            if rs > ri:
                dw = wi * (float(hs) / float(hi))
                dh = hs
            else:
                dw = ws
                dh = hi * (float(ws) / float(wi))

            try:
                print("doing smooth scale:" + img)
                simage = pygame.transform.smoothscale(image,
                                                      (int(dw), int(dh)))
            except:
                print("smoothscale failed doing normal scale for:" + img)
                simage = pygame.transform.scale(image, (int(dw), int(dh)))

        xoffset = (ws - simage.get_width()) / 2
        yoffset = (hs - simage.get_height()) / 2
        Debug().p("displayImage ws:" + str(ws) + " hs:" + str(hs) + " rs:" +
                  str(rs) + "  wi:" + str(wi) + " hi:" + str(hi) + " ri:" +
                  str(ri) + " dw:" + str(dw) + " dh:" + str(dh) + " xoffset:" +
                  str(xoffset) + " yoffset:" + str(yoffset))
        self.screen.fill((0, 0, 0))
        self.screen.blit(simage, (xoffset, yoffset))
        pygame.display.flip()
        return True