<commit_before>#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""A script to control an HEOS player, see <https://github.com/ping13/heospy>
for details.

Specification of the HEOS interface at
http://rn.dmglobal.com/euheos/HEOS_CLI_ProtocolSpecification.pdf

"""

import json
import os
import telnetlib
import re
import logging
import argparse
import six
import sys
import time
from collections import OrderedDict

from . import ssdp # Simple Service Discovery Protocol (SSDP), https://gist.github.com/dankrause/6000248


# determine a default path for the config file
DEFAULT_CONFIG_PATH = "."
for location in os.curdir, os.path.expanduser("~/.heospy"), os.environ.get("HEOSPY_CONF"):
    if location is None:
        continue
    try:
        testname = os.path.join(location,"config.json")
        if os.path.exists(testname):
            DEFAULT_CONFIG_PATH = location
            break
    except IOError:
        pass

    
TIMEOUT = 15

class HeosPlayerConfigException(Exception):
    pass
class HeosPlayerGeneralException(Exception):
    pass

class HeosPlayer(object):
    """Representation of an HEOS player with a specific player id.

This needs a JSON config file with a minimal content:

{
  "player_name": "Living Room",
  "user": "<EMAIL>",
  "pw": "do-not-use-qwerty-as-password"
}

"""

    URN_SCHEMA = "urn:schemas-denon-com:device:ACT-Denon:1"
    
    def __init__(self, rediscover = False,
                 config_file = os.path.join(DEFAULT_CONFIG_PATH, 'config.json')):
        """Initialize HEOS player."""
        self.heosurl = 'heos://'

        try:
            with open(config_file) as json_data_file:
                self._config = json.load(json_data_file)
        except IOError:
            error_msg = "cannot read your config file '{}'".format(config_file)
            logging.error(error_msg)
            raise HeosPlayerConfigException(error_msg)
        
        logging.debug("use config file '{}'".format(config_file))
        
        self.host = self._config.get("host")
        self.pid = self._config.get("pid")
        self.main_player_name = self._config.get("player_name", self._config.get("main_player_name"))
        self._config_file = config_file
        self.names = dict()
        self.names["players"] = self._config.get("players", {})
        self.names["groups"] = self._config.get("groups", {})
        self.groups = None
        
        if self.main_player_name is None:
            logging.warn("No main player name given.")
            raise HeosPlayerGeneralException("No main player name given.")
        
        # if host and pid is not known, detect the first HEOS device.
        if rediscover or (not self.host or not self.pid):
            logging.info("Starting to discover your HEOS player '{}' in your local network".format(self.main_player_name))
            ssdp_list = ssdp.discover(self.URN_SCHEMA)
            logging.debug("found {} possible hosts: {}".format(len(ssdp_list), ssdp_list))
            self.telnet = None
            for response in ssdp_list:
                if response.st == self.URN_SCHEMA:
                    try:
                        self.host = re.match(r"http:..([^\:]+):", response.location).group(1)
                        logging.debug("Testing host '{}'".format(self.host))                    
                        self.telnet = telnetlib.Telnet(self.host, 1255)
                        logging.debug("Telnet '{}'".format(self.telnet))                    
                        self.pid = self._get_player(self.main_player_name)
                        logging.debug("pid '{}'".format(self.pid))                                            
                        if self.pid:
                            self.main_player_name = self._config.get("player_name", self._config.get("main_player_name"))
                            logging.info("Found main player '{}' in your local network".format(self.main_player_name))
                            break
                    except Exception as e:
                        logging.error(e)
                        pass
            if self.telnet == None:
                msg = "couldn't discover any HEOS player with Simple Service Discovery Protocol (SSDP)."
                logging.error(msg)
                raise HeosPlayerGeneralException(msg)

            self._update_groups_players()
            
        else:
            logging.info("My cache says your HEOS player '{}' is at {}".format(self.main_player_name,
                                                                               self.host))
            try:
                self.telnet = telnetlib.Telnet(self.host, 1255, timeout=TIMEOUT)
            except Exception as e:
                raise HeosPlayerGeneralException("telnet failed")

        # check if we've found what we were looking for
        if self.host is None:
            logging.error("No HEOS player found in your local network")
        elif self.pid is None:
            logging.error("No player with name '{}' found for being a main player!".format(self.main_player_name))
        else:
            # get user and password
            if self.login(user=self._config.get("user"),
                          pw = self._config.get("pw")):
                self.user = self._config.get("user")

                
        # save config
        if (rediscover or self._config.get("pid") is None) and self.host and self.pid:
                
            logging.info("Save host and pid in {}".format(config_file))
            self._config["pid"] = self.pid<commit_msg>worked out some unicode issues with the main player name<commit_after>#!/usr/bin/env python
# -*- encoding: utf-8 -*-

"""A script to control an HEOS player, see <https://github.com/ping13/heospy>
for details.

Specification of the HEOS interface at
http://rn.dmglobal.com/euheos/HEOS_CLI_ProtocolSpecification.pdf

"""

import json
import os
import telnetlib
import re
import logging
import argparse
import six
import sys
import time
from collections import OrderedDict

from . import ssdp # Simple Service Discovery Protocol (SSDP), https://gist.github.com/dankrause/6000248


# determine a default path for the config file
DEFAULT_CONFIG_PATH = "."
for location in os.curdir, os.path.expanduser("~/.heospy"), os.environ.get("HEOSPY_CONF"):
    if location is None:
        continue
    try:
        testname = os.path.join(location,"config.json")
        if os.path.exists(testname):
            DEFAULT_CONFIG_PATH = location
            break
    except IOError:
        pass


TIMEOUT = 15

class HeosPlayerConfigException(Exception):
    pass
class HeosPlayerGeneralException(Exception):
    pass

class HeosPlayer(object):
    """Representation of an HEOS player with a specific player id.

This needs a JSON config file with a minimal content:

{
  "player_name": "Living Room",
  "user": "<EMAIL>",
  "pw": "do-not-use-qwerty-as-password"
}

"""

    URN_SCHEMA = "urn:schemas-denon-com:device:ACT-Denon:1"
    
    def __init__(self, rediscover = False,
                 config_file = os.path.join(DEFAULT_CONFIG_PATH, 'config.json')):
        """Initialize HEOS player."""
        self.heosurl = 'heos://'

        try:
            with open(config_file) as json_data_file:
                self._config = json.load(json_data_file)
        except IOError:
            error_msg = "cannot read your config file '{}'".format(config_file)
            logging.error(error_msg)
            raise HeosPlayerConfigException(error_msg)
        
        logging.debug("use config file '{}'".format(config_file))
        
        self.host = self._config.get("host")
        self.pid = self._config.get("pid")
        self.main_player_name = self._config.get("player_name", self._config.get("main_player_name"))
        self._config_file = config_file
        self.names = dict()
        self.names["players"] = self._config.get("players", {})
        self.names["groups"] = self._config.get("groups", {})
        self.groups = None
        
        if self.main_player_name is None:
            logging.warn("No main player name given.")
            raise HeosPlayerGeneralException("No main player name given.")
        
        # if host and pid is not known, detect the first HEOS device.
        if rediscover or (not self.host or not self.pid):
            logging.info(u"Starting to discover your HEOS player '{}' in your local network".format(self.main_player_name))
            ssdp_list = ssdp.discover(self.URN_SCHEMA)
            logging.debug("found {} possible hosts: {}".format(len(ssdp_list), ssdp_list))
            self.telnet = None
            for response in ssdp_list:
                if response.st == self.URN_SCHEMA:
                    try:
                        self.host = re.match(r"http:..([^\:]+):", response.location).group(1)
                        logging.debug("Testing host '{}'".format(self.host))                    
                        self.telnet = telnetlib.Telnet(self.host, 1255)
                        logging.debug("Telnet '{}'".format(self.telnet))                    
                        self.pid = self._get_player(self.main_player_name)
                        logging.debug("pid '{}'".format(self.pid))                                            
                        if self.pid:
                            self.main_player_name = self._config.get("player_name", self._config.get("main_player_name"))
                            logging.info(u"Found main player '{}' in your local network".format(self.main_player_name))
                            break
                    except Exception as e:
                        logging.error(e)
                        pass
            if self.telnet == None:
                msg = "couldn't discover any HEOS player with Simple Service Discovery Protocol (SSDP)."
                logging.error(msg)
                raise HeosPlayerGeneralException(msg)

            self._update_groups_players()
            
        else:
            print(repr(self.main_player_name))
            logging.info(u"My cache says your HEOS player '{}' is at {}".format(self.main_player_name,
                                                                                self.host))
            try:
                self.telnet = telnetlib.Telnet(self.host, 1255, timeout=TIMEOUT)
            except Exception as e:
                raise HeosPlayerGeneralException("telnet failed")

        # check if we've found what we were looking for
        if self.host is None:
            logging.error("No HEOS player found in your local network")
        elif self.pid is None:
            logging.error(u"No player with name '{}' found for being a main player!".format(self.main_player_name))
        else:
            # get user and password
            if self.login(user=self._config.get("user"),
                          pw = self._config.get("pw")):
                self.user = self._config.get("user")

                
        # save config
        if (rediscover or self._config.get("pid") is None) and self.host and self.pid:
                
            logging.info("Save host and pid in {}".format(config_file))
            self._config["pid"] = self.pid
{'fraction_non_alphanumeric': 0.10612135792568832, 'fraction_numerical': 0.003920520359975051, 'mean_word_length': 1.9025084044478924, 'pattern_counts': {'":': 6, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '771355', 'n_tokens_mistral': 3154, 'n_tokens_neox': 3029, 'n_words': 769}