<commit_before>"""Provide configuration end points for Z-Wave."""
import asyncio
import logging

import homeassistant.core as ha
from homeassistant.const import HTTP_NOT_FOUND, HTTP_OK
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.config import EditKeyBasedConfigView
from homeassistant.components.zwave import const, DEVICE_CONFIG_SCHEMA_ENTRY
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)
CONFIG_PATH = 'zwave_device_config.yaml'
OZW_LOG_FILENAME = 'OZW_Log.txt'
URL_API_OZW_LOG = '/api/zwave/ozwlog'


@asyncio.coroutine
def async_setup(hass):
    """Set up the Z-Wave config API."""
    hass.http.register_view(EditKeyBasedConfigView(
        'zwave', 'device_config', CONFIG_PATH, cv.entity_id,
        DEVICE_CONFIG_SCHEMA_ENTRY
    ))
    hass.http.register_view(ZWaveNodeValueView)
    hass.http.register_view(ZWaveNodeGroupView)
    hass.http.register_view(ZWaveNodeConfigView)
    hass.http.register_view(ZWaveUserCodeView)
    hass.http.register_static_path(
        URL_API_OZW_LOG, hass.config.path(OZW_LOG_FILENAME), False)
    hass.http.register_view(ZWaveConfigWriteView)

    return True


class ZWaveConfigWriteView(HomeAssistantView):
    """View to save the ZWave configuration to zwcfg_xxxxx.xml."""

    url = "/api/zwave/saveconfig"
    name = "api:zwave:saveconfig"

    @ha.callback
    def post(self, request):
        """Save cache configuration to zwcfg_xxxxx.xml."""
        hass = request.app['hass']
        network = hass.data.get(const.DATA_NETWORK)
        if network is None:
            return self.json_message('No Z-Wave network data found',
                                     HTTP_NOT_FOUND)
        _LOGGER.info("Z-Wave configuration written to file.")
        network.write_config()
        return self.json_message('Z-Wave configuration saved to file.',<commit_msg>Add loglinefetch for frontend API call (#10579)<commit_after>"""Provide configuration end points for Z-Wave."""
import asyncio
import logging

from collections import deque
from aiohttp.web import Response
import homeassistant.core as ha
from homeassistant.const import HTTP_NOT_FOUND, HTTP_OK
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.config import EditKeyBasedConfigView
from homeassistant.components.zwave import const, DEVICE_CONFIG_SCHEMA_ENTRY
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)
CONFIG_PATH = 'zwave_device_config.yaml'
OZW_LOG_FILENAME = 'OZW_Log.txt'


@asyncio.coroutine
def async_setup(hass):
    """Set up the Z-Wave config API."""
    hass.http.register_view(EditKeyBasedConfigView(
        'zwave', 'device_config', CONFIG_PATH, cv.entity_id,
        DEVICE_CONFIG_SCHEMA_ENTRY
    ))
    hass.http.register_view(ZWaveNodeValueView)
    hass.http.register_view(ZWaveNodeGroupView)
    hass.http.register_view(ZWaveNodeConfigView)
    hass.http.register_view(ZWaveUserCodeView)
    hass.http.register_view(ZWaveLogView)
    hass.http.register_view(ZWaveConfigWriteView)

    return True


class ZWaveLogView(HomeAssistantView):
    """View to read the ZWave log file."""

    url = "/api/zwave/ozwlog"
    name = "api:zwave:ozwlog"

# pylint: disable=no-self-use
    @asyncio.coroutine
    def get(self, request):
        """Retrieve the lines from ZWave log."""
        try:
            lines = int(request.query.get('lines', 0))
        except ValueError:
            return Response(text='Invalid datetime', status=400)

        hass = request.app['hass']
        response = yield from hass.async_add_job(self._get_log, hass, lines)

        return Response(text='\n'.join(response))

    def _get_log(self, hass, lines):
        """Retrieve the logfile content."""
        logfilepath = hass.config.path(OZW_LOG_FILENAME)
        with open(logfilepath, 'r') as logfile:
            data = (line.rstrip() for line in logfile)
            if lines == 0:
                loglines = list(data)
            else:
                loglines = deque(data, lines)
        return loglines


class ZWaveConfigWriteView(HomeAssistantView):
    """View to save the ZWave configuration to zwcfg_xxxxx.xml."""

    url = "/api/zwave/saveconfig"
    name = "api:zwave:saveconfig"

    @ha.callback
    def post(self, request):
        """Save cache configuration to zwcfg_xxxxx.xml."""
        hass = request.app['hass']
        network = hass.data.get(const.DATA_NETWORK)
        if network is None:
            return self.json_message('No Z-Wave network data found',
                                     HTTP_NOT_FOUND)
        _LOGGER.info("Z-Wave configuration written to file.")
        network.write_config()
        return self.json_message('Z-Wave configuration saved to file.',
{'fraction_non_alphanumeric': 0.09519832985386222, 'fraction_numerical': 0.0020876826722338203, 'mean_word_length': 3.448467966573816, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6527283', 'n_tokens_mistral': 1508, 'n_tokens_neox': 1471, 'n_words': 325}