Exemplo n.º 1
0
 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()
Exemplo n.º 2
0
def doSetVolume(val):
  vcmd = { 'cmd' : 'Volume', 'args' : {'value' : val}}
  for ip in Hosts().getHostIps():
    if ip == Hosts().getLocalHost():
      setVolume(val)
      continue
    Hosts().sendToHost(ip,vcmd)
Exemplo n.º 3
0
def sendVoiceMsg(cmdStr):
  cmd = { 'cmd' : cmdStr, 'args' : [""] }
  for ip in Hosts().getHostIps():
    phrase = Hosts().getAttr(ip,'phrase')
    if phrase['enabled'] and phrase['voice']:
        Hosts().sendToHost(ip,cmd)
  return 0
Exemplo n.º 4
0
    def test_constructor(self):
        '''Constructors and read'''
        eq=self.assertEqual
        h=Hosts()
        eq(h.keys(),[])
                      
        h=Hosts(mc='1.0.0.1', mc02='1.0.0.2')
        eq(h['mc'],'1.0.0.1')
        eq(h['mc02'],'1.0.0.2')
        eq(h['1.0.0.1'],'mc')
        eq(h['1.0.0.2'],'mc02')

        h=Hosts({'pc':'1.0.0.3','pc02':'1.0.0.4'})
        eq(h['pc'],'1.0.0.3')
        eq(h['pc02'],'1.0.0.4')
        eq(h['1.0.0.3'],'pc')
        eq(h['1.0.0.4'],'pc02')
        
        h=Hosts(self.hostsfile, ac03='1.0.0.5', ac02='1.0.0.6')
        eq(h['ac03'],'1.0.0.5')
        eq(h['ac02'],'1.0.0.6')
        eq(h['broadcasthost'],'255.255.255.255')
        eq(h['127.0.0.1'],'localhost localhost.yemen')
        eq(h['localhost.yemen'],'127.0.0.1')
        eq(h['localhost'],'127.0.0.1')
Exemplo n.º 5
0
def doStartMusic(cmd):
  smcmd = { 'cmd' : 'StartMusic', 'args' : [""] }
  hosts = Hosts().getHostIps()
  for ip in hosts:
    music = Hosts().getAttr(ip,'music')
    if music['enabled']:
      Hosts().sendToHost(ip,smcmd)
  return 0
Exemplo n.º 6
0
def sendRecogMsg(cmdStr):
  cmd = { 'cmd' : cmdStr, 'args' : [""] }
  rval = ""
  for ip in Hosts().getHostIps():
    recog = Hosts().getAttr(ip,'recog')
    if recog['enabled'] and recog['engine']:
        rval = Hosts().sendToHost(ip,cmd)
  return rval
Exemplo n.º 7
0
    def doProbe(self, args):
        state = {}
        state['status'] = "ok"
        attr = Hosts().getHost(Hosts().getLocalHost())
        for k in attr.keys():
            state[k] = attr[k]
        for cb in self.probeCallbacks:
            info = cb()
            for k in info.keys():
                state[k] = info[k]

        return json.dumps(state)
Exemplo n.º 8
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)
Exemplo n.º 9
0
def sendCargs(p,cargs):
  if len(p.name) + len(p.ip) + len(p.sub) == 0:
    Hosts().sendToHosts(cargs)
    return 0
  if len(p.name) != 0:
    Hosts().sendByName(p.name,cargs)
  if len(p.sub) != 0:
    Hosts().sendWithSubnet(p.sub,cargs)
  if len(p.ip) != 0:
    for h in parms.ip:
      print "h:",h
      Hosts().sendToHost(h,cargs)
  return 0
Exemplo n.º 10
0
def doHaltMusic(cmd):
  hmcmd = { 'cmd' : 'HaltMusic', 'args' : [""] }
  hscmd = { 'cmd' : 'HaltSound', 'args' : [""] }
  hosts = Hosts().getHostIps()
  for ip in hosts:
    music = Hosts().getAttr(ip,'music')
    Debug().p("Test Halt for ip %s music: %s"%(ip,music))
    if music['enabled'] and music['player']:
      Hosts().sendToHost(ip,hmcmd)
      Debug().p("Halt Player for ip %s music: %s"%(ip,music))
    if music['enabled']:
      Debug().p("Halt Music for ip %s music: %s"%(ip,music))
      Hosts().sendToHost(ip,hscmd)
  return 0
Exemplo n.º 11
0
 def __init__(self, username):
     self.name = username
     configparser = ConfigParser()
     configparser.read(config_file)
     gateway_hostgroup = configparser.get('General', 'gateway_group')
     self.hosts = Hosts(username, gateway_hostgroup)
     self.allowed_ssh_hosts = self.hosts.list_allowed()
Exemplo n.º 12
0
def doTest(args):
  print "Hit return to stop test"
  hosts = Hosts().getHosts()
  loop = True
  while loop:
    for h in hosts:
      vs = h['ip'].split(".")
      cmd = []
      cmd.append("Phrase")
      cmd.append("%s"%(vs[3]))
      cmd.append("-r")
      cmd.append("0")
      cmd.append("-s")
      cmd.append("%s"%(vs[3]))
      stop = "Phrase -s %s"%(vs[3])
      print ("host %s sub %s cmd %s"%(h['ip'],vs[3],cmd))
      doPhrase(cmd)
      i,o,e = select.select([sys.stdin],[],[],5)
      cmd = []
      cmd.append("Phrase")
      cmd.append("-s")
      cmd.append("%s"%(vs[3]))
      doPhrase(cmd)
      if len(i):
        loop = False
        input = sys.stdin.readline()
        break
Exemplo n.º 13
0
    def test_scenario3(self):
        '''Scenario 3.'''
        h=Hosts(self.hostsfile)
        h['localhost'] =  '10.0.0.3'
        h['10.0.0.3'] ='toto'
        del h['toto']
        del h['broadcasthost']
        
        # Add a name to an address, change the address of a hostname
        h['localhost'] =  '127.0.0.1'
        h.append('localhost', 'localhost.yemen')

        del h['127.0.0.1']
        h.write(self.emptyfile)
        
        correct =  """##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
1.0.0.1		localhost localhost.yemen   # very pertinent comment
::1             localhost
fe80::1%lo0	localhost
1.0.0.2			mc02
"""


        self.assertEqual(file(self.emptyfile).read(), '')
Exemplo n.º 14
0
    def test_scenario2(self):
        '''Scenario 2.'''
        d=dict([ ('localhost','1.0.0.1'), ('1.0.0.2','mc02') ])
        Hosts(d).write(self.emptyfile)

        correct = '1.0.0.1\t\t\tlocalhost\n1.0.0.2\t\t\tmc02\n'
        self.assertEqual(file(self.emptyfile).read(), correct)
Exemplo n.º 15
0
 def __init__(self, username):
     self.name = username
     gateway_hostgroup = config.get('gateway_group')
     idp = config.get('idp')
     logging.debug("Core: using Identity Provider {0}".format(idp))
     self.hosts = Hosts(config, self.name, gateway_hostgroup, idp)
     self.allowed_ssh_hosts, self.hostgroups = self.hosts.list_allowed()
Exemplo n.º 16
0
 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 = []
Exemplo n.º 17
0
    def test_write(self):
        '''Write'''

        h=Hosts()
        h['localhost'], h['mc02'] = '1.0.0.1', '1.0.0.2'
        h.write(self.emptyfile)
        h.write(self.emptyfile)

        correct = '1.0.0.1\t\t\tlocalhost\n1.0.0.2\t\t\tmc02\n'
        self.assertEqual(file(self.emptyfile).read(), correct)
Exemplo n.º 18
0
    def test_remove_one(self):
        self.hosts.set_one("test", "1.2.3.4")
        self.hosts.write(self.hosts_file)

        self.hosts = Hosts(self.hosts_file)

        self.hosts.remove_one("test")
        self.hosts.write(self.hosts_file)

        self.assertDoesNotHaveHostLine("1.2.3.4 test")
Exemplo n.º 19
0
    def test_del(self):
        '''Del'''
        h=Hosts()

        h['mc'], h['mc02'], h['127.0.0.1'] = '10.0.0.1', '10.0.0.2', 'localhost'
        del h['10.0.0.1']
        del h['mc02']
        del h['localhost']
        self.assertRaises(KeyError, h.__delitem__, 'tata')
        self.assertEqual(h.keys(), [])
Exemplo n.º 20
0
 def __init__(self, modules, refresh_rate=REFRESH_RATE, debug=False):
     self.hosts = Hosts()
     self.refresh_rate = refresh_rate
     self.debug = debug
     self.modules = [(m, Client('{}.local:{}'.format(m.hostname, OPC_PORT)))
                     for m in modules]
     self.active = True
     self.time_taken = 0.0
     self.i = 0
     self.update()
Exemplo n.º 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()
Exemplo n.º 22
0
 def __init__(self,output):
   super(RecogAnalyzer,self).__init__()
   self.name = "RecogAnalyzer"
   self.queue = Queue()
   recog = Hosts().getLocalAttr("recog")
   self.chooseLen=recog['chooseLen']
   self.chooseSize=recog['chooseSize']
   self.output = output
   self.running = True
   self.choices = []
   self.lastTime = time.time()
Exemplo n.º 23
0
    def test_keys_values(self):
        '''Parsing regexp'''
        line=Hosts().line
        for (i,(a,h)) in self.options:
            m=line.match(i)
            self.assertEqual( m.group('address'),   a ) 
            self.assertEqual( m.group('hostnames'), h )


        for i in self.broken_options:
            self.assertEqual( line.match(i), None )
Exemplo n.º 24
0
    def test_read(self):
        '''Read'''
        eq=self.assertEqual
        h=Hosts()
        h.read(self.hostsfile)

        eq(h.keys(), ['localhost.yemen', 'broadcasthost', 'localhost', '127.0.0.1', '255.255.255.255'])
        eq(h['broadcasthost'],'255.255.255.255')
        eq(h['127.0.0.1'],'localhost localhost.yemen')
        eq(h['localhost.yemen'],'127.0.0.1')
        eq(h['localhost'],'127.0.0.1')
Exemplo n.º 25
0
 def __init__(self):
     super(Voice, self).__init__()
     self.name = "Voice"
     self.queue = Queue.Queue()
     self.voiceMinVol = .7
     self.halted = True
     self.running = True
     if Hosts().getLocalAttr('hasServer'):
         Server().register({
             'StartVoice': self.startVoice,
             'HaltVoice': self.haltVoice
         })
Exemplo n.º 26
0
    def test_purge_empty_records(self):
        with open(self.hosts_file, 'a') as f:
            f.write('1.2.3.4')

        self.assertHasHostLine('1.2.3.4')

        hosts = Hosts(self.hosts_file)
        hosts.set_one("test", "1.2.3.4")
        hosts.set_one("", "1.2.3.4")
        hosts.write(self.hosts_file)

        self.assertDoesNotHaveHostLine('1.2.3.4')
Exemplo n.º 27
0
    def __init__(self, defaultCollection="playerCollection"):
        super(MusicPlayer, self).__init__()
        self.done = False
        self.name = "MusicPlayer"
        self.running = None
        self.mutex = threading.Lock()
        self.queue = Queue.Queue()
        self.collection = defaultCollection
        self.waitTime = None
        self.musicBlocks = {}
        for ip in Hosts().getHostIps():
            music = Hosts().getAttr(ip, "music")
            if music['enabled']:
                self.musicBlocks[ip] = MusicBlock()

        SoundFile().setCurrentCollection(self.collection)
        if Hosts().getLocalAttr("hasServer"):
            Server().register({
                "HaltMusic": self.haltMusic,
                "StartMusic": self.startMusic,
                "Mute": self.mute
            })
Exemplo n.º 28
0
 def __init__(self):
     super(ImageHandler, self).__init__()
     self.name = "ImageHandler"
     print("starting: %s" % self.name)
     Watchdog().add(self)
     self.currentId = None
     self.queue = Queue.Queue()
     if Hosts().getLocalAttr('hasServer'):
         Server().register({
             'AddImage': self.addImage,
             'RmCacheDir': self.rmCacheDir,
             'SetImageDir': self.setImageDir,
             'ClearCache': self.clearCache
         })
Exemplo n.º 29
0
 def __init__(self):
   super(RecogHandler,self).__init__()
   self.name = "RecogHandler"
   print("starting: %s"%self.name)
   self.queue = Queue.Queue()
   if Hosts().getLocalAttr('hasServer'):
     Server().register({
       'StartRecog' : self.startRecog
       ,'HaltRecog' : self.haltRecog
       ,'GetRecog' : self.getRecog
     })
   self.threads=[]
   self.finalIps = []
   self.searchIps = []
   for ip in Hosts().getHostIps():
     recog = Hosts().getAttr(ip,'recog')
     if recog['enabled'] and recog['phrase'] == "final":
       Debug().p("%s ip %s wants final phrase"%(self.name,ip))
       self.finalIps.append(ip)
     if recog['enabled'] and recog['phrase'] == "search":
       Debug().p("%s ip %s wants search phrase"%(self.name,ip))
       self.searchIps.append(ip)
   self.running = True
   Display().text("Recog not Running")
Exemplo n.º 30
0
 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")