Ejemplo n.º 1
0
def write_platformio_project():
    mkdir_p(CORE.build_path)

    content = get_ini_content()
    if not get_bool_env(ENV_NOGITIGNORE):
        write_gitignore()
    write_platformio_ini(content)
Ejemplo n.º 2
0
def test_get_bool_env(monkeypatch, var, value, default, expected):
    if value is None:
        monkeypatch.delenv(var, raising=False)
    else:
        monkeypatch.setenv(var, value)

    actual = helpers.get_bool_env(var, default)

    assert actual == expected
Ejemplo n.º 3
0
def template_args():
    version = const.__version__
    return {
        'version': version,
        'docs_link': 'https://beta.esphome.io/'
        if 'b' in version else 'https://esphome.io/',
        'get_static_file_url': get_static_file_url,
        'relative_url': RELATIVE_URL,
        'streamer_mode': get_bool_env('ESPHOME_STREAMER_MODE'),
    }
Ejemplo n.º 4
0
def template_args():
    version = const.__version__
    if "b" in version:
        docs_link = "https://beta.esphome.io/"
    elif "dev" in version:
        docs_link = "https://next.esphome.io/"
    else:
        docs_link = "https://www.esphome.io/"
    return {
        "version": version,
        "docs_link": docs_link,
        "get_static_file_url": get_static_file_url,
        "relative_url": settings.relative_url,
        "streamer_mode": get_bool_env("ESPHOME_STREAMER_MODE"),
        "config_dir": settings.config_dir,
    }
Ejemplo n.º 5
0
def template_args():
    version = const.__version__
    if 'b' in version:
        docs_link = 'https://beta.esphome.io/'
    elif 'dev' in version:
        docs_link = 'https://next.esphome.io/'
    else:
        docs_link = 'https://www.esphome.io/'
    return {
        'version': version,
        'docs_link': docs_link,
        'get_static_file_url': get_static_file_url,
        'relative_url': settings.relative_url,
        'streamer_mode': get_bool_env('ESPHOME_STREAMER_MODE'),
        'config_dir': settings.config_dir,
    }
Ejemplo n.º 6
0
def start_web_server(args):
    global CONFIG_DIR
    global PASSWORD_DIGEST
    global USING_PASSWORD
    global ON_HASSIO
    global USING_HASSIO_AUTH
    global COOKIE_SECRET

    CONFIG_DIR = args.configuration
    mkdir_p(CONFIG_DIR)
    mkdir_p(os.path.join(CONFIG_DIR, ".esphome"))

    ON_HASSIO = args.hassio
    if ON_HASSIO:
        USING_HASSIO_AUTH = not get_bool_env('DISABLE_HA_AUTHENTICATION')
        USING_PASSWORD = False
    else:
        USING_HASSIO_AUTH = False
        USING_PASSWORD = args.password

    if USING_PASSWORD:
        if IS_PY2:
            PASSWORD_DIGEST = hmac.new(args.password).digest()
        else:
            PASSWORD_DIGEST = hmac.new(args.password.encode()).digest()

    if USING_HASSIO_AUTH or USING_PASSWORD:
        path = esphome_storage_path(CONFIG_DIR)
        storage = EsphomeStorageJSON.load(path)
        if storage is None:
            storage = EsphomeStorageJSON.get_default()
            storage.save(path)
        COOKIE_SECRET = storage.cookie_secret

    app = make_app(args.verbose)
    if args.socket is not None:
        _LOGGER.info(
            "Starting dashboard web server on unix socket %s and configuration dir %s...",
            args.socket, CONFIG_DIR)
        server = tornado.httpserver.HTTPServer(app)
        socket = tornado.netutil.bind_unix_socket(args.socket, mode=0o666)
        server.add_socket(socket)
    else:
        _LOGGER.info(
            "Starting dashboard web server on port %s and configuration dir %s...",
            args.port, CONFIG_DIR)
        app.listen(args.port)

        if args.open_ui:
            import webbrowser

            webbrowser.open('localhost:{}'.format(args.port))

    if STATUS_USE_PING:
        status_thread = PingStatusThread()
    else:
        status_thread = MDNSStatusThread()
    status_thread.start()
    try:
        tornado.ioloop.IOLoop.current().start()
    except KeyboardInterrupt:
        _LOGGER.info("Shutting down...")
        STOP_EVENT.set()
        PING_REQUEST.set()
        status_thread.join()
        if args.socket is not None:
            os.remove(args.socket)
Ejemplo n.º 7
0
# pylint: disable=unused-import, wrong-import-order
from typing import Optional  # noqa

from esphome.zeroconf import DashboardStatus, Zeroconf

_LOGGER = logging.getLogger(__name__)
CONFIG_DIR = ''
PASSWORD_DIGEST = ''
COOKIE_SECRET = None
USING_PASSWORD = False
ON_HASSIO = False
USING_HASSIO_AUTH = True
HASSIO_MQTT_CONFIG = None
RELATIVE_URL = os.getenv('ESPHOME_DASHBOARD_RELATIVE_URL', '/')
STATUS_USE_PING = get_bool_env('ESPHOME_DASHBOARD_USE_PING')

if IS_PY2:
    cookie_authenticated_yes = 'yes'
else:
    cookie_authenticated_yes = b'yes'


def template_args():
    version = const.__version__
    return {
        'version': version,
        'docs_link': 'https://beta.esphome.io/'
        if 'b' in version else 'https://esphome.io/',
        'get_static_file_url': get_static_file_url,
        'relative_url': RELATIVE_URL,
Ejemplo n.º 8
0
        if key in kwargs:
            kwargs[key] = sanitize_double_quotes(kwargs[key])

    if "platform" not in kwargs:
        kwargs[
            "platform"] = "ESP8266" if board in ESP8266_BOARD_PINS else "ESP32"
    platform = kwargs["platform"]

    write_file(path, wizard_file(**kwargs))
    storage = StorageJSON.from_wizard(name, name + ".local", platform, board)
    storage_path = ext_storage_path(os.path.dirname(path),
                                    os.path.basename(path))
    storage.save(storage_path)


if get_bool_env(ENV_QUICKWIZARD):

    def sleep(time):
        pass

else:
    from time import sleep


def safe_print_step(step, big):
    safe_print()
    safe_print()
    safe_print(f"============= STEP {step} =============")
    safe_print(big)
    safe_print("===================================")
    sleep(0.25)
Ejemplo n.º 9
0
def make_app(debug=get_bool_env(ENV_DEV)):
    def log_function(handler):
        if handler.get_status() < 400:
            log_method = access_log.info

            if isinstance(handler, SerialPortRequestHandler) and not debug:
                return
            if isinstance(handler, PingRequestHandler) and not debug:
                return
        elif handler.get_status() < 500:
            log_method = access_log.warning
        else:
            log_method = access_log.error

        request_time = 1000.0 * handler.request.request_time()
        # pylint: disable=protected-access
        log_method(
            "%d %s %.2fms",
            handler.get_status(),
            handler._request_summary(),
            request_time,
        )

    class StaticFileHandler(tornado.web.StaticFileHandler):
        def set_extra_headers(self, path):
            self.set_header("Cache-Control",
                            "no-store, no-cache, must-revalidate, max-age=0")

    app_settings = {
        "debug": debug,
        "cookie_secret": settings.cookie_secret,
        "log_function": log_function,
        "websocket_ping_interval": 30.0,
        "template_path": get_base_frontend_path(),
    }
    rel = settings.relative_url
    app = tornado.web.Application(
        [
            (f"{rel}", MainRequestHandler),
            (f"{rel}login", LoginHandler),
            (f"{rel}logout", LogoutHandler),
            (f"{rel}logs", EsphomeLogsHandler),
            (f"{rel}upload", EsphomeUploadHandler),
            (f"{rel}compile", EsphomeCompileHandler),
            (f"{rel}validate", EsphomeValidateHandler),
            (f"{rel}clean-mqtt", EsphomeCleanMqttHandler),
            (f"{rel}clean", EsphomeCleanHandler),
            (f"{rel}vscode", EsphomeVscodeHandler),
            (f"{rel}ace", EsphomeAceEditorHandler),
            (f"{rel}update-all", EsphomeUpdateAllHandler),
            (f"{rel}info", InfoRequestHandler),
            (f"{rel}edit", EditRequestHandler),
            (f"{rel}download.bin", DownloadBinaryRequestHandler),
            (f"{rel}manifest.json", ManifestRequestHandler),
            (f"{rel}serial-ports", SerialPortRequestHandler),
            (f"{rel}ping", PingRequestHandler),
            (f"{rel}delete", DeleteRequestHandler),
            (f"{rel}undo-delete", UndoDeleteRequestHandler),
            (f"{rel}wizard", WizardRequestHandler),
            (f"{rel}static/(.*)", StaticFileHandler, {
                "path": get_static_path()
            }),
            (f"{rel}devices", ListDevicesHandler),
            (f"{rel}import", ImportRequestHandler),
            (f"{rel}secret_keys", SecretKeysRequestHandler),
            (f"{rel}rename", EsphomeRenameHandler),
        ],
        **app_settings,
    )

    return app
Ejemplo n.º 10
0
 def using_ha_addon_auth(self):
     if not self.on_ha_addon:
         return False
     return not get_bool_env("DISABLE_HA_AUTHENTICATION")
Ejemplo n.º 11
0
 def status_use_ping(self):
     return get_bool_env("ESPHOME_DASHBOARD_USE_PING")
Ejemplo n.º 12
0
    kwargs['password'] = sanitize_double_quotes(kwargs['password'])

    if 'platform' not in kwargs:
        kwargs[
            'platform'] = 'ESP8266' if board in ESP8266_BOARD_PINS else 'ESP32'
    platform = kwargs['platform']

    with codecs.open(path, 'w', 'utf-8') as f_handle:
        f_handle.write(wizard_file(**kwargs))
    storage = StorageJSON.from_wizard(name, name + '.local', platform, board)
    storage_path = ext_storage_path(os.path.dirname(path),
                                    os.path.basename(path))
    storage.save(storage_path)


if get_bool_env('ESPHOME_QUICKWIZARD'):

    def sleep(time):
        pass
else:
    from time import sleep


def safe_print_step(step, big):
    safe_print()
    safe_print()
    safe_print("============= STEP {} =============".format(step))
    safe_print(big)
    safe_print("===================================")
    sleep(0.25)
Ejemplo n.º 13
0
 def using_hassio_auth(self):
     if not self.on_hassio:
         return False
     return not get_bool_env('DISABLE_HA_AUTHENTICATION')