class WebSocketFacade(): def __init__(self): self.waiters = [] self.bus = Bus() def addWaiters(self, waiter): self.bus.subscribe(waiter.service, self.write_message) self.waiters.append(waiter) def write_message(self, bus, key, obj): for waiter in self.waiters: try: if waiter.service == key: if hasattr(obj, "__dict__"): jsonObj = json.dumps(obj.__dict__, default=lambda o: o.__dict__) else: jsonObj = json.dumps(obj, default=lambda o: o.__dict__) waiter.write_message(jsonObj) except Exception as e: logger.error("erreur WS : %s", e.__str__()) def removeWaiters(self, waiter): self.waiters.remove(waiter)
def __init__(self): self.bus = Bus() self.gtts = PlayerTTS() self.isActive = True self.bus.subscribe('newDeviceConnected', self.lanceVocalconnect) self.bus.subscribe('deviceDeconnected', self.deconnectVocal) self.bus.subscribe('vocalOrdre', self.lanceVocalOrdre) self.bus.subscribe('loadDic', self.lanceLoadDecoder)
def __init__(self): self.bus = Bus()
def __init__(self): self.t = LoadDevice(self) self.bus = Bus()
class DevicesDAO(): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(DevicesDAO, cls).__new__(cls, *args, **kwargs) return cls._instance devices = [] def __init__(self): self.t = LoadDevice(self) self.bus = Bus() def load(self): if not self.t.isAlive(): self.t = LoadDevice(self) self.t.start() return self.devices def loadCallback(self): self.bus.publish('loadDeviceDAO', self.devices) def connectedDevice(self, macAddress, ressources, port, ip=None): c = ConnectedDevice(self, macAddress, ressources, port, ip) c.start() def connectedDeviseCallback(self): self.bus.publish('connectedDeviceDAO', self.devices) def updateOrSave(self, args): logger.debug('updateOrSave devices BDD') devices = [] #try: fecha = time.strftime('%Y-%m-%d %H:%M:%S') _db = mysql.connector.connect(host=HOST_DB, port=PORT_DB, user=USER_DB, passwd=PASSWD_DB, db=DB_DB) cr = _db.cursor() sqlToInsert = """ INSERT INTO devices (id, mcAdress, mcVendor, name, ip, lastDateDetect, hautParleur, microfone, ecran, camera, kodi, mobile) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ) """ sqlToUpdate = """ UPDATE devices SET mcAdress = %s, mcVendor = %s, name = %s, ip = %s, lastDateDetect = %s, hautParleur = %s, microfone = %s, ecran = %s, camera = %s, kodi = %s, mobile = %s where id = %s """ for arg in args: device = Device(arg.ip, arg.mcAdress, arg.mcVendor) device.setName(arg.name) device.setLastDateDetect(fecha) device.setHasCamera(arg.hasCamera) device.setHasEcran(arg.hasEcran) device.setHasHautParleur(arg.hasHautParleur) device.setHasKodi(arg.hasKodi) device.setHasMicrofone(arg.hasMicrofone) device.setIsMobile(arg.isMobile) if hasattr(arg, 'id'): device.setId(arg.id) data = (arg.mcAdress, arg.mcVendor, arg.name, arg.ip, fecha, arg.hasHautParleur, arg.hasMicrofone, arg.hasEcran, arg.hasCamera, arg.hasKodi, arg.isMobile, arg.id) cr.execute(sqlToUpdate, data) else: idDevice = str(uuid.uuid4()) device.setId(idDevice) data = (idDevice, arg.mcAdress, arg.mcVendor, arg.name, arg.ip, fecha, arg.hasHautParleur, arg.hasEcran, arg.hasMicrofone, arg.hasCamera, arg.hasKodi, arg.isMobile) cr.execute(sqlToInsert, data) devices.append(device) _db.commit() return self.load() def delete(self): logger.debug('Delete device BDD')
class Vocal(object): VARIABLES = {} ORDRES = { "fin_ordre": { "function": "finOrdre", "action": ["launch"], "message_fr": ["fin ordre"], }, "reboot_box": { "function": "rebootBox", "action": ["launch", "reboot"], "message_fr": ["redémarrage complet", "complet"], }, "reboot_sat": { "function": "rebootsat", "action": ["launch", "reboot"], "message_fr": ["redémarrage satellite", "satellite"], }, } threads = {} decoder = None def __init__(self): self.bus = Bus() self.gtts = PlayerTTS() self.isActive = True self.bus.subscribe('newDeviceConnected', self.lanceVocalconnect) self.bus.subscribe('deviceDeconnected', self.deconnectVocal) self.bus.subscribe('vocalOrdre', self.lanceVocalOrdre) self.bus.subscribe('loadDic', self.lanceLoadDecoder) def lanceVocalOrdre(self, bus, key, obj): """ Point d'entré du module pour gérer les ordres associés par la reconnaissance vocale """ groupe = obj['groupe'] if groupe != 'vocal': return ordre = self.ORDRES[obj['ordre']] print("Ordre lancé : " + obj['ordre']) #print ("appel de la function : " + ordre["function"]) print("origine : " + obj["origine"]) # print ("recognised : " + str(obj["recognised"])) print("input : " + str(obj["input"])) def contains(self, ip): """" Utils qui permet de vérifier si l'IP est deja contenu dans la liste return @boolean """ exist = False for t in self.threads: if ip == t: exist = True break return exist def lanceVocalconnect(self, bus, key, obj): """ Reçu sur le bus par le déclenchement de l'événement 'newDeviceConnected' obj = { ip : 'ip du satelite', port : 'port de connexion + 1' } Création d'un thread VocalThread """ ip = obj['ip'] port = obj['port'] + PORT_VOCAL_ADD try: if not self.contains(ip): thread = DecodeThread(self, ip, port) self.threads[ip] = thread if self.isActive: thread.startSatelliteSynchro() thread.start() except Exception as e: print('Vocal.py : erreur lanceVocalconnect : ' + str(e.__str__())) def deconnectVocal(self, bus, key, obj): """ Reçu sur le bus par le déclenchement de l'événement 'deviceDeconnected' va détruire le thread a la deconnexion du satelite """ ipDeconnected = obj['ip'] for thread in self.threads: if ipDeconnected == thread: print("Destruction du thread vocal : " + ipDeconnected) t = self.threads[thread] if t.isAlive(): t.stop() del self.threads[ipDeconnected] def isVocalActive(self, args=None): """ return un objet JSON de isVocal utiliser lors de la connexion du satellite pour lui renvoyer si le vocal est actif ou pas. Activation par IHM """ obj = {} obj['vocalActive'] = self.isVocal() return obj def isVocal(self): return self.isActive def getFilesVocal(self): return self.vocal_files def setLang(self, args): lang = args[0].lang self.gtts.setLang(lang) return 'test' def activate(self): self.lanceLoadDecoder() def lanceLoadDecoder(self, bus=None, key=None, obj=None): config = Decoder.default_config() config.set_string(str('-hmm'), str(hmmd)) config.set_string(str('-lm'), str(lmdir)) config.set_string(str('-dict'), str(dictp)) self.decoder = Decoder(config) self.decoder.start_utt() def startVocal(self, args=None): """ Activer par l'IHM """ print("vocal.py : Start vocal") self.isActive = True for ip in self.threads: thread = self.threads[ip] ip, port = thread.getInfo() print("vocal.py : Start vocal thread = > " + str(ip)) newT = DecodeThread(self, self.decoder, ip, port) self.threads[ip] = newT if not newT.isAlive(): newT.startSatelliteSynchro() newT.start() print("vocal.py : Start vocal thread = > " + str(ip) + " => Ok ") def stopVocal(self, args=None): """ Activer par l'IHM """ print("vocal.py : Stop vocal") self.isActive = False for thread in self.threads: t = self.threads[thread] ip, port = t.getInfo() print("vocal.py : Stop vocal thread = > " + str(ip)) if t.isAlive(): t.stop() print("vocal.py : Stop vocal thread = > " + str(ip) + " => Ok ") def synchronize(self, text, play=False, label=None, ip=None): try: self.bus.publish('monitoringVocalService', text) textToRead = label if label else text # print textToRead if play and textToRead != '': self.gtts.play(textToRead, ip) except Exception as e: print('Vocal.py => synchronize : ' + e.__str__()) def loadActions(self, actions): self.actions = actions def loadOrdres(self, ordres): self.ordres = ordres def loadVariables(self, variables): self.variables = variables def loadNumeric(self, numeric): self.numeric = numeric
def __init__(self): self.waiters = [] self.bus = Bus()