🔨 Fix IntelliSense / PIO conflicts (#23058)

Co-authored-by: Scott Lahteine <github@thinkyhead.com>
This commit is contained in:
Robby Candra 2021-11-04 17:28:42 +07:00 committed by Scott Lahteine
parent f97635de36
commit fc2020c6ec
37 changed files with 1075 additions and 1041 deletions

View File

@ -4,11 +4,12 @@
# Windows: bossac.exe # Windows: bossac.exe
# Other: leave unchanged # Other: leave unchanged
# #
import pioutil
if pioutil.is_pio_build():
import platform
current_OS = platform.system()
import platform if current_OS == 'Windows':
current_OS = platform.system()
if current_OS == 'Windows':
Import("env") Import("env")

View File

@ -1,26 +1,30 @@
# #
# sets output_port # upload_extra_script.py
# set the output_port
# if target_filename is found then that drive is used # if target_filename is found then that drive is used
# else if target_drive is found then that drive is used # else if target_drive is found then that drive is used
# #
from __future__ import print_function from __future__ import print_function
target_filename = "FIRMWARE.CUR" import pioutil
target_drive = "REARM" if pioutil.is_pio_build():
import os,getpass,platform target_filename = "FIRMWARE.CUR"
target_drive = "REARM"
current_OS = platform.system() import os,getpass,platform
Import("env")
def print_error(e): current_OS = platform.system()
Import("env")
def print_error(e):
print('\nUnable to find destination disk (%s)\n' \ print('\nUnable to find destination disk (%s)\n' \
'Please select it in platformio.ini using the upload_port keyword ' \ 'Please select it in platformio.ini using the upload_port keyword ' \
'(https://docs.platformio.org/en/latest/projectconf/section_env_upload.html) ' \ '(https://docs.platformio.org/en/latest/projectconf/section_env_upload.html) ' \
'or copy the firmware (.pio/build/%s/firmware.bin) manually to the appropriate disk\n' \ 'or copy the firmware (.pio/build/%s/firmware.bin) manually to the appropriate disk\n' \
%(e, env.get('PIOENV'))) %(e, env.get('PIOENV')))
def before_upload(source, target, env): def before_upload(source, target, env):
try: try:
# #
# Find a disk for upload # Find a disk for upload
@ -120,4 +124,4 @@ def before_upload(source, target, env):
except Exception as e: except Exception as e:
print_error(str(e)) print_error(str(e))
env.AddPreAction("upload", before_upload) env.AddPreAction("upload", before_upload)

View File

@ -30,6 +30,8 @@ if __name__ == "__main__":
# extra script for linker options # extra script for linker options
else: else:
import pioutil
if pioutil.is_pio_build():
from SCons.Script import DefaultEnvironment from SCons.Script import DefaultEnvironment
env = DefaultEnvironment() env = DefaultEnvironment()
env.Append( env.Append(

View File

@ -2,18 +2,20 @@
# SAMD51_grandcentral_m4.py # SAMD51_grandcentral_m4.py
# Customizations for env:SAMD51_grandcentral_m4 # Customizations for env:SAMD51_grandcentral_m4
# #
from os.path import join, isfile import pioutil
import shutil if pioutil.is_pio_build():
from pprint import pprint from os.path import join, isfile
import shutil
from pprint import pprint
Import("env") Import("env")
mf = env["MARLIN_FEATURES"] mf = env["MARLIN_FEATURES"]
rxBuf = mf["RX_BUFFER_SIZE"] if "RX_BUFFER_SIZE" in mf else "0" rxBuf = mf["RX_BUFFER_SIZE"] if "RX_BUFFER_SIZE" in mf else "0"
txBuf = mf["TX_BUFFER_SIZE"] if "TX_BUFFER_SIZE" in mf else "0" txBuf = mf["TX_BUFFER_SIZE"] if "TX_BUFFER_SIZE" in mf else "0"
serialBuf = str(max(int(rxBuf), int(txBuf), 350)) serialBuf = str(max(int(rxBuf), int(txBuf), 350))
build_flags = env.get('BUILD_FLAGS') build_flags = env.get('BUILD_FLAGS')
build_flags.append("-DSERIAL_BUFFER_SIZE=" + serialBuf) build_flags.append("-DSERIAL_BUFFER_SIZE=" + serialBuf)
env.Replace(BUILD_FLAGS=build_flags) env.Replace(BUILD_FLAGS=build_flags)

View File

@ -1,40 +1,43 @@
# #
# buildroot/share/PlatformIO/scripts/STM32F103RC_MEEB_3DP.py # STM32F103RC_MEEB_3DP.py
# #
try: import pioutil
if pioutil.is_pio_build():
try:
import configparser import configparser
except ImportError: except ImportError:
import ConfigParser as configparser import ConfigParser as configparser
import os import os
Import("env", "projenv") Import("env", "projenv")
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read("platformio.ini") config.read("platformio.ini")
# #
# Upload actions # Upload actions
# #
def before_upload(source, target, env): def before_upload(source, target, env):
env.Execute("pwd") env.Execute("pwd")
def after_upload(source, target, env): def after_upload(source, target, env):
env.Execute("pwd") env.Execute("pwd")
env.AddPreAction("upload", before_upload) env.AddPreAction("upload", before_upload)
env.AddPostAction("upload", after_upload) env.AddPostAction("upload", after_upload)
flash_size = 0 flash_size = 0
vect_tab_addr = 0 vect_tab_addr = 0
for define in env['CPPDEFINES']: for define in env['CPPDEFINES']:
if define[0] == "VECT_TAB_ADDR": if define[0] == "VECT_TAB_ADDR":
vect_tab_addr = define[1] vect_tab_addr = define[1]
if define[0] == "STM32_FLASH_SIZE": if define[0] == "STM32_FLASH_SIZE":
flash_size = define[1] flash_size = define[1]
print('Use the {0:s} address as the marlin app entry point.'.format(vect_tab_addr)) print('Use the {0:s} address as the marlin app entry point.'.format(vect_tab_addr))
print('Use the {0:d}KB flash version of stm32f103rct6 chip.'.format(flash_size)) print('Use the {0:d}KB flash version of stm32f103rct6 chip.'.format(flash_size))
import marlin import marlin
marlin.custom_ld_script("STM32F103RC_MEEB_3DP.ld") marlin.custom_ld_script("STM32F103RC_MEEB_3DP.ld")

View File

@ -1,25 +1,28 @@
# #
# buildroot/share/PlatformIO/scripts/STM32F103RC_fysetc.py # STM32F103RC_fysetc.py
# #
from os.path import join import pioutil
from os.path import expandvars if pioutil.is_pio_build():
Import("env") import os
from os.path import join
from os.path import expandvars
Import("env")
# Custom HEX from ELF # Custom HEX from ELF
env.AddPostAction( env.AddPostAction(
join("$BUILD_DIR", "${PROGNAME}.elf"), join("$BUILD_DIR", "${PROGNAME}.elf"),
env.VerboseAction(" ".join([ env.VerboseAction(" ".join([
"$OBJCOPY", "-O ihex", "$TARGET", "$OBJCOPY", "-O ihex", "$TARGET",
"\"" + join("$BUILD_DIR", "${PROGNAME}.hex") + "\"", # Note: $BUILD_DIR is a full path "\"" + join("$BUILD_DIR", "${PROGNAME}.hex") + "\"", # Note: $BUILD_DIR is a full path
]), "Building $TARGET")) ]), "Building $TARGET"))
# In-line command with arguments # In-line command with arguments
UPLOAD_TOOL="stm32flash" UPLOAD_TOOL="stm32flash"
platform = env.PioPlatform() platform = env.PioPlatform()
if platform.get_package_dir("tool-stm32duino") != None: if platform.get_package_dir("tool-stm32duino") != None:
UPLOAD_TOOL=expandvars("\"" + join(platform.get_package_dir("tool-stm32duino"),"stm32flash","stm32flash") + "\"") UPLOAD_TOOL=expandvars("\"" + join(platform.get_package_dir("tool-stm32duino"),"stm32flash","stm32flash") + "\"")
env.Replace( env.Replace(
UPLOADER=UPLOAD_TOOL, UPLOADER=UPLOAD_TOOL,
UPLOADCMD=expandvars(UPLOAD_TOOL + " -v -i rts,-dtr,dtr -R -b 115200 -g 0x8000000 -w \"" + join("$BUILD_DIR","${PROGNAME}.hex")+"\"" + " $UPLOAD_PORT") UPLOADCMD=expandvars(UPLOAD_TOOL + " -v -i rts,-dtr,dtr -R -b 115200 -g 0x8000000 -w \"" + join("$BUILD_DIR","${PROGNAME}.hex")+"\"" + " $UPLOAD_PORT")
) )

View File

@ -1,30 +1,32 @@
# #
# STM32F1_create_variant.py # STM32F1_create_variant.py
# #
import os,shutil,marlin import pioutil
from SCons.Script import DefaultEnvironment if pioutil.is_pio_build():
from platformio import util import os,shutil,marlin
from SCons.Script import DefaultEnvironment
from platformio import util
env = DefaultEnvironment() env = DefaultEnvironment()
platform = env.PioPlatform() platform = env.PioPlatform()
board = env.BoardConfig() board = env.BoardConfig()
FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoststm32-maple") FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoststm32-maple")
assert os.path.isdir(FRAMEWORK_DIR) assert os.path.isdir(FRAMEWORK_DIR)
source_root = os.path.join("buildroot", "share", "PlatformIO", "variants") source_root = os.path.join("buildroot", "share", "PlatformIO", "variants")
assert os.path.isdir(source_root) assert os.path.isdir(source_root)
variant = board.get("build.variant") variant = board.get("build.variant")
variant_dir = os.path.join(FRAMEWORK_DIR, "STM32F1", "variants", variant) variant_dir = os.path.join(FRAMEWORK_DIR, "STM32F1", "variants", variant)
source_dir = os.path.join(source_root, variant) source_dir = os.path.join(source_root, variant)
assert os.path.isdir(source_dir) assert os.path.isdir(source_dir)
if os.path.isdir(variant_dir): if os.path.isdir(variant_dir):
shutil.rmtree(variant_dir) shutil.rmtree(variant_dir)
if not os.path.isdir(variant_dir): if not os.path.isdir(variant_dir):
os.mkdir(variant_dir) os.mkdir(variant_dir)
marlin.copytree(source_dir, variant_dir) marlin.copytree(source_dir, variant_dir)

View File

@ -2,4 +2,5 @@
# add_nanolib.py # add_nanolib.py
# #
Import("env") Import("env")
env.Append(LINKFLAGS=["--specs=nano.specs"]) env.Append(LINKFLAGS=["--specs=nano.specs"])

View File

@ -1,13 +1,14 @@
# #
# buildroot/share/PlatformIO/scripts/chitu_crypt.py # chitu_crypt.py
# Customizations for Chitu boards # Customizations for Chitu boards
# #
import os,random,struct,uuid,marlin import pioutil
if pioutil.is_pio_build():
import os,random,struct,uuid,marlin
# Relocate firmware from 0x08000000 to 0x08008800
marlin.relocate_firmware("0x08008800")
# Relocate firmware from 0x08000000 to 0x08008800 def calculate_crc(contents, seed):
marlin.relocate_firmware("0x08008800")
def calculate_crc(contents, seed):
accumulating_xor_value = seed; accumulating_xor_value = seed;
for i in range(0, len(contents), 4): for i in range(0, len(contents), 4):
@ -15,7 +16,7 @@ def calculate_crc(contents, seed):
accumulating_xor_value = accumulating_xor_value ^ value accumulating_xor_value = accumulating_xor_value ^ value
return accumulating_xor_value return accumulating_xor_value
def xor_block(r0, r1, block_number, block_size, file_key): def xor_block(r0, r1, block_number, block_size, file_key):
# This is the loop counter # This is the loop counter
loop_counter = 0x0 loop_counter = 0x0
@ -59,7 +60,7 @@ def xor_block(r0, r1, block_number, block_size, file_key):
#increment the loop_counter #increment the loop_counter
loop_counter = loop_counter + 1 loop_counter = loop_counter + 1
def encrypt_file(input, output_file, file_length): def encrypt_file(input, output_file, file_length):
input_file = bytearray(input.read()) input_file = bytearray(input.read())
block_size = 0x800 block_size = 0x800
key_length = 0x18 key_length = 0x18
@ -102,8 +103,8 @@ def encrypt_file(input, output_file, file_length):
output_file.write(input_file) output_file.write(input_file)
return return
# Encrypt ${PROGNAME}.bin and save it as 'update.cbd' # Encrypt ${PROGNAME}.bin and save it as 'update.cbd'
def encrypt(source, target, env): def encrypt(source, target, env):
firmware = open(target[0].path, "rb") firmware = open(target[0].path, "rb")
update = open(target[0].dir.path + '/update.cbd', "wb") update = open(target[0].dir.path + '/update.cbd', "wb")
length = os.path.getsize(target[0].path) length = os.path.getsize(target[0].path)
@ -113,4 +114,4 @@ def encrypt(source, target, env):
firmware.close() firmware.close()
update.close() update.close()
marlin.add_post_action(encrypt); marlin.add_post_action(encrypt);

View File

@ -2,36 +2,38 @@
# common-cxxflags.py # common-cxxflags.py
# Convenience script to apply customizations to CPP flags # Convenience script to apply customizations to CPP flags
# #
Import("env") import pioutil
if pioutil.is_pio_build():
Import("env")
cxxflags = [ cxxflags = [
#"-Wno-incompatible-pointer-types", #"-Wno-incompatible-pointer-types",
#"-Wno-unused-const-variable", #"-Wno-unused-const-variable",
#"-Wno-maybe-uninitialized", #"-Wno-maybe-uninitialized",
#"-Wno-sign-compare" #"-Wno-sign-compare"
] ]
if "teensy" not in env['PIOENV']: if "teensy" not in env['PIOENV']:
cxxflags += ["-Wno-register"] cxxflags += ["-Wno-register"]
env.Append(CXXFLAGS=cxxflags) env.Append(CXXFLAGS=cxxflags)
# #
# Add CPU frequency as a compile time constant instead of a runtime variable # Add CPU frequency as a compile time constant instead of a runtime variable
# #
def add_cpu_freq(): def add_cpu_freq():
if 'BOARD_F_CPU' in env: if 'BOARD_F_CPU' in env:
env['BUILD_FLAGS'].append('-DBOARD_F_CPU=' + env['BOARD_F_CPU']) env['BUILD_FLAGS'].append('-DBOARD_F_CPU=' + env['BOARD_F_CPU'])
# Useful for JTAG debugging # Useful for JTAG debugging
# #
# It will separate release and debug build folders. # It will separate release and debug build folders.
# It useful to keep two live versions: a debug version for debugging and another for # It useful to keep two live versions: a debug version for debugging and another for
# release, for flashing when upload is not done automatically by jlink/stlink. # release, for flashing when upload is not done automatically by jlink/stlink.
# Without this, PIO needs to recompile everything twice for any small change. # Without this, PIO needs to recompile everything twice for any small change.
if env.GetBuildType() == "debug" and env.get('UPLOAD_PROTOCOL') not in ['jlink', 'stlink']: if env.GetBuildType() == "debug" and env.get('UPLOAD_PROTOCOL') not in ['jlink', 'stlink']:
env['BUILD_DIR'] = '$PROJECT_BUILD_DIR/$PIOENV/debug' env['BUILD_DIR'] = '$PROJECT_BUILD_DIR/$PIOENV/debug'
# On some platform, F_CPU is a runtime variable. Since it's used to convert from ns # On some platform, F_CPU is a runtime variable. Since it's used to convert from ns
# to CPU cycles, this adds overhead preventing small delay (in the order of less than # to CPU cycles, this adds overhead preventing small delay (in the order of less than
# 30 cycles) to be generated correctly. By using a compile time constant instead # 30 cycles) to be generated correctly. By using a compile time constant instead
# the compiler will perform the computation and this overhead will be avoided # the compiler will perform the computation and this overhead will be avoided
add_cpu_freq() add_cpu_freq()

View File

@ -1,16 +1,16 @@
# #
# common-dependencies-post.py # post:common-dependencies-post.py
# Convenience script to add build flags for Marlin Enabled Features # Convenience script to add build flags for Marlin Enabled Features
# #
import pioutil
if pioutil.is_pio_build():
Import("env", "projenv")
Import("env") def apply_board_build_flags():
Import("projenv")
def apply_board_build_flags():
if not 'BOARD_CUSTOM_BUILD_FLAGS' in env['MARLIN_FEATURES']: if not 'BOARD_CUSTOM_BUILD_FLAGS' in env['MARLIN_FEATURES']:
return return
projenv.Append(CCFLAGS=env['MARLIN_FEATURES']['BOARD_CUSTOM_BUILD_FLAGS'].split()) projenv.Append(CCFLAGS=env['MARLIN_FEATURES']['BOARD_CUSTOM_BUILD_FLAGS'].split())
# We need to add the board build flags in a post script # We need to add the board build flags in a post script
# so the platform build script doesn't overwrite the custom CCFLAGS # so the platform build script doesn't overwrite the custom CCFLAGS
apply_board_build_flags() apply_board_build_flags()

View File

@ -2,15 +2,21 @@
# common-dependencies.py # common-dependencies.py
# Convenience script to check dependencies and add libs and sources for Marlin Enabled Features # Convenience script to check dependencies and add libs and sources for Marlin Enabled Features
# #
import subprocess,os,re,pioutil import pioutil
Import("env") if pioutil.is_pio_build():
# Detect that 'vscode init' is running import subprocess,os,re
if pioutil.is_vscode_init(): Import("env")
env.Exit(0)
PIO_VERSION_MIN = (5, 0, 3) from platformio.package.meta import PackageSpec
try: from platformio.project.config import ProjectConfig
verbose = 0
FEATURE_CONFIG = {}
def validate_pio():
PIO_VERSION_MIN = (5, 0, 3)
try:
from platformio import VERSION as PIO_VERSION from platformio import VERSION as PIO_VERSION
weights = (1000, 100, 1) weights = (1000, 100, 1)
version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)]) version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)])
@ -28,28 +34,16 @@ try:
print("**************************************************") print("**************************************************")
print() print()
exit(1) exit(1)
except SystemExit: except SystemExit:
exit(1) exit(1)
except: except:
print("Can't detect PlatformIO Version") print("Can't detect PlatformIO Version")
from platformio.package.meta import PackageSpec def blab(str,level=1):
from platformio.project.config import ProjectConfig
#print(env.Dump())
try:
verbose = int(env.GetProjectOption('custom_verbose'))
except:
verbose = 0
def blab(str,level=1):
if verbose >= level: if verbose >= level:
print("[deps] %s" % str) print("[deps] %s" % str)
FEATURE_CONFIG = {} def add_to_feat_cnf(feature, flines):
def add_to_feat_cnf(feature, flines):
try: try:
feat = FEATURE_CONFIG[feature] feat = FEATURE_CONFIG[feature]
@ -76,7 +70,7 @@ def add_to_feat_cnf(feature, flines):
feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep] feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep]
blab("[%s] lib_deps = %s" % (feature, dep), 3) blab("[%s] lib_deps = %s" % (feature, dep), 3)
def load_config(): def load_config():
blab("========== Gather [features] entries...") blab("========== Gather [features] entries...")
items = ProjectConfig().items('features') items = ProjectConfig().items('features')
for key in items: for key in items:
@ -101,7 +95,7 @@ def load_config():
blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val )) blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val ))
add_to_feat_cnf(opt, val) add_to_feat_cnf(opt, val)
def get_all_known_libs(): def get_all_known_libs():
known_libs = [] known_libs = []
for feature in FEATURE_CONFIG: for feature in FEATURE_CONFIG:
feat = FEATURE_CONFIG[feature] feat = FEATURE_CONFIG[feature]
@ -111,20 +105,20 @@ def get_all_known_libs():
known_libs.append(PackageSpec(dep).name) known_libs.append(PackageSpec(dep).name)
return known_libs return known_libs
def get_all_env_libs(): def get_all_env_libs():
env_libs = [] env_libs = []
lib_deps = env.GetProjectOption('lib_deps') lib_deps = env.GetProjectOption('lib_deps')
for dep in lib_deps: for dep in lib_deps:
env_libs.append(PackageSpec(dep).name) env_libs.append(PackageSpec(dep).name)
return env_libs return env_libs
def set_env_field(field, value): def set_env_field(field, value):
proj = env.GetProjectConfig() proj = env.GetProjectConfig()
proj.set("env:" + env['PIOENV'], field, value) proj.set("env:" + env['PIOENV'], field, value)
# All unused libs should be ignored so that if a library # All unused libs should be ignored so that if a library
# exists in .pio/lib_deps it will not break compilation. # exists in .pio/lib_deps it will not break compilation.
def force_ignore_unused_libs(): def force_ignore_unused_libs():
env_libs = get_all_env_libs() env_libs = get_all_env_libs()
known_libs = get_all_known_libs() known_libs = get_all_known_libs()
diff = (list(set(known_libs) - set(env_libs))) diff = (list(set(known_libs) - set(env_libs)))
@ -132,7 +126,7 @@ def force_ignore_unused_libs():
blab("Ignore libraries: %s" % lib_ignore) blab("Ignore libraries: %s" % lib_ignore)
set_env_field('lib_ignore', lib_ignore) set_env_field('lib_ignore', lib_ignore)
def apply_features_config(): def apply_features_config():
load_config() load_config()
blab("========== Apply enabled features...") blab("========== Apply enabled features...")
for feature in FEATURE_CONFIG: for feature in FEATURE_CONFIG:
@ -198,12 +192,12 @@ def apply_features_config():
lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']] lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']]
set_env_field('lib_ignore', lib_ignore) set_env_field('lib_ignore', lib_ignore)
# #
# Find a compiler, considering the OS # Find a compiler, considering the OS
# #
ENV_BUILD_PATH = os.path.join(env.Dictionary('PROJECT_BUILD_DIR'), env['PIOENV']) ENV_BUILD_PATH = os.path.join(env.Dictionary('PROJECT_BUILD_DIR'), env['PIOENV'])
GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path") GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
def search_compiler(): def search_compiler():
try: try:
filepath = env.GetProjectOption('custom_gcc') filepath = env.GetProjectOption('custom_gcc')
blab("Getting compiler from env") blab("Getting compiler from env")
@ -255,10 +249,10 @@ def search_compiler():
blab("Couldn't find a compiler! Fallback to %s" % filepath) blab("Couldn't find a compiler! Fallback to %s" % filepath)
return filepath return filepath
# #
# Use the compiler to get a list of all enabled features # Use the compiler to get a list of all enabled features
# #
def load_marlin_features(): def load_marlin_features():
if 'MARLIN_FEATURES' in env: if 'MARLIN_FEATURES' in env:
return return
@ -289,10 +283,10 @@ def load_marlin_features():
marlin_features[feature] = definition marlin_features[feature] = definition
env['MARLIN_FEATURES'] = marlin_features env['MARLIN_FEATURES'] = marlin_features
# #
# Return True if a matching feature is enabled # Return True if a matching feature is enabled
# #
def MarlinFeatureIsEnabled(env, feature): def MarlinFeatureIsEnabled(env, feature):
load_marlin_features() load_marlin_features()
r = re.compile('^' + feature + '$') r = re.compile('^' + feature + '$')
found = list(filter(r.match, env['MARLIN_FEATURES'])) found = list(filter(r.match, env['MARLIN_FEATURES']))
@ -309,13 +303,16 @@ def MarlinFeatureIsEnabled(env, feature):
return some_on return some_on
# validate_pio()
# Add a method for other PIO scripts to query enabled features
#
env.AddMethod(MarlinFeatureIsEnabled)
# try:
# Add dependencies for enabled Marlin features verbose = int(env.GetProjectOption('custom_verbose'))
# except:
apply_features_config() pass
force_ignore_unused_libs()
# Add a method for other PIO scripts to query enabled features
env.AddMethod(MarlinFeatureIsEnabled)
# Add dependencies for enabled Marlin features
apply_features_config()
force_ignore_unused_libs()

View File

@ -1,16 +1,18 @@
# #
# buildroot/share/PlatformIO/scripts/custom_board.py # custom_board.py
# #
# - For build.address replace VECT_TAB_ADDR to relocate the firmware # - For build.address replace VECT_TAB_ADDR to relocate the firmware
# - For build.ldscript use one of the linker scripts in buildroot/share/PlatformIO/ldscripts # - For build.ldscript use one of the linker scripts in buildroot/share/PlatformIO/ldscripts
# #
import marlin import pioutil
board = marlin.env.BoardConfig() if pioutil.is_pio_build():
import marlin
board = marlin.env.BoardConfig()
address = board.get("build.address", "") address = board.get("build.address", "")
if address: if address:
marlin.relocate_firmware(address) marlin.relocate_firmware(address)
ldscript = board.get("build.ldscript", "") ldscript = board.get("build.ldscript", "")
if ldscript: if ldscript:
marlin.custom_ld_script(ldscript) marlin.custom_ld_script(ldscript)

View File

@ -1,20 +1,18 @@
# #
# buildroot/share/PlatformIO/scripts/download_mks_assets.py # download_mks_assets.py
# Added by HAS_TFT_LVGL_UI to download assets from Makerbase repo # Added by HAS_TFT_LVGL_UI to download assets from Makerbase repo
# #
Import("env") import pioutil
import os,requests,zipfile,tempfile,shutil,pioutil if pioutil.is_pio_build():
Import("env")
import os,requests,zipfile,tempfile,shutil
# Detect that 'vscode init' is running url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip"
if pioutil.is_vscode_init(): deps_path = env.Dictionary("PROJECT_LIBDEPS_DIR")
env.Exit(0) zip_path = os.path.join(deps_path, "mks-assets.zip")
assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip" def download_mks_assets():
deps_path = env.Dictionary("PROJECT_LIBDEPS_DIR")
zip_path = os.path.join(deps_path, "mks-assets.zip")
assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
def download_mks_assets():
print("Downloading MKS Assets") print("Downloading MKS Assets")
r = requests.get(url, stream=True) r = requests.get(url, stream=True)
# the user may have a very clean workspace, # the user may have a very clean workspace,
@ -25,7 +23,7 @@ def download_mks_assets():
for chunk in r.iter_content(chunk_size=128): for chunk in r.iter_content(chunk_size=128):
fd.write(chunk) fd.write(chunk)
def copy_mks_assets(): def copy_mks_assets():
print("Copying MKS Assets") print("Copying MKS Assets")
output_path = tempfile.mkdtemp() output_path = tempfile.mkdtemp()
zip_obj = zipfile.ZipFile(zip_path, 'r') zip_obj = zipfile.ZipFile(zip_path, 'r')
@ -44,8 +42,8 @@ def copy_mks_assets():
shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path) shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path)
shutil.rmtree(output_path, ignore_errors=True) shutil.rmtree(output_path, ignore_errors=True)
if os.path.exists(zip_path) == False: if os.path.exists(zip_path) == False:
download_mks_assets() download_mks_assets()
if os.path.exists(assets_path) == False: if os.path.exists(assets_path) == False:
copy_mks_assets() copy_mks_assets()

View File

@ -1,13 +1,16 @@
# #
# fix_framework_weakness.py # fix_framework_weakness.py
# #
from os.path import join, isfile import pioutil
import shutil if pioutil.is_pio_build():
from pprint import pprint
Import("env") import shutil
from os.path import join, isfile
from pprint import pprint
if env.MarlinFeatureIsEnabled("POSTMORTEM_DEBUGGING"): Import("env")
if env.MarlinFeatureIsEnabled("POSTMORTEM_DEBUGGING"):
FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-arduinoststm32-maple") FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-arduinoststm32-maple")
patchflag_path = join(FRAMEWORK_DIR, ".exc-patching-done") patchflag_path = join(FRAMEWORK_DIR, ".exc-patching-done")

View File

@ -5,50 +5,52 @@
# the appropriate framework variants folder, so that its contents # the appropriate framework variants folder, so that its contents
# will be picked up by PlatformIO just like any other variant. # will be picked up by PlatformIO just like any other variant.
# #
import os,shutil,marlin import pioutil
from SCons.Script import DefaultEnvironment if pioutil.is_pio_build():
from platformio import util import os,shutil,marlin
from SCons.Script import DefaultEnvironment
from platformio import util
env = DefaultEnvironment() env = DefaultEnvironment()
# #
# Get the platform name from the 'platform_packages' option, # Get the platform name from the 'platform_packages' option,
# or look it up by the platform.class.name. # or look it up by the platform.class.name.
# #
platform = env.PioPlatform() platform = env.PioPlatform()
from platformio.package.meta import PackageSpec from platformio.package.meta import PackageSpec
platform_packages = env.GetProjectOption('platform_packages') platform_packages = env.GetProjectOption('platform_packages')
if len(platform_packages) == 0: if len(platform_packages) == 0:
framewords = { framewords = {
"Ststm32Platform": "framework-arduinoststm32", "Ststm32Platform": "framework-arduinoststm32",
"AtmelavrPlatform": "framework-arduino-avr" "AtmelavrPlatform": "framework-arduino-avr"
} }
platform_name = framewords[platform.__class__.__name__] platform_name = framewords[platform.__class__.__name__]
else: else:
platform_name = PackageSpec(platform_packages[0]).name platform_name = PackageSpec(platform_packages[0]).name
if platform_name in [ "usb-host-msc", "usb-host-msc-cdc-msc", "usb-host-msc-cdc-msc-2", "usb-host-msc-cdc-msc-3", "tool-stm32duino" ]: if platform_name in [ "usb-host-msc", "usb-host-msc-cdc-msc", "usb-host-msc-cdc-msc-2", "usb-host-msc-cdc-msc-3", "tool-stm32duino" ]:
platform_name = "framework-arduinoststm32" platform_name = "framework-arduinoststm32"
FRAMEWORK_DIR = platform.get_package_dir(platform_name) FRAMEWORK_DIR = platform.get_package_dir(platform_name)
assert os.path.isdir(FRAMEWORK_DIR) assert os.path.isdir(FRAMEWORK_DIR)
board = env.BoardConfig() board = env.BoardConfig()
#mcu_type = board.get("build.mcu")[:-2] #mcu_type = board.get("build.mcu")[:-2]
variant = board.get("build.variant") variant = board.get("build.variant")
#series = mcu_type[:7].upper() + "xx" #series = mcu_type[:7].upper() + "xx"
# Prepare a new empty folder at the destination # Prepare a new empty folder at the destination
variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant) variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant)
if os.path.isdir(variant_dir): if os.path.isdir(variant_dir):
shutil.rmtree(variant_dir) shutil.rmtree(variant_dir)
if not os.path.isdir(variant_dir): if not os.path.isdir(variant_dir):
os.mkdir(variant_dir) os.mkdir(variant_dir)
# Source dir is a local variant sub-folder # Source dir is a local variant sub-folder
source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant) source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant)
assert os.path.isdir(source_dir) assert os.path.isdir(source_dir)
marlin.copytree(source_dir, variant_dir) marlin.copytree(source_dir, variant_dir)

View File

@ -1,11 +1,12 @@
# #
# buildroot/share/PlatformIO/scripts/jgaurora_a5s_a1_with_bootloader.py # jgaurora_a5s_a1_with_bootloader.py
# Customizations for env:jgaurora_a5s_a1 # Customizations for env:jgaurora_a5s_a1
# #
import os,marlin import pioutil
if pioutil.is_pio_build():
# Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin' import os,marlin
def addboot(source, target, env): # Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin'
def addboot(source, target, env):
firmware = open(target[0].path, "rb") firmware = open(target[0].path, "rb")
lengthfirmware = os.path.getsize(target[0].path) lengthfirmware = os.path.getsize(target[0].path)
bootloader_bin = "buildroot/share/PlatformIO/scripts/" + "jgaurora_bootloader.bin" bootloader_bin = "buildroot/share/PlatformIO/scripts/" + "jgaurora_bootloader.bin"
@ -36,4 +37,4 @@ def addboot(source, target, env):
os.rename(target[0].path, firmware_without_bootloader_bin) os.rename(target[0].path, firmware_without_bootloader_bin)
#os.rename(target[0].dir.path+'/firmware_with_bootloader.bin', target[0].dir.path+'/firmware.bin') #os.rename(target[0].dir.path+'/firmware_with_bootloader.bin', target[0].dir.path+'/firmware.bin')
marlin.add_post_action(addboot); marlin.add_post_action(addboot);

View File

@ -1,31 +1,33 @@
# #
# buildroot/share/PlatformIO/scripts/lerdge.py # lerdge.py
# Customizations for Lerdge build environments: # Customizations for Lerdge build environments:
# env:LERDGEX env:LERDGEX_usb_flash_drive # env:LERDGEX env:LERDGEX_usb_flash_drive
# env:LERDGES env:LERDGES_usb_flash_drive # env:LERDGES env:LERDGES_usb_flash_drive
# env:LERDGEK env:LERDGEK_usb_flash_drive # env:LERDGEK env:LERDGEK_usb_flash_drive
# #
import os,marlin import pioutil
Import("env") if pioutil.is_pio_build():
import os,marlin
Import("env")
from SCons.Script import DefaultEnvironment from SCons.Script import DefaultEnvironment
board = DefaultEnvironment().BoardConfig() board = DefaultEnvironment().BoardConfig()
def encryptByte(byte): def encryptByte(byte):
byte = 0xFF & ((byte << 6) | (byte >> 2)) byte = 0xFF & ((byte << 6) | (byte >> 2))
i = 0x58 + byte i = 0x58 + byte
j = 0x05 + byte + (i >> 8) j = 0x05 + byte + (i >> 8)
byte = (0xF8 & i) | (0x07 & j) byte = (0xF8 & i) | (0x07 & j)
return byte return byte
def encrypt_file(input, output_file, file_length): def encrypt_file(input, output_file, file_length):
input_file = bytearray(input.read()) input_file = bytearray(input.read())
for i in range(len(input_file)): for i in range(len(input_file)):
input_file[i] = encryptByte(input_file[i]) input_file[i] = encryptByte(input_file[i])
output_file.write(input_file) output_file.write(input_file)
# Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt # Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt
def encrypt(source, target, env): def encrypt(source, target, env):
fwpath = target[0].path fwpath = target[0].path
enname = board.get("build.encrypt") enname = board.get("build.encrypt")
print("Encrypting %s to %s" % (fwpath, enname)) print("Encrypting %s to %s" % (fwpath, enname))
@ -39,9 +41,9 @@ def encrypt(source, target, env):
enfile.close() enfile.close()
os.remove(fwpath) os.remove(fwpath)
if 'encrypt' in board.get("build").keys(): if 'encrypt' in board.get("build").keys():
if board.get("build.encrypt") != "": if board.get("build.encrypt") != "":
marlin.add_post_action(encrypt) marlin.add_post_action(encrypt)
else: else:
print("LERDGE builds require output file via board_build.encrypt = 'filename' parameter") print("LERDGE builds require output file via board_build.encrypt = 'filename' parameter")
exit(1) exit(1)

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/marlin.py # marlin.py
# Helper module with some commonly-used functions # Helper module with some commonly-used functions
# #
import os,shutil import os,shutil

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin.py # mks_robin.py
# #
import robin import robin
robin.prepare("0x08007000", "mks_robin.ld", "Robin.bin") robin.prepare("0x08007000", "mks_robin.ld", "Robin.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_e3.py # mks_robin_e3.py
# #
import robin import robin
robin.prepare("0x08005000", "mks_robin_e3.ld", "Robin_e3.bin") robin.prepare("0x08005000", "mks_robin_e3.ld", "Robin_e3.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_e3p.py # mks_robin_e3p.py
# #
import robin import robin
robin.prepare("0x08007000", "mks_robin_e3p.ld", "Robin_e3p.bin") robin.prepare("0x08007000", "mks_robin_e3p.ld", "Robin_e3p.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_lite.py # mks_robin_lite.py
# #
import robin import robin
robin.prepare("0x08005000", "mks_robin_lite.ld", "mksLite.bin") robin.prepare("0x08005000", "mks_robin_lite.ld", "mksLite.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_lite3.py # mks_robin_lite3.py
# #
import robin import robin
robin.prepare("0x08005000", "mks_robin_lite.ld", "mksLite3.bin") robin.prepare("0x08005000", "mks_robin_lite.ld", "mksLite3.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_mini.py # mks_robin_mini.py
# #
import robin import robin
robin.prepare("0x08007000", "mks_robin_mini.ld", "Robin_mini.bin") robin.prepare("0x08007000", "mks_robin_mini.ld", "Robin_mini.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_nano.py # mks_robin_nano.py
# #
import robin import robin
robin.prepare("0x08007000", "mks_robin_nano.ld", "Robin_nano.bin") robin.prepare("0x08007000", "mks_robin_nano.ld", "Robin_nano.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_nano35.py # mks_robin_nano35.py
# #
import robin import robin
robin.prepare("0x08007000", "mks_robin_nano.ld", "Robin_nano35.bin") robin.prepare("0x08007000", "mks_robin_nano.ld", "Robin_nano35.bin")

View File

@ -1,5 +1,5 @@
# #
# buildroot/share/PlatformIO/scripts/mks_robin_pro.py # mks_robin_pro.py
# #
import robin import robin
robin.prepare("0x08007000", "mks_robin_pro.ld", "Robin_pro.bin") robin.prepare("0x08007000", "mks_robin_pro.ld", "Robin_pro.bin")

View File

@ -8,18 +8,20 @@
# #
# - For 'board_build.rename' add a post-action to rename the firmware file. # - For 'board_build.rename' add a post-action to rename the firmware file.
# #
import os,sys,marlin import pioutil
Import("env") if pioutil.is_pio_build():
import os,sys,marlin
Import("env")
from SCons.Script import DefaultEnvironment from SCons.Script import DefaultEnvironment
board = DefaultEnvironment().BoardConfig() board = DefaultEnvironment().BoardConfig()
board_keys = board.get("build").keys() board_keys = board.get("build").keys()
# #
# For build.offset define LD_FLASH_OFFSET, used by ldscript.ld # For build.offset define LD_FLASH_OFFSET, used by ldscript.ld
# #
if 'offset' in board_keys: if 'offset' in board_keys:
LD_FLASH_OFFSET = board.get("build.offset") LD_FLASH_OFFSET = board.get("build.offset")
marlin.relocate_vtab(LD_FLASH_OFFSET) marlin.relocate_vtab(LD_FLASH_OFFSET)
@ -36,10 +38,10 @@ if 'offset' in board_keys:
if "-Wl,--defsym=LD_MAX_DATA_SIZE" in flag: if "-Wl,--defsym=LD_MAX_DATA_SIZE" in flag:
env["LINKFLAGS"][i] = "-Wl,--defsym=LD_MAX_DATA_SIZE=" + str(maximum_ram_size - 40) env["LINKFLAGS"][i] = "-Wl,--defsym=LD_MAX_DATA_SIZE=" + str(maximum_ram_size - 40)
# #
# For build.encrypt rename and encode the firmware file. # For build.encrypt rename and encode the firmware file.
# #
if 'encrypt' in board_keys: if 'encrypt' in board_keys:
# Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt # Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt
def encrypt(source, target, env): def encrypt(source, target, env):
@ -48,10 +50,10 @@ if 'encrypt' in board_keys:
if board.get("build.encrypt") != "": if board.get("build.encrypt") != "":
marlin.add_post_action(encrypt) marlin.add_post_action(encrypt)
# #
# For build.rename simply rename the firmware file. # For build.rename simply rename the firmware file.
# #
if 'rename' in board_keys: if 'rename' in board_keys:
def rename_target(source, target, env): def rename_target(source, target, env):
firmware = os.path.join(target[0].dir.path, board.get("build.rename")) firmware = os.path.join(target[0].dir.path, board.get("build.rename"))

View File

@ -1,14 +1,16 @@
# #
# Convert the ELF to an SREC file suitable for some bootloaders # Convert the ELF to an SREC file suitable for some bootloaders
# #
import os,sys import pioutil
from os.path import join if pioutil.is_pio_build():
import os,sys
from os.path import join
Import("env") Import("env")
board = env.BoardConfig() board = env.BoardConfig()
board_keys = board.get("build").keys() board_keys = board.get("build").keys()
if 'encrypt' in board_keys: if 'encrypt' in board_keys:
env.AddPostAction( env.AddPostAction(
join("$BUILD_DIR", "${PROGNAME}.bin"), join("$BUILD_DIR", "${PROGNAME}.bin"),
env.VerboseAction(" ".join([ env.VerboseAction(" ".join([

View File

@ -1,8 +1,8 @@
# #
# buildroot/share/PlatformIO/scripts/pioutil.py # pioutil.py
# #
# Detect that 'vscode init' is running # Make sure 'vscode init' is not the current command
def is_vscode_init(): def is_pio_build():
from SCons.Script import COMMAND_LINE_TARGETS from SCons.Script import COMMAND_LINE_TARGETS
return "idedata" in COMMAND_LINE_TARGETS or "_idedata" in COMMAND_LINE_TARGETS return "idedata" not in COMMAND_LINE_TARGETS and "_idedata" not in COMMAND_LINE_TARGETS

View File

@ -2,14 +2,13 @@
# preflight-checks.py # preflight-checks.py
# Check for common issues prior to compiling # Check for common issues prior to compiling
# #
import os,re,sys,pioutil import pioutil
Import("env") if pioutil.is_pio_build():
# Detect that 'vscode init' is running import os,re,sys
if pioutil.is_vscode_init(): Import("env")
env.Exit(0)
def get_envs_for_board(board): def get_envs_for_board(board):
with open(os.path.join("Marlin", "src", "pins", "pins.h"), "r") as file: with open(os.path.join("Marlin", "src", "pins", "pins.h"), "r") as file:
if sys.platform == 'win32': if sys.platform == 'win32':
@ -35,7 +34,7 @@ def get_envs_for_board(board):
return [ "env:"+s for s in envlist ] return [ "env:"+s for s in envlist ]
return [] return []
def check_envs(build_env, board_envs, config): def check_envs(build_env, board_envs, config):
if build_env in board_envs: if build_env in board_envs:
return True return True
ext = config.get(build_env, 'extends', default=None) ext = config.get(build_env, 'extends', default=None)
@ -48,7 +47,7 @@ def check_envs(build_env, board_envs, config):
return True return True
return False return False
def sanity_check_target(): def sanity_check_target():
# Sanity checks: # Sanity checks:
if 'PIOENV' not in env: if 'PIOENV' not in env:
raise SystemExit("Error: PIOENV is not defined. This script is intended to be used with PlatformIO") raise SystemExit("Error: PIOENV is not defined. This script is intended to be used with PlatformIO")
@ -98,4 +97,4 @@ def sanity_check_target():
err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin) err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin)
raise SystemExit(err) raise SystemExit(err)
sanity_check_target() sanity_check_target()

View File

@ -2,8 +2,8 @@
# random-bin.py # random-bin.py
# Set a unique firmware name based on current date and time # Set a unique firmware name based on current date and time
# #
Import("env") import pioutil
if pioutil.is_pio_build():
from datetime import datetime from datetime import datetime
Import("env")
env['PROGNAME'] = datetime.now().strftime("firmware-%Y%m%d-%H%M%S") env['PROGNAME'] = datetime.now().strftime("firmware-%Y%m%d-%H%M%S")

View File

@ -1,10 +1,12 @@
# #
# buildroot/share/PlatformIO/scripts/robin.py # robin.py
# #
import marlin
# Apply customizations for a MKS Robin # Apply customizations for a MKS Robin
def prepare(address, ldname, fwname): def prepare(address, ldname, fwname):
import pioutil
if pioutil.is_pio_build():
import marlin
def encrypt(source, target, env): def encrypt(source, target, env):
marlin.encrypt_mks(source, target, env, fwname) marlin.encrypt_mks(source, target, env, fwname)
marlin.relocate_firmware(address) marlin.relocate_firmware(address)

View File

@ -1,25 +1,27 @@
# #
# simulator.py
# PlatformIO pre: script for simulator builds # PlatformIO pre: script for simulator builds
# #
import pioutil
if pioutil.is_pio_build():
# Get the environment thus far for the build
Import("env")
# Get the environment thus far for the build #print(env.Dump())
Import("env")
#print(env.Dump()) #
# Give the binary a distinctive name
#
# env['PROGNAME'] = "MarlinSimulator"
# Give the binary a distinctive name
#
env['PROGNAME'] = "MarlinSimulator" #
# If Xcode is installed add the path to its Frameworks folder,
# or if Mesa is installed try to use its GL/gl.h.
#
# import sys
# If Xcode is installed add the path to its Frameworks folder, if sys.platform == 'darwin':
# or if Mesa is installed try to use its GL/gl.h.
#
import sys
if sys.platform == 'darwin':
# #
# Silence half of the ranlib warnings. (No equivalent for 'ARFLAGS') # Silence half of the ranlib warnings. (No equivalent for 'ARFLAGS')
@ -49,4 +51,4 @@ if sys.platform == 'darwin':
# Break out of the PIO build immediately # Break out of the PIO build immediately
sys.exit(1) sys.exit(1)
env.AddCustomTarget("upload", "$BUILD_DIR/${PROGNAME}", "$BUILD_DIR/${PROGNAME}") env.AddCustomTarget("upload", "$BUILD_DIR/${PROGNAME}", "$BUILD_DIR/${PROGNAME}")

View File

@ -1,59 +1,61 @@
# #
# stm32_serialbuffer.py # stm32_serialbuffer.py
# #
Import("env") import pioutil
if pioutil.is_pio_build():
Import("env")
# Marlin uses the `RX_BUFFER_SIZE` \ `TX_BUFFER_SIZE` options to # Get a build flag's value or None
# configure buffer sizes for receiving \ transmitting serial data. def getBuildFlagValue(name):
# Stm32duino uses another set of defines for the same purpose, so this
# script gets the values from the configuration and uses them to define
# `SERIAL_RX_BUFFER_SIZE` and `SERIAL_TX_BUFFER_SIZE` as global build
# flags so they are available for use by the platform.
#
# The script will set the value as the default one (64 bytes)
# or the user-configured one, whichever is higher.
#
# Marlin's default buffer sizes are 128 for RX and 32 for TX.
# The highest value is taken (128/64).
#
# If MF_*_BUFFER_SIZE, SERIAL_*_BUFFER_SIZE, USART_*_BUF_SIZE, are
# defined, the first of these values will be used as the minimum.
build_flags = env.ParseFlags(env.get('BUILD_FLAGS'))["CPPDEFINES"]
mf = env["MARLIN_FEATURES"]
# Get a build flag's value or None
def getBuildFlagValue(name):
for flag in build_flags: for flag in build_flags:
if isinstance(flag, list) and flag[0] == name: if isinstance(flag, list) and flag[0] == name:
return flag[1] return flag[1]
return None return None
# Get an overriding buffer size for RX or TX from the build flags # Get an overriding buffer size for RX or TX from the build flags
def getInternalSize(side): def getInternalSize(side):
return getBuildFlagValue(f"MF_{side}_BUFFER_SIZE") or \ return getBuildFlagValue(f"MF_{side}_BUFFER_SIZE") or \
getBuildFlagValue(f"SERIAL_{side}_BUFFER_SIZE") or \ getBuildFlagValue(f"SERIAL_{side}_BUFFER_SIZE") or \
getBuildFlagValue(f"USART_{side}_BUF_SIZE") getBuildFlagValue(f"USART_{side}_BUF_SIZE")
# Get the largest defined buffer size for RX or TX # Get the largest defined buffer size for RX or TX
def getBufferSize(side, default): def getBufferSize(side, default):
# Get a build flag value or fall back to the given default # Get a build flag value or fall back to the given default
internal = int(getInternalSize(side) or default) internal = int(getInternalSize(side) or default)
flag = side + "_BUFFER_SIZE" flag = side + "_BUFFER_SIZE"
# Return the largest value # Return the largest value
return max(int(mf[flag]), internal) if flag in mf else internal return max(int(mf[flag]), internal) if flag in mf else internal
# Add a build flag if it's not already defined # Add a build flag if it's not already defined
def tryAddFlag(name, value): def tryAddFlag(name, value):
if getBuildFlagValue(name) is None: if getBuildFlagValue(name) is None:
env.Append(BUILD_FLAGS=[f"-D{name}={value}"]) env.Append(BUILD_FLAGS=[f"-D{name}={value}"])
# Get the largest defined buffer sizes for RX or TX, using defaults for undefined # Marlin uses the `RX_BUFFER_SIZE` \ `TX_BUFFER_SIZE` options to
rxBuf = getBufferSize("RX", 128) # configure buffer sizes for receiving \ transmitting serial data.
txBuf = getBufferSize("TX", 64) # Stm32duino uses another set of defines for the same purpose, so this
# script gets the values from the configuration and uses them to define
# `SERIAL_RX_BUFFER_SIZE` and `SERIAL_TX_BUFFER_SIZE` as global build
# flags so they are available for use by the platform.
#
# The script will set the value as the default one (64 bytes)
# or the user-configured one, whichever is higher.
#
# Marlin's default buffer sizes are 128 for RX and 32 for TX.
# The highest value is taken (128/64).
#
# If MF_*_BUFFER_SIZE, SERIAL_*_BUFFER_SIZE, USART_*_BUF_SIZE, are
# defined, the first of these values will be used as the minimum.
build_flags = env.ParseFlags(env.get('BUILD_FLAGS'))["CPPDEFINES"]
mf = env["MARLIN_FEATURES"]
# Provide serial buffer sizes to the stm32duino platform # Get the largest defined buffer sizes for RX or TX, using defaults for undefined
tryAddFlag("SERIAL_RX_BUFFER_SIZE", rxBuf) rxBuf = getBufferSize("RX", 128)
tryAddFlag("SERIAL_TX_BUFFER_SIZE", txBuf) txBuf = getBufferSize("TX", 64)
tryAddFlag("USART_RX_BUF_SIZE", rxBuf)
tryAddFlag("USART_TX_BUF_SIZE", txBuf) # Provide serial buffer sizes to the stm32duino platform
tryAddFlag("SERIAL_RX_BUFFER_SIZE", rxBuf)
tryAddFlag("SERIAL_TX_BUFFER_SIZE", txBuf)
tryAddFlag("USART_RX_BUF_SIZE", rxBuf)
tryAddFlag("USART_TX_BUF_SIZE", txBuf)

View File

@ -326,7 +326,6 @@ platform = ${common_stm32f1.platform}
extends = common_stm32f1 extends = common_stm32f1
board = marlin_CHITU_F103 board = marlin_CHITU_F103
extra_scripts = ${common_stm32f1.extra_scripts} extra_scripts = ${common_stm32f1.extra_scripts}
pre:buildroot/share/PlatformIO/scripts/common-dependencies.py
pre:buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py pre:buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py
buildroot/share/PlatformIO/scripts/chitu_crypt.py buildroot/share/PlatformIO/scripts/chitu_crypt.py
build_flags = ${common_stm32f1.build_flags} build_flags = ${common_stm32f1.build_flags}