def main():
    args = parse_commandline_args()
    connection = utils.open_connection(args)

    if args.all:
        scan_queue = list()

        # Broadcast ping
        utils.write_command(connection, commands.encode_ping(), list(range(1, 128)))
        reader = utils.read_can_datagrams(connection)
        while True:
            dt = next(reader)

            if dt is None: # Timeout
                break

            _, _, src = dt
            scan_queue.append(src)

    else:
        scan_queue = args.ids

    # Broadcast ask for config
    configs = utils.write_command_retry(connection,
                                        commands.encode_read_config(),
                                        scan_queue)

    for id, raw_config in configs.items():
        configs[id] = msgpack.unpackb(raw_config, encoding='ascii')

    print(json.dumps(configs, indent=4, sort_keys=True))
Example #2
0
def main():
    """
    Entry point of the application.
    """
    args = parse_commandline_args()
    with open(args.binary_file, 'rb') as input_file:
        binary = input_file.read()

    serial_port = utils.open_connection(args)

    online_boards = check_online_boards(serial_port, args.ids)

    if online_boards != set(args.ids):
        offline_boards = [str(i) for i in set(args.ids) - online_boards]
        print("Boards {} are offline, aborting..."
              .format(", ".join(offline_boards)))
        exit(2)

    print("Flashing firmware (size: {} bytes)".format(len(binary)))
    flash_binary(serial_port, binary, args.base_address, args.device_class,
                 args.ids)

    print("Verifying firmware...")
    valid_nodes_set = set(check_binary(serial_port, binary,
                                       args.base_address, args.ids))
    nodes_set = set(args.ids)

    if valid_nodes_set == nodes_set:
        print("OK")
    else:
        verification_failed(nodes_set - valid_nodes_set)

    if args.run:
        run_application(serial_port, args.ids)
Example #3
0
async def send_message(host, port, token, message, logger):
    async with open_connection(host, port, logger) as rw:
        reader, writer = rw
        if await authorise(token, reader, writer, logger):
            await logger(decode_message(await reader.readline()))
            await submit_message(message, reader, writer, logger)
        else:
            print("Problems with authorization. Check your token")
def main():
    args = parse_commandline_args()
    connection = utils.open_connection(args)
    if args.all is True:
        ids = list(range(1, 128))
    else:
        ids = args.ids

    utils.write_command(connection, commands.encode_jump_to_main(), ids)
Example #5
0
async def get_auth_token(host, port, nickname, logger):
    async with open_connection(host, port, logger) as rw:
        reader, writer = rw
        credentials = await register(nickname, reader, writer, logger)
        if not credentials:
            print("Problems with new user registration. Try again later")
            return
        token = credentials['account_hash']
        print(f"Save your token: {token}")
        return token
def main():
    args = parse_commandline_args()
    config = json.loads(args.file.read())

    if "ID" in config.keys():
        print("This tool cannot be used to change node IDs.")
        print("Use bootloader_change_id.py instead.")
        sys.exit(1)

    connection = utils.open_connection(args)
    utils.config_update_and_save(connection, config, args.ids)
def main():
    args = parse_commandline_args()
    connection = utils.open_connection(args)

    config = {"ID": args.new}
    utils.write_command_retry(connection,
                              commands.encode_update_config(config),
                              [args.old])
    utils.write_command_retry(connection,
                              commands.encode_save_config(),
                              [args.new])
Example #8
0
async def connect_and_read(host, port, history_file):
    """Connect to chat server, read and save all messages to history_file."""
    async with open_connection(host, port) as (reader, _):

        async with aiofiles.open(history_file, mode='a') as chat_log_file:
            while not reader.at_eof():
                async with timeout(READ_TIMEOUT):
                    line = await reader.readline()

                formatted_line = f'[{make_timestamp()}] {line.decode()}'
                logger.debug(repr(formatted_line))

                await chat_log_file.write(formatted_line)
                await chat_log_file.flush()
async def run_chat_writer(host, port, nickname, auth_token, message):
    if nickname and not auth_token:
        logging.info('Auth token not given. Executing user registration...')

        async with open_connection(host=host, port=port) as (reader, writer):
            user_credentials = await register(
                reader=reader,
                writer=writer,
                nickname=nickname,
            )
        auth_token = user_credentials['account_hash']

        logging.info(f'Registered successfully. Your auth token: {auth_token}')

    async with open_connection(host=host, port=port) as (reader, writer):
        logging.info('Executing user authorisation...')

        is_successfully_authorised = await authorise(
            reader=reader,
            writer=writer,
            auth_token=auth_token,
        )

        if not is_successfully_authorised:
            logging.info('Unknown token. Check it or re-register.')
            return

        logging.info('Successfully authorised')

        logging.info('Sending message...')

        await submit_message(
            reader=reader,
            writer=writer,
            message=message,
        )
        logging.info('Message sent successfully')
Example #10
0
async def connect_and_register(host, port, nickname):
    """Connect to chat server and try to register nickname."""
    async with open_connection(host, port) as (reader, writer):

        line = await reader.readline()
        decoded_line = line.decode()
        logger.debug('> %r', line)
        if not decoded_line.startswith(
                'Hello %username%! Enter your personal hash or leave it empty to create new account.\n'):
            raise ProtocolError(f'wrong hello message {line!r}')

        token_message = '\n'
        logger.debug('< %r', token_message)
        writer.write(token_message.encode())
        await writer.drain()

        line = await reader.readline()
        decoded_line = line.decode()
        logger.debug('> %r', line)
        if not decoded_line.startswith('Enter preferred nickname below:\n'):
            raise ProtocolError(f'wrong prompt message {line!r}')

        register_nickname_message = f'{nickname}\n'
        logger.debug('< %r', register_nickname_message)
        writer.write(register_nickname_message.encode())
        await writer.drain()

        line = await reader.readline()
        decoded_line = line.decode()
        logger.debug('> %r', line)
        if not decoded_line.startswith('{') or 'account_hash' not in decoded_line:
            raise WrongToken(f'cant register {line!r}')

        token_json = json.loads(decoded_line)
        token = token_json.get('account_hash')

        if not token:
            raise WrongToken(f'token not found in register answer {token_json!r}')

        return token
Example #11
0
async def run_chat_reading_cycle(host,
                                 port,
                                 output_file_object,
                                 connection_attempts_count_without_timeout=2,
                                 timeout_between_connection_attempts=3):
    current_connection_attempt = 0

    while True:
        try:
            current_connection_attempt += 1

            async with open_connection(host=host,
                                       port=port) as (reader, writer):
                current_connection_attempt = 0

                await write_to_file(
                    file_object=output_file_object,
                    text='Connection established\n',
                )
                while True:
                    message = await reader.readline()
                    await write_to_file(
                        file_object=output_file_object,
                        text=f'{message.decode()}',
                    )
        except (socket.gaierror, ConnectionRefusedError, ConnectionResetError):
            if current_connection_attempt < connection_attempts_count_without_timeout:
                await write_to_file(
                    file_object=output_file_object,
                    text='No connection. Retrying.\n',
                )
            else:
                await write_to_file(
                    file_object=output_file_object,
                    text=f'No connection. '
                    f'Retrying in {timeout_between_connection_attempts} sec.\n',
                )
                await asyncio.sleep(timeout_between_connection_attempts)
Example #12
0
def scrape_external_links(movie):
    connection = open_connection(movie.link)
    for item in connection.find_all('a', class_="external text"):
        # URLs are in the format: https://www.sitename.com/foo/
        # Splitting by . gives us: https://www . sitename . com/foo/
        # Allowing an easy way to retrieve the website name
        url = item['href']
        url_split = url.split('.')
        if len(url_split) > 2:
            if url_split[0] is not 'http://www':
                url = ''.join(['http://www.', url_split[1], ".", url_split[2]])
                url_split = url.split('.')
            url_name = url_split[1]
            # Determine which website the url belongs to
            parse_url(url, url_name, url_split, movie)
            # An error has occurred here: The url should have been split, most likely a mistake on wikipedia
        elif len(url_split) < 2:
            ss = ""
            for s in url_split:
                ss = ss + s
            # Debugging code: Print the broken url
            print("site_split: %s, site: %s, Movie: %s" %
                  (ss, url, movie.link))
Example #13
0
async def connect_and_send(host, port, token, message):
    """Connect to chat server, login and send message."""
    async with open_connection(host, port) as (reader, writer):

        await login(token, reader, writer)
        await send_message(message, reader, writer)
Example #14
0
 def open_spider(self, spider):
     self.db = open_connection()