コード例 #1
0
    def get_reply(self):
        """Waits for and returns Reply.

        Returns:
            First complete reply if expected message ID was not specified,
            otherwise first complete reply of expected message ID.

        Raises:
            PacketCorrupted: Packet is corrupt.
        """
        try:
            #self.open() ################################ IN CASE GUI CLOSED PORT
            # Wait for the '@' character.
            while not self.conn.read() == "@" and self.port_enabled:
                pass

            # Read one line at a time until packet is complete and parsed.
            packet = bitstring.BitStream("0x40")
            while self.port_enabled:
                try:
                    # Read until new line.
                    current_line = self.conn.readline()
                    for char in current_line:
                        packet.append("0x{:02X}".format(ord(char)))
                except:
                    rospy.logwarn(
                        'trying to read socket with port enabled = %s',
                        self.port_enabled)

            # Try to parse.
                try:
                    reply = Reply(packet)
                    break
                except PacketIncomplete:
                    # Keep looking.
                    continue
            if self.port_enabled:
                rospy.logdebug("Received %s: %s", reply.name, reply.payload)
                return reply
            else:
                return Reply(bitstring.BitStream("0x000A"))
        except select.error as (code, msg):
            # Set SIGINT as KeyboardInterrupt correctly, because pyserial has
            # problems.
            # if code == errno.EINTR:
            #     raise KeyboardInterrupt()
            #
            # # Otherwise, reraise.
            # raise
            rospy.logerr('could not read stream. Have you closed the port?')
            return
コード例 #2
0
def welcome(update: Update):
    """
    /start
    Проверить, существует ли такой клиент
    Существующих приветствует и предлагает меню
    Несуществующих регистрирует, и уведомляет админа(ов)
    """

    if not x.client:
        u = yield Reply(
            text='Добро пожаловать в скейт-парк "ЦЕХ"! Представьтесь, пожалуйста',
            reply_markup=Kbd(
                [[Btn('Вот мой контакт', request_contact=True)]],
                resize_keyboard=True,
                one_time_keyboard=True
            )
        )
        """:type: Update"""

        client = create_client(u)
        change_fi = f'Приятно познакомиться, {client.first_name}!\n' \
                    f'Ваш персональный ID - {client.id}\n' \
                    f'Хотите изменить имя и фамилию? ' \
                    f'Если вы укажете реальное имя, нам с вами будет легче общаться'
        u = yield Reply(text=change_fi, reply_markup=Kbd(
            [[Btn('Да, хочу'), Btn('Нет, всё в порядке')]],
            resize_keyboard=True,
            one_time_keyboard=True
        ))
        """:type: Update"""

        if u.message.text == 'Да, хочу':
            u = yield Reply('Напишите ваше имя и фамилию', remove_kb=True)
            while True:
                fi = u.message.text.title().split()
                if len(fi) != 2:
                    u = yield 'Я думаю, двух слов вам должно хватить, попробуйте ещё раз'
                else:
                    break

            client.first_name, client.last_name = fi
            dbc.s.commit()
            aware_about_new_client(client)
            yield Reply(f'Отлично, добро пожаловать, {client.first_name}!', remove_kb=True)
        else:
            aware_about_new_client(client)
            yield Reply(f'Ну что ж, добро пожаловать, {client.first_name}!', remove_kb=True)
    else:
        yield from client_menu()
コード例 #3
0
def ride():
    u = yield Reply('Какой вариант вам подходит?',
                    reply_markup=Kbd([[
                        Btn(RideVariant.HOURLY.value),
                        Btn(RideVariant.DAILY.value)
                    ], [Btn(RideVariant.BY_AMOUNT.value)]],
                                     one_time_keyboard=True,
                                     resize_keyboard=True))
コード例 #4
0
def client_menu():
    k = Kbd([[Btn(Actions.ENTER_RIDE.value),
              Btn(Actions.ENTER_HANGOUT.value)]],
            resize_keyboard=True,
            one_time_keyboard=True)
    u = yield Reply('Чего изволите?', reply_markup=k)
    while True:
        try:
            action = Actions(u.message.text)
        except Exception:
            u = yield 'Я не понимаю, чего вы хотите, давайте ещё раз'
        else:
            break
    yield f'Вы выбрали {action}'
コード例 #5
0
    def get_reply(self):
        """Waits for and returns Reply.

        Returns:
            First complete reply if expected message ID was not specified,
            otherwise first complete reply of expected message ID.

        Raises:
            PacketCorrupted: Packet is corrupt.
        """
        try:
            #self.open() ################################ IN CASE GUI CLOSED PORT
            # Wait for the '@' character.
            while not self.conn.read() == "@":
                pass

            # Read one line at a time until packet is complete and parsed.
            packet = bitstring.BitStream("0x40")
            while True:
                # Read until new line.
                current_line = self.conn.readline()
                for char in current_line:
                    packet.append("0x{:02X}".format(ord(char)))

                # Try to parse.
                try:
                    reply = Reply(packet)
                    break
                except PacketIncomplete:
                    # Keep looking.
                    continue

            rospy.logdebug("Received %s: %s", reply.name, reply.payload)
            return reply
        except select.error as (code, msg):
            # Set SIGINT as KeyboardInterrupt correctly, because pyserial has
            # problems.
            if code == errno.EINTR:
                raise KeyboardInterrupt()

            # Otherwise, reraise.
            raise
コード例 #6
0
ファイル: test_replies.py プロジェクト: asmodehn/replies
    async def run():
        replies.add(replies.GET, "http://example.com/zero")
        replies.add(replies.GET, "http://example.com/one")
        replies.add(replies.GET, "http://example.com/two")
        replies.add(replies.GET, re.compile(r"http://example\.com/three"))
        replies.add(replies.GET, re.compile(r"http://example\.com/four"))
        re.purge()
        replies.remove(replies.GET, "http://example.com/two")
        replies.remove(Reply(method=replies.GET,
                             url="http://example.com/zero"))
        replies.remove(replies.GET, re.compile(r"http://example\.com/four"))

        with pytest.raises(ConnectionError):
            await asks.get("http://example.com/zero")
        asks.get("http://example.com/one")
        with pytest.raises(ConnectionError):
            await asks.get("http://example.com/two")
        asks.get("http://example.com/three")
        with pytest.raises(ConnectionError):
            await asks.get("http://example.com/four")
コード例 #7
0
ファイル: test_replies.py プロジェクト: asmodehn/replies
        assert_response(resp, "")
        assert len(replies.calls) == 1
        assert replies.calls[0].request.url == "http://example.com/"

        resp = await asks.get("http://example.com?foo=bar")
        assert_response(resp, "")
        assert len(replies.calls) == 2
        assert replies.calls[1].request.url == "http://example.com/?foo=bar"


@pytest.mark.parametrize(
    "original,replacement",
    [
        ("http://example.com/two", "http://example.com/two"),
        (
            Reply(method=replies.GET, url="http://example.com/two"),
            Reply(method=replies.GET,
                  url="http://example.com/two",
                  body="testtwo"),
        ),
        (
            re.compile(r"http://example\.com/two"),
            re.compile(r"http://example\.com/two"),
        ),
    ],
)
def test_replace(original, replacement):
    @replies.activate
    def run():
        replies.add(replies.GET, "http://example.com/one", body="test1")
コード例 #8
0
ファイル: connection.py プロジェクト: derogab/adl-server
    def run(self):
        print('[Info] Connection from : ', self.caddress)

        # Send back a message
        try:
            self.csocket.send(Reply.handshake())
        except:
            print('[Error] No handshake')

        # Init timeout
        timeout = 0

        # Create teacher and wizard for each connection
        teacher = Teacher()
        wizard = Wizard()

        # create queue
        queue = ''

        # Get all data from this connection
        while True:

            try:
                data = self.csocket.recv(2048)
            except:
                print('[Warning] Connection closed by client.')

            if data:

                try:
                    # decode data
                    data = data.decode()
                    # add data to queue
                    queue = queue + data
                except:
                    # nothing to do
                    pass

                # Reinit timeout
                timeout = 0
            else:
                # Increse timeout
                timeout = timeout + 1

            if queue:
                # Cut point
                cut = queue.rfind('\n') + 1
                # Create a separate thread for data analysis
                my_worker = Worker(self.csocket, queue[:cut], wizard, teacher)
                my_worker.start()
                # Pop queue
                queue = queue[cut:]

            # Check timeout
            if timeout > Constants.connection_max_timeout:
                print('[Info] Force disconnect')
                break

        # Send closing a message
        self.__send_message(Reply.goodbye())

        print('[Info] Client at ', self.caddress, ' disconnected...')
コード例 #9
0
    def run(self):
        msg = self.data_received.strip()

        if msg:

            array = msg.split('\n')

            for x in array:

                x = x.strip()

                if x:

                    request = False
                    try:
                        request = json.loads(x)
                    except:
                        print('[Error] JSON decode failed.')

                    if request and request[
                            'status'] == Constants.request_status_success:

                        # get mode
                        mode = request['mode']
                        # get data
                        data = request['data']

                        # exec something by type
                        if data['type'] == Constants.request_type_data:

                            # send ack
                            self.__send_message(Reply.ack())

                            # mode
                            if mode == Constants.request_mode_analyzer:

                                # kill teacher
                                self.teacher = None

                                # get data
                                archive = data['archive']
                                index = data['info']['index']
                                sensor = data['info']['sensor']
                                position = data['info']['position']
                                values = data['values']

                                # collect data in my wizard
                                self.wizard.collect(archive, index, sensor,
                                                    position, values)

                                # predict sometimes
                                if index % Constants.something_value == 0:
                                    prediction, accuracy = self.wizard.predict(
                                    )
                                    # send prediction
                                    self.__send_message(
                                        Reply.prediction(prediction))

                            if mode == Constants.request_mode_learning:

                                # kill wizard
                                self.wizard = None

                                # get data
                                archive = data['archive']
                                index = data['info']['index']
                                activity = data['info']['activity']
                                sensor = data['info']['sensor']
                                position = data['info']['position']
                                values = data['values']

                                # collect data in my teacher
                                self.teacher.collect(archive, index, activity,
                                                     sensor, position, values)

                        if data['type'] == Constants.request_type_close:

                            print('[Info] Closing connection.')

                            # send close message
                            try:
                                self.__send_message(Reply.close())
                            except:
                                print(
                                    '[Warning] Connection already closed by client.'
                                )

                            # save received data
                            if self.teacher and mode == Constants.request_mode_learning:
                                # save collected data to datasets
                                self.teacher.save()

                        if data['type'] == Constants.request_type_destroy:

                            print('[Info] Client destroyed.')

                            # send close message
                            try:
                                self.__send_message(Reply.destroy())
                            except:
                                print(
                                    '[Warning] Connection already closed by client.'
                                )

                            # save received data
                            if self.teacher and mode == Constants.request_mode_learning:
                                # train all the data
                                self.teacher.teach()

                    else:
                        print('[Error] Data received error.')