使用 PlatformIO 自动增加内部版本号

pvo*_*voj 3 microcontroller build arduino platformio

我有几个用于家庭自动化的微控制器项目。我的每个节点都有一个在代码中手动设置的版本号。这个版本号是在节点启动的时候报告的,通知我运行的是哪个代码。

有时在对代码进行一些更改后会忘记更改版本号。所以必须找到一个自动解决方案。

我对解决方案有一些想法:

  1. 创建文件(version.h):#define BUILDNO xxx
  2. 将其包含在相关的 c 代码中
  3. 每次构建前自动增加 xxx

可以实施吗?或者有没有其他类似结果的解决方案?

pvo*_*voj 6

我根据我的问题的答案做了一些研究。PlatformIO 可以在编译之前运行自定义脚本。以下是生成内部版本号并将其包含到项目代码中的过程:

  1. 在项目文件夹中创建一个 Python 脚本:buildscript_versioning.py
FILENAME_BUILDNO = 'versioning'
FILENAME_VERSION_H = 'include/version.h'
version = 'v0.1.'

import datetime

build_no = 0
try:
    with open(FILENAME_BUILDNO) as f:
        build_no = int(f.readline()) + 1
except:
    print('Starting build number from 1..')
    build_no = 1
with open(FILENAME_BUILDNO, 'w+') as f:
    f.write(str(build_no))
    print('Build number: {}'.format(build_no))

hf = """
#ifndef BUILD_NUMBER
  #define BUILD_NUMBER "{}"
#endif
#ifndef VERSION
  #define VERSION "{} - {}"
#endif
#ifndef VERSION_SHORT
  #define VERSION_SHORT "{}"
#endif
""".format(build_no, version+str(build_no), datetime.datetime.now(), version+str(build_no))
with open(FILENAME_VERSION_H, 'w+') as f:
    f.write(hf)
Run Code Online (Sandbox Code Playgroud)
  1. platformio.ini 中添加一行:
    extra_scripts = 
        pre:buildscript_versioning.py
Run Code Online (Sandbox Code Playgroud)

构建您的项目将运行脚本。将创建 2 个文件:

  • versioning : 一个简单的文本文件来存储最后一个版本号

  • include/version.h : 要包含的头文件

现在您可以将此行添加到您的 C 代码中:

#include <version.h>
Run Code Online (Sandbox Code Playgroud)

我在这里开始了一个带有一些文档的 gitlab 存储库:https ://gitlab.com/pvojnisek/buildnumber-for-platformio/tree/master 欢迎进一步的想法!

  • 根据 [platformio 文档](http://docs.platformio.org/en/latest/projectconf/advanced_scripting.html#launch-types),如果要执行脚本,则需要在脚本名称前加上“pre:”前缀在构建之前,否则如果没有前缀,它将默认为“post:”。示例: `extra_scripts = \n pre:pre_extra_script.py \n post:post_extra_script1.py \n ` (2认同)
  • 虽然这绝对可行,但使用字符数组而不是预处理器定义可能会更好。如果预处理器定义发生更改,PIO 必须重新编译编译单元中的所有文件(所有库等)。使用字符数组允许 PIO 仅重新编译包含“version.h”文件的项目源文件。 (2认同)