Пример #1
0
 async def test_verbose_ignore_by_backend():
     env = set_env()
     sut = Controller(env)
     sut.daemon_request = mock.Mock()
     sut.daemon_request.return_value = coro('11' * 32)
     res = await sut.transaction_get('ff' * 32, True)
     assert res == '11' * 32
Пример #2
0
 async def test_verbose_failure():
     env = set_env()
     sut = Controller(env)
     sut.daemon_request = mock.Mock()
     sut.daemon_request.return_value = coro(
         raise_exception('some unhandled error'))
     await sut.transaction_get('ff' * 32, True)
Пример #3
0
def main_loop():
    '''Start the server.'''
    if os.geteuid() == 0:
        raise Exception('DO NOT RUN AS ROOT! Create an unpriveleged user '
                        'account and use that')

    loop = asyncio.get_event_loop()
    #loop.set_debug(True)

    def on_signal(signame):
        '''Call on receipt of a signal to cleanly shutdown.'''
        logging.warning('received {} signal, initiating shutdown'
                        .format(signame))
        controller.initiate_shutdown()

    def on_exception(loop, context):
        '''Suppress spurious messages it appears we cannot control.'''
        message = context.get('message')
        if not message in SUPPRESS_MESSAGES:
            if not ('task' in context and
                    'accept_connection2()' in repr(context.get('task'))):
                loop.default_exception_handler(context)

    controller = Controller(Env())
    future = asyncio.ensure_future(controller.main_loop())

    # Install signal handlers
    for signame in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(getattr(signal, signame),
                                partial(on_signal, signame))

    # Install exception handler
    loop.set_exception_handler(on_exception)
    loop.run_until_complete(future)
    loop.close()
Пример #4
0
 async def test_no_verbose():
     env = set_env()
     sut = Controller(env)
     sut.daemon_request = mock.Mock()
     response = 'cafebabe' * 64
     sut.daemon_request.return_value = coro(response)
     res = await sut.transaction_get('ff' * 32)
     assert res == response
Пример #5
0
    def test_should_trigger_wait_for_themes(self):
        socket = MockSocket()
        controller = Controller(socket, NO_OF_PLAYERS)
        controller.trigger = MagicMock()
        theme_list = MagicMock()

        controller.request_theme_choices(theme_list)

        controller.trigger.assert_called_once_with("THEMES_REQUESTED")
Пример #6
0
 def setUp(self) -> None:
     michael = User(user_id='mscott', email='*****@*****.**', profile=Profile(name='Michael Scott', college='Scranton University'))
     users_repository: UsersRepository = MagicMock()
     users_repository.get = MagicMock(return_value=michael)
     users_repository.create = MagicMock(return_value=michael)
     users_repository.update = MagicMock(return_value=michael)
     connections_repository: ConnectionsRepository = MagicMock()
     recommendations_repository: RecommendationsRepository = MagicMock()
     self.controller = Controller(users_repository, connections_repository, recommendations_repository)
Пример #7
0
    def test_should_call_connection_send_method(self):
        socket = MockSocket()
        socket.send_to_all = MagicMock()
        theme_list = ["This", "is", "the", "Theme", "List"]

        controller = Controller(socket, NO_OF_PLAYERS)
        controller.request_theme_choices(theme_list)

        socket.send_to_all.assert_any_call(theme_list, "data-theme-list")
        socket.send_to_all.assert_called_with("CHOOSE_THEME", "event")
def main():
    '''Set up logging and run the server.'''
    logging.basicConfig(level=logging.INFO)
    logging.info('ElectrumX server starting')
    try:
        controller = Controller(Env())
        controller.run()
    except Exception:
        traceback.print_exc()
        logging.critical('ElectrumX server terminated abnormally')
    else:
        logging.info('ElectrumX server terminated normally')
Пример #9
0
 def handle_response(self, method, result, error):
     if method in ('groups', 'sessions') and not error:
         if method == 'groups':
             lines = Controller.groups_text_lines(result)
         else:
             lines = Controller.sessions_text_lines(result)
         for line in lines:
             print(line)
     elif error:
         print('error: {} (code {:d})'
               .format(error['message'], error['code']))
     else:
         print(json.dumps(result, indent=4, sort_keys=True))
Пример #10
0
def main():
    '''Set up logging and run the server.'''
    #logging.basicConfig(level=logging.DEBUG)
    logging.basicConfig(filename='aaa.log', level=logging.DEBUG, filemode='w')
    logging.info('ElectrumX server starting')
    try:
        controller = Controller(Env())
        controller.run()
    except Exception:
        traceback.print_exc()
        logging.critical('ElectrumX server terminated abnormally')
    else:
        logging.info('ElectrumX server terminated normally')
Пример #11
0
def main():
    '''Set up logging and run the server.'''
    log_fmt = Env.default('LOG_FORMAT', '%(levelname)s:%(name)s:%(message)s')
    logging.basicConfig(level=logging.DEBUG, format=log_fmt)
    logging.info('ElectrumX server starting')
    try:
        controller = Controller(Env())
        controller.run()
    except Exception:
        traceback.print_exc()
        logging.critical('ElectrumX server terminated abnormally')
    else:
        logging.info('ElectrumX server terminated normally')
Пример #12
0
    async def test_verbose_ok():
        env = set_env()
        sut = Controller(env)
        sut.daemon_request = mock.Mock()
        response = {"hex": "00" * 32, "blockhash": "ff" * 32}
        sut.daemon_request.return_value = coro(response)
        res = await sut.transaction_get('ff' * 32, True)
        assert res == response

        response = {"hex": "00" * 32, "blockhash": None}
        sut.daemon_request.return_value = coro(response)
        res = await sut.transaction_get('ff' * 32, True)
        assert res == response
Пример #13
0
def main():
    '''Set up logging and run the server.'''
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-7s %(message)-100s '
                               '[%(filename)s:%(lineno)d]')
    logging.info('ElectrumX server starting')
    try:
        controller = Controller(Env())
        controller.run()
    except Exception:
        traceback.print_exc()
        logging.critical('ElectrumX server terminated abnormally')
    else:
        logging.info('ElectrumX server terminated normally')
Пример #14
0
def main():
    setup()

    try:
        print(BANNER)
    except UnicodeEncodeError:
        # Thrown on my Raspberry PI (via SSH).
        print(MESSAGE_ATTENTION + "Failed to print fancy banner, skipping...")

    while True:
        try:
            server_port = int(
                input(MESSAGE_INPUT + "Server port to listen on: "))
            break
        except ValueError:
            continue

    model = Model()
    view = View()
    Controller(view, model, server_port)

    # Start the view, blocks until exit.
    view.start()

    print(MESSAGE_INFO +
          "Feel free to submit any issues or feature requests on GitHub.")
    print(MESSAGE_INFO + "Goodbye!")
Пример #15
0
    def test_should_give_the_best_rated_themes(self):
        """
        Gives the best results in order
        """
        socket = MockSocket()
        theme_choices = [
            ["1", "2", "5"],
            ["1", "4", "7"],
            ["1", "3", "2"],
            ["2", "3", "4"],
            ["1", "3", "5"],
            ["1", "2", "6"],
        ]

        controller = Controller(socket, NO_OF_PLAYERS)
        result = controller.decide_themes(theme_choices, result_size=3)

        assert result == ["1", "2", "3"]
Пример #16
0
    def __init__(self):
        self.logger = get_logger('server')

        gpio.init()

        self.serial_tty = serial.Serial(settings.TTY_ADDRESS,
                                        baudrate=settings.TTY_BAUDRATE,
                                        timeout=settings.TTY_TIMEOUT)

        self.motor_left = Motor("\xAA\x0A\x06", self.serial_tty, 'left',
                                "\x0B", "\x0A", "\x09", "\x08", self.logger)
        self.motor_right = Motor("\xAA\x0A\x07", self.serial_tty, 'right',
                                 "\x0F", "\x0E", "\x0D", "\x0C", self.logger)
        self.light = Light(getattr(port, settings.LIGHT_PORT))
        self.video = Video()
        self.i2c_controller = Controller(settings.I2C_ADDRESS,
                                         settings.I2C_PORT)

        self.server = SocketServer.UDPServer(
            (settings.SERVER_HOST, settings.SERVER_PORT), self.handle_request)
        self.server.timeout = settings.MOTOR_COMMAND_TIMEOUT

        self.sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                    socket.IPPROTO_UDP)
        self.sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sender.bind(
            (settings.SOCKET_CLIENT_HOST, settings.SOCKET_CLIENT_PORT))

        self.is_running = False
        self.last_handle_request_time = 0

        self.last_light_value = 0
        self.last_light_value_time = time()

        self.last_video_value = 0
        self.last_video_value_time = time()

        # дата актуальности, данные телеметрии, температура, фото датчик
        self.telem_values = [0, 0, 0, 0]
Пример #17
0
def main():
    setup()

    try:
        print(BANNER)
    except UnicodeEncodeError:
        # Thrown on my Raspberry PI (via SSH).
        print(MESSAGE_ATTENTION + "Failed to print fancy banner, skipping...")

    parser = ArgumentParser()
    parser.add_argument("-p",
                        "--port",
                        help="server port to listen on",
                        type=int)
    arguments = parser.parse_args()

    if arguments.port:
        server_port = arguments.port
    else:
        while True:
            try:
                server_port = int(
                    input(MESSAGE_INPUT + "Server port to listen on: "))
                break
            except ValueError:
                continue

    model = Model()
    view = ViewCLI()
    controller = Controller(view, model, server_port)

    # Start the controller, blocks until exit.
    controller.start()

    print(MESSAGE_INFO +
          "Feel free to submit any issues or feature requests on GitHub.")
    print(MESSAGE_INFO + "Goodbye!")
Пример #18
0
def main():
    print(BANNER)
    setup()

    while True:
        try:
            server_port = int(input(MESSAGE_INPUT + "Server port to listen on: "))
            break
        except ValueError:
            continue

    model = Model()
    view = View()
    Controller(view, model, server_port)

    # Start the view, blocks until exit.
    view.start()

    print(MESSAGE_INFO + "Feel free to submit any issues or feature requests on GitHub.")
    print(MESSAGE_INFO + "Goodbye!")
Пример #19
0
class TestController(unittest.TestCase):

    def setUp(self) -> None:
        michael = User(user_id='mscott', email='*****@*****.**', profile=Profile(name='Michael Scott', college='Scranton University'))
        users_repository: UsersRepository = MagicMock()
        users_repository.get = MagicMock(return_value=michael)
        users_repository.create = MagicMock(return_value=michael)
        users_repository.update = MagicMock(return_value=michael)
        connections_repository: ConnectionsRepository = MagicMock()
        recommendations_repository: RecommendationsRepository = MagicMock()
        self.controller = Controller(users_repository, connections_repository, recommendations_repository)

    def test_get_user(self) -> None:
        user = self.controller.get_user('foo')
        self.controller.usersRepository.get.assert_called_once_with('foo')
        assert isinstance(user, User)

    def test_update_user_details(self) -> None:
        user = self.controller.update_user_details('mscott', college='University of New York')
        self.controller.usersRepository.update.assert_called_once()
        assert isinstance(user, User)

    def test_add_user(self) -> None:
        user = self.controller.add_user(name='Michael Scott', email='*****@*****.**', college='Scranton University')
        self.controller.usersRepository.create.assert_called_once()
        assert isinstance(user, User)

    def test_remove_user(self) -> None:
        user = self.controller.add_user(name='Michael Scott', email='*****@*****.**', college='Scranton University')
        assert isinstance(user, User)
        self.controller.remove_user(user.id)
        assert self.controller.usersRepository.delete.called_once_with(user.id)

    def test_get_connections(self) -> None:
        pass

    def test_add_connection(self) -> None:
        pass

    def test_remove_connection(self) -> None:
        pass

    def test_get_recommendations(self) -> None:
        pass
Пример #20
0
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import sys
sys.path.insert(0, os.path.abspath('..'))
from server.controller import Controller

# -- Project information -----------------------------------------------------

project = 'ElectrumX'
copyright = '2016-2018, Neil Booth'
author = 'Neil Booth'

# The short X.Y version
version = Controller.short_version()
# The full version including branding
release = Controller.VERSION

# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []

# Add any paths that contain templates here, relative to this directory.
Пример #21
0
 async def test_wrong_txhash():
     env = set_env()
     sut = Controller(env)
     sut.daemon_request = mock.Mock()
     await sut.transaction_get('cafe')
     sut.daemon_request.assert_not_called()
Пример #22
0
class Application(object):
    def __init__(self):
        self.logger = get_logger('server')

        gpio.init()

        self.serial_tty = serial.Serial(settings.TTY_ADDRESS,
                                        baudrate=settings.TTY_BAUDRATE,
                                        timeout=settings.TTY_TIMEOUT)

        self.motor_left = Motor("\xAA\x0A\x06", self.serial_tty, 'left',
                                "\x0B", "\x0A", "\x09", "\x08", self.logger)
        self.motor_right = Motor("\xAA\x0A\x07", self.serial_tty, 'right',
                                 "\x0F", "\x0E", "\x0D", "\x0C", self.logger)
        self.light = Light(getattr(port, settings.LIGHT_PORT))
        self.video = Video()
        self.i2c_controller = Controller(settings.I2C_ADDRESS,
                                         settings.I2C_PORT)

        self.server = SocketServer.UDPServer(
            (settings.SERVER_HOST, settings.SERVER_PORT), self.handle_request)
        self.server.timeout = settings.MOTOR_COMMAND_TIMEOUT

        self.sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                    socket.IPPROTO_UDP)
        self.sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sender.bind(
            (settings.SOCKET_CLIENT_HOST, settings.SOCKET_CLIENT_PORT))

        self.is_running = False
        self.last_handle_request_time = 0

        self.last_light_value = 0
        self.last_light_value_time = time()

        self.last_video_value = 0
        self.last_video_value_time = time()

        # дата актуальности, данные телеметрии, температура, фото датчик
        self.telem_values = [0, 0, 0, 0]

    def motors_off(self):
        """
        выключаем все моторы
        """
        self.logger.debug('motors off')
        self.motor_left.off()
        self.motor_right.off()

    def handle_axis_motion(self, values):
        """
        обработчик событий 3х мерного джоя
        """
        left_value = int(values[JoyButtons.JOY_L_UD] * 255) + int(
            values[JoyButtons.JOY_L_LR] * 255)
        right_value = int(values[JoyButtons.JOY_L_UD] * 255) - int(
            values[JoyButtons.JOY_L_LR] * 255)
        self.motor_left.process_value(left_value)
        self.motor_right.process_value(right_value)
        return [left_value, right_value]

    def _get_value(self, value):
        """
        преобразуем значение -1...+1 в значение от 0...65535
        """
        if value < -1:
            value = -1
        elif value > 1:
            value = 1

        try:
            value = int((65535 * (value + 1)) / 2)
        except ZeroDivisionError:
            value = 0

        return value

    def __process_light_value(self, value):
        """
        обработка включения/выключения фар
        """
        if value:
            if self.last_light_value == value:
                ct = time()
                if 6 > (ct - self.last_light_value_time) > 3:
                    self.light.toggle_state()
                    self.last_light_value_time = ct
            elif self.last_light_value == 0:
                self.last_light_value_time = time()
        self.last_light_value = value

    def __process_video_value(self, value):
        """
        обработка включения/выключения видео
        """
        if value:
            if self.last_video_value == value:
                ct = time()
                if 6 > (ct - self.last_video_value_time) > 3:
                    self.video.toggle_state()
                    self.last_video_value_time = ct
            elif self.last_video_value == 0:
                self.last_video_value_time = time()
        self.last_video_value = value

    def handle_buttons(self, values):
        """
        обработчик состояния кнопок
        """

        # обработаем включение/выключение фонарика
        self.__process_light_value(values[settings.LIGHT_KEY])
        # обработаем включение/выключение видео
        self.__process_video_value(values[settings.VIDEO_KEY])

        # отправим контроллеру значения для команд
        self.i2c_controller.write_values(
            self._get_value(values[JoyButtons.JOY_LT]),
            self._get_value(values[JoyButtons.JOY_RT]),
            self._get_value(values[JoyButtons.JOY_L_LR]),
            self._get_value(values[JoyButtons.JOY_L_UD]),
            255 if values[JoyButtons.JOY_LB] > 0 else 0,
            255 if values[JoyButtons.JOY_RB] > 0 else 0,
            255 if values[JoyButtons.JOY_B_AXIS_L] > 0 else 0,
            255 if values[JoyButtons.JOY_B_AXIS_R] > 0 else 0,
        )
        return [self.light.state, self.video.state]

    def handle_controller_values(self, values):
        """
        обработка остальных кнопок
        :param values:
        """

    def update_telem_values(self):
        """
        обновляем данные телеметрии
        """
        values = self.i2c_controller.read_values()

        if values:
            self.telem_values = values

    def handle_request(self, request, client_address, server):
        """
        обрабатывает запрос
        :param request: запрос
        :param client_address: адрес клиента
        :param server: сервер
        """

        self.last_handle_request_time = time()

        _request, _socket = request

        if ',' not in _request:
            return

        try:
            joy_state = [
                float(i) if '.' in i else int(i) for i in _request.split(',')
            ]
        except (ValueError, TypeError):
            return

        if len(joy_state) == JoyButtons.JOY_COUNT_STATES:

            # обрабатываем кнопки
            values = self.handle_axis_motion(joy_state)
            values.extend(self.handle_buttons(joy_state))
            # обрабатываем остальные параметры
            self.handle_controller_values(joy_state)

            if (self.last_handle_request_time -
                    self.telem_values[0]) > settings.TELEM_UPDATE_TIME:
                # обновляем данные телеметрии
                self.update_telem_values()

            values.extend(self.telem_values)

            self.sender.sendto(','.join(str(i) for i in values),
                               (client_address[0], settings.DASHBOARD_PORT))

    def start(self):
        """"""
        self.logger.debug('start')
        self.motors_off()

        self.is_running = True
        self.last_handle_request_time = time()

        while self.is_running:
            if (time() - self.last_handle_request_time
                ) > settings.MOTOR_COMMAND_TIMEOUT:
                self.last_handle_request_time = time()
                self.motors_off()

            # проверка пока приходит телеметрия
            self.server.handle_request()

        print 'Finished'
        self.motors_off()

        raw_input('Выключите питание, нажмите клавишу ВВОД, чтобы продолжить')

    def run(self):
        """
        запускаем приложение
        """
        try:
            self.start()
        except KeyboardInterrupt:
            self.motors_off()
            raw_input(
                'Выключите питание, нажмите клавишу ВВОД, чтобы продолжить')
            self.motors_off()
        except Exception as err:
            self.logger.debug(err)
            import traceback
            self.logger.debug(traceback.format_exc())
Пример #23
0
import logging
from typing import List, Dict

from flask import request
from flask_restful import Resource

from server import utils
from server.controller import Controller
from server.exceptions import DataIntegrityException
from server.models import User
from server.app import config, api

logger = logging.getLogger(__name__)

controller = Controller(
    users_repository=config.usersRepository,
    connections_repository=config.connectionsRepository,
    recommendations_repository=config.recommendationsRepository)


class User(Resource):
    """ Exposes a User as a RESTful resource.

    """
    @staticmethod
    def _json_mapper(user: User) -> Dict:
        """ gets the json mapping for a user object.

        The json API representation of a user need not be coupled to the domain model of a user.
        This method provides the object-API mapping for a user.

        Args: