示例#1
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")
示例#2
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")
    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()
示例#4
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")
示例#5
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()
示例#6
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()
    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()
示例#8
0
文件: admin.py 项目: Nico0084/domogik
    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())
    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()
示例#10
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())
示例#11
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")
示例#12
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()
示例#13
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()
    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()
示例#15
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 :)")
    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()
示例#17
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")
示例#18
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")
示例#19
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()
示例#20
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()
示例#21
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()
示例#22
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:
            self.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
        self.device_list = {}
        thread_sensors = None
        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_properties = self.get_parameter(a_device, "properties")
            sensor_address = self.get_parameter(a_device, "device")
            self.device_list.update({
                device_id: {
                    'name': device_name,
                    'address': sensor_address,
                    'properties': sensor_properties
                }
            })

            if device_type != "onewire.pio_output_switch":
                sensor_interval = self.get_parameter(a_device, "interval")
                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.debug(u"==> Sensor list of device '{0}': '{1}'".format(device_id, self.sensors[device_id]))
                # Affiche: INFO ==> Sensor list of device id:5: '{u'onewire counter diff': 38, u'onewire counter': 37}'

                if sensor_interval > 0:
                    self.log.debug(u"==> Add '%s' device in reading thread" %
                                   device_name)
                    self.onewire.add_sensor(device_id, device_name,
                                            sensor_address, sensor_properties,
                                            sensor_interval)
                else:
                    self.log.debug(
                        u"==> Reading thread for '%s' device is DISABLED (interval < 0) !"
                        % device_name)

            else:
                self.log.info(
                    u"==> Device '{0}' (id:{1}/{2}), command = {3}/{4}".format(
                        device_name, device_id, device_type, sensor_address,
                        sensor_properties))

        thread_sensors = threading.Thread(
            None, self.onewire.loop_read_sensor, 'Main_reading_sensors',
            (self.send_pub_data, self.get_stop()), {})
        thread_sensors.start()
        self.register_thread(thread_sensors)

        #self.log.info(u"==> Add devices detection test.")
        #self.add_detected_device("onewire.thermometer_temp", "Mon device 1", "ref 1", "descrip 1", 64, "temperature", "28.5C1FD0040000")
        #self.add_detected_device("onewire.counter_count", "Mon device 2", "ref 2", "descrip 2", 64, "counters.A", "1D.61BF0D000000")

        self.ready()
示例#23
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', log_prefix='core_')
        # logging initialization
        self.log.info(u"Admin Server initialisation...")
        self.log.debug(u"locale : {0}".format(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']
                if self.use_ssl.strip() == "True":
                    self.use_ssl = True
                self.key_file = conf_admin['ssl_key']
                self.cert_file = conf_admin['ssl_certificate']
                if 'clean_json' in conf_admin:
                    self.clean_json = conf_admin['clean_json']
                else:
                    self.clean_json = False
                if 'rest_auth' in conf_admin and conf_admin[
                        'rest_auth'] == 'True':
                    self.rest_auth = True
                else:
                    self.rest_auth = 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.error(
                    "Error while reading configuration for section [admin] : using default values instead"
                )
            self.log.info(u"Configuration : interfaces:port = {0}:{1}".format(
                self.interfaces, self.port))
            self.log.info(u"Configuration : use_ssl = {0}".format(
                self.use_ssl))

            # 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"{0}".format(self.get_exception()))
示例#24
0
文件: rest.py 项目: Nico0084/domogik
    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())
示例#25
0
    def __init__(self):
        """ Implements a listener for KNX command messages 
			and launch background listening for KNX events
		"""
        # Declare the plugin name
        Plugin.__init__(self, name='knx')

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

        knx_device = str(self.get_config('knx'))
        knx_cache = self.get_config('knx')
        self.knx_host = self.get_config(
            'host_ip')  #get ip address of the daemon
        self.knx_host_type = self.get_config(
            'host_type')  #get the type of daemon EIBD or KNXTOOL
        self.log.info('Host ip: |%s|' % self.knx_host)
        self.log.info('Host type: |%s|' % self.knx_host_type)
        self.device = self.get_device_list(
            quit_if_no_device=True)  # get all device list

        self.knx = KNX(self.log, self.send_pub_data, self.knx_host,
                       self.knx_host_type)
        try:
            self.log.info("Start listening to KNX")
            self.knx_listen = threading.Thread(None, self.knx.listen,
                                               "listen_knx", (), {})
            self.knx_listen.start()
            self.register_thread(self.knx_listen)
        except KNXException as err:
            self.log.error(err.value)
            self.force_leave()
            return

        for item in self.device:
            self.log.info(item)
            if item["parameters"].get("address_stat", "default") != "default":
                if item["parameters"]["address_stat"]["value"] != "":
                    for sensor in item["sensors"]:
                        sensors_list[item["parameters"]["address_stat"]
                                     ["value"]] = item["sensors"][sensor]["id"]
                        if datapoint_list.get(
                                item["parameters"]["address_stat"]["value"],
                                "Default") == "Default":
                            datapoint_list[item["parameters"]["address_stat"]
                                           ["value"]] = item["parameters"][
                                               "Stat_Datapoint"]["value"]
                        else:
                            if item["parameters"]["address_cmd"]["value"] != "":
                                sensors_list[item["parameters"]["address_cmd"][
                                    "value"]] = item["sensors"]["state"]["id"]

            if item["parameters"].get(
                    "address_cmd",
                    "default") != "default":  # problème si sensor alone
                if item["parameters"]["address_cmd"]["value"] != "":
                    for command in item["commands"]:
                        commands_list[item["commands"][command]["id"]] = item[
                            "parameters"]["address_cmd"]["value"]
                    if datapoint_list.get(
                            item["parameters"]["address_cmd"]["value"],
                            "Default") == "Default":
                        datapoint_list[item["parameters"]["address_cmd"]
                                       ["value"]] = item["parameters"][
                                           "Cmd_Datapoint"]["value"]
                else:
                    self.log.error("No command group for item")

        self.read_sensors()
        self.log.info('Sensor list: %s' % sensors_list)
        self.log.info('Command List: %s' % commands_list)
        self.log.info('Datapoint dict: %s' % datapoint_list)
        self.register_cb_update_devices(self.reload_devices)
        self.log.info("Plugin ready :)")
        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()
示例#27
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()
示例#28
0
    def __init__(self):
        """
            Init plugin
        """
        Plugin.__init__(self, name='withingdevice')

        # 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
        api_key = str(self.get_config('api_key'))
        api_secret = str(self.get_config('api_secret'))
        period = int(self.get_config('period'))

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

        # ### 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 wihting lib
        try:
            self.WITHINGclass = WITHINGclass(self.log,
                                             api_key,
                                             api_secret,
                                             period,
                                             dataPath=pathData)
        except withingException as e:
            self.log.error(e.value)
            self.force_leave()
            return

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

            device_name = a_device["name"]
            device_id = a_device["id"]
            device_type = a_device["device_type_id"]

            user_id = self.get_parameter(a_device, "userid")

            self.device_list.update(
                {device_id: {
                    'name': device_name,
                    'named': user_id
                }})
            self.log.info(u"==> Device '{0}' (id:{1}/{2}), name = {3}".format(
                device_name, device_id, device_type, user_id))
            self.log.debug(u"==> Sensor list of device '{0}': '{1}'".format(
                device_id, self.sensors[device_id]))
            self.WITHINGclass.add_sensor(device_id, device_name, device_type,
                                         user_id)
            self.log.debug(u"==> Launch reading thread for '%s' device !" %
                           device_name)

        thread_sensors = threading.Thread(
            None, self.WITHINGclass.loop_read_sensor, 'Main_reading_sensors',
            (self.send_pub_data, self.send_data, self.get_stop()), {})
        thread_sensors.start()
        self.register_thread(thread_sensors)
        self.ready()
示例#29
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())
示例#30
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()
    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()
示例#32
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()