<commit_before>import click
import json
import logging
import os
import re
import signal
import sys
import time

from os.path import abspath
from subprocess import PIPE, TimeoutExpired
from datetime import datetime, timedelta
from tempfile import mkstemp

from .subprocess_run import run

import wifi
from pyramid.paster import get_app, setup_logging

import configparser

import yaml

from . import supervisor

from .device_discovery import PhilipsHueBridgeApiClient, discover_devices, read_json


IFACES_AVAILABLE = '/etc/network/interfaces.available/{}'
IFACES_D = '/etc/network/interfaces.d/{}'
WPA_SUPPLICANT_FS = '/etc/wpa_supplicant/wpa_supplicant.conf'
WPA_SUPPLICANT_CONF = '''ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={{
    ssid="{ssid}"
    psk="{password}"
}}
'''
DEFAULT_SCAN_INTERVAL_SECONDS = 1 * 60  # 1 minute


logger = logging.getLogger(__name__)


@click.group()
@click.pass_context
@click.option('--config', '-c', required=True, type=click.Path(exists=True), help='app configuration file')
def wifi_setup(ctx, config):
    ctx.obj = get_app(abspath(config)).registry.settings


@wifi_setup.command(name='status')
@click.pass_context
def wifi_setup_status(ctx):
    wlan_infra = ctx.obj['wlan_infra']
    try:
        wpa_status = run(['wpa_cli', '-i', wlan_infra, 'status'], stdout=PIPE, timeout=5).stdout.decode()
    except TimeoutExpired:
        wpa_status = ""
    ssid_match = re.search("^ssid=(.*)$", wpa_status, flags=re.MULTILINE)
    ssid = ssid_match.group(1) if ssid_match else None
    ip_address_match = re.search("^ip_address=(.*)$", wpa_status, flags=re.MULTILINE)
    ip_address = ip_address_match.group(1) if ip_address_match else None
    connected = 'wpa_state=COMPLETED' in wpa_status
    if ssid and connected:
        status = 'connected' if ip_address else 'connecting'
    else:
        status = 'unavailable'
    click.echo("infra_ssid=%s" % (ssid or ""))
    click.echo("infra_status=%s" % status)


@click.command(help='scan the wifi interfaces for networks (requires root privileges)')
@click.option('--config', '-c', required=True, type=click.Path(exists=True), help='app configuration file')
@click.option('--forever/--no-forever', default=False, help='scan forever (until interupted')
@click.option('--waitsec', default=20, help='How many seconds to wait inbetween scans (only when forever')
def scan_wifi(config, forever=False, waitsec=20):
    app = get_app(abspath(config))
    device = app.registry.settings['wlan_infra']
    run(['ifup', device])
    while True:
        click.echo("Scanning for wifi networks")
        networks = get_networks(device=device)
        with open(app.registry.settings['wifi_networks_path'], 'w') as wifi_file:
            json.dump({'ssids': networks}, wifi_file, indent=2)
            wifi_file.write('\n')
        if not forever:
            exit(0)
        time.sleep(waitsec)


def get_networks(device):
    try:
        return [c.ssid for c in wifi.Cell.all(device) if c.ssid]
    except wifi.exceptions.InterfaceError as e:
        click.echo("Scanning wifi networks failed: %s" % e)
        return []


@click.command(help="Activate the wifi-onboarding setup")
@click.option('--config', '-c', required=True, type=click.Path(exists=True), help="app configuration file")
def enter_wifi_setup(config):
    app = get_app(abspath(config))
    WIFI_SETUP_FLAG_PATH = app.registry.settings['wifi_setup_flag_path']
    if not os.path.exists(WIFI_SETUP_FLAG_PATH):
        click.echo("Not entering wifi setup mode. %s not found" % WIFI_SETUP_FLAG_PATH)
        exit(0)
    click.echo("Entering wifi setup mode")
    device = app.registry.settings['wlan_adhoc']
    retries = 3 # Activating ad-hoc network can fail, we try it 3 times
    while retries > 0:
        click.echo("Trying to create ad-hoc network (%s attempts left)" % retries)
        activate_adhoc(device)
        run(['/usr/bin/supervisorctl', 'start', 'dhcpd'])
        dhcpd_status = run(
            ['/usr/bin/supervisorctl', 'status', 'dhcpd'],
            stdout=PIPE)
        dhcpd_is_running = 'RUNNING' in dhcpd_status.stdout.decode()
        if dhcpd_is_running:
            click.echo("Ad-hoc network successfully created")
            click.echo("Start scanning nearby wifi networks")
            run(['/usr/bin/supervisorctl', 'start', 'scan_wifi'])
            click.echo("Restart avahi daemon")<commit_msg>Clean code<commit_after>import click
import json
import logging
import os
import re
import signal
import sys
import time

from os.path import abspath
from subprocess import PIPE, TimeoutExpired
from datetime import datetime, timedelta
from tempfile import mkstemp

from .subprocess_run import run

import wifi
from pyramid.paster import get_app, setup_logging

import configparser

import yaml

from . import supervisor

from .device_discovery import PhilipsHueBridgeApiClient, discover_devices, read_json


IFACES_AVAILABLE = '/etc/network/interfaces.available/{}'
IFACES_D = '/etc/network/interfaces.d/{}'
WPA_SUPPLICANT_FS = '/etc/wpa_supplicant/wpa_supplicant.conf'
WPA_SUPPLICANT_CONF = '''ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={{
    ssid="{ssid}"
    psk="{password}"
}}
'''
DEFAULT_SCAN_INTERVAL_SECONDS = 1 * 60  # 1 minute


logger = logging.getLogger(__name__)


@click.group()
@click.pass_context
@click.option('--config', '-c', required=True, type=click.Path(exists=True), help='app configuration file')
def wifi_setup(ctx, config):
    ctx.obj = get_app(abspath(config)).registry.settings


@wifi_setup.command(name='status')
@click.pass_context
def wifi_setup_status(ctx):
    wlan_infra = ctx.obj['wlan_infra']
    try:
        wpa_status = run(['wpa_cli', '-i', wlan_infra, 'status'], stdout=PIPE, timeout=5).stdout.decode()
    except TimeoutExpired:
        wpa_status = ""
    ssid_match = re.search("^ssid=(.*)$", wpa_status, flags=re.MULTILINE)
    ssid = ssid_match.group(1) if ssid_match else None
    ip_address_match = re.search("^ip_address=(.*)$", wpa_status, flags=re.MULTILINE)
    ip_address = ip_address_match.group(1) if ip_address_match else None
    connected = 'wpa_state=COMPLETED' in wpa_status
    if ssid and connected:
        status = 'connected' if ip_address else 'connecting'
    else:
        status = 'unavailable'
    click.echo("infra_ssid=%s" % (ssid or ""))
    click.echo("infra_status=%s" % status)


@click.command(help='scan the wifi interfaces for networks (requires root privileges)')
@click.option('--config', '-c', required=True, type=click.Path(exists=True), help='app configuration file')
@click.option('--forever/--no-forever', default=False, help='scan forever (until interupted')
@click.option('--waitsec', default=20, help='How many seconds to wait inbetween scans (only when forever')
def scan_wifi(config, forever=False, waitsec=20):
    app = get_app(abspath(config))
    device = app.registry.settings['wlan_infra']
    run(['ifup', device])
    while True:
        click.echo("Scanning for wifi networks")
        networks = get_networks(device=device)
        with open(app.registry.settings['wifi_networks_path'], 'w') as wifi_file:
            json.dump({'ssids': networks}, wifi_file, indent=2)
            wifi_file.write('\n')
        if not forever:
            exit(0)
        time.sleep(waitsec)


def get_networks(device):
    try:
        return [c.ssid for c in wifi.Cell.all(device) if c.ssid]
    except wifi.exceptions.InterfaceError as e:
        click.echo("Scanning wifi networks failed: %s" % e)
        return []


@click.command(help="Activate the wifi-onboarding setup")
@click.option('--config', '-c', required=True, type=click.Path(exists=True), help="app configuration file")
def enter_wifi_setup(config):
    app = get_app(abspath(config))
    WIFI_SETUP_FLAG_PATH = app.registry.settings['wifi_setup_flag_path']
    if not os.path.exists(WIFI_SETUP_FLAG_PATH):
        click.echo("Not entering wifi setup mode. %s not found" % WIFI_SETUP_FLAG_PATH)
        exit(0)
    click.echo("Entering wifi setup mode")
    device = app.registry.settings['wlan_adhoc']
    retries = 3  # Activating ad-hoc network can fail, we try it 3 times
    while retries > 0:
        click.echo("Trying to create ad-hoc network (%s attempts left)" % retries)
        activate_adhoc(device)
        run(['/usr/bin/supervisorctl', 'start', 'dhcpd'])
        dhcpd_status = run(
            ['/usr/bin/supervisorctl', 'status', 'dhcpd'],
            stdout=PIPE)
        dhcpd_is_running = 'RUNNING' in dhcpd_status.stdout.decode()
        if dhcpd_is_running:
            click.echo("Ad-hoc network successfully created")
            click.echo("Start scanning nearby wifi networks")
            run(['/usr/bin/supervisorctl', 'start', 'scan_wifi'])
            click.echo("Restart avahi daemon")
{'fraction_non_alphanumeric': 0.12854228066198142, 'fraction_numerical': 0.004080707322602585, 'mean_word_length': 3.959527824620573, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5423686', 'n_tokens_mistral': 2987, 'n_tokens_neox': 2876, 'n_words': 662}