Esempio n. 1
0
	def makeEvent (self, event, value):
		#payload=('{"event":"SoC Temperature","value":"%s","unit":"°C"}' % (self.getSocTemperature()))
		if event is "motion":
			topic = EventTopics.getBehaviourMotion() + "/" + str(self.getIpAddress())
		else:
			topic = EventTopics.getSensorMeasurementEvent() + "/" + str(self.getIpAddress()) + "/" + event
		timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
		payload = (MQTTPayload.getActuationPayload() %  (str(topic), str(value), str(event), str(self.getIpAddress()), str(timestamp)))
		return topic, payload
Esempio n. 2
0
 def makeEvent(self, event, value):
     #payload=('{"event":"SoC Temperature","value":"%s","unit":"°C"}' % (self.getSocTemperature()))
     if event is "motion":
         topic = EventTopics.getBehaviourMotion() + "/" + str(
             self.getIpAddress())
     else:
         topic = EventTopics.getSensorMeasurementEvent() + "/" + str(
             self.getIpAddress()) + "/" + event
     timestamp = datetime.datetime.fromtimestamp(
         time.time()).strftime('%Y-%m-%d %H:%M:%S')
     payload = (MQTTPayload.getActuationPayload() %
                (str(topic), str(value), str(event), str(
                    self.getIpAddress()), str(timestamp)))
     return topic, payload
Esempio n. 3
0
class DelayTimerActionRule(AbstractActionRule):

	def __init__(self, context, logger, mqttServiceProvider):
		super(DelayTimerActionRule, self).__init__(context, logger, mqttServiceProvider)
		self.isDelayTimerOn = False
		self.DEFAULT_TIMER_IN_MINUTES = 10
		self.defaultTimerInMills = self.toMinutes(self.DEFAULT_TIMER_IN_MINUTES) 
		
	def run (self):
		self.logger.info("DelayTimerActionRule.run(): switching off the applicances")
		isRuleEnabled = True
		try:
			isRuleEnabled = Utilities.to_bool (self.context.getProperty(ConfigurationConstants.getIsRuleEnabled()))
		except ValueError, e:
			self.logger.error("Error on DelayTimerActionRule.run(): %s. Setting True as defalut value for isRuleEnabled" % (e))

		fullActuatorList = self.context.getProperty(ConfigurationConstants.getFullActuatorList())
		if isRuleEnabled and fullActuatorList:
			tokens =  ''.join(fullActuatorList.split()).split(';')
			for tok in tokens:
				if tok:
					eventTopic = self.makeActionEvent(EventTopics.getActuatorAction(), tok, ActuationCommands.getSwitchOff())
					self.publishEvent(eventTopic, tok, ActuationCommands.getSwitchOff(), ActuationCommands.getSwitchOff())
					try:
						time.sleep(0.01)
					except Exception, e:
						self.logger.error("Error on DelayTimerActionRule.run(): %s" % (e))
	def GET(self, *ids, **params):
		result = ""
		if len(ids) > 0:
			param_0 = str(ids[0]).lower()
			if param_0 == "actuate":					
				timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
				payload = (MQTTPayload.getActuationPayload() %  (EventTopics.getSwitchOffAll(), "True", "switchoffall", "no_device", str(timestamp)))		
				self.mqtt.syncPublish(EventTopics.getSwitchOffAll(), payload, 2)
				result += payload

		else:
			self.logger.error("Command not found")
			raise cherrypy.HTTPError("404 Not found", "command not found")

	
		return result	
Esempio n. 5
0
	def sendCommands(self, action):
		fullActuatorList = self.context.getProperty(ConfigurationConstants.getFullActuatorList())
		if fullActuatorList:
			tokens =  ''.join(fullActuatorList.split()).split(';')
			for tok in tokens:
				if tok:
					eventTopic = self.makeActionEvent(EventTopics.getActuatorAction(), tok, action)
					self.publishEvent(eventTopic, tok, action, action)
					try:
						time.sleep(0.01)
					except Exception, e:
						self.logger.error("Error on TimeShiftActionRule.sendCommands(): %s" % (e))
Esempio n. 6
0
class SwitchOffAllActionRule(AbstractActionRule):
    def __init__(self, context, logger, mqttServiceProvider):
        super(SwitchOffAllActionRule, self).__init__(context, logger,
                                                     mqttServiceProvider)

    def process(self):
        self.logger.debug("Processing SwitchOffAllActionRule...")
        isRuleEnabled = True
        presence = False

        try:
            isRuleEnabled = Utilities.to_bool(
                self.context.getProperty(
                    ConfigurationConstants.getIsRuleEnabled()))
        except ValueError, e:
            self.logger.error(
                "Error on SwitchOffAllActionRule.process(): %s. Setting True as default value for isRuleEnabled"
                % (e))

        isTobeOff = self.context.getProperty(
            ConfigurationConstants.getSwitchOffAll())

        if isRuleEnabled and isTobeOff == "True":

            fullActuatorList = self.context.getProperty(
                ConfigurationConstants.getFullActuatorList())
            if fullActuatorList:
                devices = ''.join(fullActuatorList.split()).split(';')
                for dev in devices:
                    if dev:
                        try:
                            eventTopic = self.makeActionEvent(
                                EventTopics.getActuatorAction(), dev,
                                ActuationCommands.getSwitchOff())
                            self.publishEvent(eventTopic, dev,
                                              ActuationCommands.getSwitchOff(),
                                              ActuationCommands.getSwitchOff())
                            self.context.updateProperty(
                                ConfigurationConstants.getSwitchOffAll(),
                                "False")
                        except Exception, e:
                            self.logger.error(
                                "Error on SwitchOffAllActionRule.process(): %s"
                                % (e))
Esempio n. 7
0
	def PUT(self, *ids):
		result = ""
		if len(ids)  > 1:
			param_0 = str(ids[0]).lower()
			param_1 = str(ids[1]).lower()
			if param_0 == "configuration" and param_1 == "updaterule":

				fullpath = os.path.join(os.getcwd(), "../conf/home_structure.json")
				if os.path.exists(fullpath):
					try:
						json_data=open(fullpath).read()
						localHome = json.loads(json_data)

						remoteHomeJson = cherrypy.request.body.read()
						remoteHome = json.loads(remoteHomeJson)

						timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
						for localRule in localHome['rules']:
							for remoteRule in remoteHome['rules']:
								if localRule['ruleSID'] == remoteRule['ruleSID']:
									localRule['isRuleEnabled'] = remoteRule['isRuleEnabled'] 
									topic = EventTopics.getRuleEnabler() + "/" + localRule['ruleSID'] 
									payload = (MQTTPayload.getActuationPayload() %  (str(topic), str(localRule['isRuleEnabled']), EventTopics.getRuleEnabler(), localRule['ruleSID'], str(timestamp)))
									self.mqtt.syncPublish(topic, payload, 2)

						f = open(fullpath,'w')
						string = json.dumps(localHome)
						f.write(string)
						f.close()
					except Exception, e:
						self.logger.error("Unable to update \"home_structure.conf\": %s" % e)
						raise cherrypy.HTTPError("404 Not found", "unable to update \"home_structure.conf\": %s" % e)		

					result += self.getConfiguration()
				else:
					self.logger.error("The file \"home_structure.conf\" is not found in \"conf\" directory")
					raise cherrypy.HTTPError("404 Not found", "the file \"home_structure.conf\" is not found in \"conf\" directory")
			else:
				self.logger.error("Wrongparameters %s. Use /rest/home/configuration/updaterule" % str (ids))
				raise cherrypy.HTTPError("404 Not found", "wrong parameters %s. Use /rest/home/configuration/updaterule" % str (ids))
Esempio n. 8
0
	def mekeTopic(self, device, measureType):
		return EventTopics.getSensorMeasurementEvent() + "/" + str(device) + "/" + str(measureType).lower()
Esempio n. 9
0
 def mekeTopic(self, device, measureType):
     return EventTopics.getSensorMeasurementEvent() + "/" + str(
         device) + "/" + str(measureType).lower()
Esempio n. 10
0
 def publishUnlook(self):
     eventTopic = self.makeActionEvent(EventTopics.getLookAction(),
                                       "alldevices",
                                       ActuationCommands.getLook())
     self.publishEvent(eventTopic, "alldevices",
                       ActuationCommands.getLook(), False)