コード例 #1
0
ファイル: Module.py プロジェクト: monschiTee/ProjectAlice
    def __init__(self,
                 supportedIntents: list,
                 authOnlyIntents: dict = None,
                 databaseSchema: dict = None):
        self._logger = logging.getLogger('ProjectAlice')

        try:
            path = Path(inspect.getfile(
                self.__class__)).with_suffix('.install')
            self._install = json.loads(path.read_text())
        except FileNotFoundError:
            raise ModuleStartingFailed(
                error='[{}] Cannot find install file'.format(
                    type(self).__name__))
        except Exception as e:
            raise ModuleStartingFailed(
                error='[{}] Failed loading module: {}'.format(
                    type(self).__name__, e))

        self._name = self._install['name']
        self._active = True
        self._delayed = False
        self._databaseSchema = databaseSchema

        self._supportedIntents = supportedIntents
        self._authOnlyIntents = authOnlyIntents or dict()
コード例 #2
0
    def onStart(self) -> list:
        super().onStart()

        if self.getConfig('phueBridgeIp'):
            if self._connectBridge():
                self.delayed = False
                return self.supportedIntents
            else:
                self.updateConfig('phueAutodiscoverFallback', True)
                self.updateConfig('phueBridgeIp', '')
        elif self.getConfig('phueAutodiscoverFallback'):
            try:
                request = requests.get('https://www.meethue.com/api/nupnp')
                response = request.json()
                firstBridge = response[0]
                self.logInfo(
                    f"Autodiscover found bridge at {firstBridge['internalipaddress']}, saving ip to config.json"
                )
                self.updateConfig('phueAutodiscoverFallback', False)
                self.updateConfig('phueBridgeIp',
                                  firstBridge['internalipaddress'])
                if not self._connectBridge():
                    raise ModuleStartingFailed(
                        moduleName=self.name, error='Cannot connect to bridge')
                return self.supportedIntents
            except IndexError:
                self.logInfo('No bridge found')

        raise ModuleStartingFailed(moduleName=self.name,
                                   error='Cannot connect to bridge')
コード例 #3
0
ファイル: Module.py プロジェクト: aluavin/ProjectAlice
    def __init__(self,
                 supportedIntents: Iterable = None,
                 authOnlyIntents: dict = None,
                 databaseSchema: dict = None):
        super().__init__(logDepth=4)
        try:
            path = Path(inspect.getfile(
                self.__class__)).with_suffix('.install')
            self._install = json.loads(path.read_text())
        except FileNotFoundError:
            raise ModuleStartingFailed(
                error=f'[{type(self).__name__}] Cannot find install file')
        except Exception as e:
            raise ModuleStartingFailed(
                error=f'[{type(self).__name__}] Failed loading module: {e}')

        self._name = self._install['name']
        self._author = self._install['author']
        self._version = self._install['version']
        self._updateAvailable = False
        self._active = True
        self._delayed = False
        self._required = False
        self._databaseSchema = databaseSchema
        self._widgets = dict()

        if not supportedIntents:
            supportedIntents = list()

        self._myIntents: List[Intent] = list()
        self._supportedIntents: Dict[str, Tuple[(str, Intent),
                                                Callable]] = dict()
        for item in (*supportedIntents, *self.intentMethods()):
            if isinstance(item, tuple):
                self._supportedIntents[str(item[0])] = item
                self._myIntents.append(item[0])
            elif isinstance(item, Intent):
                self._supportedIntents[str(item)] = (item, self.onMessage)
                self._myIntents.append(item)
            elif isinstance(item, str):
                self._supportedIntents[item] = (item, self.onMessage)

        self._authOnlyIntents: Dict[str, AccessLevel] = {
            str(intent): level.value
            for intent, level in authOnlyIntents.items()
        } if authOnlyIntents else dict()
        self._utteranceSlotCleaner = re.compile('{(.+?):=>.+?}')
        self.loadWidgets()
コード例 #4
0
    def onStart(self):
        super().onStart()
        redQueenIdentityFile = self._getRedQueenIdentityFileName()
        redQueenIdentityFileTemplate = redQueenIdentityFile + '.dist'

        if not os.path.isfile(redQueenIdentityFile):
            if os.path.isfile(redQueenIdentityFileTemplate):
                shutil.copyfile(redQueenIdentityFileTemplate,
                                redQueenIdentityFile)
                self._logger.info('[{}] New Red Queen is born'.format(
                    self.name))

                with open(self._getRedQueenIdentityFileName(), 'r') as f:
                    self._redQueen = json.load(f)

                self._redQueen['infos']['born'] = time.strftime("%d.%m.%Y")
                self._saveRedQueenIdentity()
            else:
                self._logger.info(
                    '[{}] Cannot find Red Queen identity template'.format(
                        self.name))
                raise ModuleStartingFailed(moduleName=self.name)
        else:
            self._logger.info('[{}] Found existing Red Queen identity'.format(
                self.name))
            with open(self._getRedQueenIdentityFileName(), 'r') as f:
                self._redQueen = json.load(f)

        return self._SUPPORTED_INTENTS
コード例 #5
0
    def onStart(self) -> list:
        super().onStart()
        if not self.getConfig('password'):
            raise ModuleStartingFailed(moduleName=self.name,
                                       error='No credentials provided')

        if not self._auth():
            raise ModuleStartingFailed(moduleName=self.name,
                                       error='Authentication failed')

        try:
            self._weatherData = lnetatmo.WeatherStationData(self._netatmoAuth)
        except lnetatmo.NoDevice:
            raise ModuleStartingFailed(moduleName=self.name,
                                       error='No Netatmo device found')

        return self.supportedIntents
コード例 #6
0
    def onStart(self) -> list:
        super().onStart()
        if not self.getConfig('password'):
            raise ModuleStartingFailed(
                moduleName=self.name,
                error=f'[{self.name}] No credentials provided')

        if not self._auth():
            raise ModuleStartingFailed(
                moduleName=self.name,
                error=f'[{self.name}] Authentication failed')

        try:
            self._weatherData = lnetatmo.WeatherStationData(self._netatmoAuth)
        except lnetatmo.NoDevice:
            raise ModuleStartingFailed(
                moduleName=self.name,
                error=f'[{self.name}] No Netatmo device found')
        else:
            return self._SUPPORTED_INTENTS
コード例 #7
0
    def __init__(self,
                 supportedIntents: typing.Iterable,
                 authOnlyIntents: dict = None,
                 databaseSchema: dict = None):
        self._logger = logging.getLogger('ProjectAlice')

        try:
            path = Path(inspect.getfile(
                self.__class__)).with_suffix('.install')
            self._install = json.loads(path.read_text())
        except FileNotFoundError:
            raise ModuleStartingFailed(
                error=f'[{type(self).__name__}] Cannot find install file')
        except Exception as e:
            raise ModuleStartingFailed(
                error=f'[{type(self).__name__}] Failed loading module: {e}')

        self._name = self._install['name']
        self._author = self._install['author']
        self._version = self._install['version']
        self._updateAvailable = False
        self._active = True
        self._delayed = False
        self._required = False
        self._databaseSchema = databaseSchema
        self._widgets = dict()

        if isinstance(supportedIntents, dict):
            self._supportedIntents = supportedIntents
        elif isinstance(supportedIntents, list):
            self._supportedIntents = {
                intent: None
                for intent in supportedIntents
            }

        self._authOnlyIntents = authOnlyIntents or dict()

        self._utteranceSlotCleaner = re.compile('{(.+?):=>.+?}')

        self.loadWidgets()
コード例 #8
0
    def _connectXmpp(self):
        server = self.getConfig('aliceXmppServer')
        port = self.getConfig('aliceXmppPort')
        ssl = self.getConfig('aliceXmppSSL')
        if ssl == 'legacy':
            self._xmpp.connect(address=(server, port),
                               use_tls=False,
                               use_ssl=True)
        elif ssl == 'tls':
            self._xmpp.connect(address=(server, port), use_tls=True)
        elif not ssl:
            self._xmpp.connect(address=(server, port), use_tls=False)
        else:
            raise ModuleStartingFailed(
                'Invalid value in aliceXmppSSL: must be "legacy", "tls", or left empty'
            )

        self._thread = self.ThreadManager.newThread(name='AliceXmppClient',
                                                    target=self._xmpp.process,
                                                    kwargs={'block': True},
                                                    autostart=True)
コード例 #9
0
 def _connectAccount(self):
     try:
         self._bring = self.bring()
     except BringApi.AuthentificationFailed:
         raise ModuleStartingFailed(
             self._name, 'Please check your account login and password')