Beispiel #1
0
    def _run(self):
        if "platform" not in self.options:
            raise exception.UndefinedEnvPlatform(self.name)

        build_vars = self._get_build_variables()
        build_targets = self._get_build_targets()

        telemetry.on_run_environment(self.options, build_targets)

        # install dependent libraries
        if "lib_install" in self.options:
            _autoinstall_libdeps(self.cmd_ctx, [
                int(d.strip())
                for d in self.options['lib_install'].split(",") if d.strip()
            ], self.verbose)
        if "lib_deps" in self.options:
            _autoinstall_libdeps(self.cmd_ctx, [
                d.strip() for d in self.options['lib_deps'].split(
                    "\n" if "\n" in self.options['lib_deps'] else ", ")
                if d.strip()
            ], self.verbose)

        try:
            p = PlatformFactory.newPlatform(self.options['platform'])
        except exception.UnknownPlatform:
            self.cmd_ctx.invoke(cmd_platform_install,
                                platforms=[self.options['platform']])
            p = PlatformFactory.newPlatform(self.options['platform'])

        return p.run(build_vars, build_targets, self.silent, self.verbose)
Beispiel #2
0
    def process(self):
        if "platform" not in self.options:
            raise exception.UndefinedEnvPlatform(self.name)

        build_vars = self.get_build_variables()
        build_targets = list(self.get_build_targets())

        telemetry.on_run_environment(self.options, build_targets)

        # skip monitor target, we call it above
        if "monitor" in build_targets:
            build_targets.remove("monitor")

        try:
            p = PlatformFactory.newPlatform(self.options["platform"])
        except exception.UnknownPlatform:
            self.cmd_ctx.invoke(
                cmd_platform_install,
                platforms=[self.options["platform"]],
                skip_default_package=True,
            )
            p = PlatformFactory.newPlatform(self.options["platform"])

        result = p.run(build_vars, build_targets, self.silent, self.verbose,
                       self.jobs)
        return result["returncode"] == 0
    def _run(self):
        if "platform" not in self.options:
            raise exception.UndefinedEnvPlatform(self.name)

        build_vars = self.get_build_variables()
        build_targets = self.get_build_targets()

        telemetry.on_run_environment(self.options, build_targets)

        # skip monitor target, we call it above
        if "monitor" in build_targets:
            build_targets.remove("monitor")
        if "nobuild" not in build_targets:
            # install dependent libraries
            if "lib_install" in self.options:
                _autoinstall_libdeps(self.cmd_ctx, [
                    int(d.strip())
                    for d in self.options['lib_install'].split(",")
                    if d.strip()
                ], self.verbose)
            if "lib_deps" in self.options:
                _autoinstall_libdeps(
                    self.cmd_ctx,
                    util.parse_conf_multi_values(self.options['lib_deps']),
                    self.verbose)

        try:
            p = PlatformFactory.newPlatform(self.options['platform'])
        except exception.UnknownPlatform:
            self.cmd_ctx.invoke(cmd_platform_install,
                                platforms=[self.options['platform']],
                                skip_default_package=True)
            p = PlatformFactory.newPlatform(self.options['platform'])

        return p.run(build_vars, build_targets, self.silent, self.verbose)
Beispiel #4
0
    def _run(self):
        if "platform" not in self.options:
            raise exception.UndefinedEnvPlatform(self.name)

        build_vars = self._get_build_variables()
        build_targets = self._get_build_targets()

        telemetry.on_run_environment(self.options, build_targets)

        if "nobuild" not in build_targets:
            # install dependent libraries
            if "lib_install" in self.options:
                _autoinstall_libdeps(
                    self.cmd_ctx,
                    [int(d.strip()) for d in self.options["lib_install"].split(",") if d.strip()],
                    self.verbose,
                )
            if "lib_deps" in self.options:
                _autoinstall_libdeps(
                    self.cmd_ctx, [d.strip() for d in self.options["lib_deps"].split(", ") if d.strip()], self.verbose
                )

        try:
            p = PlatformFactory.newPlatform(self.options["platform"])
        except exception.UnknownPlatform:
            self.cmd_ctx.invoke(cmd_platform_install, platforms=[self.options["platform"]], skip_default_package=True)
            p = PlatformFactory.newPlatform(self.options["platform"])

        return p.run(build_vars, build_targets, self.silent, self.verbose)
def pytest_generate_tests(metafunc):
    if "pioproject_dir" not in metafunc.fixturenames:
        return
    examples_dirs = []

    # repo examples
    examples_dirs.append(normpath(join(dirname(__file__), "..", "examples")))

    # dev/platforms
    for manifest in PlatformManager().get_installed():
        p = PlatformFactory.newPlatform(manifest['__pkg_dir'])
        if not p.is_embedded():
            continue
        examples_dir = join(p.get_dir(), "examples")
        assert isdir(examples_dir)
        examples_dirs.append(examples_dir)

    project_dirs = []
    for examples_dir in examples_dirs:
        for root, _, files in walk(examples_dir):
            if "platformio.ini" not in files or ".skiptest" in files:
                continue
            project_dirs.append(root)
    project_dirs.sort()
    metafunc.parametrize("pioproject_dir", project_dirs)
Beispiel #6
0
def pytest_generate_tests(metafunc):
    if "pioproject_dir" not in metafunc.fixturenames:
        return
    examples_dirs = []

    # repo examples
    examples_dirs.append(normpath(join(dirname(__file__), "..", "examples")))

    # dev/platforms
    for manifest in PlatformManager().get_installed():
        p = PlatformFactory.newPlatform(manifest['__pkg_dir'])
        if not p.is_embedded():
            continue
        # issue with "version `CXXABI_1.3.9' not found (required by sdcc)"
        if "linux" in util.get_systype() and p.name in ("intel_mcs51",
                                                        "ststm8"):
            continue
        examples_dir = join(p.get_dir(), "examples")
        assert isdir(examples_dir)
        examples_dirs.append(examples_dir)

    project_dirs = []
    for examples_dir in examples_dirs:
        platform_examples = []
        for root, _, files in walk(examples_dir):
            if "platformio.ini" not in files or ".skiptest" in files:
                continue
            platform_examples.append(root)

        # test random 3 examples
        random.shuffle(platform_examples)
        project_dirs.extend(platform_examples[:3])
    project_dirs.sort()
    metafunc.parametrize("pioproject_dir", project_dirs)
Beispiel #7
0
def pytest_generate_tests(metafunc):
    if "pioproject_dir" not in metafunc.fixturenames:
        return
    examples_dirs = []

    # repo examples
    examples_dirs.append(normpath(join(dirname(__file__), "..", "examples")))

    # dev/platforms
    for manifest in PlatformManager().get_installed():
        p = PlatformFactory.newPlatform(manifest['__pkg_dir'])
        if not p.is_embedded():
            continue
        examples_dir = join(p.get_dir(), "examples")
        assert isdir(examples_dir)
        examples_dirs.append(examples_dir)

    project_dirs = []
    for examples_dir in examples_dirs:
        platform_examples = []
        for root, _, files in walk(examples_dir):
            if "platformio.ini" not in files or ".skiptest" in files:
                continue
            platform_examples.append(root)

        # test random 3 examples
        random.shuffle(platform_examples)
        project_dirs.extend(platform_examples[:3])
    project_dirs.sort()
    metafunc.parametrize("pioproject_dir", project_dirs)
Beispiel #8
0
def platform_list(json_output):
    platforms = []
    pm = PlatformManager()
    for manifest in pm.get_installed():
        p = PlatformFactory.newPlatform(
            pm.get_manifest_path(manifest['__pkg_dir']))
        platforms.append({
            "name":
            p.name,
            "title":
            p.title,
            "description":
            p.description,
            "version":
            p.version,
            "url":
            p.vendor_url,
            "packages":
            p.get_installed_packages().keys(),
            'forDesktop':
            any([p.name.startswith(n) for n in ("native", "linux", "windows")])
        })

    if json_output:
        click.echo(json.dumps(platforms))
    else:
        _print_platforms(platforms)
Beispiel #9
0
def PioPlatform(env):
    variables = env.GetProjectOptions(as_dict=True)
    if "framework" in variables:
        # support PIO Core 3.0 dev/platforms
        variables['pioframework'] = variables['framework']
    p = PlatformFactory.newPlatform(env['PLATFORM_MANIFEST'])
    p.configure_default_packages(variables, COMMAND_LINE_TARGETS)
    return p
Beispiel #10
0
def get_dependencies():
    lm = LibraryManager(platformio.util.get_projectlibdeps_dir())
    dependencies = {library['name']: library['version']
                    for library in lm.get_installed()}
    platform = env['PIOPLATFORM']
    dependencies[platform] = PlatformFactory.newPlatform(platform).version
    dependencies['PlatformIO'] = platformio.__version__
    return dependencies
Beispiel #11
0
def get_dependencies():
    lib_storage = os.path.join(env['PROJECTLIBDEPS_DIR'], env['PIOENV'])
    lm = LibraryManager(lib_storage)
    dependencies = {library['name']: library['version']
                    for library in lm.get_installed()}
    platform = env['PIOPLATFORM']
    dependencies[platform] = PlatformFactory.newPlatform(platform).version
    dependencies['PlatformIO'] = platformio.__version__
    return dependencies
Beispiel #12
0
def _get_installed_platform_data(platform,
                                 with_boards=True,
                                 expose_packages=True):
    p = PlatformFactory.newPlatform(platform)
    data = dict(
        name=p.name,
        title=p.title,
        description=p.description,
        version=p.version,
        homepage=p.homepage,
        repository=p.repository_url,
        url=p.vendor_url,
        docs=p.docs_url,
        license=p.license,
        forDesktop=not p.is_embedded(),
        frameworks=sorted(list(p.frameworks) if p.frameworks else []),
        packages=list(p.packages) if p.packages else [],
    )

    # if dump to API
    # del data['version']
    # return data

    # overwrite VCS version and add extra fields
    manifest = PlatformManager().load_manifest(dirname(p.manifest_path))
    assert manifest
    for key in manifest:
        if key == "version" or key.startswith("__"):
            data[key] = manifest[key]

    if with_boards:
        data["boards"] = [c.get_brief_data() for c in p.get_boards().values()]

    if not data["packages"] or not expose_packages:
        return data

    data["packages"] = []
    installed_pkgs = p.get_installed_packages()
    for name, opts in p.packages.items():
        item = dict(
            name=name,
            type=p.get_package_type(name),
            requirements=opts.get("version"),
            optional=opts.get("optional") is True,
        )
        if name in installed_pkgs:
            for key, value in installed_pkgs[name].items():
                if key not in ("url", "version", "description"):
                    continue
                item[key] = value
                if key == "version":
                    item["originalVersion"] = util.get_original_version(value)
        data["packages"].append(item)

    return data
Beispiel #13
0
def update_boards():
    lines = []

    lines.append(RST_COPYRIGHT)
    lines.append(".. _boards:")
    lines.append("")

    lines.append("Boards")
    lines.append("======")

    lines.append("""
Rapid Embedded Development, Continuous and IDE integration in a few
steps with PlatformIO thanks to built-in project generator for the most
popular embedded boards and IDE.

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by horizontal.
""")

    platforms = {}
    for data in BOARDS:
        platform = data['platform']
        if platform in platforms:
            platforms[platform].append(data)
        else:
            platforms[platform] = [data]

    for platform, boards in sorted(platforms.items()):
        p = PlatformFactory.newPlatform(platform)
        lines.append(p.title)
        lines.append("-" * len(p.title))
        lines.append("""
.. toctree::
    :maxdepth: 1
        """)
        for board in sorted(boards, key=lambda item: item['name']):
            lines.append("    %s/%s" % (platform, board["id"]))
        lines.append("")

    emboards_rst = join(DOCS_ROOT_DIR, "boards", "index.rst")
    with open(emboards_rst, "w") as f:
        f.write("\n".join(lines))

    # individual board page
    for data in BOARDS:
        # if data['id'] != "m5stack-core-esp32":
        #     continue
        rst_path = join(DOCS_ROOT_DIR, "boards", data["platform"],
                        "%s.rst" % data["id"])
        if not isdir(dirname(rst_path)):
            os.makedirs(dirname(rst_path))
        update_embedded_board(rst_path, data)
Beispiel #14
0
def update_boards():
    lines = []

    lines.append(RST_COPYRIGHT)
    lines.append(".. _boards:")
    lines.append("")

    lines.append("Boards")
    lines.append("======")

    lines.append("""
Rapid Embedded Development, Continuous and IDE integration in a few
steps with PlatformIO thanks to built-in project generator for the most
popular embedded boards and IDE.

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by horizontal.
""")

    platforms = {}
    for data in BOARDS:
        platform = data['platform']
        if platform in platforms:
            platforms[platform].append(data)
        else:
            platforms[platform] = [data]

    for platform, boards in sorted(platforms.iteritems()):
        p = PlatformFactory.newPlatform(platform)
        lines.append(p.title)
        lines.append("-" * len(p.title))
        lines.append("""
.. toctree::
    :maxdepth: 1
        """)
        for board in sorted(boards, key=lambda item: item['name']):
            lines.append("    %s/%s" % (platform, board["id"]))
        lines.append("")

    emboards_rst = join(DOCS_ROOT_DIR, "boards", "index.rst")
    with open(emboards_rst, "w") as f:
        f.write("\n".join(lines))

    # individual board page
    for data in BOARDS:
        # if data['id'] != "m5stack-core-esp32":
        #     continue
        rst_path = join(DOCS_ROOT_DIR, "boards", data["platform"],
                        "%s.rst" % data["id"])
        if not isdir(dirname(rst_path)):
            os.makedirs(dirname(rst_path))
        update_embedded_board(rst_path, data)
Beispiel #15
0
def _get_installed_platform_data(platform,
                                 with_boards=True,
                                 expose_packages=True):
    p = PlatformFactory.newPlatform(platform)
    data = dict(
        name=p.name,
        title=p.title,
        description=p.description,
        version=p.version,
        homepage=p.homepage,
        repository=p.repository_url,
        url=p.vendor_url,
        docs=p.docs_url,
        license=p.license,
        forDesktop=not p.is_embedded(),
        frameworks=sorted(p.frameworks.keys() if p.frameworks else []),
        packages=p.packages.keys() if p.packages else [])

    # if dump to API
    # del data['version']
    # return data

    # overwrite VCS version and add extra fields
    manifest = PlatformManager().load_manifest(dirname(p.manifest_path))
    assert manifest
    for key in manifest:
        if key == "version" or key.startswith("__"):
            data[key] = manifest[key]

    if with_boards:
        data['boards'] = [c.get_brief_data() for c in p.get_boards().values()]

    if not data['packages'] or not expose_packages:
        return data

    data['packages'] = []
    installed_pkgs = p.get_installed_packages()
    for name, opts in p.packages.items():
        item = dict(
            name=name,
            type=p.get_package_type(name),
            requirements=opts.get("version"),
            optional=opts.get("optional") is True)
        if name in installed_pkgs:
            for key, value in installed_pkgs[name].items():
                if key not in ("url", "version", "description"):
                    continue
                item[key] = value
                if key == "version":
                    item["originalVersion"] = _original_version(value)
        data['packages'].append(item)

    return data
Beispiel #16
0
def update_examples_readme():
    examples_dir = join(util.get_source_dir(), "..", "examples")

    # Platforms
    embedded = []
    desktop = []
    for manifest in PLATFORM_MANIFESTS:
        p = PlatformFactory.newPlatform(manifest['name'])
        url = campaign_url(
            "http://docs.platformio.org/en/latest/platforms/%s.html#examples" %
            p.name,
            source="github",
            medium="examples")
        line = "* [%s](%s)" % (p.title, url)
        if p.is_embedded():
            embedded.append(line)
        else:
            desktop.append(line)

    # Frameworks
    frameworks = []
    for framework in API_FRAMEWORKS:
        url = campaign_url(
            "http://docs.platformio.org/en/latest/frameworks/%s.html#examples"
            % framework['name'],
            source="github",
            medium="examples")
        frameworks.append("* [%s](%s)" % (framework['title'], url))

    with open(join(examples_dir, "README.md"), "w") as fp:
        fp.write("""# PlatformIO Project Examples

- [Development platforms](#development-platforms):
  - [Embedded](#embedded)
  - [Desktop](#desktop)
- [Frameworks](#frameworks)

## Development platforms

### Embedded

%s

### Desktop

%s

## Frameworks

%s
""" % ("\n".join(embedded), "\n".join(desktop), "\n".join(frameworks)))
Beispiel #17
0
def platform_show(platform):

    def _detail_version(version):
        if version.count(".") != 2:
            return version
        _, y = version.split(".")[:2]
        if int(y) < 100:
            return version
        if len(y) % 2 != 0:
            y = "0" + y
        parts = [str(int(y[i * 2:i * 2 + 2])) for i in range(len(y) / 2)]
        return "%s (%s)" % (version, ".".join(parts))

    try:
        p = PlatformFactory.newPlatform(platform)
    except exception.UnknownPlatform:
        raise exception.PlatformNotInstalledYet(platform)

    click.echo("{name} ~ {title}".format(
        name=click.style(
            p.name, fg="cyan"), title=p.title))
    click.echo("=" * (3 + len(p.name + p.title)))
    click.echo(p.description)
    click.echo()
    click.echo("Version: %s" % p.version)
    if p.homepage:
        click.echo("Home: %s" % p.homepage)
    if p.license:
        click.echo("License: %s" % p.license)
    if p.frameworks:
        click.echo("Frameworks: %s" % ", ".join(p.frameworks.keys()))

    if not p.packages:
        return

    installed_pkgs = p.get_installed_packages()
    for name, opts in p.packages.items():
        click.echo()
        click.echo("Package %s" % click.style(name, fg="yellow"))
        click.echo("-" * (8 + len(name)))
        if p.get_package_type(name):
            click.echo("Type: %s" % p.get_package_type(name))
        click.echo("Requirements: %s" % opts.get("version"))
        click.echo("Installed: %s" % ("Yes" if name in installed_pkgs else
                                      "No (optional)"))
        if name in installed_pkgs:
            for key, value in installed_pkgs[name].items():
                if key in ("url", "version", "description"):
                    if key == "version":
                        value = _detail_version(value)
                    click.echo("%s: %s" % (key.title(), value))
Beispiel #18
0
def update_examples_readme():
    examples_dir = join(util.get_source_dir(), "..", "examples")

    # Platforms
    embedded = []
    desktop = []
    for manifest in PLATFORM_MANIFESTS:
        p = PlatformFactory.newPlatform(manifest['name'])
        url = campaign_url(
            "http://docs.platformio.org/en/latest/platforms/%s.html#examples" %
            p.name,
            source="github",
            medium="examples")
        line = "* [%s](%s)" % (p.title, url)
        if p.is_embedded():
            embedded.append(line)
        else:
            desktop.append(line)

    # Frameworks
    frameworks = []
    for framework in API_FRAMEWORKS:
        url = campaign_url(
            "http://docs.platformio.org/en/latest/frameworks/%s.html#examples"
            % framework['name'],
            source="github",
            medium="examples")
        frameworks.append("* [%s](%s)" % (framework['title'], url))

    with open(join(examples_dir, "README.md"), "w") as fp:
        fp.write("""# PlatformIO Project Examples

- [Development platforms](#development-platforms):
  - [Embedded](#embedded)
  - [Desktop](#desktop)
- [Frameworks](#frameworks)

## Development platforms

### Embedded

%s

### Desktop

%s

## Frameworks

%s
""" % ("\n".join(embedded), "\n".join(desktop), "\n".join(frameworks)))
Beispiel #19
0
def platform_show(platform):
    def _detail_version(version):
        if version.count(".") != 2:
            return version
        _, y = version.split(".")[:2]
        if int(y) < 100:
            return version
        if len(y) % 2 != 0:
            y = "0" + y
        parts = [str(int(y[i * 2:i * 2 + 2])) for i in range(len(y) / 2)]
        return "%s (%s)" % (version, ".".join(parts))

    try:
        p = PlatformFactory.newPlatform(platform)
    except exception.UnknownPlatform:
        raise exception.PlatformNotInstalledYet(platform)

    click.echo("{name} ~ {title}".format(name=click.style(p.name, fg="cyan"),
                                         title=p.title))
    click.echo("=" * (3 + len(p.name + p.title)))
    click.echo(p.description)
    click.echo()
    click.echo("Version: %s" % p.version)
    if p.homepage:
        click.echo("Home: %s" % p.homepage)
    if p.license:
        click.echo("License: %s" % p.license)
    if p.frameworks:
        click.echo("Frameworks: %s" % ", ".join(p.frameworks.keys()))

    if not p.packages:
        return

    installed_pkgs = p.get_installed_packages()
    for name, opts in p.packages.items():
        click.echo()
        click.echo("Package %s" % click.style(name, fg="yellow"))
        click.echo("-" * (8 + len(name)))
        if p.get_package_type(name):
            click.echo("Type: %s" % p.get_package_type(name))
        click.echo("Requirements: %s" % opts.get("version"))
        click.echo("Installed: %s" %
                   ("Yes" if name in installed_pkgs else "No (optional)"))
        if name in installed_pkgs:
            for key, value in installed_pkgs[name].items():
                if key in ("url", "version", "description"):
                    if key == "version":
                        value = _detail_version(value)
                    click.echo("%s: %s" % (key.title(), value))
Beispiel #20
0
    def _run(self):
        if "platform" not in self.options:
            raise exception.UndefinedEnvPlatform(self.name)

        build_vars = self.get_build_variables()
        build_targets = self.get_build_targets()

        telemetry.on_run_environment(self.options, build_targets)

        # skip monitor target, we call it above
        if "monitor" in build_targets:
            build_targets.remove("monitor")
        if "nobuild" not in build_targets:
            # install dependent libraries
            if "lib_install" in self.options:
                _autoinstall_libdeps(self.cmd_ctx, [
                    int(d.strip())
                    for d in self.options['lib_install'].split(",")
                    if d.strip()
                ], self.verbose)
            if "lib_deps" in self.options:
                _autoinstall_libdeps(
                    self.cmd_ctx,
                    util.parse_conf_multi_values(self.options['lib_deps']),
                    self.verbose)

        try:
            p = PlatformFactory.newPlatform(self.options['platform'])
        except exception.UnknownPlatform:
            self.cmd_ctx.invoke(
                cmd_platform_install,
                platforms=[self.options['platform']],
                skip_default_package=True)
            p = PlatformFactory.newPlatform(self.options['platform'])

        return p.run(build_vars, build_targets, self.silent, self.verbose)
Beispiel #21
0
def get_builtin_libs(storage_names=None):
    items = []
    storage_names = storage_names or []
    pm = PlatformManager()
    for manifest in pm.get_installed():
        p = PlatformFactory.newPlatform(manifest['__pkg_dir'])
        for storage in p.get_lib_storages():
            if storage_names and storage['name'] not in storage_names:
                continue
            lm = LibraryManager(storage['path'])
            items.append({
                "name": storage['name'],
                "path": storage['path'],
                "items": lm.get_installed()
            })
    return items
Beispiel #22
0
def get_builtin_libs(storage_names=None):
    items = []
    storage_names = storage_names or []
    pm = PlatformManager()
    for manifest in pm.get_installed():
        p = PlatformFactory.newPlatform(manifest['__pkg_dir'])
        for storage in p.get_lib_storages():
            if storage_names and storage['name'] not in storage_names:
                continue
            lm = LibraryManager(storage['path'])
            items.append({
                "name": storage['name'],
                "path": storage['path'],
                "items": lm.get_installed()
            })
    return items
Beispiel #23
0
def platform_update(  # pylint: disable=too-many-locals
        platforms, only_packages, only_check, dry_run, json_output):
    pm = PlatformManager()
    pkg_dir_to_name = {}
    if not platforms:
        platforms = []
        for manifest in pm.get_installed():
            platforms.append(manifest["__pkg_dir"])
            pkg_dir_to_name[manifest["__pkg_dir"]] = manifest.get(
                "title", manifest["name"])

    only_check = dry_run or only_check

    if only_check and json_output:
        result = []
        for platform in platforms:
            pkg_dir = platform if isdir(platform) else None
            requirements = None
            url = None
            if not pkg_dir:
                name, requirements, url = pm.parse_pkg_uri(platform)
                pkg_dir = pm.get_package_dir(name, requirements, url)
            if not pkg_dir:
                continue
            latest = pm.outdated(pkg_dir, requirements)
            if (not latest and not PlatformFactory.newPlatform(
                    pkg_dir).are_outdated_packages()):
                continue
            data = _get_installed_platform_data(pkg_dir,
                                                with_boards=False,
                                                expose_packages=False)
            if latest:
                data["versionLatest"] = latest
            result.append(data)
        return click.echo(dump_json_to_unicode(result))

    # cleanup cached board and platform lists
    app.clean_cache()
    for platform in platforms:
        click.echo(
            "Platform %s" %
            click.style(pkg_dir_to_name.get(platform, platform), fg="cyan"))
        click.echo("--------")
        pm.update(platform, only_packages=only_packages, only_check=only_check)
        click.echo()

    return True
Beispiel #24
0
def pytest_generate_tests(metafunc):
    if "pioproject_dir" not in metafunc.fixturenames:
        return
    examples_dirs = []

    # repo examples
    examples_dirs.append(normpath(join(dirname(__file__), "..", "examples")))

    # dev/platforms
    for manifest in PlatformManager().get_installed():
        p = PlatformFactory.newPlatform(manifest["__pkg_dir"])
        ignore_conds = [
            not p.is_embedded(),
            p.name == "ststm8",
            # issue with "version `CXXABI_1.3.9' not found (required by sdcc)"
            "linux" in util.get_systype() and p.name == "intel_mcs51",
        ]
        if any(ignore_conds):
            continue
        examples_dir = join(p.get_dir(), "examples")
        assert isdir(examples_dir)
        examples_dirs.append(examples_dir)

    project_dirs = []
    for examples_dir in examples_dirs:
        candidates = {}
        for root, _, files in walk(examples_dir):
            if "platformio.ini" not in files or ".skiptest" in files:
                continue
            if "zephyr-" in root and PY2:
                continue
            group = basename(root)
            if "-" in group:
                group = group.split("-", 1)[0]
            if group not in candidates:
                candidates[group] = []
            candidates[group].append(root)

        project_dirs.extend([
            random.choice(examples) for examples in candidates.values()
            if examples
        ])

    metafunc.parametrize("pioproject_dir", sorted(project_dirs))
Beispiel #25
0
def generate_platforms_contents(platforms):
    if not platforms:
        return []
    lines = []
    lines.append("""
Platforms
---------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")

    for name in sorted(platforms):
        p = PlatformFactory.newPlatform(name)
        lines.append("""
    * - :ref:`platform_{name}`
      - {description}""".format(name=p.name, description=p.description))
    return lines
Beispiel #26
0
def platform_update(platforms, only_packages, only_check, json_output):
    pm = PlatformManager()
    pkg_dir_to_name = {}
    if not platforms:
        platforms = []
        for manifest in pm.get_installed():
            platforms.append(manifest['__pkg_dir'])
            pkg_dir_to_name[manifest['__pkg_dir']] = manifest.get(
                "title", manifest['name'])

    if only_check and json_output:
        result = []
        for platform in platforms:
            pkg_dir = platform if isdir(platform) else None
            requirements = None
            url = None
            if not pkg_dir:
                name, requirements, url = pm.parse_pkg_uri(platform)
                pkg_dir = pm.get_package_dir(name, requirements, url)
            if not pkg_dir:
                continue
            latest = pm.outdated(pkg_dir, requirements)
            if (not latest and not PlatformFactory.newPlatform(
                    pkg_dir).are_outdated_packages()):
                continue
            data = _get_installed_platform_data(
                pkg_dir, with_boards=False, expose_packages=False)
            if latest:
                data['versionLatest'] = latest
            result.append(data)
        return click.echo(json.dumps(result))
    else:
        # cleanup cached board and platform lists
        app.clean_cache()
        for platform in platforms:
            click.echo("Platform %s" % click.style(
                pkg_dir_to_name.get(platform, platform), fg="cyan"))
            click.echo("--------")
            pm.update(
                platform, only_packages=only_packages, only_check=only_check)
            click.echo()

    return True
Beispiel #27
0
def generate_platforms_contents(platforms):
    if not platforms:
        return []
    lines = []
    lines.append("""
Platforms
---------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")

    for name in sorted(platforms):
        p = PlatformFactory.newPlatform(name)
        lines.append("""
    * - :ref:`platform_{name}`
      - {description}""".format(name=p.name, description=p.description))
    return lines
Beispiel #28
0
def platform_update(platforms, only_packages, only_check, json_output):
    pm = PlatformManager()
    pkg_dir_to_name = {}
    if not platforms:
        platforms = []
        for manifest in pm.get_installed():
            platforms.append(manifest['__pkg_dir'])
            pkg_dir_to_name[manifest['__pkg_dir']] = manifest.get(
                "title", manifest['name'])

    if only_check and json_output:
        result = []
        for platform in platforms:
            pkg_dir = platform if isdir(platform) else None
            requirements = None
            url = None
            if not pkg_dir:
                name, requirements, url = pm.parse_pkg_input(platform)
                pkg_dir = pm.get_package_dir(name, requirements, url)
            if not pkg_dir:
                continue
            latest = pm.outdated(pkg_dir, requirements)
            if (not latest and not PlatformFactory.newPlatform(
                    pkg_dir).are_outdated_packages()):
                continue
            data = _get_installed_platform_data(pkg_dir,
                                                with_boards=False,
                                                expose_packages=False)
            if latest:
                data['versionLatest'] = latest
            result.append(data)
        return click.echo(json.dumps(result))
    else:
        # cleanup cached board and platform lists
        app.clean_cache()
        for platform in platforms:
            click.echo("Platform %s" % click.style(
                pkg_dir_to_name.get(platform, platform), fg="cyan"))
            click.echo("--------")
            pm.update(platform,
                      only_packages=only_packages,
                      only_check=only_check)
            click.echo()
Beispiel #29
0
def platform_list(json_output):
    platforms = []
    pm = PlatformManager()
    for manifest in pm.get_installed():
        p = PlatformFactory.newPlatform(
            pm.get_manifest_path(manifest['__pkg_dir']))
        platforms.append({
            "name": p.name,
            "title": p.title,
            "description": p.description,
            "version": p.version,
            "url": p.vendor_url,
            "packages": p.get_installed_packages().keys(),
            'forDesktop': any([
                p.name.startswith(n) for n in ("native", "linux", "windows")
            ])
        })

    if json_output:
        click.echo(json.dumps(platforms))
    else:
        _print_platforms(platforms)
def platform_show(platform):
    try:
        p = PlatformFactory.newPlatform(platform)
    except exception.UnknownPlatform:
        raise exception.PlatformNotInstalledYet(platform)

    click.echo("{name} ~ {title}".format(
        name=click.style(
            p.name, fg="cyan"), title=p.title))
    click.echo("=" * (3 + len(p.name + p.title)))
    click.echo(p.description)
    click.echo()
    click.echo("Version: %s" % p.version)
    if p.homepage:
        click.echo("Home: %s" % p.homepage)
    if p.license:
        click.echo("License: %s" % p.license)
    if p.frameworks:
        click.echo("Frameworks: %s" % ", ".join(p.frameworks.keys()))

    if not p.packages:
        return

    installed_pkgs = p.get_installed_packages()
    for name, opts in p.packages.items():
        click.echo()
        click.echo("Package %s" % click.style(name, fg="yellow"))
        click.echo("-" * (8 + len(name)))
        if p.get_package_type(name):
            click.echo("Type: %s" % p.get_package_type(name))
        click.echo("Requirements: %s" % opts.get("version"))
        click.echo("Installed: %s" % ("Yes" if name in installed_pkgs else
                                      "No (optional)"))
        if name in installed_pkgs:
            for key, value in installed_pkgs[name].items():
                if key in ("url", "version", "description"):
                    click.echo("%s: %s" % (key.title(), value))
Beispiel #31
0
    def get_test_port(self):
        # if test port is specified manually or in config
        if self.options.get("test_port"):
            return self.options.get("test_port")
        if self.env_options.get("test_port"):
            return self.env_options.get("test_port")

        assert set(["platform", "board"]) & set(self.env_options.keys())
        p = PlatformFactory.newPlatform(self.env_options['platform'])
        board_hwids = p.board_config(self.env_options['board']).get(
            "build.hwids", [])
        port = None
        elapsed = 0
        while elapsed < 5 and not port:
            for item in util.get_serialports():
                port = item['port']
                for hwid in board_hwids:
                    hwid_str = ("%s:%s" % (hwid[0], hwid[1])).replace("0x", "")
                    if hwid_str in item['hwid']:
                        return port

            # check if port is already configured
            try:
                serial.Serial(port, timeout=self.SERIAL_TIMEOUT).close()
            except serial.SerialException:
                port = None

            if not port:
                sleep(0.25)
                elapsed += 0.25

        if not port:
            raise exception.PlatformioException(
                "Please specify `test_port` for environment or use "
                "global `--test-port` option.")
        return port
Beispiel #32
0
def pytest_generate_tests(metafunc):
    if "pioproject_dir" not in metafunc.fixturenames:
        return
    examples_dirs = []

    # repo examples
    examples_dirs.append(normpath(join(dirname(__file__), "..", "examples")))

    # dev/platforms
    for manifest in PlatformManager().get_installed():
        p = PlatformFactory.newPlatform(manifest["__pkg_dir"])
        examples_dir = join(p.get_dir(), "examples")
        assert isdir(examples_dir)
        examples_dirs.append(examples_dir)

    project_dirs = []
    for examples_dir in examples_dirs:
        candidates = {}
        for root, _, files in walk(examples_dir):
            if "platformio.ini" not in files or ".skiptest" in files:
                continue
            if "zephyr-" in root and PY2:
                continue
            group = basename(root)
            if "-" in group:
                group = group.split("-", 1)[0]
            if group not in candidates:
                candidates[group] = []
            candidates[group].append(root)

        project_dirs.extend([
            random.choice(examples) for examples in candidates.values()
            if examples
        ])

    metafunc.parametrize("pioproject_dir", sorted(project_dirs))
Beispiel #33
0
def generate_framework(type_, data, rst_dir=None):
    print "Processing framework: %s" % type_

    compatible_platforms = [
        m for m in PLATFORM_MANIFESTS
        if is_compat_platform_and_framework(m['name'], type_)
    ]
    compatible_boards = [
        board for board in BOARDS if type_ in board['frameworks']
    ]

    lines = []

    lines.append(RST_COPYRIGHT)
    lines.append(".. _framework_%s:" % type_)
    lines.append("")

    lines.append(data['title'])
    lines.append("=" * len(data['title']))
    lines.append("")
    lines.append(":Configuration:")
    lines.append("  :ref:`projectconf_env_framework` = ``%s``" % type_)
    lines.append("")
    lines.append(data['description'])
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.
""" % campaign_url(data['url']))

    lines.append("""
.. contents:: Contents
    :local:
    :depth: 1""")

    # Extra
    if isfile(join(rst_dir, "%s_extra.rst" % type_)):
        lines.append(".. include:: %s_extra.rst" % type_)

    #
    # Debugging
    #
    if compatible_boards:
        lines.extend(
            generate_debug_contents(
                compatible_boards,
                extra_rst="%s_debug.rst" % type_ if isfile(
                    join(rst_dir, "%s_debug.rst" % type_)) else None))

    if compatible_platforms:
        # examples
        lines.append("""
Examples
--------
""")
        for manifest in compatible_platforms:
            p = PlatformFactory.newPlatform(manifest['name'])
            lines.append(
                "* `%s for %s <%s>`_" %
                (data['title'], manifest['title'],
                 campaign_url(
                     "%s/tree/master/examples" % p.repository_url[:-4])))

        # Platforms
        lines.extend(
            generate_platforms_contents(
                [manifest['name'] for manifest in compatible_platforms]))

    #
    # Boards
    #
    if compatible_boards:
        vendors = {}
        for board in compatible_boards:
            if board['vendor'] not in vendors:
                vendors[board['vendor']] = []
            vendors[board['vendor']].append(board)
        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by horizontal.
""")
        for vendor, boards in sorted(vendors.items()):
            lines.append(str(vendor))
            lines.append("~" * len(vendor))
            lines.extend(generate_boards_table(boards))
    return "\n".join(lines)
Beispiel #34
0
def check_internal_updates(ctx, what):
    last_check = app.get_state_item("last_check", {})
    interval = int(app.get_setting("check_%s_interval" % what)) * 3600 * 24
    if (time() - interval) < last_check.get(what + "_update", 0):
        return

    last_check[what + '_update'] = int(time())
    app.set_state_item("last_check", last_check)

    util.internet_on(raise_exception=True)

    pm = PlatformManager() if what == "platforms" else LibraryManager()
    outdated_items = []
    for manifest in pm.get_installed():
        if manifest['name'] in outdated_items:
            continue
        conds = [
            pm.outdated(manifest['__pkg_dir']), what == "platforms"
            and PlatformFactory.newPlatform(
                manifest['__pkg_dir']).are_outdated_packages()
        ]
        if any(conds):
            outdated_items.append(manifest['name'])

    if not outdated_items:
        return

    terminal_width, _ = click.get_terminal_size()

    click.echo("")
    click.echo("*" * terminal_width)
    click.secho(
        "There are the new updates for %s (%s)" % (what,
                                                   ", ".join(outdated_items)),
        fg="yellow")

    if not app.get_setting("auto_update_" + what):
        click.secho("Please update them via ", fg="yellow", nl=False)
        click.secho(
            "`platformio %s update`" %
            ("lib --global" if what == "libraries" else "platform"),
            fg="cyan",
            nl=False)
        click.secho(" command.\n", fg="yellow")
        click.secho(
            "If you want to manually check for the new versions "
            "without updating, please use ",
            fg="yellow",
            nl=False)
        click.secho(
            "`platformio %s update --only-check`" %
            ("lib --global" if what == "libraries" else "platform"),
            fg="cyan",
            nl=False)
        click.secho(" command.", fg="yellow")
    else:
        click.secho("Please wait while updating %s ..." % what, fg="yellow")
        if what == "platforms":
            ctx.invoke(cmd_platform_update, platforms=outdated_items)
        elif what == "libraries":
            ctx.obj = pm
            ctx.invoke(cmd_lib_update, libraries=outdated_items)
        click.echo()

        telemetry.on_event(
            category="Auto", action="Update", label=what.title())

    click.echo("*" * terminal_width)
    click.echo("")
Beispiel #35
0
def update_embedded_board(rst_path, board):
    platform = PlatformFactory.newPlatform(board['platform'])
    board_config = platform.board_config(board['id'])

    board_manifest_url = platform.repository_url
    assert board_manifest_url
    if board_manifest_url.endswith(".git"):
        board_manifest_url = board_manifest_url[:-4]
    board_manifest_url += "/blob/master/boards/%s.json" % board['id']

    variables = dict(
        id=board['id'],
        name=board['name'],
        platform=board['platform'],
        platform_description=platform.description,
        url=campaign_url(board['url']),
        mcu=board_config.get("build", {}).get("mcu", ""),
        mcu_upper=board['mcu'].upper(),
        f_cpu=board['fcpu'],
        f_cpu_mhz=int(board['fcpu']) / 1000000,
        ram=util.format_filesize(board['ram']),
        rom=util.format_filesize(board['rom']),
        vendor=board['vendor'],
        board_manifest_url=board_manifest_url,
        upload_protocol=board_config.get("upload.protocol", ""))

    lines = [RST_COPYRIGHT]
    lines.append(".. _board_{platform}_{id}:".format(**variables))
    lines.append("")
    lines.append(board['name'])
    lines.append("=" * len(board['name']))
    lines.append("""
.. contents::

Hardware
--------

Platform :ref:`platform_{platform}`: {platform_description}

.. list-table::

  * - **Microcontroller**
    - {mcu_upper}
  * - **Frequency**
    - {f_cpu_mhz}MHz
  * - **Flash**
    - {rom}
  * - **RAM**
    - {ram}
  * - **Vendor**
    - `{vendor} <{url}>`__
""".format(**variables))

    #
    # Configuration
    #
    lines.append("""
Configuration
-------------

Please use ``{id}`` ID for :ref:`projectconf_env_board` option in :ref:`projectconf`:

.. code-block:: ini

  [env:{id}]
  platform = {platform}
  board = {id}

You can override default {name} settings per build environment using
``board_***`` option, where ``***`` is a JSON object path from
board manifest `{id}.json <{board_manifest_url}>`_. For example,
``board_build.mcu``, ``board_build.f_cpu``, etc.

.. code-block:: ini

  [env:{id}]
  platform = {platform}
  board = {id}

  ; change microcontroller
  board_build.mcu = {mcu}

  ; change MCU frequency
  board_build.f_cpu = {f_cpu}L
""".format(**variables))

    #
    # Uploading
    #
    upload_protocols = board_config.get("upload.protocols", [])
    if len(upload_protocols) > 1:
        lines.append("""
Uploading
---------
%s supports the next uploading protocols:
""" % board['name'])
        for protocol in upload_protocols:
            lines.append("* ``%s``" % protocol)
        lines.append("""
Default protocol is ``%s``""" % variables['upload_protocol'])
        lines.append("""
You can change upload protocol using :ref:`projectconf_upload_protocol` option:

.. code-block:: ini

  [env:{id}]
  platform = {platform}
  board = {id}

  upload_protocol = {upload_protocol}
""".format(**variables))

    #
    # Debugging
    #
    lines.append("Debugging")
    lines.append("---------")
    if not board['debug']:
        lines.append(
            ":ref:`piodebug` currently does not support {name} board.".format(
                **variables))
    else:
        default_debug_tool = board_config.get_debug_tool_name()
        has_onboard_debug = any(
            t.get("onboard") for (_, t) in board['debug']['tools'].items())
        lines.append("""
:ref:`piodebug` - "1-click" solution for debugging with a zero configuration.

.. warning::
    You will need to install debug tool drivers depending on your system.
    Please click on compatible debug tool below for the further
    instructions and configuration information.

You can switch between debugging :ref:`debugging_tools` using
:ref:`projectconf_debug_tool` option in :ref:`projectconf`.
""")
        if has_onboard_debug:
            lines.append(
                "{name} has on-board debug probe and **IS READY** for "
                "debugging. You don't need to use/buy external debug probe.".
                format(**variables))
        else:
            lines.append(
                "{name} does not have on-board debug probe and **IS NOT "
                "READY** for debugging. You will need to use/buy one of "
                "external probe listed below.".format(**variables))
        lines.append("""
.. list-table::
  :header-rows:  1

  * - Compatible Tools
    - On-board
    - Default""")
        for (tool_name, tool_data) in sorted(board['debug']['tools'].items()):
            lines.append("""  * - :ref:`debugging_tool_{name}`
    - {onboard}
    - {default}""".format(
                name=tool_name,
                onboard="Yes" if tool_data.get("onboard") else "",
                default="Yes" if tool_name == default_debug_tool else ""))

    if board['frameworks']:
        lines.extend(generate_frameworks_contents(board['frameworks']))

    with open(rst_path, "w") as f:
        f.write("\n".join(lines))
Beispiel #36
0
def update_project_examples():
    platform_readme_tpl = """
# {title}: development platform for [PlatformIO](https://platformio.org)

{description}

* [Home](https://platformio.org/platforms/{name}) (home page in PlatformIO Registry)
* [Documentation](https://docs.platformio.org/page/platforms/{name}.html) (advanced usage, packages, boards, frameworks, etc.)

# Examples

{examples}
"""
    framework_readme_tpl = """
# {title}: framework for [PlatformIO](https://platformio.org)

{description}

* [Home](https://platformio.org/frameworks/{name}) (home page in PlatformIO Registry)
* [Documentation](https://docs.platformio.org/page/frameworks/{name}.html)

# Examples

{examples}
"""

    project_examples_dir = join(fs.get_source_dir(), "..", "examples")
    framework_examples_md_lines = {}
    embedded = []
    desktop = []

    for manifest in PLATFORM_MANIFESTS:
        p = PlatformFactory.newPlatform(manifest['name'])
        github_url = p.repository_url[:-4]

        # Platform README
        platform_examples_dir = join(p.get_dir(), "examples")
        examples_md_lines = []
        if isdir(platform_examples_dir):
            for item in sorted(os.listdir(platform_examples_dir)):
                example_dir = join(platform_examples_dir, item)
                if not isdir(example_dir) or not os.listdir(example_dir):
                    continue
                url = "%s/tree/master/examples/%s" % (github_url, item)
                examples_md_lines.append("* [%s](%s)" % (item, url))

        readme_dir = join(project_examples_dir, "platforms", p.name)
        if not isdir(readme_dir):
            os.makedirs(readme_dir)
        with open(join(readme_dir, "README.md"), "w") as fp:
            fp.write(
                platform_readme_tpl.format(
                    name=p.name,
                    title=p.title,
                    description=p.description,
                    examples="\n".join(examples_md_lines)))

        # Framework README
        for framework in API_FRAMEWORKS:
            if not is_compat_platform_and_framework(p.name, framework['name']):
                continue
            if framework['name'] not in framework_examples_md_lines:
                framework_examples_md_lines[framework['name']] = []
            lines = []
            lines.append("- [%s](%s)" % (p.title, github_url))
            lines.extend("  %s" % l for l in examples_md_lines)
            lines.append("")
            framework_examples_md_lines[framework['name']].extend(lines)

        # Root README
        line = "* [%s](%s)" % (p.title, "%s/tree/master/examples" % github_url)
        if p.is_embedded():
            embedded.append(line)
        else:
            desktop.append(line)

    # Frameworks
    frameworks = []
    for framework in API_FRAMEWORKS:
        readme_dir = join(project_examples_dir, "frameworks",
                          framework['name'])
        if not isdir(readme_dir):
            os.makedirs(readme_dir)
        with open(join(readme_dir, "README.md"), "w") as fp:
            fp.write(
                framework_readme_tpl.format(
                    name=framework['name'],
                    title=framework['title'],
                    description=framework['description'],
                    examples="\n".join(
                        framework_examples_md_lines[framework['name']])))
        url = campaign_url(
            "https://docs.platformio.org/en/latest/frameworks/%s.html#examples"
            % framework['name'],
            source="github",
            medium="examples")
        frameworks.append("* [%s](%s)" % (framework['title'], url))

    with open(join(project_examples_dir, "README.md"), "w") as fp:
        fp.write("""# PlatformIO Project Examples

- [Development platforms](#development-platforms):
  - [Embedded](#embedded)
  - [Desktop](#desktop)
- [Frameworks](#frameworks)

## Development platforms

### Embedded

%s

### Desktop

%s

## Frameworks

%s
""" % ("\n".join(embedded), "\n".join(desktop), "\n".join(frameworks)))
Beispiel #37
0
def update_embedded_board(rst_path, board):
    platform = PlatformFactory.newPlatform(board['platform'])
    board_config = platform.board_config(board['id'])

    board_manifest_url = platform.repository_url
    assert board_manifest_url
    if board_manifest_url.endswith(".git"):
        board_manifest_url = board_manifest_url[:-4]
    board_manifest_url += "/blob/master/boards/%s.json" % board['id']

    variables = dict(id=board['id'],
                     name=board['name'],
                     platform=board['platform'],
                     platform_description=platform.description,
                     url=campaign_url(board['url']),
                     mcu=board_config.get("build", {}).get("mcu", ""),
                     mcu_upper=board['mcu'].upper(),
                     f_cpu=board['fcpu'],
                     f_cpu_mhz=int(int(board['fcpu']) / 1000000),
                     ram=fs.format_filesize(board['ram']),
                     rom=fs.format_filesize(board['rom']),
                     vendor=board['vendor'],
                     board_manifest_url=board_manifest_url,
                     upload_protocol=board_config.get("upload.protocol", ""))

    lines = [RST_COPYRIGHT]
    lines.append(".. _board_{platform}_{id}:".format(**variables))
    lines.append("")
    lines.append(board['name'])
    lines.append("=" * len(board['name']))
    lines.append("""
.. contents::

Hardware
--------

Platform :ref:`platform_{platform}`: {platform_description}

.. list-table::

  * - **Microcontroller**
    - {mcu_upper}
  * - **Frequency**
    - {f_cpu_mhz:d}MHz
  * - **Flash**
    - {rom}
  * - **RAM**
    - {ram}
  * - **Vendor**
    - `{vendor} <{url}>`__
""".format(**variables))

    #
    # Configuration
    #
    lines.append("""
Configuration
-------------

Please use ``{id}`` ID for :ref:`projectconf_env_board` option in :ref:`projectconf`:

.. code-block:: ini

  [env:{id}]
  platform = {platform}
  board = {id}

You can override default {name} settings per build environment using
``board_***`` option, where ``***`` is a JSON object path from
board manifest `{id}.json <{board_manifest_url}>`_. For example,
``board_build.mcu``, ``board_build.f_cpu``, etc.

.. code-block:: ini

  [env:{id}]
  platform = {platform}
  board = {id}

  ; change microcontroller
  board_build.mcu = {mcu}

  ; change MCU frequency
  board_build.f_cpu = {f_cpu}L
""".format(**variables))

    #
    # Uploading
    #
    upload_protocols = board_config.get("upload.protocols", [])
    if len(upload_protocols) > 1:
        lines.append("""
Uploading
---------
%s supports the next uploading protocols:
""" % board['name'])
        for protocol in sorted(upload_protocols):
            lines.append("* ``%s``" % protocol)
        lines.append("""
Default protocol is ``%s``""" % variables['upload_protocol'])
        lines.append("""
You can change upload protocol using :ref:`projectconf_upload_protocol` option:

.. code-block:: ini

  [env:{id}]
  platform = {platform}
  board = {id}

  upload_protocol = {upload_protocol}
""".format(**variables))

    #
    # Debugging
    #
    lines.append("Debugging")
    lines.append("---------")
    if not board['debug']:
        lines.append(
            ":ref:`piodebug` currently does not support {name} board.".format(
                **variables))
    else:
        default_debug_tool = board_config.get_debug_tool_name()
        has_onboard_debug = any(
            t.get("onboard") for (_, t) in board['debug']['tools'].items())
        lines.append("""
:ref:`piodebug` - "1-click" solution for debugging with a zero configuration.

.. warning::
    You will need to install debug tool drivers depending on your system.
    Please click on compatible debug tool below for the further
    instructions and configuration information.

You can switch between debugging :ref:`debugging_tools` using
:ref:`projectconf_debug_tool` option in :ref:`projectconf`.
""")
        if has_onboard_debug:
            lines.append(
                "{name} has on-board debug probe and **IS READY** for "
                "debugging. You don't need to use/buy external debug probe.".
                format(**variables))
        else:
            lines.append(
                "{name} does not have on-board debug probe and **IS NOT "
                "READY** for debugging. You will need to use/buy one of "
                "external probe listed below.".format(**variables))
        lines.append("""
.. list-table::
  :header-rows:  1

  * - Compatible Tools
    - On-board
    - Default""")
        for (tool_name, tool_data) in sorted(board['debug']['tools'].items()):
            lines.append("""  * - :ref:`debugging_tool_{name}`
    - {onboard}
    - {default}""".format(
                name=tool_name,
                onboard="Yes" if tool_data.get("onboard") else "",
                default="Yes" if tool_name == default_debug_tool else ""))

    if board['frameworks']:
        lines.extend(generate_frameworks_contents(board['frameworks']))

    with open(rst_path, "w") as f:
        f.write("\n".join(lines))
Beispiel #38
0
def generate_framework(type_, data):
    print "Processing framework: %s" % type_
    lines = []

    lines.append(
        """..  Copyright 2014-present PlatformIO <*****@*****.**>
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
""")

    lines.append(".. _framework_%s:" % type_)
    lines.append("")

    _title = "Framework ``%s``" % type_
    lines.append(_title)
    lines.append("=" * len(_title))
    lines.append(data['description'])
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.
""" % data['url'])

    lines.append(".. contents::")

    lines.append("""
Platforms
---------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")

    _found_platform = False
    for manifest in PLATFORM_MANIFESTS:
        if not is_compat_platform_and_framework(manifest['name'], type_):
            continue
        _found_platform = True
        p = PlatformFactory.newPlatform(manifest['name'])
        lines.append("""
    * - :ref:`platform_{type_}`
      - {description}""".format(
            type_=manifest['name'], description=p.description))
    if not _found_platform:
        del lines[-1]

    lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <http://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by horizontal.
""")

    vendors = {}
    for data in BOARDS:
        frameworks = data['frameworks']
        vendor = data['vendor']
        if type_ in frameworks:
            if vendor in vendors:
                vendors[vendor].append(data)
            else:
                vendors[vendor] = [data]
    for vendor, boards in sorted(vendors.iteritems()):
        lines.append(str(vendor))
        lines.append("~" * len(vendor))
        lines.append(generate_boards(boards))
    return "\n".join(lines)
Beispiel #39
0
def update_debugging():
    vendors = {}
    platforms = []
    frameworks = []
    for data in BOARDS:
        if not data['debug']:
            continue
        platforms.append(data['platform'])
        frameworks.extend(data['frameworks'])
        vendor = data['vendor']
        if vendor in vendors:
            vendors[vendor].append(data)
        else:
            vendors[vendor] = [data]

    lines = []
    # Platforms
    lines.append(""".. _debugging_platforms:

Platforms
---------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")

    for manifest in PLATFORM_MANIFESTS:
        if manifest['name'] not in platforms:
            continue
        p = PlatformFactory.newPlatform(manifest['name'])
        lines.append("""
    * - :ref:`platform_{type_}`
      - {description}""".format(
            type_=manifest['name'], description=p.description))

    # Frameworks
    lines.append("""
Frameworks
----------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")
    for framework in API_FRAMEWORKS:
        if framework['name'] not in frameworks:
            continue
        lines.append("""
    * - :ref:`framework_{name}`
      - {description}""".format(**framework))

    # Boards
    lines.append("""
Boards
------

.. note::
    For more detailed ``board`` information please scroll tables below by horizontal.
""")
    for vendor, boards in sorted(vendors.iteritems()):
        lines.append(str(vendor))
        lines.append("~" * len(vendor))
        lines.extend(generate_boards(boards, extend_debug=True))

    with open(
            join(util.get_source_dir(), "..", "docs", "plus", "debugging.rst"),
            "r+") as fp:
        content = fp.read()
        fp.seek(0)
        fp.truncate()
        fp.write(content[:content.index(".. _debugging_platforms:")] +
                 "\n".join(lines))
Beispiel #40
0
def validate_debug_options(cmd_ctx, env_options):
    def _cleanup_cmds(items):
        items = ProjectConfig.parse_multi_values(items)
        return [
            "$LOAD_CMDS" if item == "$LOAD_CMD" else item for item in items
        ]

    try:
        platform = PlatformFactory.newPlatform(env_options['platform'])
    except exception.UnknownPlatform:
        cmd_ctx.invoke(cmd_platform_install,
                       platforms=[env_options['platform']],
                       skip_default_package=True)
        platform = PlatformFactory.newPlatform(env_options['platform'])

    board_config = platform.board_config(env_options['board'])
    tool_name = board_config.get_debug_tool_name(env_options.get("debug_tool"))
    tool_settings = board_config.get("debug", {}).get("tools",
                                                      {}).get(tool_name, {})
    server_options = None

    # specific server per a system
    if isinstance(tool_settings.get("server", {}), list):
        for item in tool_settings['server'][:]:
            tool_settings['server'] = item
            if util.get_systype() in item.get("system", []):
                break

    # user overwrites debug server
    if env_options.get("debug_server"):
        server_options = {
            "cwd": None,
            "executable": None,
            "arguments": env_options.get("debug_server")
        }
        server_options['executable'] = server_options['arguments'][0]
        server_options['arguments'] = server_options['arguments'][1:]
    elif "server" in tool_settings:
        server_package = tool_settings['server'].get("package")
        server_package_dir = platform.get_package_dir(
            server_package) if server_package else None
        if server_package and not server_package_dir:
            platform.install_packages(with_packages=[server_package],
                                      skip_default_package=True,
                                      silent=True)
            server_package_dir = platform.get_package_dir(server_package)
        server_options = dict(
            cwd=server_package_dir if server_package else None,
            executable=tool_settings['server'].get("executable"),
            arguments=[
                a.replace("$PACKAGE_DIR", escape_path(server_package_dir))
                if server_package_dir else a
                for a in tool_settings['server'].get("arguments", [])
            ])

    extra_cmds = _cleanup_cmds(env_options.get("debug_extra_cmds"))
    extra_cmds.extend(_cleanup_cmds(tool_settings.get("extra_cmds")))
    result = dict(
        tool=tool_name,
        upload_protocol=env_options.get(
            "upload_protocol",
            board_config.get("upload", {}).get("protocol")),
        load_cmds=_cleanup_cmds(
            env_options.get(
                "debug_load_cmds",
                tool_settings.get("load_cmds",
                                  tool_settings.get("load_cmd", "load")))),
        load_mode=env_options.get("debug_load_mode",
                                  tool_settings.get("load_mode", "always")),
        init_break=env_options.get(
            "debug_init_break", tool_settings.get("init_break",
                                                  "tbreak main")),
        init_cmds=_cleanup_cmds(
            env_options.get("debug_init_cmds",
                            tool_settings.get("init_cmds"))),
        extra_cmds=extra_cmds,
        require_debug_port=tool_settings.get("require_debug_port", False),
        port=reveal_debug_port(
            env_options.get("debug_port", tool_settings.get("port")),
            tool_name, tool_settings),
        server=server_options)
    return result
Beispiel #41
0
def initPioPlatform(name):
    return PlatformFactory.newPlatform(name)
Beispiel #42
0
def device_monitor(**kwargs):  # pylint: disable=too-many-branches
    # load default monitor filters
    filters_dir = os.path.join(fs.get_source_dir(), "commands", "device", "filters")
    for name in os.listdir(filters_dir):
        if not name.endswith(".py"):
            continue
        device_helpers.load_monitor_filter(os.path.join(filters_dir, name))

    project_options = {}
    try:
        with fs.cd(kwargs["project_dir"]):
            project_options = device_helpers.get_project_options(kwargs["environment"])
        kwargs = device_helpers.apply_project_monitor_options(kwargs, project_options)
    except NotPlatformIOProjectError:
        pass

    platform = None
    if "platform" in project_options:
        with fs.cd(kwargs["project_dir"]):
            platform = PlatformFactory.newPlatform(project_options["platform"])
            device_helpers.register_platform_filters(
                platform, kwargs["project_dir"], kwargs["environment"]
            )

    if not kwargs["port"]:
        ports = util.get_serial_ports(filter_hwid=True)
        if len(ports) == 1:
            kwargs["port"] = ports[0]["port"]
        elif "platform" in project_options and "board" in project_options:
            board_hwids = device_helpers.get_board_hwids(
                kwargs["project_dir"], platform, project_options["board"],
            )
            for item in ports:
                for hwid in board_hwids:
                    hwid_str = ("%s:%s" % (hwid[0], hwid[1])).replace("0x", "")
                    if hwid_str in item["hwid"]:
                        kwargs["port"] = item["port"]
                        break
                if kwargs["port"]:
                    break
    elif kwargs["port"] and (set(["*", "?", "[", "]"]) & set(kwargs["port"])):
        for item in util.get_serial_ports():
            if fnmatch(item["port"], kwargs["port"]):
                kwargs["port"] = item["port"]
                break

    # override system argv with patched options
    sys.argv = ["monitor"] + device_helpers.options_to_argv(
        kwargs,
        project_options,
        ignore=("port", "baud", "rts", "dtr", "environment", "project_dir"),
    )

    if not kwargs["quiet"]:
        click.echo(
            "--- Available filters and text transformations: %s"
            % ", ".join(sorted(miniterm.TRANSFORMATIONS.keys()))
        )
        click.echo("--- More details at http://bit.ly/pio-monitor-filters")
    try:
        miniterm.main(
            default_port=kwargs["port"],
            default_baudrate=kwargs["baud"] or 9600,
            default_rts=kwargs["rts"],
            default_dtr=kwargs["dtr"],
        )
    except Exception as e:
        raise exception.MinitermException(e)
Beispiel #43
0
def generate_platform(name, has_extra=False):
    print "Processing platform: %s" % name

    compatible_boards = [
        board for board in BOARDS if name in board['platform']
    ]

    lines = []

    lines.append(
        """..  Copyright (c) 2014-present PlatformIO <*****@*****.**>
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
""")
    p = PlatformFactory.newPlatform(name)

    lines.append(".. _platform_%s:" % p.name)
    lines.append("")

    lines.append(p.title)
    lines.append("=" * len(p.title))
    lines.append(":ref:`projectconf_env_platform` = ``%s``" % p.name)
    lines.append("")
    lines.append(p.description)
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.""" %
                 campaign_url(p.vendor_url))
    lines.append("""
.. contents:: Contents
    :local:
    :depth: 1
""")

    #
    # Extra
    #
    if has_extra:
        lines.append(".. include:: %s_extra.rst" % p.name)

    #
    # Examples
    #
    lines.append("""
Examples
--------

Examples are listed from `%s development platform repository <%s>`_:
""" % (p.title,
       campaign_url(
           "https://github.com/platformio/platform-%s/tree/develop/examples" %
           p.name)))
    examples_dir = join(p.get_dir(), "examples")
    if isdir(examples_dir):
        for eitem in os.listdir(examples_dir):
            if not isdir(join(examples_dir, eitem)):
                continue
            url = ("https://github.com/platformio/platform-%s"
                   "/tree/develop/examples/%s" % (p.name, eitem))
            lines.append("* `%s <%s>`_" % (eitem, campaign_url(url)))

    #
    # Debugging
    #
    if compatible_boards:
        lines.extend(
            generate_debug_boards(
                compatible_boards, skip_columns=["Platform"]))

    #
    # Development version of dev/platform
    #
    lines.append("""
Stable and upstream versions
----------------------------

You can switch between `stable releases <https://github.com/platformio/platform-{name}/releases>`__
of {title} development platform and the latest upstream version using
:ref:`projectconf_env_platform` option as described below:

.. code-block:: ini

    ; Custom stable version
    [env:stable]
    platform ={name}@x.y.z
    board = ...
    ...

    ; The latest upstream/development version
    [env:upstream]
    platform = https://github.com/platformio/platform-{name}.git
    board = ...
    ...
""".format(name=p.name, title=p.title))

    #
    # Packages
    #
    _packages_content = generate_packages(name, p.packages.keys(),
                                          p.is_embedded())
    if _packages_content:
        lines.append(_packages_content)

    #
    # Frameworks
    #
    _frameworks_lines = []
    for framework in API_FRAMEWORKS:
        if not is_compat_platform_and_framework(name, framework['name']):
            continue
        _frameworks_lines.append("""
    * - :ref:`framework_{name}`
      - {description}""".format(**framework))

    if _frameworks_lines:
        lines.append("""
Frameworks
----------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")
        lines.extend(_frameworks_lines)

    #
    # Boards
    #
    if compatible_boards:
        vendors = {}
        for board in compatible_boards:
            if board['vendor'] not in vendors:
                vendors[board['vendor']] = []
            vendors[board['vendor']].append(board)

        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by
      horizontal.
""")

        for vendor, boards in sorted(vendors.items()):
            lines.append(str(vendor))
            lines.append("~" * len(vendor))
            lines.extend(generate_boards(boards, skip_columns=["Platform"]))

    return "\n".join(lines)
Beispiel #44
0
def generate_framework(type_, data, has_extra=False):
    print "Processing framework: %s" % type_

    compatible_platforms = [
        m for m in PLATFORM_MANIFESTS
        if is_compat_platform_and_framework(m['name'], type_)
    ]
    compatible_boards = [
        board for board in BOARDS if type_ in board['frameworks']
    ]

    lines = []

    lines.append(
        """..  Copyright (c) 2014-present PlatformIO <*****@*****.**>
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
""")

    lines.append(".. _framework_%s:" % type_)
    lines.append("")

    lines.append(data['title'])
    lines.append("=" * len(data['title']))
    lines.append(":ref:`projectconf_env_framework` = ``%s``" % type_)
    lines.append("")
    lines.append(data['description'])
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.
""" % campaign_url(data['url']))

    lines.append("""
.. contents:: Contents
    :local:
    :depth: 1""")

    # Extra
    if has_extra:
        lines.append(".. include:: %s_extra.rst" % type_)

    #
    # Debugging
    #
    if compatible_boards:
        lines.extend(generate_debug_boards(compatible_boards))

    if compatible_platforms:
        # examples
        lines.append("""
Examples
--------
""")
        for manifest in compatible_platforms:
            lines.append("* `%s for %s <%s>`_" % (
                data['title'], manifest['title'],
                campaign_url(
                    "https://github.com/platformio/platform-%s/tree/develop/examples"
                    % manifest['name'])))

        # Platforms
        lines.append("""
Platforms
---------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")

        for manifest in compatible_platforms:
            p = PlatformFactory.newPlatform(manifest['name'])
            lines.append("""
    * - :ref:`platform_{type_}`
      - {description}""".format(
                type_=manifest['name'], description=p.description))

    #
    # Boards
    #
    if compatible_boards:
        vendors = {}
        for board in compatible_boards:
            if board['vendor'] not in vendors:
                vendors[board['vendor']] = []
            vendors[board['vendor']].append(board)
        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by horizontal.
""")
        for vendor, boards in sorted(vendors.items()):
            lines.append(str(vendor))
            lines.append("~" * len(vendor))
            lines.extend(generate_boards(boards))
    return "\n".join(lines)
Beispiel #45
0
def is_compat_platform_and_framework(platform, framework):
    p = PlatformFactory.newPlatform(platform)
    return framework in (p.frameworks or {}).keys()
Beispiel #46
0
def generate_platform(name):
    print "Processing platform: %s" % name
    lines = []

    lines.append(
        """..  Copyright 2014-present PlatformIO <*****@*****.**>
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
""")

    lines.append(".. _platform_%s:" % name)
    lines.append("")

    _title = "Platform ``%s``" % name
    lines.append(_title)
    lines.append("=" * len(_title))

    p = PlatformFactory.newPlatform(name)
    lines.append(p.description)
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.""" %
                 p.vendor_url)
    lines.append("""
.. contents::""")

    #
    # Packages
    #
    _packages_content = generate_packages(name, p.packages.keys(),
                                          p.is_embedded())
    if _packages_content:
        lines.append(_packages_content)

    #
    # Frameworks
    #
    _frameworks_lines = []
    for framework in API_FRAMEWORKS:
        if not is_compat_platform_and_framework(name, framework['name']):
            continue
        _frameworks_lines.append("""
    * - :ref:`framework_{name}`
      - {description}""".format(**framework))

    if _frameworks_lines:
        lines.append("""
Frameworks
----------
.. list-table::
    :header-rows:  1

    * - Name
      - Description""")
        lines.extend(_frameworks_lines)

    #
    # Boards
    #
    vendors = {}
    for board in BOARDS:
        vendor = board['vendor']
        if name in board['platform']:
            if vendor in vendors:
                vendors[vendor].append(board)
            else:
                vendors[vendor] = [board]

    if vendors:
        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <http://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by
      horizontal.
""")

    for vendor, boards in sorted(vendors.iteritems()):
        lines.append(str(vendor))
        lines.append("~" * len(vendor))
        lines.append(generate_boards(boards))

    return "\n".join(lines)
Beispiel #47
0
def generate_platform(name, rst_dir):
    print("Processing platform: %s" % name)

    compatible_boards = [
        board for board in BOARDS if name == board['platform']
    ]

    lines = []

    lines.append(RST_COPYRIGHT)
    p = PlatformFactory.newPlatform(name)
    assert p.repository_url.endswith(".git")
    github_url = p.repository_url[:-4]

    lines.append(".. _platform_%s:" % p.name)
    lines.append("")

    lines.append(p.title)
    lines.append("=" * len(p.title))
    lines.append("")
    lines.append(":Configuration:")
    lines.append("  :ref:`projectconf_env_platform` = ``%s``" % p.name)
    lines.append("")
    lines.append(p.description)
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.""" %
                 campaign_url(p.vendor_url))
    lines.append("""
.. contents:: Contents
    :local:
    :depth: 1
""")

    #
    # Extra
    #
    if isfile(join(rst_dir, "%s_extra.rst" % name)):
        lines.append(".. include:: %s_extra.rst" % p.name)

    #
    # Examples
    #
    lines.append("""
Examples
--------

Examples are listed from `%s development platform repository <%s>`_:
""" % (p.title, campaign_url("%s/tree/master/examples" % github_url)))
    examples_dir = join(p.get_dir(), "examples")
    if isdir(examples_dir):
        for eitem in os.listdir(examples_dir):
            example_dir = join(examples_dir, eitem)
            if not isdir(example_dir) or not os.listdir(example_dir):
                continue
            url = "%s/tree/master/examples/%s" % (github_url, eitem)
            lines.append("* `%s <%s>`_" % (eitem, campaign_url(url)))

    #
    # Debugging
    #
    if compatible_boards:
        lines.extend(
            generate_debug_contents(
                compatible_boards,
                skip_board_columns=["Platform"],
                extra_rst="%s_debug.rst" %
                name if isfile(join(rst_dir, "%s_debug.rst" %
                                    name)) else None))

    #
    # Development version of dev/platform
    #
    lines.append("""
Stable and upstream versions
----------------------------

You can switch between `stable releases <{github_url}/releases>`__
of {title} development platform and the latest upstream version using
:ref:`projectconf_env_platform` option in :ref:`projectconf` as described below.

Stable
~~~~~~

.. code-block:: ini

    ; Latest stable version
    [env:latest_stable]
    platform = {name}
    board = ...

    ; Custom stable version
    [env:custom_stable]
    platform = {name}@x.y.z
    board = ...

Upstream
~~~~~~~~

.. code-block:: ini

    [env:upstream_develop]
    platform = {github_url}.git
    board = ...
""".format(name=p.name, title=p.title, github_url=github_url))

    #
    # Packages
    #
    _packages_content = generate_packages(name, p.packages.keys(),
                                          p.is_embedded())
    if _packages_content:
        lines.append(_packages_content)

    #
    # Frameworks
    #
    compatible_frameworks = []
    for framework in API_FRAMEWORKS:
        if is_compat_platform_and_framework(name, framework['name']):
            compatible_frameworks.append(framework['name'])
    lines.extend(generate_frameworks_contents(compatible_frameworks))

    #
    # Boards
    #
    if compatible_boards:
        vendors = {}
        for board in compatible_boards:
            if board['vendor'] not in vendors:
                vendors[board['vendor']] = []
            vendors[board['vendor']].append(board)

        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll the tables below by
      horizontally.
""")

        for vendor, boards in sorted(vendors.items()):
            lines.append(str(vendor))
            lines.append("~" * len(vendor))
            lines.extend(
                generate_boards_table(boards, skip_columns=["Platform"]))

    return "\n".join(lines)
Beispiel #48
0
def initPioPlatform(name):
    return PlatformFactory.newPlatform(name)
Beispiel #49
0
def generate_platform(name, rst_dir):
    print "Processing platform: %s" % name

    compatible_boards = [
        board for board in BOARDS if name == board['platform']
    ]

    lines = []

    lines.append(RST_COPYRIGHT)
    p = PlatformFactory.newPlatform(name)
    assert p.repository_url.endswith(".git")
    github_url = p.repository_url[:-4]

    lines.append(".. _platform_%s:" % p.name)
    lines.append("")

    lines.append(p.title)
    lines.append("=" * len(p.title))
    lines.append("")
    lines.append(":Configuration:")
    lines.append("  :ref:`projectconf_env_platform` = ``%s``" % p.name)
    lines.append("")
    lines.append(p.description)
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.""" %
                 campaign_url(p.vendor_url))
    lines.append("""
.. contents:: Contents
    :local:
    :depth: 1
""")

    #
    # Extra
    #
    if isfile(join(rst_dir, "%s_extra.rst" % name)):
        lines.append(".. include:: %s_extra.rst" % p.name)

    #
    # Examples
    #
    lines.append("""
Examples
--------

Examples are listed from `%s development platform repository <%s>`_:
""" % (p.title, campaign_url("%s/tree/master/examples" % github_url)))
    examples_dir = join(p.get_dir(), "examples")
    if isdir(examples_dir):
        for eitem in os.listdir(examples_dir):
            if not isdir(join(examples_dir, eitem)):
                continue
            url = "%s/tree/master/examples/%s" % (github_url, eitem)
            lines.append("* `%s <%s>`_" % (eitem, campaign_url(url)))

    #
    # Debugging
    #
    if compatible_boards:
        lines.extend(
            generate_debug_contents(
                compatible_boards,
                skip_board_columns=["Platform"],
                extra_rst="%s_debug.rst" % name if isfile(
                    join(rst_dir, "%s_debug.rst" % name)) else None))

    #
    # Development version of dev/platform
    #
    lines.append("""
Stable and upstream versions
----------------------------

You can switch between `stable releases <{github_url}/releases>`__
of {title} development platform and the latest upstream version using
:ref:`projectconf_env_platform` option in :ref:`projectconf` as described below.

Stable
~~~~~~

.. code-block:: ini

    ; Latest stable version
    [env:latest_stable]
    platform = {name}
    board = ...

    ; Custom stable version
    [env:custom_stable]
    platform = {name}@x.y.z
    board = ...

Upstream
~~~~~~~~

.. code-block:: ini

    [env:upstream_develop]
    platform = {github_url}.git
    board = ...
""".format(name=p.name, title=p.title, github_url=github_url))

    #
    # Packages
    #
    _packages_content = generate_packages(name, p.packages.keys(),
                                          p.is_embedded())
    if _packages_content:
        lines.append(_packages_content)

    #
    # Frameworks
    #
    compatible_frameworks = []
    for framework in API_FRAMEWORKS:
        if is_compat_platform_and_framework(name, framework['name']):
            compatible_frameworks.append(framework['name'])
    lines.extend(generate_frameworks_contents(compatible_frameworks))

    #
    # Boards
    #
    if compatible_boards:
        vendors = {}
        for board in compatible_boards:
            if board['vendor'] not in vendors:
                vendors[board['vendor']] = []
            vendors[board['vendor']].append(board)

        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll tables below by
      horizontal.
""")

        for vendor, boards in sorted(vendors.items()):
            lines.append(str(vendor))
            lines.append("~" * len(vendor))
            lines.extend(
                generate_boards_table(boards, skip_columns=["Platform"]))

    return "\n".join(lines)
Beispiel #50
0
def generate_framework(type_, data, rst_dir=None):
    print("Processing framework: %s" % type_)

    compatible_platforms = [
        m for m in PLATFORM_MANIFESTS
        if is_compat_platform_and_framework(m['name'], type_)
    ]
    compatible_boards = [
        board for board in BOARDS if type_ in board['frameworks']
    ]

    lines = []

    lines.append(RST_COPYRIGHT)
    lines.append(".. _framework_%s:" % type_)
    lines.append("")

    lines.append(data['title'])
    lines.append("=" * len(data['title']))
    lines.append("")
    lines.append(":Configuration:")
    lines.append("  :ref:`projectconf_env_framework` = ``%s``" % type_)
    lines.append("")
    lines.append(data['description'])
    lines.append("""
For more detailed information please visit `vendor site <%s>`_.
""" % campaign_url(data['url']))

    lines.append("""
.. contents:: Contents
    :local:
    :depth: 1""")

    # Extra
    if isfile(join(rst_dir, "%s_extra.rst" % type_)):
        lines.append(".. include:: %s_extra.rst" % type_)

    #
    # Debugging
    #
    if compatible_boards:
        lines.extend(
            generate_debug_contents(
                compatible_boards,
                extra_rst="%s_debug.rst" %
                type_ if isfile(join(rst_dir, "%s_debug.rst" %
                                     type_)) else None))

    if compatible_platforms:
        # examples
        lines.append("""
Examples
--------
""")
        for manifest in compatible_platforms:
            p = PlatformFactory.newPlatform(manifest['name'])
            lines.append("* `%s for %s <%s>`_" %
                         (data['title'], manifest['title'],
                          campaign_url("%s/tree/master/examples" %
                                       p.repository_url[:-4])))

        # Platforms
        lines.extend(
            generate_platforms_contents(
                [manifest['name'] for manifest in compatible_platforms]))

    #
    # Boards
    #
    if compatible_boards:
        vendors = {}
        for board in compatible_boards:
            if board['vendor'] not in vendors:
                vendors[board['vendor']] = []
            vendors[board['vendor']].append(board)
        lines.append("""
Boards
------

.. note::
    * You can list pre-configured boards by :ref:`cmd_boards` command or
      `PlatformIO Boards Explorer <https://platformio.org/boards>`_
    * For more detailed ``board`` information please scroll the tables below by horizontally.
""")
        for vendor, boards in sorted(vendors.items()):
            lines.append(str(vendor))
            lines.append("~" * len(vendor))
            lines.extend(generate_boards_table(boards))
    return "\n".join(lines)
Beispiel #51
0
def is_compat_platform_and_framework(platform, framework):
    p = PlatformFactory.newPlatform(platform)
    return framework in (p.frameworks or {}).keys()
Beispiel #52
0
def update_project_examples():
    platform_readme_tpl = """
# {title}: development platform for [PlatformIO](https://platformio.org)

{description}

* [Home](https://platformio.org/platforms/{name}) (home page in PlatformIO Registry)
* [Documentation](https://docs.platformio.org/page/platforms/{name}.html) (advanced usage, packages, boards, frameworks, etc.)

# Examples

{examples}
"""
    framework_readme_tpl = """
# {title}: framework for [PlatformIO](https://platformio.org)

{description}

* [Home](https://platformio.org/frameworks/{name}) (home page in PlatformIO Registry)
* [Documentation](https://docs.platformio.org/page/frameworks/{name}.html)

# Examples

{examples}
"""

    project_examples_dir = join(util.get_source_dir(), "..", "examples")
    framework_examples_md_lines = {}
    embedded = []
    desktop = []

    for manifest in PLATFORM_MANIFESTS:
        p = PlatformFactory.newPlatform(manifest['name'])
        github_url = p.repository_url[:-4]

        # Platform README
        platform_examples_dir = join(p.get_dir(), "examples")
        examples_md_lines = []
        if isdir(platform_examples_dir):
            for item in os.listdir(platform_examples_dir):
                if not isdir(join(platform_examples_dir, item)):
                    continue
                url = "%s/tree/master/examples/%s" % (github_url, item)
                examples_md_lines.append("* [%s](%s)" % (item, url))

        readme_dir = join(project_examples_dir, "platforms", p.name)
        if not isdir(readme_dir):
            os.makedirs(readme_dir)
        with open(join(readme_dir, "README.md"), "w") as fp:
            fp.write(
                platform_readme_tpl.format(
                    name=p.name,
                    title=p.title,
                    description=p.description,
                    examples="\n".join(examples_md_lines)))

        # Framework README
        for framework in API_FRAMEWORKS:
            if not is_compat_platform_and_framework(p.name, framework['name']):
                continue
            if framework['name'] not in framework_examples_md_lines:
                framework_examples_md_lines[framework['name']] = []
            lines = []
            lines.append("- [%s](%s)" % (p.title, github_url))
            lines.extend("  %s" % l for l in examples_md_lines)
            lines.append("")
            framework_examples_md_lines[framework['name']].extend(lines)

        # Root README
        line = "* [%s](%s)" % (p.title, "%s/tree/master/examples" % github_url)
        if p.is_embedded():
            embedded.append(line)
        else:
            desktop.append(line)

    # Frameworks
    frameworks = []
    for framework in API_FRAMEWORKS:
        readme_dir = join(project_examples_dir, "frameworks",
                          framework['name'])
        if not isdir(readme_dir):
            os.makedirs(readme_dir)
        with open(join(readme_dir, "README.md"), "w") as fp:
            fp.write(
                framework_readme_tpl.format(
                    name=framework['name'],
                    title=framework['title'],
                    description=framework['description'],
                    examples="\n".join(
                        framework_examples_md_lines[framework['name']])))
        url = campaign_url(
            "https://docs.platformio.org/en/latest/frameworks/%s.html#examples"
            % framework['name'],
            source="github",
            medium="examples")
        frameworks.append("* [%s](%s)" % (framework['title'], url))

    with open(join(project_examples_dir, "README.md"), "w") as fp:
        fp.write("""# PlatformIO Project Examples

- [Development platforms](#development-platforms):
  - [Embedded](#embedded)
  - [Desktop](#desktop)
- [Frameworks](#frameworks)

## Development platforms

### Embedded

%s

### Desktop

%s

## Frameworks

%s
""" % ("\n".join(embedded), "\n".join(desktop), "\n".join(frameworks)))
Beispiel #53
0
def check_internal_updates(ctx, what):
    last_check = app.get_state_item("last_check", {})
    interval = int(app.get_setting("check_%s_interval" % what)) * 3600 * 24
    if (time() - interval) < last_check.get(what + "_update", 0):
        return

    last_check[what + '_update'] = int(time())
    app.set_state_item("last_check", last_check)

    pm = PlatformManager() if what == "platforms" else LibraryManager()
    outdated_items = []
    for manifest in pm.get_installed():
        if manifest['name'] in outdated_items:
            continue
        conds = [
            pm.outdated(manifest['__pkg_dir']), what == "platforms"
            and PlatformFactory.newPlatform(
                manifest['__pkg_dir']).are_outdated_packages()
        ]
        if any(conds):
            outdated_items.append(manifest['name'])

    if not outdated_items:
        return

    terminal_width, _ = click.get_terminal_size()

    click.echo("")
    click.echo("*" * terminal_width)
    click.secho("There are the new updates for %s (%s)" %
                (what, ", ".join(outdated_items)),
                fg="yellow")

    if not app.get_setting("auto_update_" + what):
        click.secho("Please update them via ", fg="yellow", nl=False)
        click.secho("`platformio %s update`" %
                    ("lib --global" if what == "libraries" else "platform"),
                    fg="cyan",
                    nl=False)
        click.secho(" command.\n", fg="yellow")
        click.secho(
            "If you want to manually check for the new versions "
            "without updating, please use ",
            fg="yellow",
            nl=False)
        click.secho("`platformio %s update --only-check`" %
                    ("lib --global" if what == "libraries" else "platform"),
                    fg="cyan",
                    nl=False)
        click.secho(" command.", fg="yellow")
    else:
        click.secho("Please wait while updating %s ..." % what, fg="yellow")
        if what == "platforms":
            ctx.invoke(cmd_platform_update, platforms=outdated_items)
        elif what == "libraries":
            ctx.obj = pm
            ctx.invoke(cmd_lib_update, libraries=outdated_items)
        click.echo()

        telemetry.on_event(category="Auto",
                           action="Update",
                           label=what.title())

    click.echo("*" * terminal_width)
    click.echo("")
Beispiel #54
0
def is_compat_platform_and_framework(platform, framework):
    p = PlatformFactory.newPlatform(platform)
    for pkg in p.packages.keys():
        if pkg.startswith("framework-%s" % framework):
            return True
    return False