def __init__(self, xplstat_id, key, value, static, sensor_id, ignore_values): self.xplstat_id = xplstat_id self.key = ucode(key) self.value = ucode(value) self.static = static self.sensor_id = sensor_id self.ignore_values = ucode(ignore_values)
def do_action(self): url = self._params['url'] self._log.info(u"Calling url : {0}".format(ucode(url))) try: # encode url url = ucode(url).encode('utf-8') url_elts = urlparse(url) url_args = url_elts.query.split("&") new_url_args = u"" for arg in url_args: if arg != '': tmp = arg.split("=") key = tmp[0] value = "=".join(tmp[1:]) new_url_args += u"{0}={1}&".format(quote(key), quote(value)) new_url = u"{0}://{1}{2}?{3}".format(url_elts.scheme, url_elts.netloc, url_elts.path, new_url_args) if new_url.endswith('?'): new_url = new_url[:-1] # call url self._log.debug(u"Calling url (transformed) : {0}".format(new_url)) html = urlopen(new_url) self._log.info(u"Call url OK") except: self._log.warning( u"Error when calling url from action.CallUrlAction : {0}". format(traceback.format_exc()))
def do_action(self): url = self._params['url'] self._log.info(u"Calling url : {0}".format(ucode(url))) try: # encode url url = ucode(url).encode('utf-8') url_elts = urlparse(url) url_args = url_elts.query.split("&") new_url_args = u"" for arg in url_args: if arg != '': tmp = arg.split("=") key = tmp[0] value = "=".join(tmp[1:]) new_url_args += u"{0}={1}&".format(quote(key), quote(value)) new_url = u"{0}://{1}{2}?{3}".format(url_elts.scheme, url_elts.netloc, url_elts.path, new_url_args) if new_url.endswith('?'): new_url = new_url[:-1] # call url self._log.debug(u"Calling url (transformed) : {0}".format(new_url)) html = urlopen(new_url) self._log.info(u"Call url OK") except: self._log.warning(u"Error when calling url from action.CallUrlAction : {0}".format(traceback.format_exc()))
def __init__(self, name, device_id, cmd_id, json_id, schema, stat_id): self.name = ucode(name) self.device_id = device_id self.cmd_id = cmd_id self.schema = ucode(schema) self.stat_id = stat_id self.json_id = json_id
def __init__(self, id, name, feature_type, device_type_id, value_type, parameters=None, stat_key=None, return_confirmation=False): """Class constructor @param id : device feature id @param name : device feature name (Switch, Dimmer, Thermometer, Voltmeter...) @param feature_type : device feature type (actuator / sensor) @param device_type_id : device type id @param value_type : value type the actuator can accept / the sensor can return @param parameters : parameters about the command or the returned data associated to the device, optional @param stat_key : key reference in the core_device_stats table, optional @param return_confirmation : True if the device returns a confirmation after having executed a command, optional (default False) Only relevant for actuators """ self.id = ucode(id) self.name = ucode(name) if feature_type not in ('actuator', 'sensor'): raise Exception("Feature type must me either 'actuator' or 'sensor' but NOT %s" % feature_type) self.feature_type = feature_type if self.feature_type == 'actuator' and value_type not in ACTUATOR_VALUE_TYPE_LIST: raise Exception("Can't add value type %s to an actuator it doesn't belong to list %s" % (value_type, ACTUATOR_VALUE_TYPE_LIST)) elif self.feature_type == 'sensor' and value_type not in SENSOR_VALUE_TYPE_LIST: raise Exception("Can't add value type %s to a sensor it doesn't belong to list %s" % (value_type, SENSOR_VALUE_TYPE_LIST)) self.device_type_id = device_type_id self.value_type = ucode(value_type) self.parameters = ucode(parameters) self.stat_key = ucode(stat_key) self.return_confirmation = return_confirmation
def __init__( self, device_id, name, reference, incremental, formula, data_type, conversion, h_store, h_max, h_expire, h_round, h_duplicate, timeout, ): self.device_id = device_id self.name = ucode(name) self.reference = ucode(reference) self.incremental = incremental self.formula = ucode(formula) self.data_type = ucode(data_type) self.conversion = ucode(conversion) self.history_store = h_store self.history_max = h_max self.history_expire = h_expire self.history_round = h_round self.history_duplicate = h_duplicate self.timeout = timeout self.value_min = None self.value_max = None
def __init__(self, xplstat_id, key, value, static, sensor_id, ignore_values, type, multiple=None): self.xplstat_id = xplstat_id self.key = ucode(key) self.value = ucode(value) self.static = static self.sensor_id = sensor_id self.ignore_values = ucode(ignore_values) self.type = ucode(type) self.multiple = ucode(multiple)
def __init__(self, device_id, name, reference, data_type, conversion, h_store, h_max, h_expire, h_round): self.device_id = device_id self.name = ucode(name) self.reference = ucode(reference) self.data_type = ucode(data_type) self.conversion = ucode(conversion) self.history_store = h_store self.history_max = h_max self.history_expire = h_expire self.history_round = h_round
def __init__(self, device_id, key, value): """Class constructor @param device_id : The device where this parameter is linked to @param key : The param name @param value : The param value """ self.device_id = device_id self.key = ucode(key) self.value = ucode(value)
def __init__(self, id, name, description=None): """Class constructor @param id : technology id (ie x10, plcbus, eibknx...) with no spaces / accents or special characters @param name : short name of the technology @param description : extended description, optional """ self.id = ucode(id) self.name = ucode(name) self.description = ucode(description)
def __init__(self, id, description=None, version=None): """Class constructor @param id : plugin id (ie x10, plcbus, eibknx...) with no spaces / accents or special characters @param description : extended description, optional @param version : version number, optional """ self.id = ucode(id) self.description = ucode(description) self.version = ucode(version)
def __init__(self, first_name, last_name, birthdate): """Class constructor @param first_name : first name @param last_name : last name @param birthdate : birthdate """ self.first_name = ucode(first_name) self.last_name = ucode(last_name) self.birthdate = birthdate
def __init__(self, name, json, disabled=False, description=None, state=None): self.name = ucode(name) self.json = ucode(json) self.disabled = disabled self.description = description self.state = state
def __init__(self, device_id, key, value, type): """Class constructor @param device_id : The device where this parameter is linked to @param key : The param name @param value : The param value @param type : The type param """ self.device_id = device_id self.key = ucode(key) self.value = ucode(value) self.type = ucode(type)
def __init__(self, id, name, plugin_id, description=None): """Class constructor @paral id : device type id @param name : short name of the type @param description : extended description, optional @param plugin_id : plugin id """ self.id = ucode(id) self.name = ucode(name) self.description = ucode(description) self.plugin_id = ucode(plugin_id)
def __init__(self, id, name, description=None, default_options=None): """Class constructor @param id : usage id @param name : short name of the usage @param description : extended description, optional @param default_options : default options, optional """ self.id = ucode(id) self.name = ucode(name) self.description = ucode(description) self.default_options = ucode(default_options)
def __init__(self, id, hostname, key, value): """Class constructor @param id : plugin id @param hostname : hostname the plugin is installed on @param key : key @param value : value """ self.id = ucode(id) self.hostname = ucode(hostname) self.key = ucode(key) self.value = ucode(value)
def __init__(self, id, name, device_technology_id, description=None): """Class constructor @paral id : device type id @param name : short name of the type @param description : extended description, optional @param device_technology_id : technology id """ self.id = ucode(id) self.name = ucode(name) self.description = ucode(description) self.device_technology_id = ucode(device_technology_id)
def __init__(self, name, reference, device_type_id, description=None): """Class constructor @param name : short name of the device @param address : device address (like 'A3' for x10, or '01.123456789ABC' for 1wire) @param reference : internal reference of the device (like AM12 for a X10 device) @param device_type_id : 'link to the device type (x10.Switch, x10.Dimmer, Computer.WOL...) @param description : extended description, optional """ self.name = ucode(name) self.reference = ucode(reference) self.device_type_id = device_type_id self.description = ucode(description)
def __init__(self, device_id, name, reference, incremental, formula, data_type, conversion, h_store, h_max, h_expire, h_round, h_duplicate): self.device_id = device_id self.name = ucode(name) self.reference = ucode(reference) self.incremental = incremental self.formula = ucode(formula) self.data_type = ucode(data_type) self.conversion = ucode(conversion) self.history_store = h_store self.history_max = h_max self.history_expire = h_expire self.history_round = h_round self.history_duplicate = h_duplicate
def __init__(self, login, password, is_admin, skin_used, person_id): """Class constructor @param login : login @param password : password @param person_id : id of the person associated to this account @param is_admin : True if the user has administrator privileges @param skin_used : skin used in the UI (default value = 'default') """ self.login = ucode(login) self.password = ucode(password) self.person_id = person_id self.is_admin = is_admin self.skin_used = ucode(skin_used)
def __init__(self, login, password, is_admin, skin_used, person_id): """Class constructor @param login : login @param password : password @param person_id : id of the person associated to this account @param is_admin : True if the user has administrator privileges @param skin_used : skin used in the UI (default value = 'default') """ self.login = ucode(login) self.__password = ucode(password) self.person_id = person_id self.is_admin = is_admin self.skin_used = ucode(skin_used)
def _instanciate(self): """ parse the json and load all needed components """ try: self._parsed_condition = self.__parse_part(self._json) # Set the trigger to the last test of each kind of test # Only SensorTest class receive generic_trigger self._log.info(u"Scenario '{0}' : configure the trigger to the last item of each test instance".format(remove_accents(self._name))) for a_kind_of_test in self._test_instances: if a_kind_of_test.startswith("sensor.SensorTest"): self._log.debug(u"Scenario '{0}' : test instance : {1} ({2} items)".format(remove_accents(self._name), a_kind_of_test, len(self._test_instances[a_kind_of_test]))) for idx, val in enumerate(self._test_instances[a_kind_of_test]): if val.__class__.__name__ == 'SensorTest': self._log.debug("Set trigger for item '{0}' to generic_trigger".format(idx)) val.set_trigger(self.generic_trigger) else: self._log.debug("Set trigger for item '{0}' to dummy".format(idx)) val.set_trigger(self._dummy) self._log.debug(u"Scenario '{0}' python generated code : \n{1}".format(remove_accents(self._name), self._parsed_condition)) # this line is to decomment only for debug purpose # it will display the evaluated if conditions # but so, it will evaluate all sensors, so it may trigger some scenarios on startup in double #self._log.debug(u"Now, the python code evaluated is : \n{0}".format(self.__parse_part(self._json, debug = True))) tmp = ast.parse(self._parsed_condition) #self._compiled_condition = compile(tmp, "Scenario {0}".format(remove_accents(self._name)), 'exec') buf = remove_accents(self._name) buf = ucode(buf) self._compiled_condition = compile(tmp, "Scenario {0}".format(buf), 'exec') if len(self._subList) > 0: self._sub = MQAsyncSub.__init__(self, zmq.Context(), 'scenario-sensor', set(self._subList)) except: raise
def do_action(self): self.log.info(u"Command : Do an action...") # live udate some values self.log.debug(u"Command : Preprocessing on parameters...") self.log.debug(u"Command : Parameters before processing : {0}".format(self._params)) params = {} for key in self._params: self._params[key] = ucode(self._params[key]) self.log.debug(u"Command : Preprocess for param : key={0}, typeofvalue={1}, value={2}".format(key, type(self._params[key]), self._params[key])) params[key] = self._params[key] if key == "color" and params[key].startswith("#"): self.log.debug(u"- Processing : for a color, if the color starts with #, remove it") params[key] = params[key][1:] self.log.debug(u"Command : Parameters after processing : {0}".format(params)) self.log.debug(u"Command : Send action command over MQ...") # do the command cli = MQSyncReq(zmq.Context()) msg = MQMessage() msg.set_action('cmd.send') msg.add_data('cmdid', self._cmdId) msg.add_data('cmdparams', params) self.log.debug(u"Command : Command id = '{0}', command params = '{1}'".format(self._cmdId, params)) # do the request res = cli.request('xplgw', msg.get(), timeout=10) if res: data = res.get_data() if not data['status']: self.log.error(u"Command : Command sending to XPL gw failed: {0}".format(res)) else: self.log.error(u"Command : XPL gw did not respond") self.log.debug(u"Command : Action done")
def __init__(self, date, timestamp, skey, device_id, value): """Class constructor @param date : date when the stat was recorded @param timestamp : corresponding timestamp @param skey : key for the stat @param device_id : device id @param value : stat value (numerical or string) """ self.date = date self.timestamp = timestamp self.skey = ucode(skey) try: self.__value_num = float(value) except ValueError: pass self.value = ucode(value) self.device_id = device_id
def __init__(self, login, password, is_admin, skin_used, person_id, lock_edit, lock_delete): """Class constructor @param login : login @param password : password @param person_id : id of the person associated to this account @param is_admin : True if the user has administrator privileges @param skin_used : skin used in the UI (default value = 'default') @param lock_edit: True id the account is locked for editing @param lock_delete: True id the account is locked for deleting """ self.login = ucode(login) self.password = ucode(password) self.person_id = person_id self.is_admin = is_admin self.skin_used = ucode(skin_used) self.lock_edit = lock_edit self.lock_delete = lock_delete
def __init__(self, sensor_id, date, value): self.sensor_id = sensor_id self.date = date try: self.value_num = float(value) except ValueError: pass except TypeError: pass self.value_str = ucode(value)
def __init__(self, name, reference, device_type_id, client_id, client_version, description=None, info_changed=None): """Class constructor @param name : short name of the device @param address : device address (like 'A3' for x10, or '01.123456789ABC' for 1wire) @param reference : internal reference of the device (like AM12 for a X10 device) @param client_id : what plugin controls this device @param device_type_id : 'link to the device type (x10.Switch, x10.Dimmer, Computer.WOL...) @param description : extended description, optional """ self.name = ucode(name) self.reference = ucode(reference) self.device_type_id = ucode(device_type_id) self.client_id = ucode(client_id) self.client_version = ucode(client_version) self.description = ucode(description) self.info_changed = info_changed
def run_chat(self): """ Nestor starts to serve his master over the chat the chat is really usefull for debugging TODO : allow Nestor to connect over irc on demand for test purpose """ # just wait for 2s to have a cleaner output #time.sleep(2) # start serving for an entire life while True: msg = raw_input(u"You > ") # first, let python handle some system messages if msg == '/quit': quit() # then, let Nestor do his work!!! #reply = self.brain.reply(self.user_name, msg) reply = self.process(msg) # let Nestor answer in the chat print(u"{0} > {1}".format(ucode(self.butler_name), ucode(reply)))
def _instanciate(self): """ parse the json and load all needed components """ try: self._parsed_condition = self.__parse_part(self._json) # Set the trigger to the last test of each kind of test # Only SensorTest class receive generic_trigger self._log.info( u"Scenario '{0}' : configure the trigger to the last item of each test instance" .format(remove_accents(self._name))) for a_kind_of_test in self._test_instances: if a_kind_of_test.startswith("sensor.SensorTest"): self._log.debug( u"Scenario '{0}' : test instance : {1} ({2} items)". format(remove_accents(self._name), a_kind_of_test, len(self._test_instances[a_kind_of_test]))) for idx, val in enumerate( self._test_instances[a_kind_of_test]): if val.__class__.__name__ == 'SensorTest': self._log.debug( "Set trigger for item '{0}' to generic_trigger" .format(idx)) val.set_trigger(self.generic_trigger) else: self._log.debug( "Set trigger for item '{0}' to dummy".format( idx)) val.set_trigger(self._dummy) self._log.debug( u"Scenario '{0}' python generated code : \n{1}".format( remove_accents(self._name), self._parsed_condition)) # this line is to decomment only for debug purpose # it will display the evaluated if conditions # but so, it will evaluate all sensors, so it may trigger some scenarios on startup in double #self._log.debug(u"Now, the python code evaluated is : \n{0}".format(self.__parse_part(self._json, debug = True))) tmp = ast.parse(self._parsed_condition) #self._compiled_condition = compile(tmp, "Scenario {0}".format(remove_accents(self._name)), 'exec') buf = remove_accents(self._name) buf = ucode(buf) self._compiled_condition = compile(tmp, "Scenario {0}".format(buf), 'exec') if len(self._subList) > 0: self._sub = MQAsyncSub.__init__(self, zmq.Context(), 'scenario-sensor', set(self._subList)) except: raise
def index(): mqConfig = mqLoader('mq').load()[0] butlerConfig = dict(dmgLoader('butler').load()[1]) qrCode = dict() qrCode["admin_url"] = str(request.url) qrCode["rest_port"] = int(app.port) qrCode["rest_path"] = "/rest" qrCode["rest_auth"] = bool(app.rest_auth) qrCode["mq_ip"] = str(mqConfig['ip']) qrCode["mq_port_pubsub"] = int(mqConfig['sub_port']) qrCode["mq_port_req_rep"] = int(mqConfig['req_rep_port']) qrCode["butler_name"] = ucode(butlerConfig['name']) qrCode["butler_sex"] = str(butlerConfig['sex']) qrCode["butler_lang"] = str(butlerConfig['lang']) return render_template('index.html', qrdata=qrCode)
def __init__(self, log, dbid, name, json, disabled, state, db): """ Create the instance @param log : A logger instance @param dbid : The id of this scenario in the db @param json : The json describing the scenario """ self._name = name # TODO : fix for Russian names for example #self._log = log.getChild(remove_accents(name)) try: self._log = log.getChild( ucode(remove_accents(name)).encode('utf-8')) except UnicodeDecodeError: self._log = log.getChild("SCENARIO") self._log.warning( "The scenario name encountered an unicode error while trying to set the log line header with the scenario name. The scenario name will not be put in the log line. It will be replaced by 'SCENARIO'" ) self._json = json self._disabled = disabled self._state = state self._dbid = dbid self._db = db self._sub = None # If not None, then a asyncSubSCriber self._subList = [ ] # A list that keeps all messages that we need to subScribe to self._test_instances = { } # list of test instances already processes. This is used to avoid triggering N time a scenario if there is N time the same test in it self.zmq = zmq.Context() # datatypes self.datatypes = {} cli = MQSyncReq(self.zmq) msg = MQMessage() msg.set_action('datatype.get') res = cli.request('manager', msg.get(), timeout=10) if res is not None: res = res.get_data() if 'datatypes' in res: self.datatypes = res['datatypes'] self._parsed_condition = None self._compiled_condition = None self._mapping = {'test': {}, 'action': {}} if not self._disabled: self._instanciate()
def index(): mqConfig = mqLoader('mq').load()[0] butlerConfig = dict(dmgLoader('butler').load()[1]) qrCode = dict() qrCode["admin_url"] = str(request.url) qrCode["rest_port"] = int(app.port) qrCode["rest_path"] = "/rest" qrCode["rest_auth"] = bool(app.rest_auth) qrCode["mq_ip"] = str(mqConfig['ip']) qrCode["mq_port_pubsub"] = int( mqConfig['sub_port']) qrCode["mq_port_req_rep"] = int(mqConfig['req_rep_port']) qrCode["butler_name"] = ucode(butlerConfig['name']) qrCode["butler_sex"] = str(butlerConfig['sex']) qrCode["butler_lang"] = str(butlerConfig['lang']) return render_template('index.html', qrdata=qrCode)
def do_action(self): self.log.info(u"Command : Do an action...") # live udate some values self.log.debug(u"Command : Preprocessing on parameters...") self.log.debug(u"Command : Parameters before processing : {0}".format( self._params)) params = {} for key in self._params: self._params[key] = ucode(self._params[key]) self.log.debug( u"Command : Preprocess for param : key={0}, typeofvalue={1}, value={2}" .format(key, type(self._params[key]), self._params[key])) params[key] = self._params[key] if key == "color" and params[key].startswith("#"): self.log.debug( u"- Processing : for a color, if the color starts with #, remove it" ) params[key] = params[key][1:] self.log.debug( u"Command : Parameters after processing : {0}".format(params)) self.log.debug(u"Command : Send action command over MQ...") # do the command cli = MQSyncReq(zmq.Context()) msg = MQMessage() msg.set_action('cmd.send') msg.add_data('cmdid', self._cmdId) msg.add_data('cmdparams', params) self.log.debug( u"Command : Command id = '{0}', command params = '{1}'".format( self._cmdId, params)) # do the request res = cli.request('xplgw', msg.get(), timeout=10) if res: data = res.get_data() if not data['status']: self.log.error( u"Command : Command sending to XPL gw failed: {0}".format( res)) else: self.log.error(u"Command : XPL gw did not respond") self.log.debug(u"Command : Action done")
def __init__(self, log, dbid, name, json, disabled, state, db): """ Create the instance @param log : A logger instance @param dbid : The id of this scenario in the db @param json : The json describing the scenario """ self._name = name # TODO : fix for Russian names for example #self._log = log.getChild(remove_accents(name)) try: self._log = log.getChild(ucode(remove_accents(name)).encode('utf-8')) except UnicodeDecodeError: self._log = log.getChild("SCENARIO") self._log.warning("The scenario name encountered an unicode error while trying to set the log line header with the scenario name. The scenario name will not be put in the log line. It will be replaced by 'SCENARIO'") self._json = json self._disabled = disabled self._state = state self._dbid = dbid self._db = db self._sub = None # If not None, then a asyncSubSCriber self._subList = [] # A list that keeps all messages that we need to subScribe to self._test_instances = {} # list of test instances already processes. This is used to avoid triggering N time a scenario if there is N time the same test in it self.zmq = zmq.Context() # datatypes self.datatypes = {} cli = MQSyncReq(self.zmq) msg = MQMessage() msg.set_action('datatype.get') res = cli.request('manager', msg.get(), timeout=10) if res is not None: res = res.get_data() if 'datatypes' in res: self.datatypes = res['datatypes'] self._parsed_condition = None self._compiled_condition = None self._mapping = { 'test': {}, 'action': {} } if not self._disabled: self._instanciate()
def __init__(self, device_id, name, reference, data_type, conversion): self.device_id = device_id self.name = ucode(name) self.reference = ucode(reference) self.data_type = ucode(data_type) self.conversion = ucode(conversion)
def __init__(self, cmd_id, key, data_type, conversion): self.cmd_id = cmd_id self.key = ucode(key) self.data_type = ucode(data_type) self.conversion = ucode(conversion)
def set_password(self, password): """Set a password for the user""" self.password = ucode(password)
def __init__(self, name, json, disabled=False): self.name = ucode(name) self.json = ucode(json) self.disabled = disabled
def __init__(self, cmd_id, key, value): self.xplcmd_id = cmd_id self.key = ucode(key) self.value = ucode(value)
def __init__(self, device_id, name, schema, json_id): self.device_id = device_id self.name = ucode(name) self.schema = ucode(schema) self.json_id = ucode(json_id)
def __init__(self, device_id, name, reference, return_confirmation): self.device_id = device_id self.name = ucode(name) self.return_confirmation = return_confirmation self.reference = ucode(reference)
def set_password(self, password): """Set a password for the user""" self.__password = ucode(password)
def __init__(self, name, json, disabled=False, description=None): self.name = ucode(name) self.json = ucode(json) self.disabled = disabled self.description = description