示例#1
0
    def delete_favorited_scene(self, sceneId):
        '''
        sceneId - must be a favorited scene.
        '''
        with self.__fav_lock:
            try:
                favSort = self.__sceneController.get_favsort_of(sceneId)
            except Exception as e:
                raise AutomationException(11092, "prevSceneId does not belongs to any scene - " + \
                                                "prevSceneId provided: " + str(sceneId) + ", error: " + str(e))
            else:
                if favSort is None:
                    raise AutomationException(13000, "sceneId does not belongs to any favorited scene - " + \
                                                    "sceneId provided: " + str(sceneId))

            # This method raise error and rollback automatically if failed, or commit once succeed.
            try:
                self.__sceneController.delete_favorited_scene(sceneId)
                self.__sceneController.commit()
            except Exception as e:
                self.__sceneController.rollback()
                Logger.log_error(
                    "SceneService.delete_favorited_scene failed to delete favorited scene, ex:",
                    str(e))
                raise AutomationException(13002, "unexpected error: " + str(e))

            #Broadcast event
            self.__broadcast_message__scene_updated(sceneId)
            self.__broadcast_message__favorited_scene_deleted(sceneId)
示例#2
0
    def list_kbx_groups(self, request):
        '''
        List kbx_groups, mostly for debugging purpose.
        '''
        # Parameters
        try:
            paramKey = "offset"
            offset = request.get_value(paramKey)
            if offset is None:
                offset = 0
                
            paramKey = "limit"
            limit = request.get_value(paramKey)
            if limit is None:
                limit = 200

        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            result = self.__apiService.list_kbx_groups(offset, limit)
            kbxGroups = [dict(val) for val in result]
            self.send_response(request.requestId, data={"kbxGroups":kbxGroups})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#3
0
    def list_favorited_scenes(self, request):
        # Parameters
        try:
            paramKey = "limit"
            limit = request.get_value(paramKey)
            limit = 200 if limit is None else limit
            
            paramKey = "offset"
            offset = request.get_value(paramKey)
            offset = 0 if offset is None else offset
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            result, total = self.__sceneService.list_favorited_scene(offset, limit)

            self.send_response(request.requestId, {"data":result, "total":total})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#4
0
        def process_method_list(methodList):
            #===================================================================
            # Basic type validation
            #===================================================================
            if not isinstance(methodList, list):
                Logger.log_error(
                    "RuleService.set_rule: 'condition' and 'execution' must be type of list."
                )
                Logger.log_debug("type:", type(methodList), "value:",
                                 methodList)
                raise AutomationException(
                    11704,
                    "List is required for both 'condition' and 'execution'")

            #===================================================================
            # Check allowed size, raise error if exceeded.
            #===================================================================
            methodListLen = len(methodList)
            if methodListLen > AppConstants.MAX_METHOD_SIZE:
                Logger.log_error(
                    "RuleService.set_rule: 'condition' and 'execution' cannot have more than",
                    AppConstants.MAX_METHOD_SIZE, "items respectively.")
                raise AutomationException(11705, "Only a maximum of " + \
                                          str(AppConstants.MAX_METHOD_SIZE) + \
                                          " items is allowed for each 'condition' and 'execution' - given size " + \
                                          str(methodListLen),
                                          lambda text: str(AppConstants.MAX_METHOD_SIZE).join(text.split(":max_item_size:")))

            #===================================================================
            # Check if all kbxMethodIds are valid and all kbxMethodParams are list
            #===================================================================
            idValidator = NumberValidator(isRequired=True, decimalPoint=False)
            if not all([
                    idValidator.is_valid(eachMethod["kbxMethodId"])
                    and isinstance(eachMethod["kbxMethodParams"], list)
                    for eachMethod in methodList
            ]):
                raise AutomationException(
                    11704,
                    "'condition' and 'execution' have incorrect data structure."
                )

            #===================================================================
            # Check if all kbxParamName and kbxParamCurrentValue exists
            #===================================================================
            paramNameValidator = StringValidator(isRequired=True)
            for eachMethod in methodList:
                methodArgs = eachMethod["kbxMethodParams"]
                for methodArg in methodArgs:
                    if not paramNameValidator.is_valid(
                            methodArg[AppConstants.ARG_NAME]):
                        raise AutomationException(
                            11704,
                            "'condition' and 'execution' have invalid params structure"
                        )

                    if not AppConstants.ARG_CURRENT_VALUE in methodArg:
                        methodArg[AppConstants.ARG_CURRENT_VALUE] = None

            return methodList
示例#5
0
    def trigger_rule(self, request):
        '''
        Trigger a rule manually
        '''
        # Parameters
        try:
            paramKey = "ruleId"
            ruleId = request.get_value(paramKey)
            
            paramKey = "checkCondition"
            checkCondition = request.get_value(paramKey)
            checkCondition = not (checkCondition is False)
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            self.__ruleService.trigger_rule(ruleId=ruleId, checkCondition=checkCondition)

            self.send_response(request.requestId)
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#6
0
    def update_kbx_group(self, request):
        '''
        Update shared method group in use manually.
        '''
        # Parameters
        try:
            paramKey = "kbxGroupId"
            kbxGroupId = request.get_value(paramKey)

        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            result = self.__apiService.update_kbx_group(kbxGroupId)
            if result is None:
                groupStatus = "Group Removed"
            else:
                groupStatus = "Group Exists"
            
            self.send_response(request.requestId, data={"groupStatus":groupStatus})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#7
0
    def list_scenes(self, request):
        '''
        List all scene summaries.
        '''
        # Parameters
        try:
            paramKey = "limit"
            limit = request.get_value(paramKey)
            limit = AppConstants.UPPER_LIMIT if limit is None else limit
            
            paramKey = "offset"
            offset = request.get_value(paramKey)
            offset = 0 if offset is None else offset
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            result, total = self.__sceneService.list_scenes(limit=limit, offset=offset)

            self.send_response(request.requestId, data={"totalCount":total, "data":result})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#8
0
    def list_methods(self, request):
        '''
        List all methods by groupId(required), section(required) accepts "if/then".
        '''
        # Parameters
        try:
            paramKey = "groupId"
            groupId = request.get_value(paramKey)
            
            paramKey = "section"
            section = request.get_value(paramKey)
            section = self.__parse_section(section)
            
            paramKey = "language"
            language = request.get_arg(paramKey)
            language = AppInfo.DEFAULT_API_LANGUAGE if language is None else language

        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            methodList, groupDict = self.__apiService.list_methods(section=section, groupId=groupId, language=language)

            self.send_response(request.requestId, data={"group":groupDict, "data":sorted(methodList, key=lambda method: method.get("kbxMethodSort", 0))})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#9
0
 def update_kbx_method(self, request):
     '''
     Update shared method in use manually.
     '''
     # Parameters
     try:
         paramKey = "kbxMethodId"
         kbxMethodId = request.get_value(paramKey)
         
     except Exception as e:
         self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
         return
     
     # Implementations
     try:
         result = self.__apiService.update_kbx_method(kbxMethodId)
         
         if result is None:
             methodStatus = "Method Removed"
         elif result is True:
             methodStatus = "Method Active"
         else:
             methodStatus = "Method Inactive"
         
         self.send_response(request.requestId, data={"methodStatus":methodStatus})
         
     except Exception as e:
         if not isinstance(e, AutomationException):
             traceback.print_exc()
             e = AutomationException(11099, str(e))
         self.send_response(request.requestId, data=e)
示例#10
0
    def get_scene_execution_result(self, request):
        '''
        Get scene execution result (aggregates details base on preferred language).
        '''
        # Parameters
        try:
            paramKey = "serId"
            serId = request.get_value(paramKey)
            
            paramKey = "language"
            language = request.get_arg(paramKey)
            language = AppInfo.DEFAULT_API_LANGUAGE if language is None else language
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            serObject = self.__serService.get_scene_execution_result(serId, language)

            self.send_response(request.requestId, data=serObject)
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#11
0
    def execute_scene(self, request):
        '''
        Execute a scene.
        '''
        # Parameters
        try:
            paramKey = "sceneId"
            sceneId = request.get_value(paramKey)
            
            paramKey = "serUrl"
            serUrl = request.get_value(paramKey)
            
            paramKey = "language"
            language = request.get_arg(paramKey)
            language = AppInfo.DEFAULT_API_LANGUAGE if language is None else language
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
            
        # Implementations
        try:
            self.__sceneService.execute_scene(sceneId=sceneId, serUrl=serUrl, language=language)

            self.send_response(request.requestId)
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#12
0
    def retry_scene_execution_result_item(self, request):
        '''
        Retry a specific or all items with error sequentially.
        '''
        # Parameters
        try:
            paramKey = "serId"
            serId = request.get_value(paramKey)
            
            paramKey = "seriIndex"
            seriIndex = request.get_value(paramKey)
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            seriIndexes = self.__serService.retry_scene_execution_result_item(serId, seriIndex)

            self.send_response(request.requestId, data={"serId":serId, "seriIndexes":seriIndexes})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#13
0
    def __date_time_range(self, request):
        try:
            dtVal = request.get_value(
                TimerModule._PARAM_DT_RANGE.get_kbx_param_name())
            startDateTime = dtVal.get_start_date_time()
            endDateTime = dtVal.get_end_date_time()

            execTime = request.get_arg(AppConstants.KEY_CONDITION_TIMESTAMP)
            execTime = int(execTime)

            if execTime > endDateTime:
                # Allow a time delta of 59 seconds
                response = bool(abs(execTime - endDateTime) <= 59)
            else:
                response = bool(startDateTime <= execTime <= endDateTime)

            if not response:
                raise AutomationException(11800)

            self.send_response({}, request.requestId)
        except AutomationException as ae:
            Logger.log_error(
                "TimerModule date_time range failed on comparison:", str(ae))
            self.send_response({}, request.requestId, ae.get_error_code(),
                               ae.get_error_message())
        except Exception as e:
            Logger.log_error(
                "TimerModule date_time range failed on comparison (unexpected):",
                str(e))
            ae = AutomationException(11099, str(e))
            self.send_response({}, request.requestId, ae.get_error_code(),
                               ae.get_error_message())
示例#14
0
    def list_scene_execution_results(self, request):
        '''
        List all scene execution results without items. (For debugging)
        '''
        # Parameters
        try:
            paramKey = "limit"
            limit = request.get_value(paramKey)
            limit = 50 if limit is None else limit
            
            paramKey = "offset"
            offset = request.get_value(paramKey)
            offset = 0 if offset is None else offset
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            result = self.__serService.list_scene_execution_results(offset, limit)

            self.send_response(request.requestId, {"data":result})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#15
0
 def set_favorited_scene(self, request):
     # Parameters
     try:
         paramKey = "sceneId"
         sceneId = request.get_value(paramKey)
         
         paramKey = "prevSceneId"
         prevSceneId = request.get_value(paramKey)
         
         if sceneId == prevSceneId:
             raise Exception("sceneId cannot equals to prevSceneId")
         
     except Exception as e:
         self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
         return
     
     # Implementations
     try:
         self.__sceneService.set_favorited_scene(sceneId, prevSceneId)
         
         self.send_response(request.requestId, data={"prevSceneId":prevSceneId})
         
     except Exception as e:
         if not isinstance(e, AutomationException):
             traceback.print_exc()
             e = AutomationException(11099, str(e))
         self.send_response(request.requestId, data=e)
示例#16
0
    def list_groups(self, request):
        '''
        List all groups, parentId is optional.
        '''
        # Parameters
        try:
            paramKey = "parentId"
            parentId = request.get_value(paramKey)
            
            paramKey = "section"
            section = request.get_value(paramKey)
            section = self.__parse_section(section)

            paramKey = "language"
            language = request.get_arg(paramKey)
            language = AppInfo.DEFAULT_API_LANGUAGE if language is None else language
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            parentGroup, groupList = self.__apiService.list_groups(section=section, parentId=parentId, language=language)

            self.send_response(request.requestId, data={"parentGroup":parentGroup, "data": groupList})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#17
0
    def enable_rule(self, request):
        '''
        Enable/Disable a rule.
        '''
        # Parameters
        try:
            paramKey = "ruleId"
            ruleId = request.get_value(paramKey)
            
            paramKey = "enabled"
            enabled = request.get_value("enabled")
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            self.__ruleService.enable_rule(ruleId=ruleId, enabled=enabled)

            self.send_response(request.requestId)
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#18
0
    def __day_of_week(self, request):
        try:
            dows = request.get_value(
                TimerModule._PARAM_DOW.get_kbx_param_name())

            execTime = request.get_arg(AppConstants.KEY_CONDITION_TIMESTAMP)
            execTime = datetime.datetime.fromtimestamp(execTime)
            execDow = execTime.isoweekday() % 7

            response = bool(execDow in dows)

            if not response:
                raise AutomationException(11800)

            self.send_response({}, request.requestId)
        except AutomationException as ae:
            Logger.log_error("TimerModule day_of_week failed on comparison:",
                             str(ae))
            self.send_response({}, request.requestId, ae.get_error_code(),
                               ae.get_error_message())
        except Exception as e:
            Logger.log_error(
                "TimerModule day_of_week failed on comparison (unexpected):",
                str(e))
            ae = AutomationException(11099, str(e))
            self.send_response({}, request.requestId, ae.get_error_code(),
                               ae.get_error_message())
示例#19
0
    def get_scene(self, request):
        '''
        Get single scene detail by scene id.
        '''
        # Parameters
        try:
            paramKey = "sceneId"
            sceneId = request.get_value(paramKey)
            
            paramKey = "language"
            language = request.get_arg("language")
            language = AppInfo.DEFAULT_API_LANGUAGE if language is None else language
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            result = self.__sceneService.get_scene(sceneId=sceneId, language=language)

            self.send_response(request.requestId, data=result)
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#20
0
    def set_rule(self, request):
        '''
        Set rule is the combination of both "update/insert rule".
        '''
        # Parameters
        try:
            paramKey = "Process post data"
            params = Helper.parse_post_data(request.get_post_data())
            
            paramKey = "condition"
            condition = json.loads(params[paramKey])
            if len(condition) == 0:
                raise Exception("'condition' cannot be empty")
            
            paramKey = "execution"
            execution = json.loads(params[paramKey])
            if len(condition) == 0:
                raise Exception("'execution' cannot be empty")
            
            paramKey = "trigger"
            trigger = json.loads(params[paramKey])
            
            paramKey = "ruleId"
            ruleId = params.get(paramKey)
            ruleId = None if Util.is_empty(ruleId) else int(ruleId)
            
            paramKey = "ruleName"
            ruleName = params[paramKey]
            if Util.is_empty(ruleName):
                raise Exception("'ruleName' cannot be empty")
            ruleName = str(ruleName)
            
            paramKey = "enabled"
            boolValidator = KBXBoolean(kbxParamName="boolValidator", kbxParamIsRequired=False)
            enabled = boolValidator.cast(params.get(paramKey))
            enabled = enabled is not False # always True unless False is specified
            
            paramKey = "ruleProtected"
            ruleProtected = boolValidator.cast(params.get(paramKey))
            ruleProtected = ruleProtected is True # Always False unless True is specified.
            
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
            
        # Implementations
        try:
            self.__ruleService.set_rule(trigger=trigger, condition=condition, execution=execution, ruleId=ruleId, \
                                        ruleName=ruleName, ruleProtected=ruleProtected, enabled=enabled)

            self.send_response(request.requestId)
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#21
0
 def __verify_scene_updated(self, sceneId):
     try:
         statusProcessed = self.__sceneController.get_status_processed(
             sceneId)
         if statusProcessed == AppConstants.SCENE_STATUS_UPDATING:
             raise AutomationException(11903, "edit/execute/delete scene is not allowed when its updating. " + \
                                       "Wait until the update process is completed.")
     except:
         raise AutomationException(11902,
                                   "Scene ID provided:" + str(sceneId))
示例#22
0
 def __check_rule_process_status(self, ruleId):
     try:
         statusProcessed = self.__ruleController.get_status_processed(
             ruleId)
         if statusProcessed != AppConstants.RULE_STATUS_UPDATED:
             raise AutomationException(
                 11703,
                 "edit/delete/execute is not allowed on rule update in progress"
             )
     except:
         raise AutomationException(
             11702, "Rule ID provided not found - " + str(ruleId))
示例#23
0
    def set_favorited_scene(self, sceneId, prevSceneId=None):
        '''
        sceneId - can be either favorited/non-favorited scene, but must be a valid scene id.
        prevSceneId - must be another favorited scene or error is raised.
        
        Both updating and executing doesn't blocks a scene from adding to/removing from favorited list.
        '''
        with self.__fav_lock:
            # Validation for sceneId.
            if not self.__sceneController.has(sceneId):
                raise AutomationException(
                    11092,
                    "sceneId does not belongs to any scene - sceneId provided: "
                    + str(sceneId))

            # Because UI display in reversed order, hence their prevSceneId == our nextSceneId
            nextSceneId = prevSceneId or None

            # Get favSort before sceneId of nextSceneId
            if nextSceneId is None:
                maxFavSort = self.__sceneController.get_largest_favsort_num(
                )  # If len of favorited list is 0, maxFavSort = 0
                # favSort stores number to be assigned to sceneId.
                favSort = maxFavSort + 1
            else:
                try:
                    # favSort stores number to be assigned to sceneId.
                    # current favSort of prevSceneId will becomes favSort of sceneId.
                    favSort = self.__sceneController.get_favsort_of(
                        nextSceneId)
                except Exception as e:
                    raise AutomationException(11092, "prevSceneId does not belongs to any scene - " + \
                                                    "prevSceneId provided: " + str(nextSceneId) + ", error: " + str(e))
                else:
                    if favSort is None:
                        raise AutomationException(13000, "prevSceneId does not belongs to any favorited scene - " + \
                                                        "prevSceneId provided: " + str(nextSceneId) + ", error: " + str(e))

            # Update favSort of the scene
            try:
                self.__sceneController.update_favorited_scene(sceneId, favSort)
                self.__sceneController.commit()
            except Exception as e:
                self.__sceneController.rollback()
                Logger.log_error(
                    "SceneService.set_favorited_scene failed to update favorited scene, ex:",
                    str(e))
                raise AutomationException(13001, "unexpected error: " + str(e))

            # Broadcast events
            self.__broadcast_message__scene_updated(sceneId)
            self.__broadcast_message__favorited_scene_added(
                sceneId, prevSceneId)
示例#24
0
    def set_scene(self, request):
        '''
        Set scene is the combination of both "update/insert scene".
        '''
        # Parameters
        try:
            paramKey = "Process post data"
            params = Helper.parse_post_data(request.get_post_data())

            paramKey = "execution"
            execution = json.loads(params[paramKey])
            if len(execution) == 0:
                raise Exception("'execution' cannot be empty")
            
            paramKey = "sceneId"
            sceneId = params.get(paramKey)
            sceneId = None if Util.is_empty(sceneId) else int(sceneId)
            
            paramKey = "sceneName"
            sceneName = params[paramKey]
            if Util.is_empty(sceneName):
                raise Exception("'sceneName' cannot be empty")
            sceneName = str(sceneName)
            
            paramKey = "sceneIcon"
            sceneIcon = params[paramKey]
            if Util.is_empty(sceneIcon):
                raise Exception("'sceneIcon' cannot be empty")
            sceneIcon = str(sceneIcon)
            
            paramKey = "sceneProtected"
            boolValidator = KBXBoolean(kbxParamName="boolValidator", kbxParamIsRequired=False)
            sceneProtected = boolValidator.cast(params.get(paramKey))
            sceneProtected = sceneProtected is True # Always False unless True is specified.
        
        except Exception as e:
            self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
            return
        
        # Implementations
        try:
            sceneId = self.__sceneService.set_scene(execution=execution, sceneId=sceneId, sceneName=sceneName, \
                                                    sceneProtected=sceneProtected, sceneIcon=sceneIcon)

            self.send_response(request.requestId, data={"sceneId":sceneId})
            
        except Exception as e:
            if not isinstance(e, AutomationException):
                traceback.print_exc()
                e = AutomationException(11099, str(e))
            self.send_response(request.requestId, data=e)
示例#25
0
    def list_groups(self, language, section, parentId=None):
        try:
            def sort_group_list(value):
                name = value.get("kbxGroupLabel")
                if name is None:
                    return ""
                else:
                    return str(name).lower()
                
            
            unknownGroupDict = {}
            unknownGroupId = self.__get_group_ids()
                
            parentId = AppConstants.GROUP_ID_AUTOMATION if parentId is None else parentId

            result = SharedMethod.list_shared_method_groups(kbxGroupParentId=parentId, kbxMethodTag=section,
                                                            enableTagCount=True, language=language)
            
            groupList = result["groupList"]
            
            # Level 1 groups which contain of SERVICES and LOCATIONS.
            if parentId == AppConstants.GROUP_ID_AUTOMATION:
                services = deque()
                groups =  deque()
                
                for groupDict in groupList:
                    kbxGroupId = groupDict["kbxGroupId"]
                    
                    # Add indicator for UI
                    groupDict["kbxGroupHasChild"] = True

                    # Reordering
                    if kbxGroupId == AppConstants.GROUP_ID_NOTIFICATION:
                        groupDict["kbxGroupDesc"] = KBXLang("group_notification_" + section)
                        services.appendleft(groupDict)
                    elif kbxGroupId == AppConstants.GROUP_ID_SERVICE:
                        groupDict["kbxGroupDesc"] = KBXLang("group_service_" + section)
                        services.append(groupDict)
                    elif kbxGroupId == unknownGroupId:
                        #append the group dict
                        unknownGroupDict = groupDict
                    else:
                        groups.append(groupDict)
                groups = sorted(groups, key=sort_group_list)
                if len(unknownGroupDict) > 0:
                    groups.append(unknownGroupDict)
                services.extend(groups)
                groupList = services
                parentGroup = None
                
            # Level 2 groups which are DEVICES or SERVICES.
            else:
                parentGroup = SharedMethod.get_shared_method_group_by_id(kbxGroupId=parentId, language=language)

            return parentGroup, groupList

        except Exception as e:
            Logger.log_error("APIService.list_groups ex:", e)
            raise AutomationException(11601, "Unexpected error - " + str(e))
示例#26
0
    def __time_range(self, request):
        try:
            try:
                tVal = request.get_value(
                    TimerModule._PARAM_TIME_RANGE.get_kbx_param_name())
                startTime = tVal.get_start_time()
                endTime = tVal.get_end_time()
            except:
                # Backward compatible to daily_task
                kbxTime = KBXTime(kbxParamName="time")
                startTime = endTime = kbxTime.cast(request.get_arg("time"))

            execTime = request.get_arg(AppConstants.KEY_CONDITION_TIMESTAMP)
            execTime = datetime.datetime.fromtimestamp(execTime)
            execTime = (execTime.hour * 3600) + (execTime.minute *
                                                 60) + (execTime.second)

            if endTime < startTime:
                checkRange = [(startTime, 86400), (0, endTime + 59)]
            else:
                checkRange = [(startTime, endTime + 59)]

            for startVal, endVal in checkRange:
                if startVal <= execTime <= endVal:
                    response = True
                    break
            else:
                response = False

            if not response:
                raise AutomationException(11800)

            self.send_response({}, request.requestId)
        except AutomationException as ae:
            Logger.log_error("TimerModule time range failed on comparison:",
                             str(ae))
            self.send_response({}, request.requestId, ae.get_error_code(),
                               ae.get_error_message())
        except Exception as e:
            Logger.log_error(
                "TimerModule time range failed on comparison (unexpected):",
                str(e))
            ae = AutomationException(11099, str(e))
            self.send_response({}, request.requestId, ae.get_error_code(),
                               ae.get_error_message())
示例#27
0
 def stop_scene(self, sceneId):
     '''
     Stop a scene execution.
     '''
     sceneExecLock = self.__sceneExecLocks.get(sceneId, None)
     if sceneExecLock is None:
         raise AutomationException(
             11905, "Call stop only after execute_scene is called")
     else:
         sceneExecLock.set_stop()
示例#28
0
 def delete_favorited_scene(self, request):
     # Parameters
     try:
         paramKey = "sceneId"
         sceneId = request.get_value(paramKey)
         
     except Exception as e:
         self.send_response(request.requestId, data=AutomationException(11097, " - ".join((paramKey, str(e)))))
         return
     
     # Implementations
     try:
         self.__sceneService.delete_favorited_scene(sceneId)
         
         self.send_response(request.requestId)
         
     except Exception as e:
         if not isinstance(e, AutomationException):
             traceback.print_exc()
             e = AutomationException(11099, str(e))
         self.send_response(request.requestId, data=e)
示例#29
0
 def update_kbx_method(self, kbxMethodId):
     '''
     Returns: 
     None: Method Removed
     True: Method Active
     False: Method Inactive
     '''
     hasKBXMethod = self.__apiController.has_kbx_method(kbxMethodId)
     if not hasKBXMethod:
         raise AutomationException(11602, "Method ID provided: " + str(kbxMethodId))
     
     try:
         kbxMethod = SharedMethod.get_shared_method_by_id(kbxMethodId, language=AppInfo.DEFAULT_API_LANGUAGE)
     except SystemException as se:
         if se.value["returnValue"] == 1608:
             self.__methodController.delete(kbxMethodId)
             return None # None: Method Removed
         else:
             raise AutomationException(11601, "Unexpected returnValue when get method: " + str(se))
     else:
         self.__methodController.update(kbxMethod)
         return kbxMethod["kbxMethodStatus"] == SharedMethod.METHOD_STATUS_ACTIVE # True: Active, False: Inactive
示例#30
0
 def update_kbx_group(self, kbxGroupId):
     '''
     Returns
     None: Group Removed
     True: Group Exists
     '''
     hasKBXGroup = self.__apiController.has_kbx_group(kbxGroupId)
     if not hasKBXGroup:
         raise AutomationException(11603, "Group ID provided: " + str(kbxGroupId))
     
     try:
         kbxGroup = SharedMethod.get_shared_method_group_by_id(kbxGroupId, enableTagCount=False, 
                                                               language=AppInfo.DEFAULT_API_LANGUAGE)
     except SystemException as se:
         if se.value["returnValue"] == 1609:
             self.__groupController.delete(kbxGroupId)
             return None
         else:
             raise AutomationException(11601, "Unexpected returnValue when get method group: " + str(se))
     else:
         self.__groupController.update(kbxGroup)
         return True