def __init__(self):
        """
            Init plugin
        """
        Plugin.__init__(self, name='nestdevice')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # ### get all config keys
        product_id = str(self.get_config('product_id'))
        product_secret = str(self.get_config('product_secret'))
        period = int(self.get_config('period'))

        # ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=False)
        self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)
        self.log.info(u"==> sensors:   %s" % format(self.sensors))

        pathData = str(self.get_data_files_directory())  # force str type for path data

        # ### Open the nest lib
        try:
            self.NESTclass = NESTclass(self.log, product_id, product_secret, period, dataPath=pathData)
        except nestException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # ### For each home device
        self.device_list = {}
        thread_sensors = None
        for a_device in self.devices:
            device_name = a_device["name"]
            device_id = a_device["id"]
            device_type = a_device["device_type_id"]
            if device_type == "nest.home":
                sensor_name = self.get_parameter(a_device, "name")
            else:
                sensor_name = self.get_parameter(a_device, "serial")
            self.device_list.update({device_id: {'name': device_name, 'named': sensor_name}})
            self.log.info(u"==> Device '{0}' (id:{1}/{2}), name = {3}".format(device_name, device_id, device_type, sensor_name))
            self.log.debug(u"==> Sensor list of device '{0}': '{1}'".format(device_id, self.sensors[device_id]))

            self.NESTclass.add_sensor(device_id, device_name, sensor_name)

        thread_sensors = threading.Thread(None,
                                          self.NESTclass.loop_read_sensor,
                                          'Main_reading_sensors',
                                          (self.send_pub_data, self.get_stop()),
                                          {})
        thread_sensors.start()
        self.register_thread(thread_sensors)
        self.ready()
Exemplo n.º 2
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='yi')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # get the config
        self.ffserver_ip = self.get_config("ffserver_ip")
        self.ffserver_port = int(self.get_config("ffserver_port"))
        self.motion_files_history = self.get_config("motion_files_history")

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device = True)

        # send sensor values
        self.send_sensor_yi_values()
 
        # generate the ffserver.conf file
        ffserver_file = os.path.join(self.get_data_files_directory(), "ffserver.conf")
        self.yi = Yi(self.log, self.get_stop(), ffserver_file, self.ffserver_ip, self.ffserver_port, self.devices, self.get_parameter)
        self.yi.generate_ffserver_config()

        # start checking for motion (each minute) on all yi
        threads = {}
        for a_device in self.devices:
            ip = self.get_parameter(a_device, "ip")
            do_download = self.get_parameter(a_device, "download_motion_files")
            sensor_motion_id = a_device['sensors']['motion']['id']
            sensor_motion_file_id = a_device['sensors']['motion_file']['id']
            thr_name = "dev_{0}".format(a_device['id'])
            threads[thr_name] = threading.Thread(None,
                                          self.yi.check_motion,
                                          thr_name,
                                          (ip, sensor_motion_id, sensor_motion_file_id, self.send_sensor_value, self.get_publish_files_directory, do_download),
                                          {})
            threads[thr_name].start()
            self.register_thread(threads[thr_name])

        # start the cleaning motion files process
        thr_clean = threading.Thread(None,
                                     self.yi.clean_motion_files,
                                     "clean",
                                     (self.motion_files_history, self.get_publish_files_directory),
                                     {})
        thr_clean.start()
        self.register_thread(thr_clean)

        # start streaming
        thr_stream = threading.Thread(None,
                                     self.yi.ffserver_start,
                                     "stream",
                                     (),
                                     {})
        thr_stream.start()
        self.register_thread(thr_stream)

        self.ready()
Exemplo n.º 3
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ messages data: %s" % format(data))
            # ==> Received 0MQ messages data: {u'command_id': 35, u'value': u'1', u'device_id': 112}
            # ==> Received 0MQ messages data: {u'command_id': 36, u'value': u'128', u'device_id': 113}
            # ==> Received 0MQ messages data: {u'command_id': 37, u'value': u'Bonjour', u'device_id': 114}

            # search for related device
            for a_device in self.devices:
                for a_cmd in a_device['commands']:
                    if data['command_id'] == a_device['commands'][a_cmd]['id']:
                        # As we will just execute a shell script, we can't really known if the command will be ok and how long it will take...
                        # so we respond first on MQ to say we got the request

                        self.log.info("Reply to command 0MQ")
                        reply_msg = MQMessage()
                        reply_msg.set_action('client.cmd.result')
                        reply_msg.add_data('status', True)
                        reply_msg.add_data('reason', '')
                        self.reply(reply_msg.get())

                        # Now, launch the speak action !
                        ip = self.get_parameter(a_device, "ip")
                        lang = 'fr-FR'
                        thr_speak = threading.Thread(None,
                                                     self.yi.speak,
                                                     "speak",
                                                     (ip, lang, data['text'], self.get_data_files_directory),
                                                     {})
                        thr_speak.start()
        self.register_thread(thr_speak)
Exemplo n.º 4
0
    def __init__(self, name, stop_cb = None, is_manager = False, parser = None,
                 daemonize = True, log_prefix = "xplplugin_", test = False, nohub = False):
        '''
        Create XplPlugin instance, which defines system handlers
        @param nohub : if set the hub discovery will be disabled
        '''

        Plugin.__init__(self, name, stop_cb = stop_cb, is_manager = is_manager, parser = parser, daemonize = daemonize, log_prefix = log_prefix, test = test)

        ### start xpl dedicated part

        self.log.info(u"Start of the xPL init")

        # start the xPL manager
        if 'broadcast' in self.config:
            broadcast = self.config['broadcast']
        else:
            broadcast = "255.255.255.255"
        if 'bind_interface' in self.config:
            self.myxpl = Manager(self.config['bind_interface'], broadcast = broadcast, plugin = self, nohub = nohub)
        else:
            self.myxpl = Manager(broadcast = broadcast, plugin = self, nohub = nohub)

        # hbeat not yet called (will be called by the ready() function by a developper plugin)
        self.enable_hbeat_called = False

        self.log.info(u"End of the xPL init")
Exemplo n.º 5
0
    def __init__(self):
        """ Create background RFPlayer manager
        """
        Plugin.__init__(self, name='rfplayer')
        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return
        self.managerRFP = None
        self._ctrlsHBeat = None
        # Get some config value
        try:
            self.pathData = self.get_data_files_directory()
        except:
            self.log.warning('Data directory access error : {0}'.format(
                traceback.format_exc()))
            self.pathData = "{0}/{1}/{2}_{3}/data/".format(
                self.libraries_directory, PACKAGES_DIR, self._type, self._name)

        # Initialize plugin Manager
        try:
            self.managerRFP = RFPManager(self, self.send_sensor)
        except Exception as e:
            raise
            self.log.error('Error on creating RFPManager : {0}'.format(e))
            self.force_leave()
            return
        self.register_cb_update_devices(self.managerRFP.refreshDevices)
        self.add_mq_sub('device.update')
        self.add_mq_sub('device.new')
        self.log.info('****** Init RFPlayer plugin manager completed ******')
        self.ready()
Exemplo n.º 6
0
    def __init__(self, name, stop_cb = None, is_manager = False, parser = None,
                 daemonize = True, log_prefix = "xplplugin_", test = False, nohub = False, source = None):
        '''
        Create XplPlugin instance, which defines system handlers
        @param nohub : if set the hub discovery will be disabled
        @param source : overwrite the source value (client-device.instance)
        '''

        Plugin.__init__(self, name, stop_cb = stop_cb, is_manager = is_manager, parser = parser, daemonize = daemonize, log_prefix = log_prefix, test = test)

        ### start xpl dedicated part

        self.log.info(u"Start of the xPL init")

        # start the xPL manager
        if 'broadcast' in self.config:
            broadcast = self.config['broadcast']
        else:
            broadcast = "255.255.255.255"
        if 'bind_interface' in self.config:
            self.myxpl = Manager(self.config['bind_interface'], broadcast = broadcast, plugin = self, nohub = nohub, source = source)
        else:
            self.myxpl = Manager(broadcast = broadcast, plugin = self, nohub = nohub)

        # hbeat not yet called (will be called by the ready() function by a developper plugin)
        self.enable_hbeat_called = False

        # define the source (in can be used in some plugins)
        if source == None:
            self.source = "{0}-{1}.{2}".format(DMG_VENDOR_ID, self.get_plugin_name(), self.get_sanitized_hostname())
        # in case we overwrite the source : 
            self.source = source
        self.log.info(u"End of the xPL init")
Exemplo n.º 7
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        #self.log.debug(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.debug(u"==> Received 0MQ messages data: %s" %
                           format(data))
            # ==> Received 0MQ messages data: {u'command_id': 35, u'value': u'1', u'device_id': 112}
            # ==> Received 0MQ messages data: {u'command_id': 36, u'value': u'128', u'device_id': 113}
            # ==> Received 0MQ messages data: {u'command_id': 37, u'value': u'Bonjour', u'device_id': 114}

            sensor_id = self.get_related_sensor_id(data['device_id'],
                                                   data['command_id'])
            self.log.debug(u"Storing data for sensor_id = {0} : '{1}'".format(
                sensor_id, data["value"]))
            status, reason = self.send_data(sensor_id, data["value"])

            self.log.info("Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 8
0
    def __init__(self,
                 name,
                 stop_cb=None,
                 is_manager=False,
                 parser=None,
                 daemonize=True,
                 log_prefix="interface_",
                 log_on_stdout=True,
                 test=False,
                 source=None):
        '''
        Create Interface instance, which defines system handlers
        @param source : overwrite the source value (client-device.instance)
        '''

        Plugin.__init__(self,
                        name,
                        type="interface",
                        stop_cb=stop_cb,
                        is_manager=is_manager,
                        parser=parser,
                        daemonize=daemonize,
                        log_prefix=log_prefix,
                        log_on_stdout=log_on_stdout,
                        test=test)

        self.log.info(u"Start of the interface init")
        # define the source (in can be used in some plugins)
        if source == None:
            self.source = "{0}-{1}.{2}".format(INTERFACE_VENDOR_ID,
                                               self.get_plugin_name(),
                                               self.get_sanitized_hostname())
        # in case we overwrite the source :
        else:
            self.source = source

        ### MQ
        self._mq_name = self.source
        #self.zmq = zmq.Context()
        self.mq_pub = MQPub(self.zmq, self._mq_name)
        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.output'])

        ### Context
        # set the context
        # All elements that may be added in the request sent over MQ
        # * media (irc, audio, sms, ...)
        # * text (from voice recognition)
        # * location (the input element location : this is configured on the input element : kitchen, garden, bedroom, ...)
        # * identity (from face recognition)
        # * mood (from kinect or anything else)
        # * sex (from voice recognition and post processing on the voice)
        self.butler_context = {
            "media": None,
            "location": None,
            "identity": None,
            "mood": None,
            "sex": None
        }
        self.log.info(u"End of the interface init")
Exemplo n.º 9
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='body')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        # if not self.check_configured():
        #    return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=True)
        # self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device:
        self.commands = self.get_commands(self.devices)
        self.sensors = self.get_sensors(self.devices)
        self.log.info(u"==> commands:   %s" % format(self.commands))    
        self.log.info(u"==> sensors:   %s" % format(self.sensors))    
        # INFO ==> sensors:   {66: {u'set_weight': 159}}  # {'device id': {'sensor name': 'sensor id'}}

        # for each device ...
        self.body_namelist = {}
        for a_device in self.devices:
            # global device parameters
            device_name = a_device["name"]                    # Ex.: "john"
            device_id = a_device["id"]                        # Ex.: "128"
            device_typeid = a_device["device_type_id"]        # Ex.: "body.body 
            self.log.info(u"==> Device '%s' (id:%s / %s), Sensor: '%s'" % (device_name, device_id, device_typeid, self.sensors[device_id]))
            # INFO ==> Device 'VDevice Binary 1' (id:112 / vdevice.info_binary), Sensor: '{u'get_info_binary': 216}'
            # INFO ==> Device 'VDevice Number 1' (id:113 / vdevice.info_number), Sensor: '{u'get_info_number': 217}'
            # INFO ==> Device 'VDevice String 1' (id:114 / vdevice.info_string), Sensor: '{u'get_info_string': 218}'
            self.body_namelist[device_id] = device_name

        self.ready()
Exemplo n.º 10
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        self.log.info(u"Received 0MQ messages: {0}".format(msg))
        action = msg.get_action().split(".")
        if action[0] == "client" and action[1] == "cmd" :
            # action on dmg device
            data = msg.get_data()
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            idsClient = self.managerClients.getIdsClient(data)
            find = False
            if idsClient != [] :
                for id in idsClient :
                    client = self.managerClients.getClient(id)
                    if client :
                        self.log.debug(u"Handle requested action for Notify client {0} : {1}".format(id, data))
                        commands = client.getDmgCommands()
                        for cmd in commands :
                            if commands[cmd]['id'] == data['command_id'] :
                                find = True
                                client.handle_cmd(data)
                                reply_msg.add_data('status', True)
                                reply_msg.add_data('reason', None)
                                break

            if not find :
                self.log.warning(u"Requested action received for unknown Notify client : {0}".format(data))
                reply_msg.add_data('status', False)
                reply_msg.add_data('reason', u"Requested action received for unknown Notify client : {0}".format(data))
            self.log.debug(u"Reply to MQ: {0}".format(reply_msg.get()))
            self.reply(reply_msg.get())
Exemplo n.º 11
0
    def __init__(self, server_interfaces, server_port):
        """ Initiate DbHelper, Logs and config
            
            Then, start HTTP server and give it initialized data
            @param server_interfaces :  interfaces of HTTP server
            @param server_port :  port of HTTP server
        """

        Plugin.__init__(self, name = 'admin')
        # logging initialization
        self.log.info(u"Admin Server initialisation...")
        self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())

	try:
            try:
                # admin config
                cfg_admin = Loader('admin')
                config_admin = cfg_admin.load()
                conf_admin = dict(config_admin[1])
                self.interfaces = conf_admin['interfaces']
                self.port = conf_admin['port']
                # if use_ssl = True, set here path for ssl certificate/key
                self.use_ssl = conf_admin['use_ssl']
                self.key_file = conf_admin['ssl_certificate']
                self.cert_file = conf_admin['ssl_key']

            except KeyError:
                # default parameters
                self.interfaces = server_interfaces
                self.port = server_port
		self.use_ssl = False
		self.key_file = ""
		self.cert_file = ""
                self.clean_json = False
                self.log.error("Error while reading configuration for section [admin] : using default values instead")
            self.log.info(u"Configuration : interfaces:port = %s:%s" % (self.interfaces, self.port))
	    
	    # get all 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:
                self.datatypes = res.get_data()['datatypes']
            else:
                self.datatypes = {}

 	    # Launch server, stats
            self.log.info(u"Admin Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
	    self.start_http()
            # calls the tornado.ioloop.instance().start()
            
            ### Component is ready
            self.ready(0)
            IOLoop.instance().start()
        except :
            self.log.error(u"%s" % self.get_exception())
Exemplo n.º 12
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='disp32x8')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        # if not self.check_configured():
        #	return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=True)
        # self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device:
        # self.sensors = self.get_sensors(self.devices)
        # self.log.info(u"==> sensors:   %s" % format(self.sensors))
        # INFO ==> sensors:   {66: {u'set_info_number': 159}}  ('device id': 'sensor name': 'sensor id')

        self.osdmsgtype = {
            "scroll": "%\n",
            "left": "@\n",
            "center": "#\n",
            "right": "*\n",
            "beep": "$\n",
            "time": "!\n"
        }

        # for each device ...
        for a_device in self.devices:
            # global device parameters
            device_name = a_device["name"]  # Ex.: ""
            device_id = a_device["id"]  # Ex.: ""
            displayip = self.get_parameter(a_device, "displayip")
            displayport = int(self.get_parameter(a_device, "displayport"))
            tempintsensorid = self.get_parameter(a_device, "tempintsensorid")
            tempextsensorid = self.get_parameter(a_device, "tempextsensorid")
            rainsensorid = self.get_parameter(
                a_device, "rainsensorid")  # id sensor flowHour pluie
            self.log.info(
                u"==> Device '%s' (id:%s), address: %s:%d, sensors id tempint: %d, tempext: %d, rain: %d"
                % (device_name, device_id, displayip, displayport,
                   tempintsensorid, tempextsensorid, rainsensorid))

            self.display = Disp32x8(self.log, self.get_stop(), displayip,
                                    displayport, self.getMQValue)

            threads = {}
            self.log.info(
                u"Start to run Display loop '{0}'".format(device_name))
            thr_name = "dev_{0}".format(device_id)
            threads[thr_name] = threading.Thread(
                None, self.display.run, thr_name,
                (tempintsensorid, tempextsensorid, rainsensorid), {})
            threads[thr_name].start()
            self.register_thread(threads[thr_name])

        self.ready()
Exemplo n.º 13
0
    def __init__(self, server_interfaces, server_port):
        """ Initiate DbHelper, Logs and config
            Then, start HTTP server and give it initialized data
            @param server_interfaces :  interfaces of HTTP server
            @param server_port :  port of HTTP server
        """

        Plugin.__init__(self, name='admin')
        # logging initialization
        self.log.info(u"Admin Server initialisation...")
        self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())

        try:
            try:
                cfg_rest = Loader('admin')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.interfaces = conf_rest['interfaces']
                self.port = conf_rest['port']
                # if rest_use_ssl = True, set here path for ssl certificate/key
                self.use_ssl = conf_rest['use_ssl']
                self.key_file = conf_rest['ssl_certificate']
                self.cert_file = conf_rest['ssl_key']
            except KeyError:
                # default parameters
                self.interfaces = server_interfaces
                self.port = server_port
                self.use_ssl = False
                self.key_file = ""
                self.cert_file = ""
                self.clean_json = False
            self.log.info(u"Configuration : interfaces:port = %s:%s" %
                          (self.interfaces, self.port))

            # get all 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:
                self.datatypes = res.get_data()['datatypes']
            else:
                self.datatypes = {}

# Launch server, stats
            self.log.info(u"Admin Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
            self.start_http()
            # calls the tornado.ioloop.instance().start()

            ### Component is ready
            self.ready(0)
            IOLoop.instance().start()
        except:
            self.log.error(u"%s" % self.get_exception())
Exemplo n.º 14
0
    def __init__(self,
                 name,
                 stop_cb=None,
                 is_manager=False,
                 parser=None,
                 daemonize=True,
                 log_prefix="xplplugin_",
                 log_on_stdout=True,
                 test=False,
                 nohub=False,
                 source=None):
        '''
        Create XplPlugin instance, which defines system handlers
        @param nohub : if set the hub discovery will be disabled
        @param source : overwrite the source value (client-device.instance)
        '''

        Plugin.__init__(self,
                        name,
                        stop_cb=stop_cb,
                        is_manager=is_manager,
                        parser=parser,
                        daemonize=daemonize,
                        log_prefix=log_prefix,
                        log_on_stdout=log_on_stdout,
                        test=test)

        ### start xpl dedicated part

        self.log.info(u"Start of the xPL init")

        # start the xPL manager
        if 'broadcast' in self.config:
            broadcast = self.config['broadcast']
        else:
            broadcast = "255.255.255.255"
        if 'bind_interface' in self.config:
            self.myxpl = Manager(self.config['bind_interface'],
                                 broadcast=broadcast,
                                 plugin=self,
                                 nohub=nohub,
                                 source=source)
        else:
            self.myxpl = Manager(broadcast=broadcast, plugin=self, nohub=nohub)

        # hbeat not yet called (will be called by the ready() function by a developper plugin)
        self.enable_hbeat_called = False

        # define the source (in can be used in some plugins)
        if source == None:
            self.source = "{0}-{1}.{2}".format(DMG_VENDOR_ID,
                                               self.get_plugin_name(),
                                               self.get_sanitized_hostname())
            # in case we overwrite the source :
            self.source = source
        self.log.info(u"End of the xPL init")
Exemplo n.º 15
0
 def __init__(self):
     """ Init plugin
     """
     Plugin.__init__(self, name='hue')
     if not os.path.exists(str(self.get_data_files_directory())):
         self.log.info(u"Directory data not exist, trying create : %s",
                       str(self.get_data_files_directory()))
         try:
             os.mkdir(str(self.get_data_files_directory()))
             self.log.info(u"Hue data directory created : %s" %
                           str(self.get_data_files_directory()))
         except Exception as e:
             self.log.error(e.message)
     if not os.access(str(self.get_data_files_directory()), os.W_OK):
         self.log.error("No write access on data directory : %s" %
                        (str(self.get_data_files_directory())))
     self.devices = self.get_device_list(quit_if_no_device=True)
     self.commands = self.get_commands(self.devices)
     self.sensors = self.get_sensors(self.devices)
     self.ip_bridge = self.get_config("ip_bridge")
     self.log.info(u"==> commands:   %s" % format(self.commands))
     self.log.info(u"==> sensors:   %s" % format(self.sensors))
     try:
         b = Bridge(
             ip=self.ip_bridge,
             config_file_path=
             "/var/lib/domogik/domogik_packages/plugin_hue/data/bridge.config"
         )
         b.connect()
     except:
         self.log.error(traceback.format_exc())
         self.force_leave()
     data = {}
     self.device_list = {}
     huethreads = {}
     for a_device in self.devices:
         device_name = a_device["name"]
         device_id = a_device["id"]
         sensor_address = self.get_parameter(a_device, "Device")
         self.device_list.update(
             {device_id: {
                 'name': device_name,
                 'address': sensor_address
             }})
         thr_name = "dev_{0}".format(a_device['id'])
         huethreads[thr_name] = threading.Thread(
             None, self.get_status, thr_name,
             (self.log, device_id, sensor_address, self.ip_bridge), {})
         self.log.info(u"Starting thread" + thr_name +
                       " with paramerters : device_id=" + str(device_id) +
                       ", sensor_address=" + str(sensor_address) +
                       ", ip_bridge=" + self.ip_bridge)
         huethreads[thr_name].start()
         self.register_thread(huethreads[thr_name])
     self.ready()
Exemplo n.º 16
0
    def force_leave(self, status=False, return_code=None):
        """ Leave threads & timers
        """
        ### Do the xPL related tasks

        # send hbeat.end message
        self._send_hbeat_end()

        ### finally call the function from the Plugin class to do the common things
        # this is called as the end ad the MQ IOLoop is a blocking call
        Plugin.force_leave(self, status, return_code)
Exemplo n.º 17
0
    def force_leave(self, status = False, return_code = None):
        """ Leave threads & timers
        """
        ### Do the xPL related tasks

        # send hbeat.end message
        self._send_hbeat_end()

        ### finally call the function from the Plugin class to do the common things
        # this is called as the end ad the MQ IOLoop is a blocking call
        Plugin.force_leave(self, status, return_code)
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            reason = None
            status = True
            data = msg.get_data()

            device_id = data["device_id"]
            command_id = data["command_id"]
            if device_id not in self.device_list:
                self.log.error(
                    u"### MQ REQ command, Device ID '%s' unknown, Have you restarted the plugin after device creation ?" % device_id)
                status = False
                reason = u"Plugin nestdevice: Unknown device ID %d" % device_id
                self.send_rep_ack(status, reason, command_id, "unknown");
                return

            device_name = self.device_list[device_id]["name"]
            self.log.info(u"==> Received for device '%s' MQ REQ command message: %s" % (device_name, format(data)))
            for a_device in self.devices:
                if a_device["id"] == device_id:
                    if a_device["device_type_id"] == "nest.home":
                        sensor_name = self.get_parameter(a_device, "name")
                        self.log.info(u"==> Received for nest name or serial '%s' MQ REQ command message: %s" % (
                        sensor_name, format(data)))
                        status, reason = self.NESTclass.writeState(sensor_name, "away", data["away"])
                    elif a_device["device_type_id"] == "nest.thermostat":
                        sensor_name = self.get_parameter(a_device, "serial")
                        self.log.info(u"==> Received for nest name or serial '%s' MQ REQ command message: %s" % (
                        sensor_name, format(data)))
                        if "temperature" in data:
			    status, reason = self.NESTclass.writeState(sensor_name, "temperature", data["temperature"])
			elif "mode" in data:
			    status, reason = self.NESTclass.writeState(sensor_name, "mode", data["mode"])
			elif "fan" in data:
			    status, reason = self.NESTclass.writeState(sensor_name, "fan", data["fan"])
			else:
                            self.log.error(u"==> Command not implemented yet")

                        # This should be eaisier but not available
                    #	    sensor_name = self.get_parameter(self.device_list[device_id], "name")
                    #


                    # TODO return status by calling back for good sensors
                    #            if status:
                    #                self.send_pub_data(device_id, format(data))
                    #                self.send_pub_data(device_id, data["away"])

            self.send_rep_ack(status, reason, command_id, device_name);
Exemplo n.º 19
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='mqtt')

        # Check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # Get all config keys
        self.mqtthost = self.get_config("mqtt_host")
        self.mqttport = self.get_config("mqtt_port")
        self.mqttprotocol = self.get_config(
            "mqtt_protocol"
        )  # Old protocol = MQTTv31 (3),  default = MQTTv311 (4)

        # Get the devices list, for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=True)
        # self.log.info(u"==> device:   %s" % format(self.devices))

        # Get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)
        # self.log.info(u"==> sensors:   %s" % format(self.sensors))        # ==> sensors:   {'device id': 'sensor name': 'sensor id'}

        # Init MQTT
        self.mqttClient = MQTT(self.log, self.send_pub_data, self.get_stop(),
                               self.mqtthost, self.mqttport, self.mqttprotocol)

        # Set MQTT devices list
        self.setMqttDevicesList(self.devices)

        # Connect to MQTT server
        try:
            self.mqttClient.connect()
        except MQTTException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # Start mqtt loop
        threads = {}
        thr_name = "mqtt-sub-listen"
        threads[thr_name] = threading.Thread(None, self.mqttClient.mqttloop,
                                             thr_name, (), {})
        threads[thr_name].start()
        self.register_thread(threads[thr_name])

        # Callback for new/update devices
        self.log.info(u"==> Add callback for new/update devices.")
        self.register_cb_update_devices(self.reload_devices)

        self.ready()
Exemplo n.º 20
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='ecocompteur')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=True)
        #self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device :
        # {device_id1 : {"sensor_name1" : sensor_id1,
        #                "sensor_name2" : sensor_id2},
        #  device_id2 : {"sensor_name1" : sensor_id1,
        #                "sensor_name2" : sensor_id2}}
        self.sensors = self.get_sensors(self.devices)

        # create a Ecocompteur for each device
        threads = {}
        ecocompteur_list = {}
        for a_device in self.devices:
            try:
                # global device parameters
                device = self.get_parameter(a_device, "device")
                device_id = a_device["id"]
                interval = self.get_parameter(a_device, "interval")

                ecocompteur_list[device] = Ecocompteur(self.log,
                                                       self.send_data,
                                                       self.get_stop(), device,
                                                       device_id, interval)

                # start the ecocompteur thread
                self.log.info(
                    u"Start monitoring ecocompteur device '{0}'".format(
                        device))
                thr_name = "{0}".format(device)
                threads[thr_name] = threading.Thread(
                    None, ecocompteur_list[device].check, thr_name, (), {})
                threads[thr_name].start()
                self.register_thread(threads[thr_name])
            except:
                self.log.error(u"{0}".format(traceback.format_exc()))
                # we don't quit plugin if an error occured
                # a ecocompteur device can be KO and the others be ok
                #self.force_leave()
                #return
        self.ready()
        self.log.info(u"Plugin ready :)")
Exemplo n.º 21
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='mysensors')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=False)

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)

        self.mysensors_gwdevice = self.get_config("gw_device")

        # Init MySensors Manager
        self.mysensorsmanager = MySensors(self.log, self.send_data,
                                          self.create_device, self.get_stop())

        # Set nodes list
        self.setMySensorsNodesList(self.devices)

        # Open the MySensors serial device
        try:
            self.mysensorsmanager.gwopen(self.mysensors_gwdevice)
        except MySensorsException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        self.log.info(u"==> Launch 'gwListen' thread")
        thr_name = "thr_gwListen"
        self.thread_gwListen = threading.Thread(None,
                                                self.mysensorsmanager.gwListen,
                                                thr_name, (), {})
        self.thread_gwListen.start()
        self.register_thread(self.thread_gwListen)

        self.log.info(u"==> Launch 'parseGwMsg' thread")
        thr_name = "thr_parseGwMsg"
        self.thread_parseGwMsg = threading.Thread(
            None, self.mysensorsmanager.parseGwMsg, thr_name, (), {})
        self.thread_parseGwMsg.start()
        self.register_thread(self.thread_parseGwMsg)

        self.log.info(u"==> Add callback for new or changed devices.")
        self.register_cb_update_devices(self.reload_devices)

        self.ready()
Exemplo n.º 22
0
    def ready(self, ioloopstart=1):
        """ to call at the end of the __init__ of classes that inherits of XplPlugin
        """
        ### First, Do only the xPL related tasks

        # activate xpl hbeat
        if self.enable_hbeat_called == True:
            self.log.error(u"in ready() : enable_hbeat() function already called : the plugin may not be fully converted to the 0.4+ Domogik format")
        else:
            self.enable_hbeat()

        # send the status for the xpl hbeat
        self.myxpl.update_status(2)

        ### finally call the function from the Plugin class to do the common things
        # this is called as the end ad the MQ IOLoop is a blocking call
        Plugin.ready(self, ioloopstart)
Exemplo n.º 23
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        # self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            reason = None
            status = True
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ messages data: %s" % format(data))

            self.log.info(u"Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 24
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        ### NON TESTE !

        Plugin.on_mdp_request(self, msg)
        #self.log.info(u"==> Received MQ message: %s" % format(msg))
        # => MQ Request received : <MQMessage(action=client.cmd, data='{u'state': u'1', u'command_id': 14, u'device_id': 39}')>

        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            #self.log.debug(u"==> Received MQ REQ command message: %s" % format(data))
            # DEBUG ==> Received MQ REQ command message: {u'value': u'1', u'command_id': 50, u'device_id': 139}
            device_id = data["device_id"]
            command_id = data["command_id"]

            # {"44.0": {"name": "Bureau", "dmgid": "120", "vtype": "V_STATUS"}}
            for node in self.mysensorsmanager.nodes:
                if '255' not in node:
                    if nodes[node]['dmgid'] == device_id:
                        nodesensor_name = nodes[node]['name']  # "Relay #1"
                        nodesensor_vtype = nodes[node]['vtype']  # "V_STATUS"
                        break
            if nodesensor_vtype in [
                    "V_STATUS", "V_UP", "V_DOWN", "V_STOP", "V_PERCENTAGE",
                    "V_IR_SEND"
            ]:
                msg = node.replace(
                    ".",
                    ";") + '1;0;' + self.mysensorsmanager.setreqType.index(
                        nodesensor_vtype) + ";" + data["value"] + "\n"
                # msg = "42;0;1;0;2;1\n"      nodeid;childsensorid;set command;no ack;vtype;value\n
                # Command from the controller (1 = SET), Outgoing message to node 42 child sensor 0, Set V_STATUS (2) variable to 1 (turn on). No ack is requested from destination node.
                self.log.info(
                    u"==> Send SET message '%s' for device '%s/%s' (id:%s) to Gateway"
                    % (msg, nodesensor_name, nodesensor_vtype.lower(),
                       device_id))
                self.mysensorsmanager.msgSendQueue.put(msg)

                # Reply MQ REP (acq) to REQ command
                self.send_rep_ack(True, None, command_id, device_name)
            else:
                self.log.error(
                    u"### Node sensor vtype not found for device '%s' (id:%s)"
                    % (nodesensor_name, device_id))
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='vigilightning')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return

        # get plugin parameters and web site source parameters
        self.vigiSource = self.get_config("wssource")
        self.checkTimes = self.get_config(
            "checktimes") * 60.0  # convert in second
        self.CalmMonitoring = self.checkTimes / 2  # X minutes monitoring
        self.OutputMonitoring = self.checkTimes * 1.5  # X minutes monitoring after last strike

        self._lastStrike = {"time": 0.0, "device_id": 0, 'alertLevel': 0}
        self._startCheck = 0.0
        self._EndCheck = 0.0
        self._connexionStatus = "On Wait"
        self._connexionError = u""
        self._msg = "Plugin starting..."

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=False)

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)

        # create a VigiStrike and thread for each device
        self.vigi_Threads = {}
        self.vigi_List = {}
        self._loadDMGDevices()
        self.webSockect = None
        # Callback for new/update devices
        self.log.info(u"==> Add callback for new/update devices.")
        self.register_cb_update_devices(self.reload_devices)
        self._wsServer = None
        # Start websocket service to source web
        ws = threading.Thread(None, self.handle_connexion,
                              "vigilightning-websocket-source", (), {})
        ws.start()
        self.register_thread(ws)
        self.ready()
Exemplo n.º 26
0
    def __init__(self,
                 name,
                 stop_cb=None,
                 is_manager=False,
                 parser=None,
                 daemonize=True,
                 log_prefix="xplplugin_",
                 test=False,
                 nohub=False):
        '''
        Create XplPlugin instance, which defines system handlers
        @param nohub : if set the hub discovery will be disabled
        '''

        Plugin.__init__(self,
                        name,
                        stop_cb=stop_cb,
                        is_manager=is_manager,
                        parser=parser,
                        daemonize=daemonize,
                        log_prefix=log_prefix,
                        test=test)

        ### start xpl dedicated part

        self.log.info(u"Start of the xPL init")

        # start the xPL manager
        if 'broadcast' in self.config:
            broadcast = self.config['broadcast']
        else:
            broadcast = "255.255.255.255"
        if 'bind_interface' in self.config:
            self.myxpl = Manager(self.config['bind_interface'],
                                 broadcast=broadcast,
                                 plugin=self,
                                 nohub=nohub)
        else:
            self.myxpl = Manager(broadcast=broadcast, plugin=self, nohub=nohub)

        # hbeat not yet called (will be called by the ready() function by a developper plugin)
        self.enable_hbeat_called = False

        self.log.info(u"End of the xPL init")
Exemplo n.º 27
0
    def ready(self, ioloopstart=1):
        """ to call at the end of the __init__ of classes that inherits of XplPlugin
        """
        ### First, Do only the xPL related tasks

        # activate xpl hbeat
        if self.enable_hbeat_called == True:
            self.log.error(
                u"in ready() : enable_hbeat() function already called : the plugin may not be fully converted to the 0.4+ Domogik format"
            )
        else:
            self.enable_hbeat()

        # send the status for the xpl hbeat
        self.myxpl.update_status(2)

        ### finally call the function from the Plugin class to do the common things
        # this is called as the end ad the MQ IOLoop is a blocking call
        Plugin.ready(self, ioloopstart)
Exemplo n.º 28
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        # self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ messages data: %s" % format(data))
            # ==> Received 0MQ messages data: {u'command_id': 35, u'value': u'1', u'device_id': 112}
            # ==> Received 0MQ messages data: {u'command_id': 36, u'value': u'128', u'device_id': 113}
            # ==> Received 0MQ messages data: {u'command_id': 37, u'value': u'Bonjour', u'device_id': 114}

            status, reason = self.send_data(data["device_id"], data["value"])

            self.log.info("Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 29
0
    def on_mdp_request(self, msg):
        """ Routine call when a MQ message arrive
		"""
        Plugin.on_mdp_request(self, msg)
        command = ""
        self.log.info("Test: %s" % msg)
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.info(data)
            cmdadr = commands_list[data["command_id"]]
            reason = None
            status = True
            val = data['value']

            self.log.info(datapoint_list)
            command_id = data['device_id']
            datatype = datapoint_list[cmdadr]
            value = encodeKNX(datatype, val)
            data_type = value[0]
            valeur = value[1]

            if data_type == "s":
                command = "groupswrite ip:%s %s %s" % (self.knx_host, cmdadr,
                                                       valeur)
                if self.knx_host_type == "KNXTOOL":
                    command = "knxtool " + command

            if data_type == "l":
                command = "groupwrite ip:%s %s %s" % (self.knx_host, cmdadr,
                                                      valeur)
                if self.knx_host_type == "KNXTOOL":
                    command = "knxtool " + command
            if command != "":
                subp = subprocess.Popen(command, shell=True)
            else:
                self.log.info("erreur command non définir, type cmd= %s" %
                              type_cmd)
                reason = "Command not define"
                status = False

            self.send_rep_ack(status, reason, command_id)
Exemplo n.º 30
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        if msg.get_action() == "client.cmd":
            data = msg.get_data()
            self.log.info(u"==> Received 0MQ message data: %s" % format(data))
            # INFO ==> Received 0MQ message data: {u'message': u'Bonjour', u'command_id': 49, u'position': u'center', u'device_id': 132}
            self.display.osdmsg = data['message'] + self.osdmsgtype[
                data['position']]
            self.log.info(u"==> Message = '%s'" % self.display.osdmsg)

            status = True
            reason = None

            self.log.info("Reply to command 0MQ")
            reply_msg = MQMessage()
            reply_msg.set_action('client.cmd.result')
            reply_msg.add_data('status', status)
            reply_msg.add_data('reason', reason)
            self.reply(reply_msg.get())
Exemplo n.º 31
0
    def __init__(self, name, stop_cb = None, is_manager = False, parser = None,
                 daemonize = True, log_prefix = "interface_", log_on_stdout = True, test = False, source = None):
        '''
        Create Interface instance, which defines system handlers
        @param source : overwrite the source value (client-device.instance)
        '''

        Plugin.__init__(self, name, type = "interface", stop_cb = stop_cb, is_manager = is_manager, parser = parser, daemonize = daemonize, log_prefix = log_prefix, log_on_stdout = log_on_stdout, test = test)

        self.log.info(u"Start of the interface init")
        # define the source (in can be used in some plugins)
        if source == None:
            self.source = "{0}-{1}.{2}".format(INTERFACE_VENDOR_ID, self.get_plugin_name(), self.get_sanitized_hostname())
        # in case we overwrite the source : 
        else:
            self.source = source

        ### MQ
        self._mq_name = self.source
        #self.zmq = zmq.Context()
        self.mq_pub = MQPub(self.zmq, self._mq_name)
        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.output'])

        ### Context
        # set the context
        # All elements that may be added in the request sent over MQ
        # * media (irc, audio, sms, ...)
        # * text (from voice recognition)
        # * location (the input element location : this is configured on the input element : kitchen, garden, bedroom, ...)
        # * identity (from face recognition)
        # * mood (from kinect or anything else) 
        # * sex (from voice recognition and post processing on the voice)
        self.butler_context = {"media" : None,
                               "location" : None,
                               "identity" : None,
                               "mood" : None,
                               "sex" : None
                              }
        self.log.info(u"End of the interface init")
Exemplo n.º 32
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='vigiallergen')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        #if not self.check_configured():
        #    return
        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=True)

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)

        # create a Vigipollens thread for each device
        self.vigiallergensthreads = {}
        self.vigiallergens_list = {}
        self._loadDMGDevices()
        # Callback for new/update devices
        self.log.info(u"==> Add callback for new/update devices.")
        self.register_cb_update_devices(self.reload_devices)
        self.ready()
Exemplo n.º 33
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        # self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            reason = None
            status = True
            data = msg.get_data()

            device_id = data["device_id"]
            command_id = data["command_id"]
            if device_id not in self.mqttdevices_list:
                self.log.error(u"### MQ REQ command, Device ID '%s' unknown" %
                               device_id)
                status = False
                reason = u"Plugin mqtt: Unknown device ID %d" % device_id
                self.send_rep_ack(status, reason, command_id, "unknown")
                # Reply MQ REP (acq) to REQ command
                return

            device_name = self.mqttdevices_list[device_id]["name"]
            self.log.info(
                u"==> Received for device '%s' MQ REQ command message: %s" %
                (device_name, format(data))
            )  # {u'value': u'1', u'command_id': 80, u'device_id': 193}

            status, reason = self.mqttClient.pubcmd(
                self.mqttdevices_list[device_id]["topic"],
                self.mqttdevices_list[device_id]["qos"], data["value"],
                device_id)
            if status:
                self.send_pub_data(device_id,
                                   data["value"])  # Update sensor command.

            # Reply MQ REP (acq) to REQ command
            self.send_rep_ack(status, reason, command_id, device_name)
Exemplo n.º 34
0
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        # self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            reason = None
            status = True
            data = msg.get_data()

            device_id = data["device_id"]
            command_id = data["command_id"]
            if device_id not in self.device_list:
                self.log.error(
                    u"### MQ REQ command, Device ID '%s' unknown, Have you restarted the plugin after device creation ?"
                    % device_id)
                status = False
                reason = u"Plugin onewired: Unknown device ID %d" % device_id
                self.send_rep_ack(status, reason, command_id, "unknown")
                # Reply MQ REP (acq) to REQ command
                return

            device_name = self.device_list[device_id]["name"]
            self.log.info(
                u"==> Received for device '%s' MQ REQ command message: %s" %
                (device_name, format(data))
            )  # {u'command_id': 70, u'value': u'1', u'device_id': 169}

            status, reason = self.onewire.writeSensor(
                self.device_list[device_id]["address"],
                self.device_list[device_id]["properties"], data["value"])
            if status:
                self.send_pub_data(device_id,
                                   data["value"])  # Update sensor command.

            # Reply MQ REP (acq) to REQ command
            self.send_rep_ack(status, reason, command_id, device_name)
Exemplo n.º 35
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='body')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        # if not self.check_configured():
        #    return

        # get the devices list
        self.devices = self.get_device_list(quit_if_no_device=True)
        # self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device:
        self.commands = self.get_commands(self.devices)
        self.sensors = self.get_sensors(self.devices)
        self.log.info(u"==> commands:   %s" % format(self.commands))
        self.log.info(u"==> sensors:   %s" % format(self.sensors))
        # INFO ==> sensors:   {66: {u'set_weight': 159}}  # {'device id': {'sensor name': 'sensor id'}}

        # for each device ...
        self.body_namelist = {}
        for a_device in self.devices:
            # global device parameters
            device_name = a_device["name"]  # Ex.: "john"
            device_id = a_device["id"]  # Ex.: "128"
            device_typeid = a_device["device_type_id"]  # Ex.: "body.body
            self.log.info(u"==> Device '%s' (id:%s / %s), Sensor: '%s'" %
                          (device_name, device_id, device_typeid,
                           self.sensors[device_id]))
            # INFO ==> Device 'VDevice Binary 1' (id:112 / vdevice.info_binary), Sensor: '{u'get_info_binary': 216}'
            # INFO ==> Device 'VDevice Number 1' (id:113 / vdevice.info_number), Sensor: '{u'get_info_number': 217}'
            # INFO ==> Device 'VDevice String 1' (id:114 / vdevice.info_string), Sensor: '{u'get_info_string': 218}'
            self.body_namelist[device_id] = device_name

        self.ready()
Exemplo n.º 36
0
    def __init__(self):
        """ Init plugin
        """
        Plugin.__init__(self, name='notify')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return
        self.managerClients = None
        # get the devices list
        self.refreshDevices()
        # get the config values
        self.managerClients = NotifyClientsManager(self, self.send_sensor)
        for a_device in self.devices :
            try :
                if self.managerClients.addClient(a_device) :
                    self.log.info(u"Ready to work with device {0}".format(getClientId(a_device)))
                else : self.log.info(u"Device parameters not configured, can't create Notify Client : {0}".format(getClientId(a_device)))
            except:
                self.log.error(traceback.format_exc())
        self.add_stop_cb(self.managerClients.stop)
        self.log.info("Plugin ready :)")
        if self.get_config("send_at_start") : self.managerClients.NotifyClientsConnection()
        self.ready()
Exemplo n.º 37
0
    def __init__(self):
        """
            Init plugin
        """
        Plugin.__init__(self, name='onewired')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # ### get all config keys
        onewire_device = str(self.get_config('1-wire_device'))
        onewire_cache = self.get_config('1-wire_cache')


        # ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=True)
        # self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)
        # self.log.info(u"==> sensors:   %s" % format(self.sensors))        # ==> sensors:   {'device id': 'sensor name': 'sensor id'}
        # Affiche: INFO ==> sensors:   {4: {u'1-wire temperature': 36}, 5: {u'1-wire counter diff': 38, u'1-wire counter': 37}}


        # ### Open one wire network
        try:
            onewire = OneWireNetwork(self.log, onewire_device, onewire_cache)
        except OneWireException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return


        # ### For each device
        threads = {}
        for a_device in self.devices:
            # self.log.info(u"a_device:   %s" % format(a_device))

            device_name = a_device["name"]                                            # Ex.: "Temp vesta"
            device_id = a_device["id"]                                                # Ex.: "73"
            device_type = a_device["device_type_id"]                                # Ex.: "onewire.thermometer_temp | onewire.batterymonitor_voltage"
            sensor_interval = self.get_parameter(a_device, "interval")
            sensor_properties = self.get_parameter(a_device, "properties")
            sensor_address = self.get_parameter(a_device, "device")
            if device_type != "onewire.pio_output":
                self.log.info(u"==> Device '{0}' (id:{1}/{2}), sensor = {3}/{4}".format(device_name, device_id, device_type, sensor_address, sensor_properties))
                # Affiche: INFO ==> Device 'TempExt' (id:4/onewire.thermometer_temp), sensor = 28.7079D0040000/temperature
                self.log.info(u"==> Sensor list of device '{0}': '{1}'".format(device_id, self.sensors[device_id]))
                # Affiche: INFO ==> Sensor list of device id:5: '{u'1-wire counter diff': 38, u'1-wire counter': 37}'

                if sensor_interval > 0:
                    self.log.info(u"==> Launch thread for '%s' device !" % device_name)
                    thr_name = "dev_{0}".format(a_device['id'])
                    threads[thr_name] = threading.Thread(None,
                                                            OnewireRead,
                                                            thr_name,
                                                            (self.log,
                                                                onewire,
                                                                device_id,
                                                                device_name,
                                                                sensor_address,
                                                                sensor_properties,
                                                                sensor_interval,
                                                                self.send_data,
                                                                self.get_stop()),
                                                        {})
                    threads[thr_name].start()
                    self.register_thread(threads[thr_name])
                    self.log.info(u"==> Wait some time before running the next scheduled threads ...")
                    time.sleep(5)        # Wait some time to not start the threads with the same interval et the same time.
                else:
                    self.log.info(u"==> Onewire sensor thread '%s' for '%s' device is DISABLED (interval < 0) !" % (thr_name, device_name))

            else:
                pass        # TODO: For ouput => listener !

        self.ready()
Exemplo n.º 38
0
    def __init__(self):
        """
            Init plugin
        """
        Plugin.__init__(self, name='ebusd')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # ### get all config keys
        device = self.get_config("device")

        # ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=False)
        self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)
        self.log.info(u"==> sensors:   %s" % format(self.sensors))

        # ### Open the ebus manager
        try:
            self.ebusdclass = ebusdclass(self.log, device)
        except ebusdException as e:
            self.log.error(e.value)
            self.force_leave()
            return

        # try opening
        try:
            self.ebusdclass.open(device)
        except ebusdException as ex:
            self.log.error(ex.value)
            self.force_leave()
            return

        # ### For each device
        self.device_list = {}
        thread_sensors = None
        for a_device in self.devices:
            device_name = a_device["name"]
            device_id = a_device["id"]
            device_type = a_device["device_type_id"]
            sensor_address = self.get_parameter(a_device, "address")
            self.device_list.update({device_id: {'name': device_name, 'named': sensor_address}})
            self.log.info(
                u"==> Device '{0}' (id:{1}/{2}), name = {3}".format(device_name, device_id, device_type,
                                                                    sensor_address))
            self.log.debug(u"==> Sensor list of device '{0}': '{1}'".format(device_id, self.sensors[device_id]))
            self.ebusdclass.add_sensor(device_id, device_name, device_type, sensor_address)

        thread_sensors = threading.Thread(None,
                                          self.ebusdclass.read_bus_for_sensor,
                                          'Main_reading_sensors',
                                          (self.send_data, self.get_stop()),
                                          {})
        thread_sensors.start()
        self.register_thread(thread_sensors)
        self.ready()
Exemplo n.º 39
0
    def __init__(self, server_interfaces, server_port):
        """ Initiate DbHelper, Logs and config
            Then, start HTTP server and give it initialized data
            @param server_interfaces :  interfaces of HTTP server
            @param server_port :  port of HTTP server
        """

        Plugin.__init__(self, name = 'rest')
        # logging initialization
        self.log.info(u"Rest Server initialisation...")
        self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())

        # API version
        self._rest_api_version = REST_API_VERSION

        try:
            ### Config
            # directory data 
            cfg = Loader('domogik')
            config = cfg.load()
            conf = dict(config[1])
            self.log_dir_path = conf['log_dir_path']

            # plugin installation path
            #self._package_path = conf['package_path']
            #self._src_prefix = None
            #self.log.info(u"Set package path to '%s' " % self._package_path)
            #self._design_dir = "%s/domogik_packages/design/" % self._package_path
            self.package_mode = True
    
            # HTTP server ip and port
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.interfaces = conf_rest['interfaces']
                self.port = conf_rest['port']
                use_ssl = False
                # if rest_use_ssl = True, set here path for ssl certificate/key
                self.use_ssl = conf_rest['use_ssl']
                self.key_file = conf_rest['ssl_certificate']
                self.cert_file = conf_rest['ssl_key']
                if 'clean_json' in conf_rest:
                    self.clean_json = conf_rest['clean_json']
                else:
                    self.clean_json = False
            except KeyError:
                # default parameters
                self.interfaces = server_interfaces
                self.port = server_port
		self.use_ssl = False
		self.key_file = ""
		self.cert_file = ""
                self.clean_json = False
            self.log.info(u"Configuration : interfaces:port = %s:%s" % (self.interfaces, self.port))
    
            # SSL configuration
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.use_ssl = conf_rest['use_ssl']
                if self.use_ssl == "True":
                    self.use_ssl = True
                else:
                    self.use_ssl = False
                self.ssl_certificate = conf_rest['ssl_certificate']
            except KeyError:
                # default parameters
                self.use_ssl = USE_SSL
                self.ssl_certificate = SSL_CERTIFICATE
            if self.use_ssl == True:
                self.log.info(u"Configuration : SSL support activated (certificate : %s)" % self.ssl_certificate)
            else:
                self.log.info(u"Configuration : SSL support not activated")
    
            # File repository
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.repo_dir = conf_rest['repository']
            except KeyError:
                # default parameters
                self.repo_dir = DEFAULT_REPO_DIR

 	    # Launch server, stats
            self.log.info(u"REST Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
            # calls the tornado.ioloop.instance().start()
            self.start_http()
            
            ### Component is ready
            self.ready(0)
            IOLoop.instance().start()
        except :
            self.log.error(u"%s" % self.get_exception())
Exemplo n.º 40
0
    def __init__(self):

        ### Option parser
        parser = ArgumentParser()
        parser.add_argument("-i", 
                          action="store_true", 
                          dest="interactive", 
                          default=False, \
                          help="Butler interactive mode (must be used WITH -f).")

        Plugin.__init__(self, name = 'butler', parser = parser)

        ### MQ
        # MQ publisher
        #self._mq_name = "interface-{0}.{1}".format(self._name, self.get_sanitized_hostname())
        self._mq_name = "butler"
        #self.zmq = zmq.Context()
        self.pub = MQPub(self.zmq, self._mq_name)

        # subscribe the MQ for interfaces inputs
        MQAsyncSub.__init__(self, self.zmq, self._name, ['interface.input'])


        ### Configuration elements
        try:
            cfg = Loader('butler')
            config = cfg.load()
            conf = dict(config[1])

            self.lang = conf['lang']
            self.butler_name = conf['name']
            self.butler_sex = conf['sex']
            self.butler_mood = None
            if self.butler_sex not in SEX_ALLOWED:
                self.log.error(u"Exiting : the butler sex configured is not valid : '{0}'. Expecting : {1}".format(self.butler_sex, SEX_ALLOWED))
                self.force_leave()
                return
       
        except:
            self.log.error(u"Exiting : error while reading the configuration file '{0}' : {1}".format(CONFIG_FILE, traceback.format_exc()))
            self.force_leave()
            return
        # user name (default is 'localuser')
        # this is not used for now on Domogik side
        self.user_name = "localuser"

        ### Prepare the brain
        # - validate packages

        # Start the brain :)
        self.brain = RiveScript(utf8=True)

        # set rivescript variables

        # Configure bot variables
        # all must be lower case....
        self.log.info("Configuring name and sex : {0}, {1}".format(self.butler_name.lower(), self.butler_sex.lower()))
        self.brain.set_variable("name", self.butler_name.lower())
        self.brain.set_variable("fullname", self.butler_name.lower())
        self.brain.set_variable("sex", self.butler_sex.lower())

        # set the PYTHONPATH
        sys.path.append(self.get_libraries_directory())

        # load the brain
        self.brain_content = None
        self.learn_content = None
        self.not_understood_content = None
        self.load_all_brain()

        # shortcut to allow the core brain package to reload the brain for learning
        self.brain.reload_butler = self.reload


        # history
        self.history = []

        print(u"*** Welcome in {0} world, your digital assistant! ***".format(self.butler_name))
        print(u"You may type /quit to let {0} have a break".format(self.butler_name))


        ### Interactive mode
        if self.options.interactive:
            self.log.info(u"Launched in interactive mode : running the chat!")
            # TODO : run as a thread
            #self.run_chat()
            thr_run_chat = Thread(None,
                                  self.run_chat,
                                  "run_chat",
                                  (),
                                  {})
            thr_run_chat.start()
        else:
            self.log.info(u"Not launched in interactive mode")
        

        ### TODO
        #self.add_stop_cb(self.shutdown)

        self.log.info(u"Butler initialized")
        self.ready()
Exemplo n.º 41
0
    def __init__(self, server_interfaces, server_port):
        """ Initiate DbHelper, Logs and config
            Then, start HTTP server and give it initialized data
            @param server_interfaces :  interfaces of HTTP server
            @param server_port :  port of HTTP server
        """

        Plugin.__init__(self, name='rest')
        # logging initialization
        self.log.info(u"Rest Server initialisation...")
        self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())

        # API version
        self._rest_api_version = REST_API_VERSION

        try:
            ### Config
            # directory data
            cfg = Loader('domogik')
            config = cfg.load()
            conf = dict(config[1])
            self.log_dir_path = conf['log_dir_path']

            # plugin installation path
            #self._package_path = conf['package_path']
            #self._src_prefix = None
            #self.log.info(u"Set package path to '%s' " % self._package_path)
            #self._design_dir = "%s/domogik_packages/design/" % self._package_path
            self.package_mode = True

            # HTTP server ip and port
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.interfaces = conf_rest['interfaces']
                self.port = conf_rest['port']
                use_ssl = False
                # if rest_use_ssl = True, set here path for ssl certificate/key
                self.use_ssl = conf_rest['use_ssl']
                self.key_file = conf_rest['ssl_certificate']
                self.cert_file = conf_rest['ssl_key']
                if 'clean_json' in conf_rest:
                    self.clean_json = conf_rest['clean_json']
                else:
                    self.clean_json = False
            except KeyError:
                # default parameters
                self.interfaces = server_interfaces
                self.port = server_port
                self.use_ssl = False
                self.key_file = ""
                self.cert_file = ""
                self.clean_json = False
            self.log.info(u"Configuration : interfaces:port = %s:%s" %
                          (self.interfaces, self.port))

            # SSL configuration
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.use_ssl = conf_rest['use_ssl']
                if self.use_ssl == "True":
                    self.use_ssl = True
                else:
                    self.use_ssl = False
                self.ssl_certificate = conf_rest['ssl_certificate']
            except KeyError:
                # default parameters
                self.use_ssl = USE_SSL
                self.ssl_certificate = SSL_CERTIFICATE
            if self.use_ssl == True:
                self.log.info(
                    u"Configuration : SSL support activated (certificate : %s)"
                    % self.ssl_certificate)
            else:
                self.log.info(u"Configuration : SSL support not activated")

            # File repository
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.repo_dir = conf_rest['repository']
            except KeyError:
                # default parameters
                self.repo_dir = DEFAULT_REPO_DIR

# Launch server, stats
            self.log.info(u"REST Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
            # calls the tornado.ioloop.instance().start()
            self.start_http()

            ### Component is ready
            self.ready(0)
            IOLoop.instance().start()
        except:
            self.log.error(u"%s" % self.get_exception())
Exemplo n.º 42
0
    def __init__(self):

        ### Option parser
        parser = ArgumentParser()
        parser.add_argument("-i",
                          action="store_true",
                          dest="interactive",
                          default=False, \
                          help="Butler interactive mode (must be used WITH -f).")

        Plugin.__init__(self, name='butler', parser=parser, log_prefix='core_')

        ### MQ
        # MQ publisher
        #self._mq_name = "interface-{0}.{1}".format(self._name, self.get_sanitized_hostname())
        self._mq_name = "butler"
        #self.zmq = zmq.Context()
        self.pub = MQPub(self.zmq, self._mq_name)

        # subscribe the MQ for interfaces inputs
        self.add_mq_sub('interface.input')
        # devices updates
        self.add_mq_sub('device.update')

        ### Configuration elements
        try:
            cfg = Loader('butler')
            config = cfg.load()
            conf = dict(config[1])

            self.lang = conf['lang']
            self.butler_name = conf['name']
            self.log.debug(u"The butler configured name is '{0}'".format(
                self.butler_name))
            self.butler_name_cleaned = clean_input(conf['name'])
            self.log.debug(u"The butler cleaned name is '{0}'".format(
                self.butler_name_cleaned))
            self.butler_sex = conf['sex']
            self.butler_mood = None
            if self.butler_sex not in SEX_ALLOWED:
                self.log.error(
                    u"Exiting : the butler sex configured is not valid : '{0}'. Expecting : {1}"
                    .format(self.butler_sex, SEX_ALLOWED))
                self.force_leave()
                return

        except:
            self.log.error(
                u"Exiting : error while reading the configuration file '{0}' : {1}"
                .format(CONFIG_FILE, traceback.format_exc()))
            self.force_leave()
            return
        # user name (default is 'localuser')
        # this is not used for now on Domogik side
        self.user_name = "localuser"

        ### Prepare the brain
        # - validate packages

        # Start the brain :)
        self.brain = RiveScript(utf8=True)

        # set rivescript variables

        # Configure bot variables
        # all must be lower case....
        self.log.info(u"Configuring name and sex : {0}, {1}".format(
            self.butler_name_cleaned.lower(), self.butler_sex.lower()))
        self.brain.set_variable(u"name", self.butler_name_cleaned.lower())
        self.brain.set_variable(u"fullname", self.butler_name.lower())
        self.brain.set_variable(u"sex", self.butler_sex.lower())

        # set the PYTHONPATH
        sys.path.append(self.get_libraries_directory())

        # load the brain
        self.brain_content = None
        self.learn_content = None
        self.not_understood_content = None
        self.load_all_brain()

        # shortcut to allow the core brain package to reload the brain for learning
        self.brain.reload_butler = self.reload

        # shortcut to allow the core brain package to do logging and access the devices in memory
        self.brain.log = self.log
        self.brain.devices = []  # will be loaded in self.reload_devices()

        # history
        self.history = []

        # load all known devices
        self.reload_devices()

        self.log.info(
            u"*** Welcome in {0} world, your digital assistant! ***".format(
                self.butler_name))

        # for chat more only
        #self.log.info(u"You may type /quit to let {0} have a break".format(self.butler_name))

        ### Interactive mode
        if self.options.interactive:
            self.log.info(u"Launched in interactive mode : running the chat!")
            # TODO : run as a thread
            #self.run_chat()
            thr_run_chat = Thread(None, self.run_chat, "run_chat", (), {})
            thr_run_chat.start()
        else:
            self.log.info(u"Not launched in interactive mode")

        ### TODO
        #self.add_stop_cb(self.shutdown)

        self.log.info(u"Butler initialized")
        self.ready()
    def __init__(self):
        """
            Init plugin
        """
        Plugin.__init__(self, name='nestdevice')

        # check if the plugin is configured. If not, this will stop the plugin and log an error
        if not self.check_configured():
            return

        # ### get all config keys
        product_id = str(self.get_config('product_id'))
        product_secret = str(self.get_config('product_secret'))
        period = int(self.get_config('period'))

        # ### get the devices list
        # for this plugin, if no devices are created we won't be able to use devices.
        self.devices = self.get_device_list(quit_if_no_device=False)
        self.log.info(u"==> device:   %s" % format(self.devices))

        # get the sensors id per device :
        self.sensors = self.get_sensors(self.devices)
        self.log.info(u"==> sensors:   %s" % format(self.sensors))

        pathData = str(
            self.get_data_files_directory())  # force str type for path data

        # ### Open the nest lib
        try:
            self.NESTclass = NESTclass(self.log,
                                       product_id,
                                       product_secret,
                                       period,
                                       dataPath=pathData)
        except nestException as e:
            self.log.error(e.value)
            print(e.value)
            self.force_leave()
            return

        # ### For each home device
        self.device_list = {}
        thread_sensors = None
        for a_device in self.devices:
            device_name = a_device["name"]
            device_id = a_device["id"]
            device_type = a_device["device_type_id"]
            if device_type == "nest.home":
                sensor_name = self.get_parameter(a_device, "name")
            else:
                sensor_name = self.get_parameter(a_device, "serial")
            self.device_list.update(
                {device_id: {
                    'name': device_name,
                    'named': sensor_name
                }})
            self.log.info(u"==> Device '{0}' (id:{1}/{2}), name = {3}".format(
                device_name, device_id, device_type, sensor_name))
            self.log.debug(u"==> Sensor list of device '{0}': '{1}'".format(
                device_id, self.sensors[device_id]))

            self.NESTclass.add_sensor(device_id, device_name, sensor_name)

        thread_sensors = threading.Thread(
            None, self.NESTclass.loop_read_sensor, 'Main_reading_sensors',
            (self.send_pub_data, self.get_stop()), {})
        thread_sensors.start()
        self.register_thread(thread_sensors)
        self.ready()
    def on_mdp_request(self, msg):
        """ Called when a MQ req/rep message is received
        """
        Plugin.on_mdp_request(self, msg)
        self.log.info(u"==> Received 0MQ messages: %s" % format(msg))
        if msg.get_action() == "client.cmd":
            reason = None
            status = True
            data = msg.get_data()

            device_id = data["device_id"]
            command_id = data["command_id"]
            if device_id not in self.device_list:
                self.log.error(
                    u"### MQ REQ command, Device ID '%s' unknown, Have you restarted the plugin after device creation ?"
                    % device_id)
                status = False
                reason = u"Plugin nestdevice: Unknown device ID %d" % device_id
                self.send_rep_ack(status, reason, command_id, "unknown")
                return

            device_name = self.device_list[device_id]["name"]
            self.log.info(
                u"==> Received for device '%s' MQ REQ command message: %s" %
                (device_name, format(data)))
            for a_device in self.devices:
                if a_device["id"] == device_id:
                    if a_device["device_type_id"] == "nest.home":
                        sensor_name = self.get_parameter(a_device, "name")
                        self.log.info(
                            u"==> Received for nest name or serial '%s' MQ REQ command message: %s"
                            % (sensor_name, format(data)))
                        status, reason = self.NESTclass.writeState(
                            sensor_name, "away", data["away"])
                    elif a_device["device_type_id"] == "nest.thermostat":
                        sensor_name = self.get_parameter(a_device, "serial")
                        self.log.info(
                            u"==> Received for nest name or serial '%s' MQ REQ command message: %s"
                            % (sensor_name, format(data)))
                        if "temperature" in data:
                            status, reason = self.NESTclass.writeState(
                                sensor_name, "temperature",
                                data["temperature"])
                        elif "mode" in data:
                            status, reason = self.NESTclass.writeState(
                                sensor_name, "mode", data["mode"])
                        elif "fan" in data:
                            status, reason = self.NESTclass.writeState(
                                sensor_name, "fan", data["fan"])
                        else:
                            self.log.error(u"==> Command not implemented yet")

                        # This should be eaisier but not available
                    #	    sensor_name = self.get_parameter(self.device_list[device_id], "name")
                    #

                    # TODO return status by calling back for good sensors
                    #            if status:
                    #                self.send_pub_data(device_id, format(data))
                    #                self.send_pub_data(device_id, data["away"])

            self.send_rep_ack(status, reason, command_id, device_name)