예제 #1
0
def main():
    input('Начнем программу, нажмите любую кнопку, чтобы продолжить...')
    print('Настроим программу...')
    is_set_up = False
    # config = Config(0.1, 0.01, 1, 100, ALGORITHMS[0], Point(0.0, 0.0), 1)
    config = Config(0.5, 0.1, 1, 1000, ALGORITHMS[0], Point(0.0, 0.0), 10)
    function = Function(config)
    while not is_set_up:
        print('Текущий конфиг:')
        print(config)
        answer = input(
            'Что введете?\n'
            '1. Шаг.\n'
            '2. Точность.\n'
            '3. Параметр а.\n'
            '4. Максимальное кол-во шагов.\n'
            '5. Алгоритм.\n'
            '6. Начальная точка.\n'
            '7. Интервал печати.\n'
            'Либо начать работу алгоритма 0, или закончить работу программы -1.\n'
            'Ответ: ')
        try:
            answer = int(answer)
            if answer == 1:
                config.step = read_step()
            elif answer == 2:
                config.precision = read_precision()
            elif answer == 3:
                config.a = read_a()
            elif answer == 4:
                config.max_steps = read_max_steps()
            elif answer == 5:
                config.algorithm = read_algorithm()
            elif answer == 6:
                config.starting_point = read_starting_point()
            elif answer == 7:
                config.print_interval = read_print_interval()
            elif answer == -1:
                print('Пока!')
                exit(0)
            elif answer == 0:
                algorithm = None
                if config.algorithm == ALGORITHMS[0]:
                    algorithm = ConstantStepAlgorithm(config, function)
                elif config.algorithm == ALGORITHMS[1]:
                    algorithm = DividingStepAlgorithm(config, function)
                elif config.algorithm == ALGORITHMS[2]:
                    algorithm = DecreasingStepAlgorithm(config, function)
                start = time()
                algorithm.run()
                print('Заняло времени: {0:> .3}с'.format(time() - start))
            else:
                raise Exception()
        except Exception:
            input('Неверный ввод, для повтора нажмите любую кнопку.')
def PlayYtQuery(query):

    if qlock.locked():
        return 'Busy', 503

    with qlock:

        try:
            print("=> Processing YouTube remote query for: '%s'\n" % query)

            # search YouTube for videos using the query string
            searchResults = YoutubeSearch(str(query), max_results=10)
            print('=> Got %d YouTube search result(s)\n' %
                  searchResults.count())
            '''for i in range(searchResults.count()):
                print('%d)' % (i + 1))
                print('Title: %s' % searchResults.as_dict()[i]['title'])
                print('ID: %s' % searchResults.as_dict()[i]['id'])
                print('Channel: %s' % searchResults.as_dict()[i]['channel'])
                print('Duration: %s' % searchResults.as_dict()[i]['duration'])
                print('Views: %s\n' % searchResults.as_dict()[i]['views'])'''

            if searchResults.count() == 0:
                return 'No results were found', 404

            # send Wake-on-LAN packet(s) to TV, in case it's off
            TvUtil.WoL()

            # initialize the YouTube remote
            remote = YouTubeRemote(Config.get('RemoteDisplayName'))

            if Config.get('ReadYtTokenFromDial'):
                # get the screen ID from the TV using the DIAL protocol
                screenId = TvUtil.getYtScreenId()
                print('=> Got YouTube screen ID from TV: %s\n' % screenId)

                # request the YouTube lounge API token using the screen ID
                loungeToken = remote.loadLoungeToken(screenId)
                print('=> Got lounge API token: %s\n' % loungeToken)

            else:
                # generate a random UUID for pairing
                code = remote.generatePairingcode()
                print('=> Generated a pairing code for the TV: %s\n' % code)

                # send YouTube pairing request to TV
                print('=> Sending a pairing request to the TV...\n')
                TvUtil.pairYt(code)

                # wait for pairing to succeed (or timeout)
                remote.waitForPairing(code)

            # set playing queue from YouTube search results
            print('=> Setting playing queue on TV...\n')
            firstVideoId = searchResults.as_dict()[0]['id']
            videoIdList = searchResults.as_csv_ids()
            remote.doCmd([
                YouTubeCmd(cmd="setPlaylist",
                           videoId=firstVideoId,
                           videoIds=videoIdList)
            ])

            # play/pause to force the YouTube player UI to be briefly visible
            time.sleep(1)
            #remote.doCmd([YouTubeCmd(cmd="dpadCommand", key='UP')])
            remote.doCmd([YouTubeCmd(cmd="pause"), YouTubeCmd(cmd="play")])

        except:
            traceback.print_exc()
            return sys.exc_info(), 500

        return 'OK'
def SetTvHost(host):
    Config.set('TvLanHost', host)
    return 'OK'
def ClearTvMac():
    Config.clear('MacAddress')
    return 'OK'
def SetTvMac(macAddr):
    macAddr = macAddr.replace(':', '')
    if len(re.findall(r'[0-9A-Fa-f]{12}', macAddr)) == 1:
        Config.set('MacAddress', macAddr.upper())
        return 'OK'
    return 'Invalid format', 400
def SetDisplayName(name):
    Config.set('RemoteDisplayName', name)
    return 'OK'
import time
import flask
import string
import threading
import traceback

from deps.ytsearch import YoutubeSearch
from deps.ytremote import YouTubeRemote, YouTubeCmd
from deps.utils import Config, WebRequest, TvUtil

if len(sys.argv) != 3:

    print('usage: %s <host> <port>' % sys.argv[0])
    exit()

Config('config.json')

api = flask.Flask(__name__)


@api.route('/ping', methods=['GET'])
def ping():
    return 'pong'


qlock = threading.Lock()


@api.route('/PlayYtQuery/<query>', methods=['GET'])
def PlayYtQuery(query):