コード例 #1
0
def module(module_name, module_id, app_id, single_file_module, add_camera):
    """Scafolds a kervi application module """
    template_engine = SuperFormatter()

    cli_path = os.path.dirname(kervi_cli.__file__)
    template_path = os.path.join(cli_path, "templates/")

    module_template = open(template_path + "module_simple_tmpl.py", 'r').read()
    module_config_template = open(template_path + "module_config_tmpl.py",
                                  'r').read()

    module_file_content = template_engine.format(
        module_template,
        id=module_id,
        app_id=app_id,
        name=module_name,
        log=module_id,
        base_port=nethelper.get_free_port([9500, 9510]),
        secret=uuid.uuid4(),
        app_ip=nethelper.get_ip_address(),
        module_ip=nethelper.get_ip_address(),
        modules="""[]""")

    module_config_content = template_engine.format(
        module_config_template,
        id=module_id,
        name=module_name,
        app_id=app_id,
        log=module_id,
        base_port=nethelper.get_free_port([9500, 9510]),
        secret=uuid.uuid4(),
        app_ip=nethelper.get_ip_address(),
        module_ip=nethelper.get_ip_address(),
        modules="""[]""")

    if not os.path.exists(module_id + ".py"):
        module_file = open(module_id + ".py", "w")
        module_file.write(module_file_content)
        module_file.close()

    if not os.path.exists(module_id + ".config.json"):
        module_file = open(module_id + ".config.json", "w")
        module_file.write(module_config_content)
        module_file.close()

    #if not single_file_module:
    #    create_full_layout(template_path)

    #if add_camera:
    #    _create_cam(template_path)

    click.echo('Your module is ready')
    click.echo("start it with python3 " + module_id + ".py")
コード例 #2
0
    def _start(self):
        self.started = True

        if self._as_service:
            import signal
            signal.signal(signal.SIGINT, handler_stop_signals)
            signal.signal(signal.SIGTERM, handler_stop_signals)

        try:
            import dashboards
        except ImportError:
            pass

        #self.spine.run()
        self.spine.send_command("startThreads", local_only=True)
        time.sleep(.5)

        module_port = self.config.network.ipc_module_port
        pluginManager = PluginManager(self.config)
        self._process_info_lock.acquire()
        #self._process_info = [{"id":"IPC", "ready":False}]
        plugin_modules = pluginManager.prepare_load()
        for plugin_module in plugin_modules:
            self._process_info.append({
                "id": plugin_module,
                "ready": False,
                "pid": None
            })
        self._process_info_lock.release()

        module_port = self.config.network.ipc_module_port
        module_port = pluginManager.load_plugins(module_port + 1)

        for module in self.config.modules:
            module_port += 1
            self._process_info_lock.acquire()
            self._process_info += [{"id": module, "ready": False, "pid": None}]
            self._process_info_lock.release()

            self._module_processes += [
                process._start_process("module-" + self.config.module.ip,
                                       module,
                                       self.config,
                                       nethelper.get_free_port([module_port]),
                                       app_helpers._KerviModuleLoader,
                                       process_id=self.config.module.id + "-" +
                                       module)
            ]

        while not self._is_ready():
            time.sleep(1)

        self._logger.info("module connected to application at: %s",
                          self._root_address)
        self._logger.info("Press ctrl + c to stop your module")
        self.spine.trigger_event("moduleReady", self.config.module.id)
        self.spine.send_command("kervi_action_module_main")
コード例 #3
0
ファイル: plugin_manager.py プロジェクト: kervi/kervi
 def _start_plugin_process(self, module_port):
     process._start_process("plugin-" +
                            self._manager._config.application.id + "." +
                            self._plugin_module,
                            "plugin_" + self._plugin_module,
                            self._manager._config,
                            nethelper.get_free_port([module_port]),
                            _KerviPluginProcess,
                            plugin_module=self._plugin_module,
                            plugin_config=self._config,
                            log_queue=self._manager._log_queue,
                            load_silent=self._manager._load_silent)
コード例 #4
0
    def __init__(self, camera_id, name, camera_source=None, **kwargs):
        CameraBase.__init__(self, camera_id, name, type="frame", **kwargs)
        self._device_driver = hal.get_camera_driver(camera_source)

        self._device_driver.camera = self
        self._frame_format = self._device_driver.buffer_type

        protocol = "http://"
        if encryption.enabled():
            protocol = "https://"

        self.ip_address = nethelper.get_ip_address()
        self.ip_port = nethelper.get_free_port()
        self.source = protocol + str(self.ip_address) + ":" + str(
            self.ip_port) + "/" + camera_id  # + ".png"
        self.source = {
            "server":
            protocol + str(self.ip_address) + ":" + str(self.ip_port),
            "path": "/" + camera_id
        }
        self.current_frame = None
        self.current_frame_number = 0

        from threading import Lock
        self.mutex = Lock()

        self.server = _HTTPFrameServer((self.ip_address, self.ip_port),
                                       _HTTPFrameHandler, self, self.mutex)

        if encryption.enabled():
            cert_file, key_file = encryption.get_cert()
            if key_file and cert_file:
                import ssl
                self.server.socket = ssl.wrap_socket(self.server.socket,
                                                     keyfile=key_file,
                                                     certfile=cert_file,
                                                     server_side=True)

        self.server_thread = threading.Thread(target=self.server.serve_forever,
                                              name="CameraStreamer server")
        self.server_thread.daemon = True
        self.server_thread.start()

        self.frame_thread = _CameraFrameThread(self, self.mutex)
コード例 #5
0
def get_default_config():
    return {
        "application": {
            "name": "Kervi",
            "id": "kervi"
        },
        "platform": {
            "driver": "auto"
        },
        "discovery": {
            "enabled": True,
            "challenge": "kervi",
            "port": nethelper.get_free_port([9434, 9435, 9436])
        },
        "log": {
            "levels": ["fatal", "error", "warning", "information", "debug"],
            "level": "verbose",
            "console_level": "verbose",
            "file": "kervi.log",
            "max_file_size": 1000000,
            "resetLog": False
        },
        "modules": [],
        "network": {
            "ip": nethelper.get_ip_address(),
            "http_port": nethelper.get_free_port([80, 8080, 8000]),
            "ws_port": nethelper.get_free_port([9000, 9001, 9002]),
            "ipc_root_port": nethelper.get_free_port([9500]),
            "ipc_root_address": nethelper.get_ip_address()
        },
        "plugin_manager": {
            "plugin_types": {
                "default": {
                    "managed": False,
                    "own_process": True
                },
                "messaging": {
                    "own_process": False,
                    "managed": True
                },
                "ui": {
                    "own_process": True,
                    "managed": False
                },
                "storage": {
                    "own_process": False,
                    "managed": True
                },
                "authentication": {
                    "own_process": False,
                    "managed": True
                },
                "message_bus": {
                    "own_process": False,
                    "managed": True
                },
                "io": {
                    "own_process": True,
                    "managed": False
                }
            }
        },
        "plugins": {
            "kervi.plugin.message_bus.zmq": True,
            "kervi.plugin.io.files": True,
            "kervi.plugin.authentication.plain": False,
            "kervi.plugin.storage.sqlite_temp": True,
            "kervi.plugin.storage.sqlite": True,
            "kervi.plugin.messaging.email": False,
            "kervi.plugin.messaging.user_log": True,
            "kervi.plugin.routing.kervi_io": False,
            "kervi.plugin.ui.web": True,
            "kervi.plugin.ipc.websocket": True
        },
        "plain_users": {
            "anonymous": {
                "enabled": True,
                "groups": []
            },
            "admin": {
                "enabled": True,
                "password": "",
                "groups": ["admin"],
                "name": "Administrator",
                "addresses": {
                    "email": "*****@*****.**",
                    "phone": ""
                }
            }
        },
        "messaging": {
            "default_channels": ["user_log"]
        },
        "encryption": {
            "ipc_secret": "",
            "use_ssl": False,
            "cert_file": "kervi.cert",
            "key_file": "kervi.key"
        },
        "unit_system": "metric",
        "display": {
            "unit_systems": {
                "systems": {
                    "metric": {
                        "length": "m",
                        "temperature": "C",
                        "speed": "m/s",
                        "volumne": "l",
                        "weight": "g",
                        "datetime": {
                            "time": "HH:mm:ss",
                            "date": "dd-MM-yyyy",
                            "datetime": "HH:mm dd-MM-yyyy",
                            "chart": {
                                "millisecond": "h:mm:ss.SSS",
                                "second": "h:mm:ss",
                                "minute": "h:mm",
                                "hour": "h",
                                "day": "MMM D",
                                "week": "ll",
                                "month": "MMM YYYY",
                                "quarter": "[Q]Q - YYYY",
                                "year": "YYYY",
                            }
                        }
                    },
                    "uk-imperial": {
                        "length": "ft",
                        "temperature": "F",
                        "speed": "m/h",
                        "volumne": "gl",
                        "weight": "g",
                        "datetime": {
                            "time": "HH:mm",
                            "date": "DD-MM-YYYY",
                            "datetime": "HH:mm DD-MM-YYYY",
                            "chart": {
                                "millisecond": "h:mm:ss.SSS",
                                "second": "h:mm:ss",
                                "minute": "h:mm",
                                "hour": "h",
                                "day": "MMM D",
                                "week": "ll",
                                "month": "MMM YYYY",
                                "quarter": "[Q]Q - YYYY",
                                "year": "YYYY",
                            }
                        }
                    },
                    "us-imperial": {
                        "length": "ft",
                        "temperature": "F",
                        "speed": "m/h",
                        "volumne": "gl",
                        "weight": "g",
                        "datetime": {
                            "time": "HH:mm",
                            "date": "DD-MM-YYYY",
                            "datetime": "HH:mm DD-MM-YYYY",
                            "chart": {
                                "millisecond": "h:mm:ss.SSS",
                                "second": "h:mm:ss",
                                "minute": "h:mm",
                                "hour": "h",
                                "day": "MMM D",
                                "week": "ll",
                                "month": "MMM YYYY",
                                "quarter": "[Q]Q - YYYY",
                                "year": "YYYY",
                            }
                        }
                    },
                }
            }
        },
        "texts": {
            "messages": {
                "value_plain":
                '''
{source_name} {value} {unit}
{message_type}
{message}
             ''',
                "value_html":
                '''
                <p>
                <b><span style="font-size:80%;color:{message_color}">⬤</span>&nbsp;{source_name}: {value} {unit}</b><br/>
                <span>{message}</span>
                <p>
                ''',
                "action_subject":
                "{action_name} {state}",
                "action_plain":
                '''
Action {action_name} {state}
{message}
                ''',
                "action_html":
                '''
                <span style='font-size:80%;color:{message_color}'>⬤</span>&nbsp;<b>Action {action_name} {state}</b><br/>
                {message}
                '''
            },
            "ui": {
                "kervi": "Kervi",
                "yes": "yes",
                "no": "no",
                "warning": "warning",
                "error": "error",
                "user_name": "User name",
                "password": "******",
                "login_fail": "Login failed invalid user name or password",
                "login": "******",
                "log_on": "Log on",
                "dashboard": "Dashboard",
                "dashboards": "Dashboards",
                "empty_app":
                "No dashboards, sensors, controllers or other components are found in this application!",
                "hello_world": "Hello world",
                "toggle_screen": "Toggle full screen",
                "source": "Source",
                "time": "Time",
                "message": "Message",
                "connecting": "Connecting, please wait",
                "pan": "pan",
                "tilt": "tilt",
                "take_picture": "Take picture",
                "record": "Record video",
                "media_folder": "Media folder"
            }
        },
        "development": {
            "debug_threads": False
        }
    }
コード例 #6
0
    def _start(self):
        self.started = True

        if self._as_service:
            import signal
            signal.signal(signal.SIGINT, handler_stop_signals)
            signal.signal(signal.SIGTERM, handler_stop_signals)

        try:
            import dashboards
        except ImportError:
            pass

        #self.spine.run()
        self.spine.send_command("startThreads", local_only=True)
        time.sleep(.5)

        module_port = self.config.network.ipc_module_port

        for module in self.config.modules:
            module_port += 1
            self._process_info_lock.acquire()
            self._process_info += [{"id":module, "ready":False}]
            self._process_info_lock.release()
                
            self._module_processes += [
                process._start_process(
                    "module-" + self.config.module.ip,
                    module,
                    self.config,
                    nethelper.get_free_port([module_port]),
                    app_helpers._KerviModuleLoader,
                    process_id=self.config.module.id + "-" + module
                )
            ]

        if not self.config.module.app_connection_local and self.config.routing.kervi_io.enabled:
            print("x")
            module_port += 1
            self._process_info_lock.acquire()
            self._process_info = [{"id":"kervi_io", "ready":False}]
            self._process_info_lock.release()

            self._module_processes += [
                process._start_process(
                    "module-routing" + self.config.module.id,
                    "kervi_io",
                    self.config,
                    nethelper.get_free_port([module_port]),
                    app_helpers._KerviIORouterProcess
                )
            ]
            #time.sleep(1)
        while not self._is_ready():
            time.sleep(1)
        
        print("module connected to application at:", self._root_address)
        print("Press ctrl + c to stop your module")
        self.spine.trigger_event(
            "moduleReady",
            self.config.module.id
        )
        self.spine.send_command("kervi_action_module_main")
コード例 #7
0
    def _start(self):
        self.started = True

        try:
            import dashboards
        except ImportError:
            pass

        import kervi.core.utility.process as process
        import kervi.utility.application_helpers as app_helpers

        #if self._as_service:
        signal.signal(signal.SIGINT, handler_stop_signals)
        signal.signal(signal.SIGTERM, handler_stop_signals)

        self.spine.send_command("startThreads", local_only=True)
        time.sleep(.5)
        module_port = self.config.network.ipc_root_port
        pluginManager = PluginManager(self.config, log_queue=self._log_queue)
        self._process_info_lock.acquire()
        plugin_modules = pluginManager.prepare_load()
        for plugin_module in plugin_modules:
            self._process_info.append({
                "id": plugin_module,
                "ready": False,
                "pid": None
            })
        self._process_info_lock.release()

        module_port = pluginManager.load_plugins(module_port + 1)

        for module in self.config.modules:
            self._process_info_lock.acquire()
            self._process_info += [{"id": module, "ready": False, "pid": None}]
            self._process_info_lock.release()

            module_port += 1
            self._module_processes += [
                process._start_process("app-" + self.config.application.id,
                                       module,
                                       self.config,
                                       nethelper.get_free_port([module_port]),
                                       app_helpers._KerviModuleLoader,
                                       log_queue=self._log_queue)
            ]

        #print("wait for ready")
        try:
            while not self.char_list and not self._is_ready():
                #print(self.char_list)
                time.sleep(1)
        except KeyboardInterrupt:
            pass

        #print("pi", self._process_info)

        if not self._in_stop:
            from kervi.dashboards import Dashboard
            Dashboard._add_default()

            self.spine.send_command("kervi_action_app_main")
            ready_message = "Your Kervi application is running"
            self._logger.info(ready_message)

            self._logger.info("Press ctrl + c to stop your application")
            self.spine.trigger_event("appReady", self.config.application.id)

            if self.config.discovery.enabled:
                self._discovery_thread = KerviAppDiscovery(
                    self.config.network.ip,
                    self.config.network.ipc_root_port,
                    self.config.discovery.port,
                    self.config.application.id,
                    self.config.discovery.challenge,
                    self.config.application.name,
                    "http://" + self.config.network.
                    ip  # + ":" + str(self.config.network.http_port)
                )
                self._discovery_thread.start()
            else:
                self._discovery_thread = None
コード例 #8
0
    def __init__(self, user_config=None):
        """ Settings is a dictionary with the following content
        """
        global _console_log

        print("\033[92mStarting kervi application \033[0m")
        import inspect
        import getopt
        self.char_list = []
        self._websocket_event = threading.Event()
        self._in_stop = False
        self._discovery_thread = None
        config_files = []
        self._webserver_info = None
        opts, args = getopt.getopt(sys.argv[1:], "c", [
            "config_file=", "as-service", "install-service",
            "uninstall-service", "start-service", "stop-service",
            "restart-service", "status-service", "detect-devices"
        ])
        for opt, arg in opts:
            if opt in ("-c", "--config_file"):
                if os.path.isfile(arg):
                    config_files += [arg]
                else:
                    print("Specified config file not found:", arg)
        script_path = os.path.abspath(inspect.stack()[1][1])
        script_name = os.path.basename(script_path)
        script_name, script_ext = os.path.splitext(script_name)

        config_files += [script_name + ".config.json"]
        config_files += ["kervi.config.json"]

        selected_config_file = None
        for config_file in config_files:
            if os.path.isfile(config_file):
                selected_config_file = config_file
                break

        from kervi.config import load
        self.config = load(config_file=selected_config_file,
                           config_user=user_config,
                           config_base=get_default_config())

        service_commands = []
        detect_devices = None
        self._as_service = False
        for opt, arg in opts:
            if opt in ("--as-service"):
                self._as_service = True

            if opt in ("--detect-devices"):
                detect_devices = True

            if opt in ("--install-service"):
                service_commands += ["install"]

            if opt in ("--uninstall-service"):
                service_commands += ["uninstall"]

            if opt in ("--start-service"):
                service_commands += ["start"]

            if opt in ("--stop-service"):
                service_commands = ["stop"]

            if opt in ("--restart-service"):
                service_commands = ["restart"]
            if opt in ("--service-status"):
                service_commands = ["status"]

        if service_commands:
            import kervi.hal as hal
            hal_driver = hal._load(self.config.platform.driver)
            if hal_driver:
                hal.service_commands(service_commands,
                                     self.config.application.name,
                                     self.config.application.id, script_path)
            exit()

        if detect_devices:
            import kervi.hal as hal
            hal_driver = hal._load(self.config.platform.driver)
            if hal_driver:
                devices = hal.detect_devices()
                print("devices:")
                _pretty_print(devices)
            exit()
        self._log_handler = KerviLogHandler(self.config)
        self._log_queue = self._log_handler._log_queue
        self._logger = KerviLog("application")
        #self._validateSettings()
        self.started = False
        self._webserver_port = None

        try:
            from kervi.version import VERSION
        except:
            VERSION = "0.0.0"

        self._logger.verbose("kervi version: %s", VERSION)

        import kervi.hal as hal
        hal_driver = hal._load(self.config.platform.driver)
        if hal_driver:
            self._logger.verbose("platform driver: %s", hal_driver)
            self._logger.verbose("board: %s", hal.get_board_name())

        from kervi.plugin.message_bus.bus_manager import BusManager
        self.bus_manager = BusManager(self._log_queue)
        self.config.network.ipc_root_port = nethelper.get_free_port(
            [self.config.network.ipc_root_port])
        self.bus_manager.load("kervi-main", self.config.network.ipc_root_port,
                              None, self.config.network.ipc_root_address)

        from kervi import spine
        self.spine = spine.Spine()
        self.spine.register_query_handler("GetApplicationInfo",
                                          self._get_application_info)
        self.spine.register_query_handler("getProcessInfo",
                                          self.get_process_info)
        self.spine.register_event_handler("modulePing", self._module_ping)
        self.spine.register_event_handler("processReady",
                                          self._process_ready,
                                          scope="app-" +
                                          self.config.application.id)
        self.spine.register_event_handler("WebAppReady",
                                          self._webapp_ready,
                                          scope="app-" +
                                          self.config.application.id)
        self.spine.register_event_handler("websocketReady",
                                          self._websocket_ready,
                                          scope="app-" +
                                          self.config.application.id)
        self._module_processes = []
        self._process_info = []
        self._process_info_lock = threading.Lock()

        self._kervi_modules = []
        self._kervi_modules_lock = threading.Lock()

        from kervi.storage.storage_manager import StorageManager
        self._storage_manager = StorageManager(self._log_queue)

        from kervi.utility.authorization_manager import AuthorizationManager
        self._authorization_manager = AuthorizationManager(self._log_queue)

        from kervi.messaging.message_manager import MessageManager
        self._message_manager = MessageManager(self._log_queue)

        self._app_actions = _AppActions(self)
コード例 #9
0
def application(app_id, app_name, single_file_app, add_camera):
    """Scaffolds a kervi application."""
    #app_id = appid
    #app_name = appname
    #single_file_app = singlefileapp
    #add_camera = addcamera
    template_engine = SuperFormatter()

    cli_path = os.path.dirname(kervi_cli.__file__)
    template_path = os.path.join(cli_path, "templates/")

    if single_file_app:
        if not os.path.exists(app_id + ".py"):
            copyfile(template_path + "app_simple_tmpl.py", app_id + ".py")

        app_config_template = open(template_path + "app_config_tmpl.py",
                                   'r').read()
        app_config_content = template_engine.format(
            app_config_template,
            id=app_id,
            name=app_name,
            log=app_id,
            base_port=nethelper.get_free_port([9500, 9510]),
            websocket_port=nethelper.get_free_port([9000]),
            ui_port=nethelper.get_free_port([80, 8080, 8081]),
            secret=uuid.uuid4(),
            modules="""[]""")

        if not os.path.exists(app_id + ".config.json"):
            app_file = open(app_id + ".config.json", "w")
            app_file.write(app_config_content)
            app_file.close()

    else:
        app_template = open(template_path + "app_tmpl.py", 'r').read()
        app_config_template = open(template_path + "app_config_tmpl.py",
                                   'r').read()

        app_file_content = template_engine.format(
            app_template,
            id=app_id,
            name=app_name,
            log=app_id,
            base_port=nethelper.get_free_port([9500, 9510]),
            websocket_port=nethelper.get_free_port([9000]),
            ui_port=nethelper.get_free_port([80, 8080, 8081]),
            secret=uuid.uuid4(),
            modules="""["sensors", "controllers", "cams"]""")

        app_config_content = template_engine.format(
            app_config_template,
            id=app_id,
            name=app_name,
            log=app_id,
            base_port=nethelper.get_free_port([9500, 9510]),
            websocket_port=nethelper.get_free_port([9000]),
            ui_port=nethelper.get_free_port([80, 8080, 8081]),
            secret=uuid.uuid4(),
            modules="""["sensors", "controllers", "cams"]""")

        if not os.path.exists(app_id + ".py"):
            app_file = open(app_id + ".py", "w")
            app_file.write(app_file_content)
            app_file.close()

        if not os.path.exists(app_id + ".config.json"):
            app_file = open(app_id + ".config.json", "w")
            app_file.write(app_config_content)
            app_file.close()

    if not single_file_app:
        create_full_layout(template_path)

    if add_camera and not single_file_app:
        _create_cam(template_path)

    click.echo('Your app is ready')
    click.echo("start it with 'python " + app_id + ".py'")
コード例 #10
0
ファイル: default_config.py プロジェクト: kervi/kervi
def get_default_config():
    return {
        "application": {
            "id": "kervi"
        },
        "module": {
            "name": "Kervi module",
            "id": "kervi_module",
            "app_connection_local": True
        },
        "discovery": {
            "enabled": True,
            "challenge": "kervi",
            "port": 9434
        },
        "modules": [],
        "network": {
            "ip": nethelper.get_ip_address(),
            "ipc_module_port": nethelper.get_free_port([9800]),
            "ipc_root_port": 9500,
            "ipc_root_address": None
        },
        "encryption": {
            "ipc_secret": "",
        },
        "media": {
            "folders": {
                "images": "images",
                "videos": "videos"
            }
        },
        "display": {
            "unit_systems": {
                "default": "metric",
                "systems": {
                    "metric": {
                        "length": "m",
                        "temperature": "C",
                        "speed": "m/s",
                        "volumne": "l",
                        "weight": "g",
                        "datetime": {
                            "time": "HH:mm",
                            "date": "DD-MM-YYYY",
                            "datetime": "HH:mm DD-MM-YYYY",
                            "chart": {
                                "millisecond": "h:mm:ss.SSS",
                                "second": "h:mm:ss",
                                "minute": "h:mm",
                                "hour": "h",
                                "day": "MMM D",
                                "week": "ll",
                                "month": "MMM YYYY",
                                "quarter": "[Q]Q - YYYY",
                                "year": "YYYY",
                            }
                        }
                    },
                    "uk-imperial": {
                        "length": "ft",
                        "temperature": "F",
                        "speed": "m/h",
                        "volumne": "gl",
                        "weight": "g",
                        "datetime": {
                            "time": "HH:mm",
                            "date": "DD-MM-YYYY",
                            "datetime": "HH:mm DD-MM-YYYY",
                            "chart": {
                                "millisecond": "h:mm:ss.SSS",
                                "second": "h:mm:ss",
                                "minute": "h:mm",
                                "hour": "h",
                                "day": "MMM D",
                                "week": "ll",
                                "month": "MMM YYYY",
                                "quarter": "[Q]Q - YYYY",
                                "year": "YYYY",
                            }
                        }
                    },
                    "us-imperial": {
                        "length": "ft",
                        "temperature": "F",
                        "speed": "m/h",
                        "volumne": "gl",
                        "weight": "g",
                        "datetime": {
                            "time": "HH:mm",
                            "date": "DD-MM-YYYY",
                            "datetime": "HH:mm DD-MM-YYYY",
                            "chart": {
                                "millisecond": "h:mm:ss.SSS",
                                "second": "h:mm:ss",
                                "minute": "h:mm",
                                "hour": "h",
                                "day": "MMM D",
                                "week": "ll",
                                "month": "MMM YYYY",
                                "quarter": "[Q]Q - YYYY",
                                "year": "YYYY",
                            }
                        }
                    },
                }
            }
        },
        "routing": {
            "kervi_io": {
                "enabled": False,
                "address": "127.0.0.1",
                "port": None,
                "api_key": None
            }
        }
    }
コード例 #11
0
    def _start(self):
        self.started = True

        try:
            import dashboards
        except ImportError:
            pass

        import kervi.core.utility.process as process
        import kervi.utility.application_helpers as app_helpers

        if self._as_service:
            signal.signal(signal.SIGINT, handler_stop_signals)
            signal.signal(signal.SIGTERM, handler_stop_signals)

        self.spine.send_command("startThreads", local_only=True)
        time.sleep(.5)
        module_port = self.config.network.ipc_root_port

        self._process_info_lock.acquire()
        self._process_info = [{"id": "IPC", "ready": False}]
        self._process_info_lock.release()

        module_port += 1
        self._module_processes += [
            process._start_process("app-" + self.config.application.id, "IPC",
                                   self.config,
                                   nethelper.get_free_port([module_port]),
                                   app_helpers._KerviSocketIPC)
        ]

        for module in self.config.modules:
            self._process_info_lock.acquire()
            self._process_info += [{"id": module, "ready": False}]
            self._process_info_lock.release()

            module_port += 1
            self._module_processes += [
                process._start_process("app-" + self.config.application.id,
                                       module, self.config,
                                       nethelper.get_free_port([module_port]),
                                       app_helpers._KerviModuleLoader)
            ]

        # if self.config.routing.kervi_io.enabled:
        #     module_port += 1
        #     self._module_processes += [
        #         process._start_process(
        #             "app-" + self.config.application.id,
        #             "kervi_io",
        #             self.config,
        #             nethelper.get_free_port([module_port]),
        #             app_helpers._KerviIORouterProcess
        #         )
        #     ]

        while not self._is_ready():
            time.sleep(1)

        #self._module_processes += app_helpers.load_plugins(self.config, module_port)

        from kervi.dashboards import Dashboard
        Dashboard._add_default()

        import platform
        if platform.system() != "Windows":
            print("\033[92mYour Kervi application is ready at http://" +
                  self.config.network.ip + ":" +
                  str(self.config.network.http_port) + "\033[0m")
        else:
            print("Your Kervi application is ready at http://" +
                  self.config.network.ip + ":" +
                  str(self.config.network.http_port))
        print("Press ctrl + c to stop your application")
        import kervi.ui.webserver as webserver
        webserver.start(self.config.network.ip, self.config.network.http_port,
                        self.config.network.ws_port)
        self.spine.trigger_event("appReady", self.config.application.id)
        self.spine.send_command("startWebSocket")
        self.spine.send_command("kervi_action_app_main")
コード例 #12
0
    def __init__(self, user_config=None):
        """ Settings is a dictionary with the following content
        """

        print("Starting kervi application")
        import inspect
        import getopt

        config_files = []

        opts, args = getopt.getopt(sys.argv[1:], "c", [
            "config_file=", "as-service", "install-service",
            "uninstall-service", "start-service", "stop-service",
            "restart-service", "status-service", "detect-devices"
        ])
        for opt, arg in opts:
            if opt in ("-c", "--config_file"):
                if os.path.isfile(arg):
                    config_files += [arg]
                else:
                    print("Specified config file not found:", arg)
        script_path = os.path.abspath(inspect.stack()[1][1])
        script_name = os.path.basename(script_path)
        script_name, script_ext = os.path.splitext(script_name)

        config_files += [script_name + ".config.json"]
        config_files += ["kervi.config.json"]

        selected_config_file = None
        for config_file in config_files:
            if os.path.isfile(config_file):
                selected_config_file = config_file
                break
        #if not selected_config_file:
        #    print("no config file found , revert to defaults")

        from kervi.config import load
        self.config = load(config_file=selected_config_file,
                           config_user=user_config,
                           config_base=get_default_config())

        service_commands = []
        detect_devices = None
        self._as_service = False
        for opt, arg in opts:
            if opt in ("--as-service"):
                self._as_service = True

            if opt in ("--detect-devices"):
                detect_devices = True

            if opt in ("--install-service"):
                service_commands += ["install"]

            if opt in ("--uninstall-service"):
                service_commands += ["uninstall"]

            if opt in ("--start-service"):
                service_commands += ["start"]

            if opt in ("--stop-service"):
                service_commands = ["stop"]

            if opt in ("--restart-service"):
                service_commands = ["restart"]
            if opt in ("--service-status"):
                service_commands = ["status"]

        if service_commands:
            import kervi.hal as hal
            hal_driver = hal._load(self.config.platform.driver)
            if hal_driver:
                hal.service_commands(service_commands,
                                     self.config.application.name,
                                     self.config.application.id, script_path)
            exit()

        if detect_devices:
            import kervi.hal as hal
            hal_driver = hal._load(self.config.platform.driver)
            if hal_driver:
                devices = hal.detect_devices()
                print("devices:")
                _pretty_print(devices)
            exit()

        #if settings:
        #    self.settings = app_helpers._deep_update(self.settings, settings)
        #self._validateSettings()
        self.started = False
        import kervi.spine as spine
        from kervi.zmq_spine import _ZMQSpine
        self.spine = _ZMQSpine()
        self.config.network.ipc_root_port = nethelper.get_free_port(
            [self.config.network.ipc_root_port])
        self.spine._init_spine("kervi-main", self.config.network.ipc_root_port,
                               None, self.config.network.ipc_root_address)
        spine.set_spine(self.spine)
        #process._start_root_spine(self.config, True, _ZMQSpine)
        #spine._init_spine("application-" + self.settings["info"]["id"])
        self.spine = spine.Spine()
        self.spine.register_query_handler("GetApplicationInfo",
                                          self._get_application_info)
        self.spine.register_query_handler("getProcessInfo",
                                          self.get_process_info)
        self.spine.register_event_handler("modulePing", self._module_ping)
        self.spine.register_event_handler("processReady",
                                          self._process_ready,
                                          scope="app-" +
                                          self.config.application.id)
        self._module_processes = []
        self._process_info = []
        self._process_info_lock = threading.Lock()

        self._kervi_modules = []
        self._kervi_modules_lock = threading.Lock()

        #from kervi.utility.storage import init_db
        #init_db(script_name)
        from kervi.storage.storage_manager import StorageManager
        self._authentication = StorageManager()

        from kervi.utility.authorization_manager import AuthorizationManager
        self._authentication = AuthorizationManager()

        from kervi.messaging.message_manager import MessageManager
        self._message_handler = MessageManager()

        self._app_actions = _AppActions(self)

        import kervi.hal as hal
        hal_driver = hal._load(self.config.platform.driver)
        if hal_driver:
            print("platform driver:", hal_driver)