예제 #1
0
	def getActionAndTemplateAndParameterValues(self, ruleConsequent):
		checkData(locals())

		actions = Actions()
		actionList = actions.getAllActions()

		for action in actionList:
			
			# A action.ruleConsequent is represented as set of templates models:
			# Example "template1 | template2 | template2"

			models = action.ruleConsequent.split('|')

			for model in models:
				parameterNumber = model.count("@val")
				originalModel = model.strip()
				model = model.replace("@val","(.+)").strip()

				matchObj = re.match( model, ruleConsequent, re.M|re.I)

				if matchObj:
					parameterValues = {}

					for i in range(0,parameterNumber):
						parameterValues[str(i)] = matchObj.group(i + 1)

					return (action, originalModel, parameterValues)

		raise NotWellFormedRuleError("Impossible to find any action corresponding to the following rule consequent > " + ruleConsequent)
예제 #2
0
	def deleteRoom(self, buildingName, roomName):
		checkData(locals())

		print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ")  not yet tested"
		print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ")  table rules_priority not correctly updated"

		from app.backend.model.room import Room
		room = Room(roomName = roomName,  buildingName = buildingName)
		room.retrieve()

		ruleList = room.getRules()
		triggerList = room.getTriggers()
		actionList = room.getActions()

		for rule in ruleList:
			rule.delete()

		for trigger in triggerList:
			room.deleteTrigger(trigger)

		for action in actionList:
			room.deleteAction(action)

		room.delete()

		return {}
예제 #3
0
	def translateAction(self, ruleConsequent, getDict = False):
		checkData(locals())

		actions = Actions()
		action, originalTemplate, parameterValues = self.getActionAndTemplateAndParameterValues(ruleConsequent)
		translationTemplate = actions.translateTemplate('Z3', originalTemplate)

		translatedParams = {}

		for key,value in parameterValues.iteritems():
			translatedParams[key] = self.__translateParameters(action.category, value)


		translation = translationTemplate

		for i in range(0,len(parameterValues.keys())):

			value = translatedParams[str(i)]
			translation = translation.replace("@val", value, 1)

		if not getDict:
			return translation, action, translatedParams
		else:
			result = {}
			result["translation"] = translation
			result["action"] = action.getDict()
			result["translatedParams"] = translatedParams
			return result
예제 #4
0
	def getInfo(self, buildingName):
		checkData(locals())
	
		building = Building(buildingName = buildingName)
		building.retrieve()

		return building.getDict()
	def setNotificationAsUnread(self, notificationId):
		checkData(locals())

		
		notification = Notification(id = notificationId)
		notification.setAsUnread()
		return {}
예제 #6
0
	def getTriggerAndTemplateAndParameterValues(self, ruleAntecedent):
		checkData(locals())

		triggers = Triggers()
		triggerList = triggers.getAllTriggers()

		for trigger in triggerList:
			
			# A trigger.ruleAntecedent is represented as set of templates models:
			# Example "template1 | template2 | template2"
			# Where each template can be like
			# "it is between %d AM and %d AM | it is between %d AM and %d PM | it is between %d PM and %d AM | it is between %d PM and %d PM"

			models = trigger.ruleAntecedent.split('|')

			for model in models:
				parameterNumber = model.count("@val")
				originalModel = model.strip()
				model = model.replace("@val","(.+)").strip()
	

				matchObj = re.match( model, ruleAntecedent, re.M|re.I)

				if matchObj:
					parameterValues = {}

					for i in range(0,parameterNumber):
						parameterValues[str(i)] = matchObj.group(i + 1)

					return (trigger, originalModel, parameterValues)

		raise NotWellFormedRuleError("Impossible to find any trigger corresponding to the following rule consequent > " + ruleAntecedent)
예제 #7
0
	def storeFeedback(self, authorUuid, alternativeContact = None, score = None, message = None):
		checkData(locals())

		feedback = Feedback(authorUuid = authorUuid, alternativeContact = alternativeContact, score = score, message = message)
		feedback.store()

		return feedback.getDict()
예제 #8
0
	def addRoom(self, groupId, roomName, buildingName):
		checkData(locals())

		group = Group(buildingName = buildingName, id = groupId)
		group.retrieve()

		from app.backend.model.room import Room
		room = Room(buildingName = buildingName, roomName = roomName)
		room.retrieve()


		if group.crossRoomsValidation:
			print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ")  This part of the method as not been tested"
			# In this case we have to check that the room doesn't belong to another CrossRoomValidatioGroup
			from app.backend.model.building import Building
			building = Building(buildingName = buildingName)
			building.retrieve()
			crvgList = building.getCrossRoomValidationGroups(roomName = roomName, validationCategories = group.crossRoomsValidationCategories)

			if len(crvgList) > 0:
				raise WrongBuildingGroupRipartitionError("A room can belong to only one cross validation group per category. Room " + str(roomName) + " in already in group " + str(crvgList[0]))

		group.addRoom(room)

		return room.getDict()
예제 #9
0
	def login(self, username, password):
		checkData(locals())

		if len(password) == 0 or len(username) == 0:
			raise MissingInputDataError("Insert username and password!")

		from app.backend.controller.usersManager import UsersManager

		usersManager = UsersManager()

		try:
			user = usersManager.getUser(username, password)
			sessionKey = self.__generateSessionKey()
			userUuid = user.uuid
			expireTimestamp = datetime.datetime.now() + datetime.timedelta(days=1)
			
			session = Session(sessionKey = sessionKey, userUuid = userUuid, expireTimestamp = expireTimestamp)
			
			try:
				session.store()
				sessionData = {"sessionKey" : sessionKey, "userUuid" : userUuid}
				return sessionData
			except SessionCreationError as e:
				raise e
			else:
				return None

		except UserNotFoundError as e:
			raise e
		else:
			return None
예제 #10
0
	def getCrossRoomValidationGroups(self, buildingName, roomName = None, validationCategories = None):
		checkData(locals())

		building = Building(buildingName = buildingName)
		building.retrieve()

		return building.getCrossRoomValidationGroups(roomName = roomName, validationCategories = validationCategories)	
예제 #11
0
	def deleteRule(self, ruleId, buildingName, roomName, editorUuid):
		checkData(locals())

		room = Room(buildingName = buildingName, roomName = roomName)
		room.retrieve()

		from app.backend.model.rule import Rule
		rule = Rule(id = ruleId)
		rule.retrieve()

		from app.backend.model.user import User
		editor = User(uuid = editorUuid)
		editor.retrieve()
		
		author = User(uuid = rule.authorUuid)
		author.retrieve()


		# If this room is not related to a room, I cannot modify it from this method
		if not rule.roomName:
			raise UserCredentialError("You cannot modify this group related rule.")

		# If this rule is not about this building
		if rule.buildingName != buildingName:
			raise UserCredentialError("You cannot modify the rule of another building.")			
			
		if author.uuid != editor.uuid:

			if not rule.groupId and not rule.getRoom().roomName in list(r.roomName for r in editor.getRooms()):
				raise UserCredentialError("You cannot modify a rule of a room you do not own.")				

			#if rule.getRoom() not in editor.getRooms():
			#	raise UserCredentialError("You cannot modify a rule of a room you do not own.")

			if rule.groupId:

				from app.backend.model.group import Group
				group = Group(buildingName = buildingName, id = groupId)
				group.retrieve()

				if not group:
					raise UserCredentialError("You cannot delete a rule of a room you do not own.")				

				if not group.crossRoomsValidation:
					raise UserCredentialError("You cannot delete a rule you do not own.")

				if not group.id in list(g.id for g in editor.getGroups()):
					raise UserCredentialError("You cannot delete a rule belonging to a group you do not own.")

				if not rule.getRoom().roomName in list(r.roomName for r in group.getRooms()):
					raise UserCredentialError("You cannot delete a rule belonging to room that does not belongs to a group you do not own.")

			if editor.level < rule.getPriority():
				raise UserCredentialError("You cannot modify this rule since it has a too high priority for your user level")			


		room.deleteRule(rule)

		return {}
예제 #12
0
	def __init__(self, buildingName = None, startDate = None, numberOfDays = None, roomFilter = None):
		
		checkData(locals())

		self.buildingName = buildingName
		self.startDate = startDate
		self.numberOfDays = numberOfDays
		self.roomFilter = roomFilter
예제 #13
0
	def getRuleInfo(self, buildingName = None, roomName = None, ruleId = None):
		checkData(locals())

		from app.backend.model.rule import Rule
		rule = Rule(id = ruleId, buildingName = buildingName, roomName = roomName)
		rule.retrieve()

		return rule.getDict(buildingName = None, roomName = None)
예제 #14
0
	def getRoomList(self, username):
		checkData(locals())

		print "\t\t\t\t\t\t\t\tTODO (" + self.__class__.__name__ + ":" + sys._getframe().f_code.co_name + ") : not yet tested"

		user = User(username = username)		
		user.retrieve()

		return user.getRooms()
예제 #15
0
	def getConflictingRules(self, roomName, buildingName, ruleBody):
		checkData(locals())

		ruleBody = ruleBody.strip()

		from app.backend.controller.triggerManager import TriggerManager
		from app.backend.controller.actionManager import ActionManager
		triggerManager = TriggerManager()
		actionManager = ActionManager()

		room = Room(buildingName = buildingName, roomName = roomName)
		room.retrieve()

		ruleList = room.getRules( includeGroupsRules = True,  includeDisabled = False)



		ruleAntecedent = ruleBody.split("then")[0].replace("if", "").strip()
		ruleConsequent = ruleBody.split("then")[1].strip()
		
		newRuleTranslatedTriggers = triggerManager.translateTrigger(ruleAntecedent)
		newRuleAction, originalModel, parameterValues = actionManager.getActionAndTemplateAndParameterValues(ruleConsequent)


		conflictingRuleList = []
		for rule in ruleList:

			currentRuleAction, originalModel, parameterValues = actionManager.getActionAndTemplateAndParameterValues(rule.consequent)
			savedRuleTranslatedTriggers = triggerManager.translateTrigger(rule.antecedent)			

			conflictingAntecedentFound = False
			
			for newRuleTrigger in newRuleTranslatedTriggers["triggers"]:

				for savedRuleTrigger in savedRuleTranslatedTriggers["triggers"]:
					
					if "between" not in newRuleTrigger["antecedent"]:

						if newRuleTrigger["antecedent"] == savedRuleTrigger["antecedent"] and (newRuleAction.category == currentRuleAction.category): 
							conflictingAntecedentFound = True

					else:

						# In the case of range based antecedent I cannot just check if it is equal but I have to see the trigger name
						if newRuleTrigger["trigger"].triggerName == savedRuleTrigger["trigger"].triggerName and (newRuleAction.category == currentRuleAction.category):
							conflictingAntecedentFound = True

					if conflictingAntecedentFound: break
				if conflictingAntecedentFound: break

			if conflictingAntecedentFound:
				conflictingRuleList.append({"ruleId" : rule.id, "ruleBody" : rule.getFullRepresentation()})



		return {"conflictingRules" : conflictingRuleList}
예제 #16
0
	def getAllBuildings(self):
		checkData(locals())

		buildings = Buildings()
		buildingList = []

		for building in buildings.getAllBuildings():
			buildingList.append(building.getDic())

		return {"buildings" : buildingList}
예제 #17
0
	def setRulePriority(self, buildingName, roomName, ruleId, rulePriority):
		checkData(locals())


		from app.backend.model.rule import Rule
		rule = Rule(id = ruleId, buildingName = buildingName, roomName = roomName)
		rule.retrieve()
		rule.setPriority(buildingName = buildingName, roomName = roomName, priority = rulePriority)

		return rule.getDict(buildingName = buildingName, roomName = roomName)
예제 #18
0
	def getRooms(self, groupId, buildingName):
		checkData(locals())

		group = Group(buildingName = buildingName, id = groupId)
		group.retrieve()

		roomList = []
		for room in group.getRooms():
			roomList.append(room.getDict())

		return {"rooms" : roomList}		
예제 #19
0
	def getTriggers(self, buildingName = None, groupId = None):
		checkData(locals())

		from app.backend.model.triggers import Triggers
		triggers = Triggers()

		triggerList = []
		for trigger in triggers.getAllTriggers():
			triggerList.append(trigger.getDict())

		return {"triggers" : triggerList}
예제 #20
0
	def addRoom(self, roomName, buildingName, description):
		checkData(locals())

		
		from app.backend.model.room import Room
		room = Room(roomName = roomName,  buildingName = buildingName, description = description)

		building = Building(buildingName = buildingName)
		building.retrieve()

		return building.addRoom(room).getDict()
예제 #21
0
	def getActions(self, buildingName = None, groupId = None):
		checkData(locals())

		from app.backend.model.actions import Actions
		actions = Actions()

		actionList = []
		for action in actions.getAllActions():
			actionList.append(action.getDict())

		return {"actions" : actionList}
예제 #22
0
	def sendNotificationByEmail(self, recipientUuid, messageSubject, messageText):
		checkData(locals())

		from app.backend.model.user import User
		recipientUser = User(uuid = recipientUuid)
		recipientUser.retrieve()
		
		recipient = recipientUser.email
		subject = "[BuldingRules Notification] " + messageSubject
		message = messageText

		self.__send_message(recipient = recipient, subject = subject, message = message)
예제 #23
0
	def getUnassignedRooms(self, buildingName):
		checkData(locals())

		building = Building(buildingName = buildingName)
		building.retrieve()

		roomList = []

		for room in building.getUnassignedRooms():
			roomList.append(room.getDict())

		return {"rooms" : roomList}
예제 #24
0
	def getTriggerCategories(self):
		checkData(locals())
		
		triggers = Triggers()
		triggerList = triggers.getAllTriggers()

		categories = []
		for trigger in triggerList:
			if trigger.category not in categories:
				categories.append(trigger.category)

		return categories
예제 #25
0
	def __init__(self, buildingName = None, roomName = None, occupancyTimeRangeFrom = None, occupancyTimeRangeTo = None, roomTemperature = None, externalTemperature = None, weather = None, currentDate = None):
		
		checkData(locals())

		self.buildingName = buildingName
		self.roomName = roomName
		self.occupancyTimeRangeFrom = occupancyTimeRangeFrom
		self.occupancyTimeRangeTo = occupancyTimeRangeTo
		self.roomTemperature = roomTemperature
		self.externalTemperature = externalTemperature
		self.weather = weather
		self.currentDate = currentDate
예제 #26
0
	def getRules(self, groupId, buildingName):
		checkData(locals())

		group = Group(buildingName = buildingName, id = groupId)
		group.retrieve()

		ruleList = group.getRules()

		response = []
		for rule in ruleList:
			response.append(rule.getDict())
			
		return {"rules" : response}
예제 #27
0
	def enableRule(self, ruleId, buildingName, roomName, editorUuid):
		checkData(locals())

		room = Room(buildingName = buildingName, roomName = roomName)
		room.retrieve()

		from app.backend.model.rule import Rule
		rule = Rule(id = ruleId)
		rule.retrieve()

		return self.editRule(ruleId = rule.id, priority = rule.getPriority(), buildingName = buildingName,  roomName = roomName, 
					editorUuid = editorUuid, groupId = rule.groupId, ruleBody = None, 
					antecedent = rule.antecedent, consequent = rule.consequent, enabled = True)
예제 #28
0
	def getBuildingList(self, username):
		checkData(locals())

		user = User(username = username)		
		user.retrieve()

		response = []
		buildingList = user.getBuildings()
		for building in buildingList:
			response.append(building.getDict())
			

		return {"buildings" : response}
예제 #29
0
	def checkUserBinding(self, buildingName, username):
		checkData(locals())


		from app.backend.model.user import User

		building = Building(buildingName = buildingName)
		building.retrieve()

		user = User(username = username)
		user.retrieve()

		building.checkUserBinding(user)
예제 #30
0
	def getActionCategories(self):
		checkData(locals())

		
		actions = Actions()
		actionList = actions.getAllActions()

		categories = []
		for action in actionList:
			if action.category not in categories:
				categories.append(action.category)

		return categories