Преглед изворни кода

🔨 Fix IntelliSense / PIO conflicts (#23058)

Co-authored-by: Scott Lahteine <github@thinkyhead.com>
Robby Candra пре 2 година
родитељ
комит
4483b8aaf0
No account linked to committer's email address
37 измењених фајлова са 1116 додато и 1082 уклоњено
  1. 10
    9
      Marlin/src/HAL/DUE/upload_extra_script.py
  2. 101
    97
      Marlin/src/HAL/LPC1768/upload_extra_script.py
  3. 16
    14
      Marlin/src/HAL/STM32F1/build_flags.py
  4. 13
    11
      buildroot/share/PlatformIO/scripts/SAMD51_grandcentral_m4.py
  5. 32
    29
      buildroot/share/PlatformIO/scripts/STM32F103RC_MEEB_3DP.py
  6. 23
    20
      buildroot/share/PlatformIO/scripts/STM32F103RC_fysetc.py
  7. 21
    19
      buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py
  8. 1
    0
      buildroot/share/PlatformIO/scripts/add_nanolib.py
  9. 84
    83
      buildroot/share/PlatformIO/scripts/chitu_crypt.py
  10. 31
    29
      buildroot/share/PlatformIO/scripts/common-cxxflags.py
  11. 11
    11
      buildroot/share/PlatformIO/scripts/common-dependencies-post.py
  12. 300
    303
      buildroot/share/PlatformIO/scripts/common-dependencies.py
  13. 11
    9
      buildroot/share/PlatformIO/scripts/custom_board.py
  14. 41
    43
      buildroot/share/PlatformIO/scripts/download_mks_assets.py
  15. 25
    22
      buildroot/share/PlatformIO/scripts/fix_framework_weakness.py
  16. 49
    47
      buildroot/share/PlatformIO/scripts/generic_create_variant.py
  17. 34
    33
      buildroot/share/PlatformIO/scripts/jgaurora_a5s_a1_with_bootloader.py
  18. 36
    34
      buildroot/share/PlatformIO/scripts/lerdge.py
  19. 8
    8
      buildroot/share/PlatformIO/scripts/marlin.py
  20. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin.py
  21. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_e3.py
  22. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_e3p.py
  23. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_lite.py
  24. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_lite3.py
  25. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_mini.py
  26. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_nano.py
  27. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_nano35.py
  28. 1
    1
      buildroot/share/PlatformIO/scripts/mks_robin_pro.py
  29. 53
    51
      buildroot/share/PlatformIO/scripts/offset_and_rename.py
  30. 15
    13
      buildroot/share/PlatformIO/scripts/openblt.py
  31. 4
    4
      buildroot/share/PlatformIO/scripts/pioutil.py
  32. 81
    82
      buildroot/share/PlatformIO/scripts/preflight-checks.py
  33. 5
    5
      buildroot/share/PlatformIO/scripts/random-bin.py
  34. 9
    7
      buildroot/share/PlatformIO/scripts/robin.py
  35. 35
    33
      buildroot/share/PlatformIO/scripts/simulator.py
  36. 58
    56
      buildroot/share/PlatformIO/scripts/stm32_serialbuffer.py
  37. 0
    1
      ini/stm32f1-maple.ini

+ 10
- 9
Marlin/src/HAL/DUE/upload_extra_script.py Прегледај датотеку

@@ -4,15 +4,16 @@
4 4
 #  Windows: bossac.exe
5 5
 #  Other: leave unchanged
6 6
 #
7
+import pioutil
8
+if pioutil.is_pio_build():
9
+	import platform
10
+	current_OS = platform.system()
7 11
 
8
-import platform
9
-current_OS = platform.system()
12
+	if current_OS == 'Windows':
10 13
 
11
-if current_OS == 'Windows':
14
+		Import("env")
12 15
 
13
-	Import("env")
14
-
15
-	# Use bossac.exe on Windows
16
-	env.Replace(
17
-	    UPLOADCMD="bossac --info --unlock --write --verify --reset --erase -U false --boot $SOURCE"
18
-	)
16
+		# Use bossac.exe on Windows
17
+		env.Replace(
18
+			UPLOADCMD="bossac --info --unlock --write --verify --reset --erase -U false --boot $SOURCE"
19
+		)

+ 101
- 97
Marlin/src/HAL/LPC1768/upload_extra_script.py Прегледај датотеку

@@ -1,123 +1,127 @@
1 1
 #
2
-# sets output_port
2
+# upload_extra_script.py
3
+# set the output_port
3 4
 #  if target_filename is found then that drive is used
4 5
 #  else if target_drive is found then that drive is used
5 6
 #
6 7
 from __future__ import print_function
7 8
 
8
-target_filename = "FIRMWARE.CUR"
9
-target_drive = "REARM"
9
+import pioutil
10
+if pioutil.is_pio_build():
10 11
 
11
-import os,getpass,platform
12
+	target_filename = "FIRMWARE.CUR"
13
+	target_drive = "REARM"
12 14
 
13
-current_OS = platform.system()
14
-Import("env")
15
+	import os,getpass,platform
15 16
 
16
-def print_error(e):
17
-	print('\nUnable to find destination disk (%s)\n' \
18
-		  'Please select it in platformio.ini using the upload_port keyword ' \
19
-		  '(https://docs.platformio.org/en/latest/projectconf/section_env_upload.html) ' \
20
-		  'or copy the firmware (.pio/build/%s/firmware.bin) manually to the appropriate disk\n' \
21
-		  %(e, env.get('PIOENV')))
17
+	current_OS = platform.system()
18
+	Import("env")
22 19
 
23
-def before_upload(source, target, env):
24
-	try:
25
-		#
26
-		# Find a disk for upload
27
-		#
28
-		upload_disk = 'Disk not found'
29
-		target_file_found = False
30
-		target_drive_found = False
31
-		if current_OS == 'Windows':
20
+	def print_error(e):
21
+		print('\nUnable to find destination disk (%s)\n' \
22
+			  'Please select it in platformio.ini using the upload_port keyword ' \
23
+			  '(https://docs.platformio.org/en/latest/projectconf/section_env_upload.html) ' \
24
+			  'or copy the firmware (.pio/build/%s/firmware.bin) manually to the appropriate disk\n' \
25
+			  %(e, env.get('PIOENV')))
26
+
27
+	def before_upload(source, target, env):
28
+		try:
29
+			#
30
+			# Find a disk for upload
32 31
 			#
33
-			# platformio.ini will accept this for a Windows upload port designation: 'upload_port = L:'
34
-			#   Windows - doesn't care about the disk's name, only cares about the drive letter
35
-			import subprocess,string
36
-			from ctypes import windll
32
+			upload_disk = 'Disk not found'
33
+			target_file_found = False
34
+			target_drive_found = False
35
+			if current_OS == 'Windows':
36
+				#
37
+				# platformio.ini will accept this for a Windows upload port designation: 'upload_port = L:'
38
+				#   Windows - doesn't care about the disk's name, only cares about the drive letter
39
+				import subprocess,string
40
+				from ctypes import windll
37 41
 
38
-			# getting list of drives
39
-			# https://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python
40
-			drives = []
41
-			bitmask = windll.kernel32.GetLogicalDrives()
42
-			for letter in string.ascii_uppercase:
43
-				if bitmask & 1:
44
-					drives.append(letter)
45
-				bitmask >>= 1
42
+				# getting list of drives
43
+				# https://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python
44
+				drives = []
45
+				bitmask = windll.kernel32.GetLogicalDrives()
46
+				for letter in string.ascii_uppercase:
47
+					if bitmask & 1:
48
+						drives.append(letter)
49
+					bitmask >>= 1
46 50
 
47
-			for drive in drives:
48
-				final_drive_name = drive + ':\\'
49
-				# print ('disc check: {}'.format(final_drive_name))
50
-				try:
51
-					volume_info = str(subprocess.check_output('cmd /C dir ' + final_drive_name, stderr=subprocess.STDOUT))
52
-				except Exception as e:
53
-					print ('error:{}'.format(e))
54
-					continue
55
-				else:
56
-					if target_drive in volume_info and not target_file_found:  # set upload if not found target file yet
57
-						target_drive_found = True
58
-						upload_disk = final_drive_name
59
-					if target_filename in volume_info:
60
-						if not target_file_found:
51
+				for drive in drives:
52
+					final_drive_name = drive + ':\\'
53
+					# print ('disc check: {}'.format(final_drive_name))
54
+					try:
55
+						volume_info = str(subprocess.check_output('cmd /C dir ' + final_drive_name, stderr=subprocess.STDOUT))
56
+					except Exception as e:
57
+						print ('error:{}'.format(e))
58
+						continue
59
+					else:
60
+						if target_drive in volume_info and not target_file_found:  # set upload if not found target file yet
61
+							target_drive_found = True
61 62
 							upload_disk = final_drive_name
62
-						target_file_found = True
63
+						if target_filename in volume_info:
64
+							if not target_file_found:
65
+								upload_disk = final_drive_name
66
+							target_file_found = True
63 67
 
64
-		elif current_OS == 'Linux':
65
-			#
66
-			# platformio.ini will accept this for a Linux upload port designation: 'upload_port = /media/media_name/drive'
67
-			#
68
-			drives = os.listdir(os.path.join(os.sep, 'media', getpass.getuser()))
69
-			if target_drive in drives:  # If target drive is found, use it.
70
-				target_drive_found = True
71
-				upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), target_drive) + os.sep
72
-			else:
68
+			elif current_OS == 'Linux':
69
+				#
70
+				# platformio.ini will accept this for a Linux upload port designation: 'upload_port = /media/media_name/drive'
71
+				#
72
+				drives = os.listdir(os.path.join(os.sep, 'media', getpass.getuser()))
73
+				if target_drive in drives:  # If target drive is found, use it.
74
+					target_drive_found = True
75
+					upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), target_drive) + os.sep
76
+				else:
77
+					for drive in drives:
78
+						try:
79
+							files = os.listdir(os.path.join(os.sep, 'media', getpass.getuser(), drive))
80
+						except:
81
+							continue
82
+						else:
83
+							if target_filename in files:
84
+								upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), drive) + os.sep
85
+								target_file_found = True
86
+								break
87
+				#
88
+				# set upload_port to drive if found
89
+				#
90
+
91
+				if target_file_found or target_drive_found:
92
+					env.Replace(
93
+						UPLOAD_FLAGS="-P$UPLOAD_PORT"
94
+					)
95
+
96
+			elif current_OS == 'Darwin':  # MAC
97
+				#
98
+				# platformio.ini will accept this for a OSX upload port designation: 'upload_port = /media/media_name/drive'
99
+				#
100
+				drives = os.listdir('/Volumes')  # human readable names
101
+				if target_drive in drives and not target_file_found:  # set upload if not found target file yet
102
+					target_drive_found = True
103
+					upload_disk = '/Volumes/' + target_drive + '/'
73 104
 				for drive in drives:
74 105
 					try:
75
-						files = os.listdir(os.path.join(os.sep, 'media', getpass.getuser(), drive))
106
+						filenames = os.listdir('/Volumes/' + drive + '/')   # will get an error if the drive is protected
76 107
 					except:
77 108
 						continue
78 109
 					else:
79
-						if target_filename in files:
80
-							upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), drive) + os.sep
110
+						if target_filename in filenames:
111
+							if not target_file_found:
112
+								upload_disk = '/Volumes/' + drive + '/'
81 113
 							target_file_found = True
82
-							break
83
-			#
84
-			# set upload_port to drive if found
85
-			#
86 114
 
87
-			if target_file_found or target_drive_found:
88
-				env.Replace(
89
-					UPLOAD_FLAGS="-P$UPLOAD_PORT"
90
-				)
91
-
92
-		elif current_OS == 'Darwin':  # MAC
93 115
 			#
94
-			# platformio.ini will accept this for a OSX upload port designation: 'upload_port = /media/media_name/drive'
116
+			# Set upload_port to drive if found
95 117
 			#
96
-			drives = os.listdir('/Volumes')  # human readable names
97
-			if target_drive in drives and not target_file_found:  # set upload if not found target file yet
98
-				target_drive_found = True
99
-				upload_disk = '/Volumes/' + target_drive + '/'
100
-			for drive in drives:
101
-				try:
102
-					filenames = os.listdir('/Volumes/' + drive + '/')   # will get an error if the drive is protected
103
-				except:
104
-					continue
105
-				else:
106
-					if target_filename in filenames:
107
-						if not target_file_found:
108
-							upload_disk = '/Volumes/' + drive + '/'
109
-						target_file_found = True
110
-
111
-		#
112
-		# Set upload_port to drive if found
113
-		#
114
-		if target_file_found or target_drive_found:
115
-			env.Replace(UPLOAD_PORT=upload_disk)
116
-			print('\nUpload disk: ', upload_disk, '\n')
117
-		else:
118
-			print_error('Autodetect Error')
118
+			if target_file_found or target_drive_found:
119
+				env.Replace(UPLOAD_PORT=upload_disk)
120
+				print('\nUpload disk: ', upload_disk, '\n')
121
+			else:
122
+				print_error('Autodetect Error')
119 123
 
120
-	except Exception as e:
121
-		print_error(str(e))
124
+		except Exception as e:
125
+			print_error(str(e))
122 126
 
123
-env.AddPreAction("upload", before_upload)
127
+	env.AddPreAction("upload", before_upload)

+ 16
- 14
Marlin/src/HAL/STM32F1/build_flags.py Прегледај датотеку

@@ -30,25 +30,27 @@ if __name__ == "__main__":
30 30
 
31 31
 # extra script for linker options
32 32
 else:
33
-  from SCons.Script import DefaultEnvironment
34
-  env = DefaultEnvironment()
35
-  env.Append(
33
+  import pioutil
34
+  if pioutil.is_pio_build():
35
+    from SCons.Script import DefaultEnvironment
36
+    env = DefaultEnvironment()
37
+    env.Append(
36 38
       ARFLAGS=["rcs"],
37 39
 
38 40
       ASFLAGS=["-x", "assembler-with-cpp"],
39 41
 
40 42
       CXXFLAGS=[
41
-          "-fabi-version=0",
42
-          "-fno-use-cxa-atexit",
43
-          "-fno-threadsafe-statics"
43
+        "-fabi-version=0",
44
+        "-fno-use-cxa-atexit",
45
+        "-fno-threadsafe-statics"
44 46
       ],
45 47
       LINKFLAGS=[
46
-          "-Os",
47
-          "-mcpu=cortex-m3",
48
-          "-ffreestanding",
49
-          "-mthumb",
50
-          "--specs=nano.specs",
51
-          "--specs=nosys.specs",
52
-          "-u_printf_float",
48
+        "-Os",
49
+        "-mcpu=cortex-m3",
50
+        "-ffreestanding",
51
+        "-mthumb",
52
+        "--specs=nano.specs",
53
+        "--specs=nosys.specs",
54
+        "-u_printf_float",
53 55
       ],
54
-  )
56
+    )

+ 13
- 11
buildroot/share/PlatformIO/scripts/SAMD51_grandcentral_m4.py Прегледај датотеку

@@ -2,18 +2,20 @@
2 2
 # SAMD51_grandcentral_m4.py
3 3
 # Customizations for env:SAMD51_grandcentral_m4
4 4
 #
5
-from os.path import join, isfile
6
-import shutil
7
-from pprint import pprint
5
+import pioutil
6
+if pioutil.is_pio_build():
7
+	from os.path import join, isfile
8
+	import shutil
9
+	from pprint import pprint
8 10
 
9
-Import("env")
11
+	Import("env")
10 12
 
11
-mf = env["MARLIN_FEATURES"]
12
-rxBuf = mf["RX_BUFFER_SIZE"] if "RX_BUFFER_SIZE" in mf else "0"
13
-txBuf = mf["TX_BUFFER_SIZE"] if "TX_BUFFER_SIZE" in mf else "0"
13
+	mf = env["MARLIN_FEATURES"]
14
+	rxBuf = mf["RX_BUFFER_SIZE"] if "RX_BUFFER_SIZE" in mf else "0"
15
+	txBuf = mf["TX_BUFFER_SIZE"] if "TX_BUFFER_SIZE" in mf else "0"
14 16
 
15
-serialBuf = str(max(int(rxBuf), int(txBuf), 350))
17
+	serialBuf = str(max(int(rxBuf), int(txBuf), 350))
16 18
 
17
-build_flags = env.get('BUILD_FLAGS')
18
-build_flags.append("-DSERIAL_BUFFER_SIZE=" + serialBuf)
19
-env.Replace(BUILD_FLAGS=build_flags)
19
+	build_flags = env.get('BUILD_FLAGS')
20
+	build_flags.append("-DSERIAL_BUFFER_SIZE=" + serialBuf)
21
+	env.Replace(BUILD_FLAGS=build_flags)

+ 32
- 29
buildroot/share/PlatformIO/scripts/STM32F103RC_MEEB_3DP.py Прегледај датотеку

@@ -1,40 +1,43 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/STM32F103RC_MEEB_3DP.py
2
+# STM32F103RC_MEEB_3DP.py
3 3
 #
4
-try:
5
-    import configparser
6
-except ImportError:
7
-    import ConfigParser as configparser
4
+import pioutil
5
+if pioutil.is_pio_build():
8 6
 
9
-import os
10
-Import("env", "projenv")
7
+	try:
8
+		import configparser
9
+	except ImportError:
10
+		import ConfigParser as configparser
11 11
 
12
-config = configparser.ConfigParser()
13
-config.read("platformio.ini")
12
+	import os
13
+	Import("env", "projenv")
14 14
 
15
-#
16
-# Upload actions
17
-#
18
-def before_upload(source, target, env):
19
-    env.Execute("pwd")
15
+	config = configparser.ConfigParser()
16
+	config.read("platformio.ini")
17
+
18
+	#
19
+	# Upload actions
20
+	#
21
+	def before_upload(source, target, env):
22
+		env.Execute("pwd")
20 23
 
21
-def after_upload(source, target, env):
22
-    env.Execute("pwd")
24
+	def after_upload(source, target, env):
25
+		env.Execute("pwd")
23 26
 
24
-env.AddPreAction("upload", before_upload)
25
-env.AddPostAction("upload", after_upload)
27
+	env.AddPreAction("upload", before_upload)
28
+	env.AddPostAction("upload", after_upload)
26 29
 
27
-flash_size = 0
28
-vect_tab_addr = 0
30
+	flash_size = 0
31
+	vect_tab_addr = 0
29 32
 
30
-for define in env['CPPDEFINES']:
31
-    if define[0] == "VECT_TAB_ADDR":
32
-        vect_tab_addr = define[1]
33
-    if define[0] == "STM32_FLASH_SIZE":
34
-        flash_size = define[1]
33
+	for define in env['CPPDEFINES']:
34
+		if define[0] == "VECT_TAB_ADDR":
35
+			vect_tab_addr = define[1]
36
+		if define[0] == "STM32_FLASH_SIZE":
37
+			flash_size = define[1]
35 38
 
36
-print('Use the {0:s} address as the marlin app entry point.'.format(vect_tab_addr))
37
-print('Use the {0:d}KB flash version of stm32f103rct6 chip.'.format(flash_size))
39
+	print('Use the {0:s} address as the marlin app entry point.'.format(vect_tab_addr))
40
+	print('Use the {0:d}KB flash version of stm32f103rct6 chip.'.format(flash_size))
38 41
 
39
-import marlin
40
-marlin.custom_ld_script("STM32F103RC_MEEB_3DP.ld")
42
+	import marlin
43
+	marlin.custom_ld_script("STM32F103RC_MEEB_3DP.ld")

+ 23
- 20
buildroot/share/PlatformIO/scripts/STM32F103RC_fysetc.py Прегледај датотеку

@@ -1,25 +1,28 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/STM32F103RC_fysetc.py
2
+# STM32F103RC_fysetc.py
3 3
 #
4
-from os.path import join
5
-from os.path import expandvars
6
-Import("env")
4
+import pioutil
5
+if pioutil.is_pio_build():
6
+	import os
7
+	from os.path import join
8
+	from os.path import expandvars
9
+	Import("env")
7 10
 
8
-# Custom HEX from ELF
9
-env.AddPostAction(
10
-	join("$BUILD_DIR", "${PROGNAME}.elf"),
11
-	env.VerboseAction(" ".join([
12
-		"$OBJCOPY", "-O ihex", "$TARGET",
13
-		"\"" + join("$BUILD_DIR", "${PROGNAME}.hex") + "\"", # Note: $BUILD_DIR is a full path
14
-	]), "Building $TARGET"))
11
+	# Custom HEX from ELF
12
+	env.AddPostAction(
13
+		join("$BUILD_DIR", "${PROGNAME}.elf"),
14
+		env.VerboseAction(" ".join([
15
+			"$OBJCOPY", "-O ihex", "$TARGET",
16
+			"\"" + join("$BUILD_DIR", "${PROGNAME}.hex") + "\"", # Note: $BUILD_DIR is a full path
17
+		]), "Building $TARGET"))
15 18
 
16
-# In-line command with arguments
17
-UPLOAD_TOOL="stm32flash"
18
-platform = env.PioPlatform()
19
-if platform.get_package_dir("tool-stm32duino") != None:
20
-	UPLOAD_TOOL=expandvars("\"" + join(platform.get_package_dir("tool-stm32duino"),"stm32flash","stm32flash") + "\"")
19
+	# In-line command with arguments
20
+	UPLOAD_TOOL="stm32flash"
21
+	platform = env.PioPlatform()
22
+	if platform.get_package_dir("tool-stm32duino") != None:
23
+		UPLOAD_TOOL=expandvars("\"" + join(platform.get_package_dir("tool-stm32duino"),"stm32flash","stm32flash") + "\"")
21 24
 
22
-env.Replace(
23
-	UPLOADER=UPLOAD_TOOL,
24
-	UPLOADCMD=expandvars(UPLOAD_TOOL + " -v -i rts,-dtr,dtr -R -b 115200 -g 0x8000000 -w \"" + join("$BUILD_DIR","${PROGNAME}.hex")+"\"" + " $UPLOAD_PORT")
25
-)
25
+	env.Replace(
26
+		UPLOADER=UPLOAD_TOOL,
27
+		UPLOADCMD=expandvars(UPLOAD_TOOL + " -v -i rts,-dtr,dtr -R -b 115200 -g 0x8000000 -w \"" + join("$BUILD_DIR","${PROGNAME}.hex")+"\"" + " $UPLOAD_PORT")
28
+	)

+ 21
- 19
buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py Прегледај датотеку

@@ -1,30 +1,32 @@
1 1
 #
2 2
 # STM32F1_create_variant.py
3 3
 #
4
-import os,shutil,marlin
5
-from SCons.Script import DefaultEnvironment
6
-from platformio import util
4
+import pioutil
5
+if pioutil.is_pio_build():
6
+	import os,shutil,marlin
7
+	from SCons.Script import DefaultEnvironment
8
+	from platformio import util
7 9
 
8
-env = DefaultEnvironment()
9
-platform = env.PioPlatform()
10
-board = env.BoardConfig()
10
+	env = DefaultEnvironment()
11
+	platform = env.PioPlatform()
12
+	board = env.BoardConfig()
11 13
 
12
-FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoststm32-maple")
13
-assert os.path.isdir(FRAMEWORK_DIR)
14
+	FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoststm32-maple")
15
+	assert os.path.isdir(FRAMEWORK_DIR)
14 16
 
15
-source_root = os.path.join("buildroot", "share", "PlatformIO", "variants")
16
-assert os.path.isdir(source_root)
17
+	source_root = os.path.join("buildroot", "share", "PlatformIO", "variants")
18
+	assert os.path.isdir(source_root)
17 19
 
18
-variant = board.get("build.variant")
19
-variant_dir = os.path.join(FRAMEWORK_DIR, "STM32F1", "variants", variant)
20
+	variant = board.get("build.variant")
21
+	variant_dir = os.path.join(FRAMEWORK_DIR, "STM32F1", "variants", variant)
20 22
 
21
-source_dir = os.path.join(source_root, variant)
22
-assert os.path.isdir(source_dir)
23
+	source_dir = os.path.join(source_root, variant)
24
+	assert os.path.isdir(source_dir)
23 25
 
24
-if os.path.isdir(variant_dir):
25
-    shutil.rmtree(variant_dir)
26
+	if os.path.isdir(variant_dir):
27
+		shutil.rmtree(variant_dir)
26 28
 
27
-if not os.path.isdir(variant_dir):
28
-    os.mkdir(variant_dir)
29
+	if not os.path.isdir(variant_dir):
30
+		os.mkdir(variant_dir)
29 31
 
30
-marlin.copytree(source_dir, variant_dir)
32
+	marlin.copytree(source_dir, variant_dir)

+ 1
- 0
buildroot/share/PlatformIO/scripts/add_nanolib.py Прегледај датотеку

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

+ 84
- 83
buildroot/share/PlatformIO/scripts/chitu_crypt.py Прегледај датотеку

@@ -1,116 +1,117 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/chitu_crypt.py
2
+# chitu_crypt.py
3 3
 # Customizations for Chitu boards
4 4
 #
5
-import os,random,struct,uuid,marlin
5
+import pioutil
6
+if pioutil.is_pio_build():
7
+	import os,random,struct,uuid,marlin
8
+	# Relocate firmware from 0x08000000 to 0x08008800
9
+	marlin.relocate_firmware("0x08008800")
6 10
 
7
-# Relocate firmware from 0x08000000 to 0x08008800
8
-marlin.relocate_firmware("0x08008800")
11
+	def calculate_crc(contents, seed):
12
+		accumulating_xor_value = seed;
9 13
 
10
-def calculate_crc(contents, seed):
11
-    accumulating_xor_value = seed;
14
+		for i in range(0, len(contents), 4):
15
+			value = struct.unpack('<I', contents[ i : i + 4])[0]
16
+			accumulating_xor_value = accumulating_xor_value ^ value
17
+		return accumulating_xor_value
12 18
 
13
-    for i in range(0, len(contents), 4):
14
-        value = struct.unpack('<I', contents[ i : i + 4])[0]
15
-        accumulating_xor_value = accumulating_xor_value ^ value
16
-    return accumulating_xor_value
19
+	def xor_block(r0, r1, block_number, block_size, file_key):
20
+		# This is the loop counter
21
+		loop_counter = 0x0
17 22
 
18
-def xor_block(r0, r1, block_number, block_size, file_key):
19
-    # This is the loop counter
20
-    loop_counter = 0x0
23
+		# This is the key length
24
+		key_length = 0x18
21 25
 
22
-    # This is the key length
23
-    key_length = 0x18
26
+		# This is an initial seed
27
+		xor_seed = 0x4BAD
24 28
 
25
-    # This is an initial seed
26
-    xor_seed = 0x4BAD
29
+		# This is the block counter
30
+		block_number = xor_seed * block_number
27 31
 
28
-    # This is the block counter
29
-    block_number = xor_seed * block_number
32
+		#load the xor key from the file
33
+		r7 =  file_key
30 34
 
31
-    #load the xor key from the file
32
-    r7 =  file_key
35
+		for loop_counter in range(0, block_size):
36
+			# meant to make sure different bits of the key are used.
37
+			xor_seed = int(loop_counter / key_length)
33 38
 
34
-    for loop_counter in range(0, block_size):
35
-        # meant to make sure different bits of the key are used.
36
-        xor_seed = int(loop_counter / key_length)
39
+			# IP is a scratch register / R12
40
+			ip = loop_counter - (key_length * xor_seed)
37 41
 
38
-        # IP is a scratch register / R12
39
-        ip = loop_counter - (key_length * xor_seed)
42
+			# xor_seed = (loop_counter * loop_counter) + block_number
43
+			xor_seed = (loop_counter * loop_counter) + block_number
40 44
 
41
-        # xor_seed = (loop_counter * loop_counter) + block_number
42
-        xor_seed = (loop_counter * loop_counter) + block_number
45
+			# shift the xor_seed left by the bits in IP.
46
+			xor_seed = xor_seed >> ip
43 47
 
44
-        # shift the xor_seed left by the bits in IP.
45
-        xor_seed = xor_seed >> ip
48
+			# load a byte into IP
49
+			ip = r0[loop_counter]
46 50
 
47
-        # load a byte into IP
48
-        ip = r0[loop_counter]
51
+			# XOR the seed with r7
52
+			xor_seed = xor_seed ^ r7
49 53
 
50
-        # XOR the seed with r7
51
-        xor_seed = xor_seed ^ r7
54
+			# and then with IP
55
+			xor_seed = xor_seed ^ ip
52 56
 
53
-        # and then with IP
54
-        xor_seed = xor_seed ^ ip
57
+			#Now store the byte back
58
+			r1[loop_counter] = xor_seed & 0xFF
55 59
 
56
-        #Now store the byte back
57
-        r1[loop_counter] = xor_seed & 0xFF
60
+			#increment the loop_counter
61
+			loop_counter = loop_counter + 1
58 62
 
59
-        #increment the loop_counter
60
-        loop_counter = loop_counter + 1
63
+	def encrypt_file(input, output_file, file_length):
64
+		input_file = bytearray(input.read())
65
+		block_size = 0x800
66
+		key_length = 0x18
61 67
 
62
-def encrypt_file(input, output_file, file_length):
63
-    input_file = bytearray(input.read())
64
-    block_size = 0x800
65
-    key_length = 0x18
68
+		uid_value = uuid.uuid4()
69
+		file_key = int(uid_value.hex[0:8], 16)
66 70
 
67
-    uid_value = uuid.uuid4()
68
-    file_key = int(uid_value.hex[0:8], 16)
71
+		xor_crc = 0xEF3D4323;
69 72
 
70
-    xor_crc = 0xEF3D4323;
73
+		# the input file is exepcted to be in chunks of 0x800
74
+		# so round the size
75
+		while len(input_file) % block_size != 0:
76
+			input_file.extend(b'0x0')
71 77
 
72
-    # the input file is exepcted to be in chunks of 0x800
73
-    # so round the size
74
-    while len(input_file) % block_size != 0:
75
-        input_file.extend(b'0x0')
78
+		# write the file header
79
+		output_file.write(struct.pack(">I", 0x443D2D3F))
80
+		# encrypt the contents using a known file header key
76 81
 
77
-    # write the file header
78
-    output_file.write(struct.pack(">I", 0x443D2D3F))
79
-    # encrypt the contents using a known file header key
82
+		# write the file_key
83
+		output_file.write(struct.pack("<I", file_key))
80 84
 
81
-    # write the file_key
82
-    output_file.write(struct.pack("<I", file_key))
85
+		#TODO - how to enforce that the firmware aligns to block boundaries?
86
+		block_count = int(len(input_file) / block_size)
87
+		print ("Block Count is ", block_count)
88
+		for block_number in range(0, block_count):
89
+			block_offset = (block_number * block_size)
90
+			block_end = block_offset + block_size
91
+			block_array = bytearray(input_file[block_offset: block_end])
92
+			xor_block(block_array, block_array, block_number, block_size, file_key)
93
+			for n in range (0, block_size):
94
+				input_file[block_offset + n] = block_array[n]
83 95
 
84
-    #TODO - how to enforce that the firmware aligns to block boundaries?
85
-    block_count = int(len(input_file) / block_size)
86
-    print ("Block Count is ", block_count)
87
-    for block_number in range(0, block_count):
88
-        block_offset = (block_number * block_size)
89
-        block_end = block_offset + block_size
90
-        block_array = bytearray(input_file[block_offset: block_end])
91
-        xor_block(block_array, block_array, block_number, block_size, file_key)
92
-        for n in range (0, block_size):
93
-            input_file[block_offset + n] = block_array[n]
96
+			# update the expected CRC value.
97
+			xor_crc = calculate_crc(block_array, xor_crc)
94 98
 
95
-        # update the expected CRC value.
96
-        xor_crc = calculate_crc(block_array, xor_crc)
99
+		# write CRC
100
+		output_file.write(struct.pack("<I", xor_crc))
97 101
 
98
-    # write CRC
99
-    output_file.write(struct.pack("<I", xor_crc))
102
+		# finally, append the encrypted results.
103
+		output_file.write(input_file)
104
+		return
100 105
 
101
-    # finally, append the encrypted results.
102
-    output_file.write(input_file)
103
-    return
106
+	# Encrypt ${PROGNAME}.bin and save it as 'update.cbd'
107
+	def encrypt(source, target, env):
108
+		firmware = open(target[0].path, "rb")
109
+		update = open(target[0].dir.path + '/update.cbd', "wb")
110
+		length = os.path.getsize(target[0].path)
104 111
 
105
-# Encrypt ${PROGNAME}.bin and save it as 'update.cbd'
106
-def encrypt(source, target, env):
107
-    firmware = open(target[0].path, "rb")
108
-    update = open(target[0].dir.path + '/update.cbd', "wb")
109
-    length = os.path.getsize(target[0].path)
112
+		encrypt_file(firmware, update, length)
110 113
 
111
-    encrypt_file(firmware, update, length)
114
+		firmware.close()
115
+		update.close()
112 116
 
113
-    firmware.close()
114
-    update.close()
115
-
116
-marlin.add_post_action(encrypt);
117
+	marlin.add_post_action(encrypt);

+ 31
- 29
buildroot/share/PlatformIO/scripts/common-cxxflags.py Прегледај датотеку

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

+ 11
- 11
buildroot/share/PlatformIO/scripts/common-dependencies-post.py Прегледај датотеку

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

+ 300
- 303
buildroot/share/PlatformIO/scripts/common-dependencies.py Прегледај датотеку

@@ -2,320 +2,317 @@
2 2
 # common-dependencies.py
3 3
 # Convenience script to check dependencies and add libs and sources for Marlin Enabled Features
4 4
 #
5
-import subprocess,os,re,pioutil
6
-Import("env")
7
-
8
-# Detect that 'vscode init' is running
9
-if pioutil.is_vscode_init():
10
-	env.Exit(0)
11
-
12
-PIO_VERSION_MIN = (5, 0, 3)
13
-try:
14
-	from platformio import VERSION as PIO_VERSION
15
-	weights = (1000, 100, 1)
16
-	version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)])
17
-	version_cur = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION)])
18
-	if version_cur < version_min:
19
-		print()
20
-		print("**************************************************")
21
-		print("******      An update to PlatformIO is      ******")
22
-		print("******  required to build Marlin Firmware.  ******")
23
-		print("******                                      ******")
24
-		print("******      Minimum version: ", PIO_VERSION_MIN, "    ******")
25
-		print("******      Current Version: ", PIO_VERSION, "    ******")
26
-		print("******                                      ******")
27
-		print("******   Update PlatformIO and try again.   ******")
28
-		print("**************************************************")
29
-		print()
30
-		exit(1)
31
-except SystemExit:
32
-	exit(1)
33
-except:
34
-	print("Can't detect PlatformIO Version")
35
-
36
-from platformio.package.meta import PackageSpec
37
-from platformio.project.config import ProjectConfig
38
-
39
-#print(env.Dump())
40
-
41
-try:
42
-	verbose = int(env.GetProjectOption('custom_verbose'))
43
-except:
44
-	verbose = 0
45
-
46
-def blab(str,level=1):
47
-	if verbose >= level:
48
-		print("[deps] %s" % str)
49
-
50
-FEATURE_CONFIG = {}
5
+import pioutil
6
+if pioutil.is_pio_build():
51 7
 
52
-def add_to_feat_cnf(feature, flines):
8
+	import subprocess,os,re
9
+	Import("env")
53 10
 
54
-	try:
55
-		feat = FEATURE_CONFIG[feature]
56
-	except:
57
-		FEATURE_CONFIG[feature] = {}
58
-
59
-	# Get a reference to the FEATURE_CONFIG under construction
60
-	feat = FEATURE_CONFIG[feature]
61
-
62
-	# Split up passed lines on commas or newlines and iterate
63
-	# Add common options to the features config under construction
64
-	# For lib_deps replace a previous instance of the same library
65
-	atoms = re.sub(r',\\s*', '\n', flines).strip().split('\n')
66
-	for line in atoms:
67
-		parts = line.split('=')
68
-		name = parts.pop(0)
69
-		if name in ['build_flags', 'extra_scripts', 'src_filter', 'lib_ignore']:
70
-			feat[name] = '='.join(parts)
71
-			blab("[%s] %s=%s" % (feature, name, feat[name]), 3)
72
-		else:
73
-			for dep in re.split(r",\s*", line):
74
-				lib_name = re.sub(r'@([~^]|[<>]=?)?[\d.]+', '', dep.strip()).split('=').pop(0)
75
-				lib_re = re.compile('(?!^' + lib_name + '\\b)')
76
-				feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep]
77
-				blab("[%s] lib_deps = %s" % (feature, dep), 3)
78
-
79
-def load_config():
80
-	blab("========== Gather [features] entries...")
81
-	items = ProjectConfig().items('features')
82
-	for key in items:
83
-		feature = key[0].upper()
84
-		if not feature in FEATURE_CONFIG:
85
-			FEATURE_CONFIG[feature] = { 'lib_deps': [] }
86
-		add_to_feat_cnf(feature, key[1])
87
-
88
-	# Add options matching custom_marlin.MY_OPTION to the pile
89
-	blab("========== Gather custom_marlin entries...")
90
-	all_opts = env.GetProjectOptions()
91
-	for n in all_opts:
92
-		key = n[0]
93
-		mat = re.match(r'custom_marlin\.(.+)', key)
94
-		if mat:
95
-			try:
96
-				val = env.GetProjectOption(key)
97
-			except:
98
-				val = None
99
-			if val:
100
-				opt = mat.group(1).upper()
101
-				blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val ))
102
-				add_to_feat_cnf(opt, val)
103
-
104
-def get_all_known_libs():
105
-	known_libs = []
106
-	for feature in FEATURE_CONFIG:
107
-		feat = FEATURE_CONFIG[feature]
108
-		if not 'lib_deps' in feat:
109
-			continue
110
-		for dep in feat['lib_deps']:
111
-			known_libs.append(PackageSpec(dep).name)
112
-	return known_libs
113
-
114
-def get_all_env_libs():
115
-	env_libs = []
116
-	lib_deps = env.GetProjectOption('lib_deps')
117
-	for dep in lib_deps:
118
-		env_libs.append(PackageSpec(dep).name)
119
-	return env_libs
120
-
121
-def set_env_field(field, value):
122
-	proj = env.GetProjectConfig()
123
-	proj.set("env:" + env['PIOENV'], field, value)
124
-
125
-# All unused libs should be ignored so that if a library
126
-# exists in .pio/lib_deps it will not break compilation.
127
-def force_ignore_unused_libs():
128
-	env_libs = get_all_env_libs()
129
-	known_libs = get_all_known_libs()
130
-	diff = (list(set(known_libs) - set(env_libs)))
131
-	lib_ignore = env.GetProjectOption('lib_ignore') + diff
132
-	blab("Ignore libraries: %s" % lib_ignore)
133
-	set_env_field('lib_ignore', lib_ignore)
134
-
135
-def apply_features_config():
136
-	load_config()
137
-	blab("========== Apply enabled features...")
138
-	for feature in FEATURE_CONFIG:
139
-		if not env.MarlinFeatureIsEnabled(feature):
140
-			continue
11
+	from platformio.package.meta import PackageSpec
12
+	from platformio.project.config import ProjectConfig
141 13
 
14
+	verbose = 0
15
+	FEATURE_CONFIG = {}
16
+
17
+	def validate_pio():
18
+		PIO_VERSION_MIN = (5, 0, 3)
19
+		try:
20
+			from platformio import VERSION as PIO_VERSION
21
+			weights = (1000, 100, 1)
22
+			version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)])
23
+			version_cur = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION)])
24
+			if version_cur < version_min:
25
+				print()
26
+				print("**************************************************")
27
+				print("******      An update to PlatformIO is      ******")
28
+				print("******  required to build Marlin Firmware.  ******")
29
+				print("******                                      ******")
30
+				print("******      Minimum version: ", PIO_VERSION_MIN, "    ******")
31
+				print("******      Current Version: ", PIO_VERSION, "    ******")
32
+				print("******                                      ******")
33
+				print("******   Update PlatformIO and try again.   ******")
34
+				print("**************************************************")
35
+				print()
36
+				exit(1)
37
+		except SystemExit:
38
+			exit(1)
39
+		except:
40
+			print("Can't detect PlatformIO Version")
41
+
42
+	def blab(str,level=1):
43
+		if verbose >= level:
44
+			print("[deps] %s" % str)
45
+
46
+	def add_to_feat_cnf(feature, flines):
47
+
48
+		try:
49
+			feat = FEATURE_CONFIG[feature]
50
+		except:
51
+			FEATURE_CONFIG[feature] = {}
52
+
53
+		# Get a reference to the FEATURE_CONFIG under construction
142 54
 		feat = FEATURE_CONFIG[feature]
143 55
 
144
-		if 'lib_deps' in feat and len(feat['lib_deps']):
145
-			blab("========== Adding lib_deps for %s... " % feature, 2)
146
-
147
-			# feat to add
148
-			deps_to_add = {}
56
+		# Split up passed lines on commas or newlines and iterate
57
+		# Add common options to the features config under construction
58
+		# For lib_deps replace a previous instance of the same library
59
+		atoms = re.sub(r',\\s*', '\n', flines).strip().split('\n')
60
+		for line in atoms:
61
+			parts = line.split('=')
62
+			name = parts.pop(0)
63
+			if name in ['build_flags', 'extra_scripts', 'src_filter', 'lib_ignore']:
64
+				feat[name] = '='.join(parts)
65
+				blab("[%s] %s=%s" % (feature, name, feat[name]), 3)
66
+			else:
67
+				for dep in re.split(r",\s*", line):
68
+					lib_name = re.sub(r'@([~^]|[<>]=?)?[\d.]+', '', dep.strip()).split('=').pop(0)
69
+					lib_re = re.compile('(?!^' + lib_name + '\\b)')
70
+					feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep]
71
+					blab("[%s] lib_deps = %s" % (feature, dep), 3)
72
+
73
+	def load_config():
74
+		blab("========== Gather [features] entries...")
75
+		items = ProjectConfig().items('features')
76
+		for key in items:
77
+			feature = key[0].upper()
78
+			if not feature in FEATURE_CONFIG:
79
+				FEATURE_CONFIG[feature] = { 'lib_deps': [] }
80
+			add_to_feat_cnf(feature, key[1])
81
+
82
+		# Add options matching custom_marlin.MY_OPTION to the pile
83
+		blab("========== Gather custom_marlin entries...")
84
+		all_opts = env.GetProjectOptions()
85
+		for n in all_opts:
86
+			key = n[0]
87
+			mat = re.match(r'custom_marlin\.(.+)', key)
88
+			if mat:
89
+				try:
90
+					val = env.GetProjectOption(key)
91
+				except:
92
+					val = None
93
+				if val:
94
+					opt = mat.group(1).upper()
95
+					blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val ))
96
+					add_to_feat_cnf(opt, val)
97
+
98
+	def get_all_known_libs():
99
+		known_libs = []
100
+		for feature in FEATURE_CONFIG:
101
+			feat = FEATURE_CONFIG[feature]
102
+			if not 'lib_deps' in feat:
103
+				continue
149 104
 			for dep in feat['lib_deps']:
150
-				deps_to_add[PackageSpec(dep).name] = dep
151
-				blab("==================== %s... " % dep, 2)
152
-
153
-			# Does the env already have the dependency?
154
-			deps = env.GetProjectOption('lib_deps')
155
-			for dep in deps:
156
-				name = PackageSpec(dep).name
157
-				if name in deps_to_add:
158
-					del deps_to_add[name]
159
-
160
-			# Are there any libraries that should be ignored?
161
-			lib_ignore = env.GetProjectOption('lib_ignore')
162
-			for dep in deps:
163
-				name = PackageSpec(dep).name
164
-				if name in deps_to_add:
165
-					del deps_to_add[name]
166
-
167
-			# Is there anything left?
168
-			if len(deps_to_add) > 0:
169
-				# Only add the missing dependencies
170
-				set_env_field('lib_deps', deps + list(deps_to_add.values()))
171
-
172
-		if 'build_flags' in feat:
173
-			f = feat['build_flags']
174
-			blab("========== Adding build_flags for %s: %s" % (feature, f), 2)
175
-			new_flags = env.GetProjectOption('build_flags') + [ f ]
176
-			env.Replace(BUILD_FLAGS=new_flags)
177
-
178
-		if 'extra_scripts' in feat:
179
-			blab("Running extra_scripts for %s... " % feature, 2)
180
-			env.SConscript(feat['extra_scripts'], exports="env")
181
-
182
-		if 'src_filter' in feat:
183
-			blab("========== Adding src_filter for %s... " % feature, 2)
184
-			src_filter = ' '.join(env.GetProjectOption('src_filter'))
185
-			# first we need to remove the references to the same folder
186
-			my_srcs = re.findall(r'[+-](<.*?>)', feat['src_filter'])
187
-			cur_srcs = re.findall(r'[+-](<.*?>)', src_filter)
188
-			for d in my_srcs:
189
-				if d in cur_srcs:
190
-					src_filter = re.sub(r'[+-]' + d, '', src_filter)
191
-
192
-			src_filter = feat['src_filter'] + ' ' + src_filter
193
-			set_env_field('src_filter', [src_filter])
194
-			env.Replace(SRC_FILTER=src_filter)
195
-
196
-		if 'lib_ignore' in feat:
197
-			blab("========== Adding lib_ignore for %s... " % feature, 2)
198
-			lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']]
199
-			set_env_field('lib_ignore', lib_ignore)
200
-
201
-#
202
-# Find a compiler, considering the OS
203
-#
204
-ENV_BUILD_PATH = os.path.join(env.Dictionary('PROJECT_BUILD_DIR'), env['PIOENV'])
205
-GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
206
-def search_compiler():
207
-	try:
208
-		filepath = env.GetProjectOption('custom_gcc')
209
-		blab("Getting compiler from env")
210
-		return filepath
211
-	except:
212
-		pass
213
-
214
-	if os.path.exists(GCC_PATH_CACHE):
215
-		with open(GCC_PATH_CACHE, 'r') as f:
216
-			return f.read()
217
-
218
-	# Find the current platform compiler by searching the $PATH
219
-	# which will be in a platformio toolchain bin folder
220
-	path_regex = re.escape(env['PROJECT_PACKAGES_DIR'])
221
-
222
-	# See if the environment provides a default compiler
223
-	try:
224
-		gcc = env.GetProjectOption('custom_deps_gcc')
225
-	except:
226
-		gcc = "g++"
227
-
228
-	if env['PLATFORM'] == 'win32':
229
-		path_separator = ';'
230
-		path_regex += r'.*\\bin'
231
-		gcc += ".exe"
232
-	else:
233
-		path_separator = ':'
234
-		path_regex += r'/.+/bin'
235
-
236
-	# Search for the compiler
237
-	for pathdir in env['ENV']['PATH'].split(path_separator):
238
-		if not re.search(path_regex, pathdir, re.IGNORECASE):
239
-			continue
240
-		for filepath in os.listdir(pathdir):
241
-			if not filepath.endswith(gcc):
105
+				known_libs.append(PackageSpec(dep).name)
106
+		return known_libs
107
+
108
+	def get_all_env_libs():
109
+		env_libs = []
110
+		lib_deps = env.GetProjectOption('lib_deps')
111
+		for dep in lib_deps:
112
+			env_libs.append(PackageSpec(dep).name)
113
+		return env_libs
114
+
115
+	def set_env_field(field, value):
116
+		proj = env.GetProjectConfig()
117
+		proj.set("env:" + env['PIOENV'], field, value)
118
+
119
+	# All unused libs should be ignored so that if a library
120
+	# exists in .pio/lib_deps it will not break compilation.
121
+	def force_ignore_unused_libs():
122
+		env_libs = get_all_env_libs()
123
+		known_libs = get_all_known_libs()
124
+		diff = (list(set(known_libs) - set(env_libs)))
125
+		lib_ignore = env.GetProjectOption('lib_ignore') + diff
126
+		blab("Ignore libraries: %s" % lib_ignore)
127
+		set_env_field('lib_ignore', lib_ignore)
128
+
129
+	def apply_features_config():
130
+		load_config()
131
+		blab("========== Apply enabled features...")
132
+		for feature in FEATURE_CONFIG:
133
+			if not env.MarlinFeatureIsEnabled(feature):
242 134
 				continue
243
-			# Use entire path to not rely on env PATH
244
-			filepath = os.path.sep.join([pathdir, filepath])
245
-			# Cache the g++ path to no search always
246
-			if os.path.exists(ENV_BUILD_PATH):
247
-				with open(GCC_PATH_CACHE, 'w+') as f:
248
-					f.write(filepath)
249 135
 
136
+			feat = FEATURE_CONFIG[feature]
137
+
138
+			if 'lib_deps' in feat and len(feat['lib_deps']):
139
+				blab("========== Adding lib_deps for %s... " % feature, 2)
140
+
141
+				# feat to add
142
+				deps_to_add = {}
143
+				for dep in feat['lib_deps']:
144
+					deps_to_add[PackageSpec(dep).name] = dep
145
+					blab("==================== %s... " % dep, 2)
146
+
147
+				# Does the env already have the dependency?
148
+				deps = env.GetProjectOption('lib_deps')
149
+				for dep in deps:
150
+					name = PackageSpec(dep).name
151
+					if name in deps_to_add:
152
+						del deps_to_add[name]
153
+
154
+				# Are there any libraries that should be ignored?
155
+				lib_ignore = env.GetProjectOption('lib_ignore')
156
+				for dep in deps:
157
+					name = PackageSpec(dep).name
158
+					if name in deps_to_add:
159
+						del deps_to_add[name]
160
+
161
+				# Is there anything left?
162
+				if len(deps_to_add) > 0:
163
+					# Only add the missing dependencies
164
+					set_env_field('lib_deps', deps + list(deps_to_add.values()))
165
+
166
+			if 'build_flags' in feat:
167
+				f = feat['build_flags']
168
+				blab("========== Adding build_flags for %s: %s" % (feature, f), 2)
169
+				new_flags = env.GetProjectOption('build_flags') + [ f ]
170
+				env.Replace(BUILD_FLAGS=new_flags)
171
+
172
+			if 'extra_scripts' in feat:
173
+				blab("Running extra_scripts for %s... " % feature, 2)
174
+				env.SConscript(feat['extra_scripts'], exports="env")
175
+
176
+			if 'src_filter' in feat:
177
+				blab("========== Adding src_filter for %s... " % feature, 2)
178
+				src_filter = ' '.join(env.GetProjectOption('src_filter'))
179
+				# first we need to remove the references to the same folder
180
+				my_srcs = re.findall(r'[+-](<.*?>)', feat['src_filter'])
181
+				cur_srcs = re.findall(r'[+-](<.*?>)', src_filter)
182
+				for d in my_srcs:
183
+					if d in cur_srcs:
184
+						src_filter = re.sub(r'[+-]' + d, '', src_filter)
185
+
186
+				src_filter = feat['src_filter'] + ' ' + src_filter
187
+				set_env_field('src_filter', [src_filter])
188
+				env.Replace(SRC_FILTER=src_filter)
189
+
190
+			if 'lib_ignore' in feat:
191
+				blab("========== Adding lib_ignore for %s... " % feature, 2)
192
+				lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']]
193
+				set_env_field('lib_ignore', lib_ignore)
194
+
195
+	#
196
+	# Find a compiler, considering the OS
197
+	#
198
+	ENV_BUILD_PATH = os.path.join(env.Dictionary('PROJECT_BUILD_DIR'), env['PIOENV'])
199
+	GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
200
+	def search_compiler():
201
+		try:
202
+			filepath = env.GetProjectOption('custom_gcc')
203
+			blab("Getting compiler from env")
250 204
 			return filepath
205
+		except:
206
+			pass
207
+
208
+		if os.path.exists(GCC_PATH_CACHE):
209
+			with open(GCC_PATH_CACHE, 'r') as f:
210
+				return f.read()
211
+
212
+		# Find the current platform compiler by searching the $PATH
213
+		# which will be in a platformio toolchain bin folder
214
+		path_regex = re.escape(env['PROJECT_PACKAGES_DIR'])
215
+
216
+		# See if the environment provides a default compiler
217
+		try:
218
+			gcc = env.GetProjectOption('custom_deps_gcc')
219
+		except:
220
+			gcc = "g++"
221
+
222
+		if env['PLATFORM'] == 'win32':
223
+			path_separator = ';'
224
+			path_regex += r'.*\\bin'
225
+			gcc += ".exe"
226
+		else:
227
+			path_separator = ':'
228
+			path_regex += r'/.+/bin'
251 229
 
252
-	filepath = env.get('CXX')
253
-	if filepath == 'CC':
254
-		filepath = gcc
255
-	blab("Couldn't find a compiler! Fallback to %s" % filepath)
256
-	return filepath
230
+		# Search for the compiler
231
+		for pathdir in env['ENV']['PATH'].split(path_separator):
232
+			if not re.search(path_regex, pathdir, re.IGNORECASE):
233
+				continue
234
+			for filepath in os.listdir(pathdir):
235
+				if not filepath.endswith(gcc):
236
+					continue
237
+				# Use entire path to not rely on env PATH
238
+				filepath = os.path.sep.join([pathdir, filepath])
239
+				# Cache the g++ path to no search always
240
+				if os.path.exists(ENV_BUILD_PATH):
241
+					with open(GCC_PATH_CACHE, 'w+') as f:
242
+						f.write(filepath)
243
+
244
+				return filepath
245
+
246
+		filepath = env.get('CXX')
247
+		if filepath == 'CC':
248
+			filepath = gcc
249
+		blab("Couldn't find a compiler! Fallback to %s" % filepath)
250
+		return filepath
257 251
 
258
-#
259
-# Use the compiler to get a list of all enabled features
260
-#
261
-def load_marlin_features():
262
-	if 'MARLIN_FEATURES' in env:
263
-		return
264
-
265
-	# Process defines
266
-	build_flags = env.get('BUILD_FLAGS')
267
-	build_flags = env.ParseFlagsExtended(build_flags)
268
-
269
-	cxx = search_compiler()
270
-	cmd = ['"' + cxx + '"']
271
-
272
-	# Build flags from board.json
273
-	#if 'BOARD' in env:
274
-	#	cmd += [env.BoardConfig().get("build.extra_flags")]
275
-	for s in build_flags['CPPDEFINES']:
276
-		if isinstance(s, tuple):
277
-			cmd += ['-D' + s[0] + '=' + str(s[1])]
278
-		else:
279
-			cmd += ['-D' + s]
280
-
281
-	cmd += ['-D__MARLIN_DEPS__ -w -dM -E -x c++ buildroot/share/PlatformIO/scripts/common-dependencies.h']
282
-	cmd = ' '.join(cmd)
283
-	blab(cmd, 4)
284
-	define_list = subprocess.check_output(cmd, shell=True).splitlines()
285
-	marlin_features = {}
286
-	for define in define_list:
287
-		feature = define[8:].strip().decode().split(' ')
288
-		feature, definition = feature[0], ' '.join(feature[1:])
289
-		marlin_features[feature] = definition
290
-	env['MARLIN_FEATURES'] = marlin_features
252
+	#
253
+	# Use the compiler to get a list of all enabled features
254
+	#
255
+	def load_marlin_features():
256
+		if 'MARLIN_FEATURES' in env:
257
+			return
258
+
259
+		# Process defines
260
+		build_flags = env.get('BUILD_FLAGS')
261
+		build_flags = env.ParseFlagsExtended(build_flags)
262
+
263
+		cxx = search_compiler()
264
+		cmd = ['"' + cxx + '"']
265
+
266
+		# Build flags from board.json
267
+		#if 'BOARD' in env:
268
+		#	cmd += [env.BoardConfig().get("build.extra_flags")]
269
+		for s in build_flags['CPPDEFINES']:
270
+			if isinstance(s, tuple):
271
+				cmd += ['-D' + s[0] + '=' + str(s[1])]
272
+			else:
273
+				cmd += ['-D' + s]
274
+
275
+		cmd += ['-D__MARLIN_DEPS__ -w -dM -E -x c++ buildroot/share/PlatformIO/scripts/common-dependencies.h']
276
+		cmd = ' '.join(cmd)
277
+		blab(cmd, 4)
278
+		define_list = subprocess.check_output(cmd, shell=True).splitlines()
279
+		marlin_features = {}
280
+		for define in define_list:
281
+			feature = define[8:].strip().decode().split(' ')
282
+			feature, definition = feature[0], ' '.join(feature[1:])
283
+			marlin_features[feature] = definition
284
+		env['MARLIN_FEATURES'] = marlin_features
285
+
286
+	#
287
+	# Return True if a matching feature is enabled
288
+	#
289
+	def MarlinFeatureIsEnabled(env, feature):
290
+		load_marlin_features()
291
+		r = re.compile('^' + feature + '$')
292
+		found = list(filter(r.match, env['MARLIN_FEATURES']))
293
+
294
+		# Defines could still be 'false' or '0', so check
295
+		some_on = False
296
+		if len(found):
297
+			for f in found:
298
+				val = env['MARLIN_FEATURES'][f]
299
+				if val in [ '', '1', 'true' ]:
300
+					some_on = True
301
+				elif val in env['MARLIN_FEATURES']:
302
+					some_on = env.MarlinFeatureIsEnabled(val)
303
+
304
+		return some_on
305
+
306
+	validate_pio()
291 307
 
292
-#
293
-# Return True if a matching feature is enabled
294
-#
295
-def MarlinFeatureIsEnabled(env, feature):
296
-	load_marlin_features()
297
-	r = re.compile('^' + feature + '$')
298
-	found = list(filter(r.match, env['MARLIN_FEATURES']))
299
-
300
-	# Defines could still be 'false' or '0', so check
301
-	some_on = False
302
-	if len(found):
303
-		for f in found:
304
-			val = env['MARLIN_FEATURES'][f]
305
-			if val in [ '', '1', 'true' ]:
306
-				some_on = True
307
-			elif val in env['MARLIN_FEATURES']:
308
-				some_on = env.MarlinFeatureIsEnabled(val)
309
-
310
-	return some_on
308
+	try:
309
+		verbose = int(env.GetProjectOption('custom_verbose'))
310
+	except:
311
+		pass
311 312
 
312
-#
313
-# Add a method for other PIO scripts to query enabled features
314
-#
315
-env.AddMethod(MarlinFeatureIsEnabled)
313
+	# Add a method for other PIO scripts to query enabled features
314
+	env.AddMethod(MarlinFeatureIsEnabled)
316 315
 
317
-#
318
-# Add dependencies for enabled Marlin features
319
-#
320
-apply_features_config()
321
-force_ignore_unused_libs()
316
+	# Add dependencies for enabled Marlin features
317
+	apply_features_config()
318
+	force_ignore_unused_libs()

+ 11
- 9
buildroot/share/PlatformIO/scripts/custom_board.py Прегледај датотеку

@@ -1,16 +1,18 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/custom_board.py
2
+# custom_board.py
3 3
 #
4 4
 # - For build.address replace VECT_TAB_ADDR to relocate the firmware
5 5
 # - For build.ldscript use one of the linker scripts in buildroot/share/PlatformIO/ldscripts
6 6
 #
7
-import marlin
8
-board = marlin.env.BoardConfig()
7
+import pioutil
8
+if pioutil.is_pio_build():
9
+	import marlin
10
+	board = marlin.env.BoardConfig()
9 11
 
10
-address = board.get("build.address", "")
11
-if address:
12
-	marlin.relocate_firmware(address)
12
+	address = board.get("build.address", "")
13
+	if address:
14
+		marlin.relocate_firmware(address)
13 15
 
14
-ldscript = board.get("build.ldscript", "")
15
-if ldscript:
16
-	marlin.custom_ld_script(ldscript)
16
+	ldscript = board.get("build.ldscript", "")
17
+	if ldscript:
18
+		marlin.custom_ld_script(ldscript)

+ 41
- 43
buildroot/share/PlatformIO/scripts/download_mks_assets.py Прегледај датотеку

@@ -1,51 +1,49 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/download_mks_assets.py
2
+# download_mks_assets.py
3 3
 # Added by HAS_TFT_LVGL_UI to download assets from Makerbase repo
4 4
 #
5
-Import("env")
6
-import os,requests,zipfile,tempfile,shutil,pioutil
5
+import pioutil
6
+if pioutil.is_pio_build():
7
+	Import("env")
8
+	import os,requests,zipfile,tempfile,shutil
7 9
 
8
-# Detect that 'vscode init' is running
9
-if pioutil.is_vscode_init():
10
-	env.Exit(0)
10
+	url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip"
11
+	deps_path = env.Dictionary("PROJECT_LIBDEPS_DIR")
12
+	zip_path = os.path.join(deps_path, "mks-assets.zip")
13
+	assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
11 14
 
12
-url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip"
13
-deps_path = env.Dictionary("PROJECT_LIBDEPS_DIR")
14
-zip_path = os.path.join(deps_path, "mks-assets.zip")
15
-assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
15
+	def download_mks_assets():
16
+		print("Downloading MKS Assets")
17
+		r = requests.get(url, stream=True)
18
+		# the user may have a very clean workspace,
19
+		# so create the PROJECT_LIBDEPS_DIR directory if not exits
20
+		if os.path.exists(deps_path) == False:
21
+			os.mkdir(deps_path)
22
+		with open(zip_path, 'wb') as fd:
23
+			for chunk in r.iter_content(chunk_size=128):
24
+				fd.write(chunk)
16 25
 
17
-def download_mks_assets():
18
-	print("Downloading MKS Assets")
19
-	r = requests.get(url, stream=True)
20
-	# the user may have a very clean workspace,
21
-	# so create the PROJECT_LIBDEPS_DIR directory if not exits
22
-	if os.path.exists(deps_path) == False:
23
-		os.mkdir(deps_path)
24
-	with open(zip_path, 'wb') as fd:
25
-		for chunk in r.iter_content(chunk_size=128):
26
-			fd.write(chunk)
26
+	def copy_mks_assets():
27
+		print("Copying MKS Assets")
28
+		output_path = tempfile.mkdtemp()
29
+		zip_obj = zipfile.ZipFile(zip_path, 'r')
30
+		zip_obj.extractall(output_path)
31
+		zip_obj.close()
32
+		if os.path.exists(assets_path) == True and os.path.isdir(assets_path) == False:
33
+			os.unlink(assets_path)
34
+		if os.path.exists(assets_path) == False:
35
+			os.mkdir(assets_path)
36
+		base_path = ''
37
+		for filename in os.listdir(output_path):
38
+			base_path = filename
39
+		for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_font')):
40
+			shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_font', filename), assets_path)
41
+		for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_pic')):
42
+			shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path)
43
+		shutil.rmtree(output_path, ignore_errors=True)
27 44
 
28
-def copy_mks_assets():
29
-	print("Copying MKS Assets")
30
-	output_path = tempfile.mkdtemp()
31
-	zip_obj = zipfile.ZipFile(zip_path, 'r')
32
-	zip_obj.extractall(output_path)
33
-	zip_obj.close()
34
-	if os.path.exists(assets_path) == True and os.path.isdir(assets_path) == False:
35
-		os.unlink(assets_path)
36
-	if os.path.exists(assets_path) == False:
37
-		os.mkdir(assets_path)
38
-	base_path = ''
39
-	for filename in os.listdir(output_path):
40
-		base_path = filename
41
-	for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_font')):
42
-		shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_font', filename), assets_path)
43
-	for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_pic')):
44
-		shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path)
45
-	shutil.rmtree(output_path, ignore_errors=True)
46
-
47
-if os.path.exists(zip_path) == False:
48
-	download_mks_assets()
45
+	if os.path.exists(zip_path) == False:
46
+		download_mks_assets()
49 47
 
50
-if os.path.exists(assets_path) == False:
51
-	copy_mks_assets()
48
+	if os.path.exists(assets_path) == False:
49
+		copy_mks_assets()

+ 25
- 22
buildroot/share/PlatformIO/scripts/fix_framework_weakness.py Прегледај датотеку

@@ -1,32 +1,35 @@
1 1
 #
2 2
 # fix_framework_weakness.py
3 3
 #
4
-from os.path import join, isfile
5
-import shutil
6
-from pprint import pprint
4
+import pioutil
5
+if pioutil.is_pio_build():
7 6
 
8
-Import("env")
7
+	import shutil
8
+	from os.path import join, isfile
9
+	from pprint import pprint
9 10
 
10
-if env.MarlinFeatureIsEnabled("POSTMORTEM_DEBUGGING"):
11
-    FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-arduinoststm32-maple")
12
-    patchflag_path = join(FRAMEWORK_DIR, ".exc-patching-done")
11
+	Import("env")
13 12
 
14
-    # patch file only if we didn't do it before
15
-    if not isfile(patchflag_path):
16
-        print("Patching libmaple exception handlers")
17
-        original_file = join(FRAMEWORK_DIR, "STM32F1", "cores", "maple", "libmaple", "exc.S")
18
-        backup_file = join(FRAMEWORK_DIR, "STM32F1", "cores", "maple", "libmaple", "exc.S.bak")
19
-        src_file = join("buildroot", "share", "PlatformIO", "scripts", "exc.S")
13
+	if env.MarlinFeatureIsEnabled("POSTMORTEM_DEBUGGING"):
14
+		FRAMEWORK_DIR = env.PioPlatform().get_package_dir("framework-arduinoststm32-maple")
15
+		patchflag_path = join(FRAMEWORK_DIR, ".exc-patching-done")
20 16
 
21
-        assert isfile(original_file) and isfile(src_file)
22
-        shutil.copyfile(original_file, backup_file)
23
-        shutil.copyfile(src_file, original_file);
17
+		# patch file only if we didn't do it before
18
+		if not isfile(patchflag_path):
19
+			print("Patching libmaple exception handlers")
20
+			original_file = join(FRAMEWORK_DIR, "STM32F1", "cores", "maple", "libmaple", "exc.S")
21
+			backup_file = join(FRAMEWORK_DIR, "STM32F1", "cores", "maple", "libmaple", "exc.S.bak")
22
+			src_file = join("buildroot", "share", "PlatformIO", "scripts", "exc.S")
24 23
 
25
-        def _touch(path):
26
-            with open(path, "w") as fp:
27
-                fp.write("")
24
+			assert isfile(original_file) and isfile(src_file)
25
+			shutil.copyfile(original_file, backup_file)
26
+			shutil.copyfile(src_file, original_file);
28 27
 
29
-        env.Execute(lambda *args, **kwargs: _touch(patchflag_path))
30
-        print("Done patching exception handler")
28
+			def _touch(path):
29
+				with open(path, "w") as fp:
30
+					fp.write("")
31 31
 
32
-    print("Libmaple modified and ready for post mortem debugging")
32
+			env.Execute(lambda *args, **kwargs: _touch(patchflag_path))
33
+			print("Done patching exception handler")
34
+
35
+		print("Libmaple modified and ready for post mortem debugging")

+ 49
- 47
buildroot/share/PlatformIO/scripts/generic_create_variant.py Прегледај датотеку

@@ -5,50 +5,52 @@
5 5
 # the appropriate framework variants folder, so that its contents
6 6
 # will be picked up by PlatformIO just like any other variant.
7 7
 #
8
-import os,shutil,marlin
9
-from SCons.Script import DefaultEnvironment
10
-from platformio import util
11
-
12
-env = DefaultEnvironment()
13
-
14
-#
15
-# Get the platform name from the 'platform_packages' option,
16
-# or look it up by the platform.class.name.
17
-#
18
-platform = env.PioPlatform()
19
-
20
-from platformio.package.meta import PackageSpec
21
-platform_packages = env.GetProjectOption('platform_packages')
22
-if len(platform_packages) == 0:
23
-    framewords = {
24
-        "Ststm32Platform": "framework-arduinoststm32",
25
-        "AtmelavrPlatform": "framework-arduino-avr"
26
-    }
27
-    platform_name = framewords[platform.__class__.__name__]
28
-else:
29
-    platform_name = PackageSpec(platform_packages[0]).name
30
-
31
-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" ]:
32
-    platform_name = "framework-arduinoststm32"
33
-
34
-FRAMEWORK_DIR = platform.get_package_dir(platform_name)
35
-assert os.path.isdir(FRAMEWORK_DIR)
36
-
37
-board = env.BoardConfig()
38
-
39
-#mcu_type = board.get("build.mcu")[:-2]
40
-variant = board.get("build.variant")
41
-#series = mcu_type[:7].upper() + "xx"
42
-
43
-# Prepare a new empty folder at the destination
44
-variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant)
45
-if os.path.isdir(variant_dir):
46
-    shutil.rmtree(variant_dir)
47
-if not os.path.isdir(variant_dir):
48
-    os.mkdir(variant_dir)
49
-
50
-# Source dir is a local variant sub-folder
51
-source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant)
52
-assert os.path.isdir(source_dir)
53
-
54
-marlin.copytree(source_dir, variant_dir)
8
+import pioutil
9
+if pioutil.is_pio_build():
10
+	import os,shutil,marlin
11
+	from SCons.Script import DefaultEnvironment
12
+	from platformio import util
13
+
14
+	env = DefaultEnvironment()
15
+
16
+	#
17
+	# Get the platform name from the 'platform_packages' option,
18
+	# or look it up by the platform.class.name.
19
+	#
20
+	platform = env.PioPlatform()
21
+
22
+	from platformio.package.meta import PackageSpec
23
+	platform_packages = env.GetProjectOption('platform_packages')
24
+	if len(platform_packages) == 0:
25
+		framewords = {
26
+			"Ststm32Platform": "framework-arduinoststm32",
27
+			"AtmelavrPlatform": "framework-arduino-avr"
28
+		}
29
+		platform_name = framewords[platform.__class__.__name__]
30
+	else:
31
+		platform_name = PackageSpec(platform_packages[0]).name
32
+
33
+	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" ]:
34
+		platform_name = "framework-arduinoststm32"
35
+
36
+	FRAMEWORK_DIR = platform.get_package_dir(platform_name)
37
+	assert os.path.isdir(FRAMEWORK_DIR)
38
+
39
+	board = env.BoardConfig()
40
+
41
+	#mcu_type = board.get("build.mcu")[:-2]
42
+	variant = board.get("build.variant")
43
+	#series = mcu_type[:7].upper() + "xx"
44
+
45
+	# Prepare a new empty folder at the destination
46
+	variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant)
47
+	if os.path.isdir(variant_dir):
48
+		shutil.rmtree(variant_dir)
49
+	if not os.path.isdir(variant_dir):
50
+		os.mkdir(variant_dir)
51
+
52
+	# Source dir is a local variant sub-folder
53
+	source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant)
54
+	assert os.path.isdir(source_dir)
55
+
56
+	marlin.copytree(source_dir, variant_dir)

+ 34
- 33
buildroot/share/PlatformIO/scripts/jgaurora_a5s_a1_with_bootloader.py Прегледај датотеку

@@ -1,39 +1,40 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/jgaurora_a5s_a1_with_bootloader.py
2
+# jgaurora_a5s_a1_with_bootloader.py
3 3
 # Customizations for env:jgaurora_a5s_a1
4 4
 #
5
-import os,marlin
5
+import pioutil
6
+if pioutil.is_pio_build():
7
+	import os,marlin
8
+	# Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin'
9
+	def addboot(source, target, env):
10
+		firmware = open(target[0].path, "rb")
11
+		lengthfirmware = os.path.getsize(target[0].path)
12
+		bootloader_bin = "buildroot/share/PlatformIO/scripts/" + "jgaurora_bootloader.bin"
13
+		bootloader = open(bootloader_bin, "rb")
14
+		lengthbootloader = os.path.getsize(bootloader_bin)
6 15
 
7
-# Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin'
8
-def addboot(source, target, env):
9
-	firmware = open(target[0].path, "rb")
10
-	lengthfirmware = os.path.getsize(target[0].path)
11
-	bootloader_bin = "buildroot/share/PlatformIO/scripts/" + "jgaurora_bootloader.bin"
12
-	bootloader = open(bootloader_bin, "rb")
13
-	lengthbootloader = os.path.getsize(bootloader_bin)
16
+		firmware_with_boothloader_bin = target[0].dir.path + '/firmware_with_bootloader.bin'
17
+		if os.path.exists(firmware_with_boothloader_bin):
18
+			os.remove(firmware_with_boothloader_bin)
19
+		firmwareimage = open(firmware_with_boothloader_bin, "wb")
20
+		position = 0
21
+		while position < lengthbootloader:
22
+			byte = bootloader.read(1)
23
+			firmwareimage.write(byte)
24
+			position += 1
25
+		position = 0
26
+		while position < lengthfirmware:
27
+			byte = firmware.read(1)
28
+			firmwareimage.write(byte)
29
+			position += 1
30
+		bootloader.close()
31
+		firmware.close()
32
+		firmwareimage.close()
14 33
 
15
-	firmware_with_boothloader_bin = target[0].dir.path + '/firmware_with_bootloader.bin'
16
-	if os.path.exists(firmware_with_boothloader_bin):
17
-		os.remove(firmware_with_boothloader_bin)
18
-	firmwareimage = open(firmware_with_boothloader_bin, "wb")
19
-	position = 0
20
-	while position < lengthbootloader:
21
-		byte = bootloader.read(1)
22
-		firmwareimage.write(byte)
23
-		position += 1
24
-	position = 0
25
-	while position < lengthfirmware:
26
-		byte = firmware.read(1)
27
-		firmwareimage.write(byte)
28
-		position += 1
29
-	bootloader.close()
30
-	firmware.close()
31
-	firmwareimage.close()
34
+		firmware_without_bootloader_bin = target[0].dir.path + '/firmware_for_sd_upload.bin'
35
+		if os.path.exists(firmware_without_bootloader_bin):
36
+			os.remove(firmware_without_bootloader_bin)
37
+		os.rename(target[0].path, firmware_without_bootloader_bin)
38
+		#os.rename(target[0].dir.path+'/firmware_with_bootloader.bin', target[0].dir.path+'/firmware.bin')
32 39
 
33
-	firmware_without_bootloader_bin = target[0].dir.path + '/firmware_for_sd_upload.bin'
34
-	if os.path.exists(firmware_without_bootloader_bin):
35
-		os.remove(firmware_without_bootloader_bin)
36
-	os.rename(target[0].path, firmware_without_bootloader_bin)
37
-	#os.rename(target[0].dir.path+'/firmware_with_bootloader.bin', target[0].dir.path+'/firmware.bin')
38
-
39
-marlin.add_post_action(addboot);
40
+	marlin.add_post_action(addboot);

+ 36
- 34
buildroot/share/PlatformIO/scripts/lerdge.py Прегледај датотеку

@@ -1,47 +1,49 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/lerdge.py
2
+# lerdge.py
3 3
 # Customizations for Lerdge build environments:
4 4
 #   env:LERDGEX  env:LERDGEX_usb_flash_drive
5 5
 #   env:LERDGES  env:LERDGES_usb_flash_drive
6 6
 #   env:LERDGEK  env:LERDGEK_usb_flash_drive
7 7
 #
8
-import os,marlin
9
-Import("env")
8
+import pioutil
9
+if pioutil.is_pio_build():
10
+	import os,marlin
11
+	Import("env")
10 12
 
11
-from SCons.Script import DefaultEnvironment
12
-board = DefaultEnvironment().BoardConfig()
13
+	from SCons.Script import DefaultEnvironment
14
+	board = DefaultEnvironment().BoardConfig()
13 15
 
14
-def encryptByte(byte):
15
-	byte = 0xFF & ((byte << 6) | (byte >> 2))
16
-	i = 0x58 + byte
17
-	j = 0x05 + byte + (i >> 8)
18
-	byte = (0xF8 & i) | (0x07 & j)
19
-	return byte
16
+	def encryptByte(byte):
17
+		byte = 0xFF & ((byte << 6) | (byte >> 2))
18
+		i = 0x58 + byte
19
+		j = 0x05 + byte + (i >> 8)
20
+		byte = (0xF8 & i) | (0x07 & j)
21
+		return byte
20 22
 
21
-def encrypt_file(input, output_file, file_length):
22
-	input_file = bytearray(input.read())
23
-	for i in range(len(input_file)):
24
-		input_file[i] = encryptByte(input_file[i])
25
-	output_file.write(input_file)
23
+	def encrypt_file(input, output_file, file_length):
24
+		input_file = bytearray(input.read())
25
+		for i in range(len(input_file)):
26
+			input_file[i] = encryptByte(input_file[i])
27
+		output_file.write(input_file)
26 28
 
27
-# Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt
28
-def encrypt(source, target, env):
29
-	fwpath = target[0].path
30
-	enname = board.get("build.encrypt")
31
-	print("Encrypting %s to %s" % (fwpath, enname))
32
-	fwfile = open(fwpath, "rb")
33
-	enfile = open(target[0].dir.path + "/" + enname, "wb")
34
-	length = os.path.getsize(fwpath)
29
+	# Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt
30
+	def encrypt(source, target, env):
31
+		fwpath = target[0].path
32
+		enname = board.get("build.encrypt")
33
+		print("Encrypting %s to %s" % (fwpath, enname))
34
+		fwfile = open(fwpath, "rb")
35
+		enfile = open(target[0].dir.path + "/" + enname, "wb")
36
+		length = os.path.getsize(fwpath)
35 37
 
36
-	encrypt_file(fwfile, enfile, length)
38
+		encrypt_file(fwfile, enfile, length)
37 39
 
38
-	fwfile.close()
39
-	enfile.close()
40
-	os.remove(fwpath)
40
+		fwfile.close()
41
+		enfile.close()
42
+		os.remove(fwpath)
41 43
 
42
-if 'encrypt' in board.get("build").keys():
43
-	if board.get("build.encrypt") != "":
44
-		marlin.add_post_action(encrypt)
45
-else:
46
-	print("LERDGE builds require output file via board_build.encrypt = 'filename' parameter")
47
-	exit(1)
44
+	if 'encrypt' in board.get("build").keys():
45
+		if board.get("build.encrypt") != "":
46
+			marlin.add_post_action(encrypt)
47
+	else:
48
+		print("LERDGE builds require output file via board_build.encrypt = 'filename' parameter")
49
+		exit(1)

+ 8
- 8
buildroot/share/PlatformIO/scripts/marlin.py Прегледај датотеку

@@ -1,5 +1,5 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/marlin.py
2
+# marlin.py
3 3
 # Helper module with some commonly-used functions
4 4
 #
5 5
 import os,shutil
@@ -10,13 +10,13 @@ env = DefaultEnvironment()
10 10
 from os.path import join
11 11
 
12 12
 def copytree(src, dst, symlinks=False, ignore=None):
13
-   for item in os.listdir(src):
14
-        s = join(src, item)
15
-        d = join(dst, item)
16
-        if os.path.isdir(s):
17
-            shutil.copytree(s, d, symlinks, ignore)
18
-        else:
19
-            shutil.copy2(s, d)
13
+	for item in os.listdir(src):
14
+		s = join(src, item)
15
+		d = join(dst, item)
16
+		if os.path.isdir(s):
17
+			shutil.copytree(s, d, symlinks, ignore)
18
+		else:
19
+			shutil.copy2(s, d)
20 20
 
21 21
 def replace_define(field, value):
22 22
 	for define in env['CPPDEFINES']:

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_e3.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_e3p.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_lite.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_lite3.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_mini.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_nano.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_nano35.py Прегледај датотеку

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

+ 1
- 1
buildroot/share/PlatformIO/scripts/mks_robin_pro.py Прегледај датотеку

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

+ 53
- 51
buildroot/share/PlatformIO/scripts/offset_and_rename.py Прегледај датотеку

@@ -8,54 +8,56 @@
8 8
 #
9 9
 # - For 'board_build.rename' add a post-action to rename the firmware file.
10 10
 #
11
-import os,sys,marlin
12
-Import("env")
13
-
14
-from SCons.Script import DefaultEnvironment
15
-board = DefaultEnvironment().BoardConfig()
16
-
17
-board_keys = board.get("build").keys()
18
-
19
-#
20
-# For build.offset define LD_FLASH_OFFSET, used by ldscript.ld
21
-#
22
-if 'offset' in board_keys:
23
-	LD_FLASH_OFFSET = board.get("build.offset")
24
-	marlin.relocate_vtab(LD_FLASH_OFFSET)
25
-
26
-	# Flash size
27
-	maximum_flash_size = int(board.get("upload.maximum_size") / 1024)
28
-	marlin.replace_define('STM32_FLASH_SIZE', maximum_flash_size)
29
-
30
-	# Get upload.maximum_ram_size (defined by /buildroot/share/PlatformIO/boards/VARIOUS.json)
31
-	maximum_ram_size = board.get("upload.maximum_ram_size")
32
-
33
-	for i, flag in enumerate(env["LINKFLAGS"]):
34
-		if "-Wl,--defsym=LD_FLASH_OFFSET" in flag:
35
-			env["LINKFLAGS"][i] = "-Wl,--defsym=LD_FLASH_OFFSET=" + LD_FLASH_OFFSET
36
-		if "-Wl,--defsym=LD_MAX_DATA_SIZE" in flag:
37
-			env["LINKFLAGS"][i] = "-Wl,--defsym=LD_MAX_DATA_SIZE=" + str(maximum_ram_size - 40)
38
-
39
-#
40
-# For build.encrypt rename and encode the firmware file.
41
-#
42
-if 'encrypt' in board_keys:
43
-
44
-	# Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt
45
-	def encrypt(source, target, env):
46
-		marlin.encrypt_mks(source, target, env, board.get("build.encrypt"))
47
-
48
-	if board.get("build.encrypt") != "":
49
-		marlin.add_post_action(encrypt)
50
-
51
-#
52
-# For build.rename simply rename the firmware file.
53
-#
54
-if 'rename' in board_keys:
55
-
56
-	def rename_target(source, target, env):
57
-		firmware = os.path.join(target[0].dir.path, board.get("build.rename"))
58
-		import shutil
59
-		shutil.copy(target[0].path, firmware)
60
-
61
-	marlin.add_post_action(rename_target)
11
+import pioutil
12
+if pioutil.is_pio_build():
13
+	import os,sys,marlin
14
+	Import("env")
15
+
16
+	from SCons.Script import DefaultEnvironment
17
+	board = DefaultEnvironment().BoardConfig()
18
+
19
+	board_keys = board.get("build").keys()
20
+
21
+	#
22
+	# For build.offset define LD_FLASH_OFFSET, used by ldscript.ld
23
+	#
24
+	if 'offset' in board_keys:
25
+		LD_FLASH_OFFSET = board.get("build.offset")
26
+		marlin.relocate_vtab(LD_FLASH_OFFSET)
27
+
28
+		# Flash size
29
+		maximum_flash_size = int(board.get("upload.maximum_size") / 1024)
30
+		marlin.replace_define('STM32_FLASH_SIZE', maximum_flash_size)
31
+
32
+		# Get upload.maximum_ram_size (defined by /buildroot/share/PlatformIO/boards/VARIOUS.json)
33
+		maximum_ram_size = board.get("upload.maximum_ram_size")
34
+
35
+		for i, flag in enumerate(env["LINKFLAGS"]):
36
+			if "-Wl,--defsym=LD_FLASH_OFFSET" in flag:
37
+				env["LINKFLAGS"][i] = "-Wl,--defsym=LD_FLASH_OFFSET=" + LD_FLASH_OFFSET
38
+			if "-Wl,--defsym=LD_MAX_DATA_SIZE" in flag:
39
+				env["LINKFLAGS"][i] = "-Wl,--defsym=LD_MAX_DATA_SIZE=" + str(maximum_ram_size - 40)
40
+
41
+	#
42
+	# For build.encrypt rename and encode the firmware file.
43
+	#
44
+	if 'encrypt' in board_keys:
45
+
46
+		# Encrypt ${PROGNAME}.bin and save it with the name given in build.encrypt
47
+		def encrypt(source, target, env):
48
+			marlin.encrypt_mks(source, target, env, board.get("build.encrypt"))
49
+
50
+		if board.get("build.encrypt") != "":
51
+			marlin.add_post_action(encrypt)
52
+
53
+	#
54
+	# For build.rename simply rename the firmware file.
55
+	#
56
+	if 'rename' in board_keys:
57
+
58
+		def rename_target(source, target, env):
59
+			firmware = os.path.join(target[0].dir.path, board.get("build.rename"))
60
+			import shutil
61
+			shutil.copy(target[0].path, firmware)
62
+
63
+		marlin.add_post_action(rename_target)

+ 15
- 13
buildroot/share/PlatformIO/scripts/openblt.py Прегледај датотеку

@@ -1,18 +1,20 @@
1 1
 #
2 2
 # Convert the ELF to an SREC file suitable for some bootloaders
3 3
 #
4
-import os,sys
5
-from os.path import join
4
+import pioutil
5
+if pioutil.is_pio_build():
6
+	import os,sys
7
+	from os.path import join
6 8
 
7
-Import("env")
9
+	Import("env")
8 10
 
9
-board = env.BoardConfig()
10
-board_keys = board.get("build").keys()
11
-if 'encrypt' in board_keys:
12
-	env.AddPostAction(
13
-		join("$BUILD_DIR", "${PROGNAME}.bin"),
14
-		env.VerboseAction(" ".join([
15
-			"$OBJCOPY", "-O", "srec",
16
-			"\"$BUILD_DIR/${PROGNAME}.elf\"", "\"" + join("$BUILD_DIR", board.get("build.encrypt")) + "\""
17
-		]), "Building $TARGET")
18
-	)
11
+	board = env.BoardConfig()
12
+	board_keys = board.get("build").keys()
13
+	if 'encrypt' in board_keys:
14
+		env.AddPostAction(
15
+			join("$BUILD_DIR", "${PROGNAME}.bin"),
16
+			env.VerboseAction(" ".join([
17
+				"$OBJCOPY", "-O", "srec",
18
+				"\"$BUILD_DIR/${PROGNAME}.elf\"", "\"" + join("$BUILD_DIR", board.get("build.encrypt")) + "\""
19
+			]), "Building $TARGET")
20
+		)

+ 4
- 4
buildroot/share/PlatformIO/scripts/pioutil.py Прегледај датотеку

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

+ 81
- 82
buildroot/share/PlatformIO/scripts/preflight-checks.py Прегледај датотеку

@@ -2,100 +2,99 @@
2 2
 # preflight-checks.py
3 3
 # Check for common issues prior to compiling
4 4
 #
5
-import os,re,sys,pioutil
6
-Import("env")
5
+import pioutil
6
+if pioutil.is_pio_build():
7 7
 
8
-# Detect that 'vscode init' is running
9
-if pioutil.is_vscode_init():
10
-	env.Exit(0)
8
+	import os,re,sys
9
+	Import("env")
11 10
 
12
-def get_envs_for_board(board):
13
-	with open(os.path.join("Marlin", "src", "pins", "pins.h"), "r") as file:
11
+	def get_envs_for_board(board):
12
+		with open(os.path.join("Marlin", "src", "pins", "pins.h"), "r") as file:
14 13
 
15
-		if sys.platform == 'win32':
16
-			envregex = r"(?:env|win):"
17
-		elif sys.platform == 'darwin':
18
-			envregex = r"(?:env|mac|uni):"
19
-		elif sys.platform == 'linux':
20
-			envregex = r"(?:env|lin|uni):"
21
-		else:
22
-			envregex = r"(?:env):"
14
+			if sys.platform == 'win32':
15
+				envregex = r"(?:env|win):"
16
+			elif sys.platform == 'darwin':
17
+				envregex = r"(?:env|mac|uni):"
18
+			elif sys.platform == 'linux':
19
+				envregex = r"(?:env|lin|uni):"
20
+			else:
21
+				envregex = r"(?:env):"
23 22
 
24
-		r = re.compile(r"if\s+MB\((.+)\)")
25
-		if board.startswith("BOARD_"):
26
-			board = board[6:]
23
+			r = re.compile(r"if\s+MB\((.+)\)")
24
+			if board.startswith("BOARD_"):
25
+				board = board[6:]
27 26
 
28
-		for line in file:
29
-			mbs = r.findall(line)
30
-			if mbs and board in re.split(r",\s*", mbs[0]):
31
-				line = file.readline()
32
-				found_envs = re.match(r"\s*#include .+" + envregex, line)
33
-				if found_envs:
34
-					envlist = re.findall(envregex + r"(\w+)", line)
35
-					return [ "env:"+s for s in envlist ]
36
-	return []
27
+			for line in file:
28
+				mbs = r.findall(line)
29
+				if mbs and board in re.split(r",\s*", mbs[0]):
30
+					line = file.readline()
31
+					found_envs = re.match(r"\s*#include .+" + envregex, line)
32
+					if found_envs:
33
+						envlist = re.findall(envregex + r"(\w+)", line)
34
+						return [ "env:"+s for s in envlist ]
35
+		return []
37 36
 
38
-def check_envs(build_env, board_envs, config):
39
-	if build_env in board_envs:
40
-		return True
41
-	ext = config.get(build_env, 'extends', default=None)
42
-	if ext:
43
-		if isinstance(ext, str):
44
-			return check_envs(ext, board_envs, config)
45
-		elif isinstance(ext, list):
46
-			for ext_env in ext:
47
-				if check_envs(ext_env, board_envs, config):
48
-					return True
49
-	return False
37
+	def check_envs(build_env, board_envs, config):
38
+		if build_env in board_envs:
39
+			return True
40
+		ext = config.get(build_env, 'extends', default=None)
41
+		if ext:
42
+			if isinstance(ext, str):
43
+				return check_envs(ext, board_envs, config)
44
+			elif isinstance(ext, list):
45
+				for ext_env in ext:
46
+					if check_envs(ext_env, board_envs, config):
47
+						return True
48
+		return False
50 49
 
51
-def sanity_check_target():
52
-	# Sanity checks:
53
-	if 'PIOENV' not in env:
54
-		raise SystemExit("Error: PIOENV is not defined. This script is intended to be used with PlatformIO")
50
+	def sanity_check_target():
51
+		# Sanity checks:
52
+		if 'PIOENV' not in env:
53
+			raise SystemExit("Error: PIOENV is not defined. This script is intended to be used with PlatformIO")
55 54
 
56
-	if 'MARLIN_FEATURES' not in env:
57
-		raise SystemExit("Error: this script should be used after common Marlin scripts")
55
+		if 'MARLIN_FEATURES' not in env:
56
+			raise SystemExit("Error: this script should be used after common Marlin scripts")
58 57
 
59
-	if 'MOTHERBOARD' not in env['MARLIN_FEATURES']:
60
-		raise SystemExit("Error: MOTHERBOARD is not defined in Configuration.h")
58
+		if 'MOTHERBOARD' not in env['MARLIN_FEATURES']:
59
+			raise SystemExit("Error: MOTHERBOARD is not defined in Configuration.h")
61 60
 
62
-	build_env = env['PIOENV']
63
-	motherboard = env['MARLIN_FEATURES']['MOTHERBOARD']
64
-	board_envs = get_envs_for_board(motherboard)
65
-	config = env.GetProjectConfig()
66
-	result = check_envs("env:"+build_env, board_envs, config)
61
+		build_env = env['PIOENV']
62
+		motherboard = env['MARLIN_FEATURES']['MOTHERBOARD']
63
+		board_envs = get_envs_for_board(motherboard)
64
+		config = env.GetProjectConfig()
65
+		result = check_envs("env:"+build_env, board_envs, config)
67 66
 
68
-	if not result:
69
-		err = "Error: Build environment '%s' is incompatible with %s. Use one of these: %s" % \
70
-			  ( build_env, motherboard, ", ".join([ e[4:] for e in board_envs if e.startswith("env:") ]) )
71
-		raise SystemExit(err)
67
+		if not result:
68
+			err = "Error: Build environment '%s' is incompatible with %s. Use one of these: %s" % \
69
+				  ( build_env, motherboard, ", ".join([ e[4:] for e in board_envs if e.startswith("env:") ]) )
70
+			raise SystemExit(err)
72 71
 
73
-	#
74
-	# Check for Config files in two common incorrect places
75
-	#
76
-	for p in [ env['PROJECT_DIR'], os.path.join(env['PROJECT_DIR'], "config") ]:
77
-		for f in [ "Configuration.h", "Configuration_adv.h" ]:
78
-			if os.path.isfile(os.path.join(p, f)):
79
-				err = "ERROR: Config files found in directory %s. Please move them into the Marlin subfolder." % p
80
-				raise SystemExit(err)
72
+		#
73
+		# Check for Config files in two common incorrect places
74
+		#
75
+		for p in [ env['PROJECT_DIR'], os.path.join(env['PROJECT_DIR'], "config") ]:
76
+			for f in [ "Configuration.h", "Configuration_adv.h" ]:
77
+				if os.path.isfile(os.path.join(p, f)):
78
+					err = "ERROR: Config files found in directory %s. Please move them into the Marlin subfolder." % p
79
+					raise SystemExit(err)
81 80
 
82
-	#
83
-	# Give warnings on every build
84
-	#
85
-	warnfile = os.path.join(env['PROJECT_BUILD_DIR'], build_env, "src", "src", "inc", "Warnings.cpp.o")
86
-	if os.path.exists(warnfile):
87
-		os.remove(warnfile)
81
+		#
82
+		# Give warnings on every build
83
+		#
84
+		warnfile = os.path.join(env['PROJECT_BUILD_DIR'], build_env, "src", "src", "inc", "Warnings.cpp.o")
85
+		if os.path.exists(warnfile):
86
+			os.remove(warnfile)
88 87
 
89
-	#
90
-	# Check for old files indicating an entangled Marlin (mixing old and new code)
91
-	#
92
-	mixedin = []
93
-	p = os.path.join(env['PROJECT_DIR'], "Marlin", "src", "lcd", "dogm")
94
-	for f in [ "ultralcd_DOGM.cpp", "ultralcd_DOGM.h" ]:
95
-		if os.path.isfile(os.path.join(p, f)):
96
-			mixedin += [ f ]
97
-	if mixedin:
98
-		err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin)
99
-		raise SystemExit(err)
88
+		#
89
+		# Check for old files indicating an entangled Marlin (mixing old and new code)
90
+		#
91
+		mixedin = []
92
+		p = os.path.join(env['PROJECT_DIR'], "Marlin", "src", "lcd", "dogm")
93
+		for f in [ "ultralcd_DOGM.cpp", "ultralcd_DOGM.h" ]:
94
+			if os.path.isfile(os.path.join(p, f)):
95
+				mixedin += [ f ]
96
+		if mixedin:
97
+			err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin)
98
+			raise SystemExit(err)
100 99
 
101
-sanity_check_target()
100
+	sanity_check_target()

+ 5
- 5
buildroot/share/PlatformIO/scripts/random-bin.py Прегледај датотеку

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

+ 9
- 7
buildroot/share/PlatformIO/scripts/robin.py Прегледај датотеку

@@ -1,12 +1,14 @@
1 1
 #
2
-# buildroot/share/PlatformIO/scripts/robin.py
2
+# robin.py
3 3
 #
4
-import marlin
5 4
 
6 5
 # Apply customizations for a MKS Robin
7 6
 def prepare(address, ldname, fwname):
8
-	def encrypt(source, target, env):
9
-		marlin.encrypt_mks(source, target, env, fwname)
10
-	marlin.relocate_firmware(address)
11
-	marlin.custom_ld_script(ldname)
12
-	marlin.add_post_action(encrypt);
7
+	import pioutil
8
+	if pioutil.is_pio_build():
9
+		import marlin
10
+		def encrypt(source, target, env):
11
+			marlin.encrypt_mks(source, target, env, fwname)
12
+		marlin.relocate_firmware(address)
13
+		marlin.custom_ld_script(ldname)
14
+		marlin.add_post_action(encrypt);

+ 35
- 33
buildroot/share/PlatformIO/scripts/simulator.py Прегледај датотеку

@@ -1,52 +1,54 @@
1 1
 #
2
+# simulator.py
2 3
 # PlatformIO pre: script for simulator builds
3 4
 #
5
+import pioutil
6
+if pioutil.is_pio_build():
7
+	# Get the environment thus far for the build
8
+	Import("env")
4 9
 
5
-# Get the environment thus far for the build
6
-Import("env")
10
+	#print(env.Dump())
7 11
 
8
-#print(env.Dump())
12
+	#
13
+	# Give the binary a distinctive name
14
+	#
9 15
 
10
-#
11
-# Give the binary a distinctive name
12
-#
13
-
14
-env['PROGNAME'] = "MarlinSimulator"
16
+	env['PROGNAME'] = "MarlinSimulator"
15 17
 
16
-#
17
-# If Xcode is installed add the path to its Frameworks folder,
18
-# or if Mesa is installed try to use its GL/gl.h.
19
-#
18
+	#
19
+	# If Xcode is installed add the path to its Frameworks folder,
20
+	# or if Mesa is installed try to use its GL/gl.h.
21
+	#
20 22
 
21
-import sys
22
-if sys.platform == 'darwin':
23
+	import sys
24
+	if sys.platform == 'darwin':
23 25
 
24
-  #
25
-  # Silence half of the ranlib warnings. (No equivalent for 'ARFLAGS')
26
-  #
27
-  env['RANLIBFLAGS'] += [ "-no_warning_for_no_symbols" ]
26
+		#
27
+		# Silence half of the ranlib warnings. (No equivalent for 'ARFLAGS')
28
+		#
29
+		env['RANLIBFLAGS'] += [ "-no_warning_for_no_symbols" ]
28 30
 
29
-  # Default paths for Xcode and a lucky GL/gl.h dropped by Mesa
30
-  xcode_path = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
31
-  mesa_path = "/opt/local/include/GL/gl.h"
31
+		# Default paths for Xcode and a lucky GL/gl.h dropped by Mesa
32
+		xcode_path = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
33
+		mesa_path = "/opt/local/include/GL/gl.h"
32 34
 
33
-  import os.path
35
+		import os.path
34 36
 
35
-  if os.path.exists(xcode_path):
37
+		if os.path.exists(xcode_path):
36 38
 
37
-    env['BUILD_FLAGS'] += [ "-F" + xcode_path ]
38
-    print("Using OpenGL framework headers from Xcode.app")
39
+			env['BUILD_FLAGS'] += [ "-F" + xcode_path ]
40
+			print("Using OpenGL framework headers from Xcode.app")
39 41
 
40
-  elif os.path.exists(mesa_path):
42
+		elif os.path.exists(mesa_path):
41 43
 
42
-    env['BUILD_FLAGS'] += [ '-D__MESA__' ]
43
-    print("Using OpenGL header from", mesa_path)
44
+			env['BUILD_FLAGS'] += [ '-D__MESA__' ]
45
+			print("Using OpenGL header from", mesa_path)
44 46
 
45
-  else:
47
+		else:
46 48
 
47
-    print("\n\nNo OpenGL headers found. Install Xcode for matching headers, or use 'sudo port install mesa' to get a GL/gl.h.\n\n")
49
+			print("\n\nNo OpenGL headers found. Install Xcode for matching headers, or use 'sudo port install mesa' to get a GL/gl.h.\n\n")
48 50
 
49
-    # Break out of the PIO build immediately
50
-    sys.exit(1)
51
+			# Break out of the PIO build immediately
52
+			sys.exit(1)
51 53
 
52
-env.AddCustomTarget("upload", "$BUILD_DIR/${PROGNAME}", "$BUILD_DIR/${PROGNAME}")
54
+	env.AddCustomTarget("upload", "$BUILD_DIR/${PROGNAME}", "$BUILD_DIR/${PROGNAME}")

+ 58
- 56
buildroot/share/PlatformIO/scripts/stm32_serialbuffer.py Прегледај датотеку

@@ -1,59 +1,61 @@
1 1
 #
2 2
 # stm32_serialbuffer.py
3 3
 #
4
-Import("env")
5
-
6
-# Marlin uses the `RX_BUFFER_SIZE` \ `TX_BUFFER_SIZE` options to
7
-# configure buffer sizes for receiving \ transmitting serial data.
8
-# Stm32duino uses another set of defines for the same purpose, so this
9
-# script gets the values from the configuration and uses them to define
10
-# `SERIAL_RX_BUFFER_SIZE` and `SERIAL_TX_BUFFER_SIZE` as global build
11
-# flags so they are available for use by the platform.
12
-#
13
-# The script will set the value as the default one (64 bytes)
14
-# or the user-configured one, whichever is higher.
15
-#
16
-# Marlin's default buffer sizes are 128 for RX and 32 for TX.
17
-# The highest value is taken (128/64).
18
-#
19
-# If MF_*_BUFFER_SIZE, SERIAL_*_BUFFER_SIZE, USART_*_BUF_SIZE, are
20
-# defined, the first of these values will be used as the minimum.
21
-build_flags = env.ParseFlags(env.get('BUILD_FLAGS'))["CPPDEFINES"]
22
-mf = env["MARLIN_FEATURES"]
23
-
24
-# Get a build flag's value or None
25
-def getBuildFlagValue(name):
26
-	for flag in build_flags:
27
-		if isinstance(flag, list) and flag[0] == name:
28
-			return flag[1]
29
-
30
-	return None
31
-
32
-# Get an overriding buffer size for RX or TX from the build flags
33
-def getInternalSize(side):
34
-	return	getBuildFlagValue(f"MF_{side}_BUFFER_SIZE") or \
35
-			getBuildFlagValue(f"SERIAL_{side}_BUFFER_SIZE") or \
36
-			getBuildFlagValue(f"USART_{side}_BUF_SIZE")
37
-
38
-# Get the largest defined buffer size for RX or TX
39
-def getBufferSize(side, default):
40
-	# Get a build flag value or fall back to the given default
41
-	internal = int(getInternalSize(side) or default)
42
-	flag = side + "_BUFFER_SIZE"
43
-	# Return the largest value
44
-	return max(int(mf[flag]), internal) if flag in mf else internal
45
-
46
-# Add a build flag if it's not already defined
47
-def tryAddFlag(name, value):
48
-	if getBuildFlagValue(name) is None:
49
-		env.Append(BUILD_FLAGS=[f"-D{name}={value}"])
50
-
51
-# Get the largest defined buffer sizes for RX or TX, using defaults for undefined
52
-rxBuf = getBufferSize("RX", 128)
53
-txBuf = getBufferSize("TX",  64)
54
-
55
-# Provide serial buffer sizes to the stm32duino platform
56
-tryAddFlag("SERIAL_RX_BUFFER_SIZE", rxBuf)
57
-tryAddFlag("SERIAL_TX_BUFFER_SIZE", txBuf)
58
-tryAddFlag("USART_RX_BUF_SIZE", rxBuf)
59
-tryAddFlag("USART_TX_BUF_SIZE", txBuf)
4
+import pioutil
5
+if pioutil.is_pio_build():
6
+	Import("env")
7
+
8
+	# Get a build flag's value or None
9
+	def getBuildFlagValue(name):
10
+		for flag in build_flags:
11
+			if isinstance(flag, list) and flag[0] == name:
12
+				return flag[1]
13
+
14
+		return None
15
+
16
+	# Get an overriding buffer size for RX or TX from the build flags
17
+	def getInternalSize(side):
18
+		return	getBuildFlagValue(f"MF_{side}_BUFFER_SIZE") or \
19
+				getBuildFlagValue(f"SERIAL_{side}_BUFFER_SIZE") or \
20
+				getBuildFlagValue(f"USART_{side}_BUF_SIZE")
21
+
22
+	# Get the largest defined buffer size for RX or TX
23
+	def getBufferSize(side, default):
24
+		# Get a build flag value or fall back to the given default
25
+		internal = int(getInternalSize(side) or default)
26
+		flag = side + "_BUFFER_SIZE"
27
+		# Return the largest value
28
+		return max(int(mf[flag]), internal) if flag in mf else internal
29
+
30
+	# Add a build flag if it's not already defined
31
+	def tryAddFlag(name, value):
32
+		if getBuildFlagValue(name) is None:
33
+			env.Append(BUILD_FLAGS=[f"-D{name}={value}"])
34
+
35
+	# Marlin uses the `RX_BUFFER_SIZE` \ `TX_BUFFER_SIZE` options to
36
+	# configure buffer sizes for receiving \ transmitting serial data.
37
+	# Stm32duino uses another set of defines for the same purpose, so this
38
+	# script gets the values from the configuration and uses them to define
39
+	# `SERIAL_RX_BUFFER_SIZE` and `SERIAL_TX_BUFFER_SIZE` as global build
40
+	# flags so they are available for use by the platform.
41
+	#
42
+	# The script will set the value as the default one (64 bytes)
43
+	# or the user-configured one, whichever is higher.
44
+	#
45
+	# Marlin's default buffer sizes are 128 for RX and 32 for TX.
46
+	# The highest value is taken (128/64).
47
+	#
48
+	# If MF_*_BUFFER_SIZE, SERIAL_*_BUFFER_SIZE, USART_*_BUF_SIZE, are
49
+	# defined, the first of these values will be used as the minimum.
50
+	build_flags = env.ParseFlags(env.get('BUILD_FLAGS'))["CPPDEFINES"]
51
+	mf = env["MARLIN_FEATURES"]
52
+
53
+	# Get the largest defined buffer sizes for RX or TX, using defaults for undefined
54
+	rxBuf = getBufferSize("RX", 128)
55
+	txBuf = getBufferSize("TX",  64)
56
+
57
+	# Provide serial buffer sizes to the stm32duino platform
58
+	tryAddFlag("SERIAL_RX_BUFFER_SIZE", rxBuf)
59
+	tryAddFlag("SERIAL_TX_BUFFER_SIZE", txBuf)
60
+	tryAddFlag("USART_RX_BUF_SIZE", rxBuf)
61
+	tryAddFlag("USART_TX_BUF_SIZE", txBuf)

+ 0
- 1
ini/stm32f1-maple.ini Прегледај датотеку

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

Loading…
Откажи
Сачувај