]> Git Repo - pico-vscode.git/blob - scripts/pico_project.py
Check if pico-vscode.cmake file exists
[pico-vscode.git] / scripts / pico_project.py
1 #!/usr/bin/env python3
2
3 #
4 # Copyright (c) 2020-2024 Raspberry Pi (Trading) Ltd.
5 #
6 # SPDX-License-Identifier: BSD-3-Clause
7 #
8
9 #
10 # Copyright (c) 2023-2024 paulober <github.com/paulober>
11 #
12 # SPDX-License-Identifier: MPL-2.0
13 #
14
15 import argparse
16 import os
17 import shutil
18 from pathlib import Path
19 import sys
20 import re
21 import platform
22 import csv
23
24 CMAKELIST_FILENAME = 'CMakeLists.txt'
25 CMAKECACHE_FILENAME = 'CMakeCache.txt'
26
27 ARM_TRIPLE = 'arm-none-eabi'
28 RISCV_TRIPLE = 'riscv32-unknown-elf'
29 COREV_TRIPLE = 'riscv32-corev-elf'
30 COMPILER_TRIPLE = ARM_TRIPLE
31 def COMPILER_NAME():
32     return f"{COMPILER_TRIPLE}-gcc"
33 def GDB_NAME():
34     return f"{COMPILER_TRIPLE}-gdb"
35 CMAKE_TOOLCHAIN_NAME = "pico_arm_gcc.cmake"
36
37 VSCODE_LAUNCH_FILENAME = 'launch.json'
38 VSCODE_C_PROPERTIES_FILENAME = 'c_cpp_properties.json'
39 VSCODE_CMAKE_KITS_FILENAME ='cmake-kits.json'
40 VSCODE_SETTINGS_FILENAME ='settings.json'
41 VSCODE_EXTENSIONS_FILENAME ='extensions.json'
42 VSCODE_TASKS_FILENAME ='tasks.json'
43 VSCODE_FOLDER='.vscode'
44
45 CONFIG_UNSET="Not set"
46
47 # Standard libraries for all builds
48 # And any more to string below, space separator
49 STANDARD_LIBRARIES = 'pico_stdlib'
50
51 # Indexed on feature name, tuple contains the C file, the H file and the CMake project name for the feature. 
52 # Some lists may contain an extra/ancillary file needed for that feature
53 GUI_TEXT = 0
54 C_FILE = 1
55 H_FILE = 2
56 LIB_NAME = 3
57 ANCILLARY_FILE = 4
58
59 features_list = {
60     'spi' :             ("SPI",             "spi.c",            "hardware/spi.h",       "hardware_spi",         ""),
61     'i2c' :             ("I2C interface",   "i2c.c",            "hardware/i2c.h",       "hardware_i2c",         ""),
62     'dma' :             ("DMA support",     "dma.c",            "hardware/dma.h",       "hardware_dma",         ""),
63     'pio' :             ("PIO interface",   "pio.c",            "hardware/pio.h",       "hardware_pio",         "blink.pio"),
64     'interp' :          ("HW interpolation", "interp.c",        "hardware/interp.h",    "hardware_interp",      ""),
65     'timer' :           ("HW timer",        "timer.c",          "hardware/timer.h",     "hardware_timer",       ""),
66     'watchdog' :        ("HW watchdog",     "watch.c",          "hardware/watchdog.h",  "hardware_watchdog",    ""),
67     'clocks' :          ("HW clocks",       "clocks.c",         "hardware/clocks.h",    "hardware_clocks",      ""),
68 }
69
70 picow_options_list = {
71     'picow_none' :      ("None", "",                            "",    "",                                                                  ""),
72     'picow_led' :       ("PicoW onboard LED", "",               "pico/cyw43_arch.h",    "pico_cyw43_arch_none",                             ""),
73     'picow_poll' :      ("Polled lwIP",     "",                 "pico/cyw43_arch.h",    "pico_cyw43_arch_lwip_poll",                        "lwipopts.h"),
74     'picow_background' :("Background lwIP", "",                 "pico/cyw43_arch.h",    "pico_cyw43_arch_lwip_threadsafe_background",       "lwipopts.h"),
75 #    'picow_freertos' :  ("Full lwIP (FreeRTOS)", "",            "pico/cyw43_arch.h",    "pico_cyw43_arch_lwip_sys_freertos",                "lwipopts.h"),
76 }
77
78 stdlib_examples_list = {
79     'uart':     ("UART",                    "uart.c",           "hardware/uart.h",      "hardware_uart"),
80     'gpio' :    ("GPIO interface",          "gpio.c",           "hardware/gpio.h",      "hardware_gpio"),
81     'div' :     ("Low level HW Divider",    "divider.c",        "hardware/divider.h",   "hardware_divider")
82 }
83
84 debugger_list = ["DebugProbe (CMSIS-DAP)", "SWD (Pi host)"]
85 debugger_config_list = ["interface/cmsis-dap.cfg", "raspberrypi-swd.cfg"]
86
87 DEFINES = 0
88 INITIALISERS = 1
89 # Could add an extra item that shows how to use some of the available functions for the feature
90 #EXAMPLE = 2
91
92 # This also contains example code for the standard library (see stdlib_examples_list)
93 code_fragments_per_feature = {
94     'uart' : [
95               (
96                 "// UART defines",
97                 "// By default the stdout UART is `uart0`, so we will use the second one",
98                 "#define UART_ID uart1",
99                 "#define BAUD_RATE 9600", "",
100                 "// Use pins 4 and 5 for UART1",
101                 "// Pins can be changed, see the GPIO function select table in the datasheet for information on GPIO assignments",
102                 "#define UART_TX_PIN 4",
103                 "#define UART_RX_PIN 5"
104               ),
105               (
106                 "// Set up our UART",
107                 "uart_init(UART_ID, BAUD_RATE);",
108                 "// Set the TX and RX pins by using the function select on the GPIO",
109                 "// Set datasheet for more information on function select",
110                 "gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);",
111                 "gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);",
112                 "// For more examples of UART use see https://github.com/raspberrypi/pico-examples/tree/master/uart"
113               )
114             ],
115     'spi' : [
116               (
117                 "// SPI Defines",
118                 "// We are going to use SPI 0, and allocate it to the following GPIO pins",
119                 "// Pins can be changed, see the GPIO function select table in the datasheet for information on GPIO assignments",
120                 "#define SPI_PORT spi0",
121                 "#define PIN_MISO 16",
122                 "#define PIN_CS   17",
123                 "#define PIN_SCK  18",
124                 "#define PIN_MOSI 19"
125               ),
126               (
127                 "// SPI initialisation. This example will use SPI at 1MHz.",
128                 "spi_init(SPI_PORT, 1000*1000);",
129                 "gpio_set_function(PIN_MISO, GPIO_FUNC_SPI);",
130                 "gpio_set_function(PIN_CS,   GPIO_FUNC_SIO);",
131                 "gpio_set_function(PIN_SCK,  GPIO_FUNC_SPI);",
132                 "gpio_set_function(PIN_MOSI, GPIO_FUNC_SPI);", "",
133                 "// Chip select is active-low, so we'll initialise it to a driven-high state",
134                 "gpio_set_dir(PIN_CS, GPIO_OUT);",
135                 "gpio_put(PIN_CS, 1);",
136                 "// For more examples of SPI use see https://github.com/raspberrypi/pico-examples/tree/master/spi"
137               )
138             ],
139     'i2c' : [
140               (
141                 "// I2C defines",
142                 "// This example will use I2C0 on GPIO8 (SDA) and GPIO9 (SCL) running at 400KHz.",
143                 "// Pins can be changed, see the GPIO function select table in the datasheet for information on GPIO assignments",
144                 "#define I2C_PORT i2c0",
145                 "#define I2C_SDA 8",
146                 "#define I2C_SCL 9",
147               ),
148               (
149                 "// I2C Initialisation. Using it at 400Khz.",
150                 "i2c_init(I2C_PORT, 400*1000);","",
151                 "gpio_set_function(I2C_SDA, GPIO_FUNC_I2C);",
152                 "gpio_set_function(I2C_SCL, GPIO_FUNC_I2C);",
153                 "gpio_pull_up(I2C_SDA);",
154                 "gpio_pull_up(I2C_SCL);",
155                 "// For more examples of I2C use see https://github.com/raspberrypi/pico-examples/tree/master/i2c",
156               )
157             ],
158     "dma" : [
159               (
160                 '// Data will be copied from src to dst',
161                 'const char src[] = "Hello, world! (from DMA)";',
162                 'char dst[count_of(src)];',
163               ),
164               (
165                 '// Get a free channel, panic() if there are none',
166                 'int chan = dma_claim_unused_channel(true);',
167                 '',
168                 '// 8 bit transfers. Both read and write address increment after each',
169                 '// transfer (each pointing to a location in src or dst respectively).',
170                 '// No DREQ is selected, so the DMA transfers as fast as it can.',
171                 '',
172                 'dma_channel_config c = dma_channel_get_default_config(chan);',
173                 'channel_config_set_transfer_data_size(&c, DMA_SIZE_8);',
174                 'channel_config_set_read_increment(&c, true);',
175                 'channel_config_set_write_increment(&c, true);',
176                 '',
177                 'dma_channel_configure(',
178                 '    chan,          // Channel to be configured',
179                 '    &c,            // The configuration we just created',
180                 '    dst,           // The initial write address',
181                 '    src,           // The initial read address',
182                 '    count_of(src), // Number of transfers; in this case each is 1 byte.',
183                 '    true           // Start immediately.',
184                 ');',
185                 '',
186                 '// We could choose to go and do something else whilst the DMA is doing its',
187                 '// thing. In this case the processor has nothing else to do, so we just',
188                 '// wait for the DMA to finish.',
189                 'dma_channel_wait_for_finish_blocking(chan);',
190                 '',
191                 '// The DMA has now copied our text from the transmit buffer (src) to the',
192                 '// receive buffer (dst), so we can print it out from there.',
193                 'puts(dst);',
194               )
195             ],
196
197     "pio" : [
198               (
199                 '#include "blink.pio.h"','',
200                 'void blink_pin_forever(PIO pio, uint sm, uint offset, uint pin, uint freq) {',
201                 '    blink_program_init(pio, sm, offset, pin);',
202                 '    pio_sm_set_enabled(pio, sm, true);',
203                 '',
204                 '    printf("Blinking pin %d at %d Hz\\n", pin, freq);',
205                 '',
206                 '    // PIO counter program takes 3 more cycles in total than we pass as',
207                 '    // input (wait for n + 1; mov; jmp)',
208                 '    pio->txf[sm] = (125000000 / (2 * freq)) - 3;',
209                 '}',
210               ),
211               (
212                 '// PIO Blinking example',
213                 'PIO pio = pio0;',
214                 'uint offset = pio_add_program(pio, &blink_program);',
215                 'printf("Loaded program at %d\\n", offset);',
216                 '',
217                 '#ifdef PICO_DEFAULT_LED_PIN',
218                 'blink_pin_forever(pio, 0, offset, PICO_DEFAULT_LED_PIN, 3);',
219                 '#else',
220                 'blink_pin_forever(pio, 0, offset, 6, 3);',
221                 '#endif',
222                 '// For more pio examples see https://github.com/raspberrypi/pico-examples/tree/master/pio',
223               )
224             ],
225
226     "clocks" :  [
227                   (),
228                   (
229                     'printf("System Clock Frequency is %d Hz\\n", clock_get_hz(clk_sys));',
230                     'printf("USB Clock Frequency is %d Hz\\n", clock_get_hz(clk_usb));',
231                     '// For more examples of clocks use see https://github.com/raspberrypi/pico-examples/tree/master/clocks',
232                   )
233                 ],
234
235     "gpio" : [
236               (
237                 "// GPIO defines",
238                 "// Example uses GPIO 2",
239                 "#define GPIO 2"
240               ),
241               (
242                 "// GPIO initialisation.",
243                 "// We will make this GPIO an input, and pull it up by default",
244                 "gpio_init(GPIO);",
245                 "gpio_set_dir(GPIO, GPIO_IN);",
246                 "gpio_pull_up(GPIO);",
247                 "// See https://github.com/raspberrypi/pico-examples/tree/master/gpio for other gpio examples, including using interrupts",
248               )
249             ],
250     "interp" :[
251                (),
252                (
253                 "// Interpolator example code",
254                 "interp_config cfg = interp_default_config();",
255                 "// Now use the various interpolator library functions for your use case",
256                 "// e.g. interp_config_clamp(&cfg, true);",
257                 "//      interp_config_shift(&cfg, 2);",
258                 "// Then set the config ",
259                 "interp_set_config(interp0, 0, &cfg);",
260                 "// For examples of interpolator use see https://github.com/raspberrypi/pico-examples/tree/master/interp"
261                )
262               ],
263
264     "timer"  : [
265                 (
266                  "int64_t alarm_callback(alarm_id_t id, void *user_data) {",
267                  "    // Put your timeout handler code in here",
268                  "    return 0;",
269                  "}"
270                 ),
271                 (
272                  "// Timer example code - This example fires off the callback after 2000ms",
273                  "add_alarm_in_ms(2000, alarm_callback, NULL, false);",
274                  "// For more examples of timer use see https://github.com/raspberrypi/pico-examples/tree/master/timer"
275                 )
276               ],
277
278     "watchdog":[ (),
279                 (
280                     "// Watchdog example code",
281                     "if (watchdog_caused_reboot()) {",
282                     "    printf(\"Rebooted by Watchdog!\\n\");",
283                     "    // Whatever action you may take if a watchdog caused a reboot",
284                     "}","",
285                     "// Enable the watchdog, requiring the watchdog to be updated every 100ms or the chip will reboot",
286                     "// second arg is pause on debug which means the watchdog will pause when stepping through code",
287                     "watchdog_enable(100, 1);","",
288                     "// You need to call this function at least more often than the 100ms in the enable call to prevent a reboot",
289                     "watchdog_update();",
290                 )
291               ],
292
293     "div"    : [ (),
294                  (
295                     "// Example of using the HW divider. The pico_divider library provides a more user friendly set of APIs ",
296                     "// over the divider (and support for 64 bit divides), and of course by default regular C language integer",
297                     "// divisions are redirected thru that library, meaning you can just use C level `/` and `%` operators and",
298                     "// gain the benefits of the fast hardware divider.",
299                     "int32_t dividend = 123456;",
300                     "int32_t divisor = -321;",
301                     "// This is the recommended signed fast divider for general use.",
302                     "divmod_result_t result = hw_divider_divmod_s32(dividend, divisor);",
303                     "printf(\"%d/%d = %d remainder %d\\n\", dividend, divisor, to_quotient_s32(result), to_remainder_s32(result));",
304                     "// This is the recommended unsigned fast divider for general use.",
305                     "int32_t udividend = 123456;",
306                     "int32_t udivisor = 321;",
307                     "divmod_result_t uresult = hw_divider_divmod_u32(udividend, udivisor);",
308                     "printf(\"%d/%d = %d remainder %d\\n\", udividend, udivisor, to_quotient_u32(uresult), to_remainder_u32(uresult));",
309                     "// See https://github.com/raspberrypi/pico-examples/tree/master/divider for more complex use"
310                  )
311                 ],
312
313     "picow_led":[ (),
314                   (
315                     "// Example to turn on the Pico W LED",
316                     "cyw43_arch_gpio_put(CYW43_WL_GPIO_LED_PIN, 1);"
317                   )
318                 ],
319
320     "picow_wifi":[ (),
321                   (
322                     '// Enable wifi station',
323                     'cyw43_arch_enable_sta_mode();\n',
324                     'printf("Connecting to Wi-Fi...\\n");',
325                     'if (cyw43_arch_wifi_connect_timeout_ms("Your Wi-Fi SSID", "Your Wi-Fi Password", CYW43_AUTH_WPA2_AES_PSK, 30000)) {',
326                     '    printf("failed to connect.\\n");',
327                     '    return 1;',
328                     '} else {',
329                     '    printf("Connected.\\n");',
330                     '    // Read the ip address in a human readable way',
331                     '    uint8_t *ip_address = (uint8_t*)&(cyw43_state.netif[0].ip_addr.addr);',
332                     '    printf("IP address %d.%d.%d.%d\\n", ip_address[0], ip_address[1], ip_address[2], ip_address[3]);',
333                     '}',
334                   )
335                 ]
336 }
337
338 # Add wifi example for poll and background modes
339 code_fragments_per_feature["picow_poll"] = code_fragments_per_feature["picow_wifi"]
340 code_fragments_per_feature["picow_background"] = code_fragments_per_feature["picow_wifi"]
341
342 configuration_dictionary = list(dict())
343
344 isMac = False
345 isWindows = False
346 isx86 = False
347 compilerPath = Path(f"/usr/bin/{COMPILER_NAME()}")
348
349 def relativeSDKPath(sdkVersion):
350     return f"/.pico-sdk/sdk/{sdkVersion}"
351
352 def relativeToolchainPath(toolchainVersion):
353     return f"/.pico-sdk/toolchain/{toolchainVersion}"
354
355 def relativeToolsPath(sdkVersion):
356     return f"/.pico-sdk/tools/{sdkVersion}"
357
358 def relativePicotoolPath(picotoolVersion):
359     return f"/.pico-sdk/picotool/{picotoolVersion}"
360
361 def relativeOpenOCDPath(openocdVersion):
362     return f"/.pico-sdk/openocd/{openocdVersion}"
363
364 def cmakeIncPath():
365     return "${USERHOME}/.pico-sdk/cmake/pico-vscode.cmake"
366
367 def propertiesSdkPath(sdkVersion, force_windows=False, force_non_windows=False):
368     if (isWindows or force_windows) and not force_non_windows:
369         return f"${{env:USERPROFILE}}{relativeSDKPath(sdkVersion)}"
370     else:
371         return f"${{env:HOME}}{relativeSDKPath(sdkVersion)}"
372     
373 def propertiesPicotoolPath(picotoolVersion, force_windows=False, force_non_windows=False):
374     if (isWindows or force_windows) and not force_non_windows:
375         return f"${{env:USERPROFILE}}{relativePicotoolPath(picotoolVersion)}"
376     else:
377         return f"${{env:HOME}}{relativePicotoolPath(picotoolVersion)}"
378
379 def codeSdkPath(sdkVersion):
380     return f"${{userHome}}{relativeSDKPath(sdkVersion)}"
381
382 def codeOpenOCDPath(openocdVersion):
383     return f"${{userHome}}{relativeOpenOCDPath(openocdVersion)}"
384
385 def propertiesToolchainPath(toolchainVersion, force_windows=False, force_non_windows=False):
386     if (isWindows or force_windows) and not force_non_windows:
387         return f"${{env:USERPROFILE}}{relativeToolchainPath(toolchainVersion)}"
388     else:
389         return f"${{env:HOME}}{relativeToolchainPath(toolchainVersion)}"
390
391 def codeToolchainPath(toolchainVersion):
392     return f"${{userHome}}{relativeToolchainPath(toolchainVersion)}"
393
394 def semver_compare_ge(first, second):
395     """ Compare two semantic version strings and return True if the first is greater or equal to the second """
396     first_tuple = tuple(map(int, first.split(".")))
397     second_tuple = tuple(map(int, second.split(".")))
398     
399     assert len(first_tuple) == 3
400     assert len(second_tuple) == 3
401
402     return first_tuple >= second_tuple
403
404 def CheckPrerequisites():
405     global isMac, isWindows, isx86
406     isMac = (platform.system() == 'Darwin')
407     isWindows = (platform.system() == 'Windows')
408     isx86 = (platform.machine().lower() in ['x86_64', 'amd64'])
409
410     # Do we have a compiler?
411     return shutil.which(COMPILER_NAME(), 1, os.environ["Path" if isWindows else "PATH"])
412
413
414 def CheckSDKPath(gui):
415     sdkPath = os.getenv('PICO_SDK_PATH')
416
417     if sdkPath == None:
418         m = 'Unable to locate the Raspberry Pi Pico SDK, PICO_SDK_PATH is not set'
419         print(m)
420     elif not os.path.isdir(sdkPath):
421         m = 'Unable to locate the Raspberry Pi Pico SDK, PICO_SDK_PATH does not point to a directory'
422         print(m)
423         sdkPath = None
424
425     return sdkPath
426
427 def GetFilePath(filename):
428     if os.path.islink(__file__):
429         script_file = os.readlink(__file__)
430     else:
431         script_file = __file__
432     return os.path.join(os.path.dirname(script_file), filename)
433
434 def ParseCommandLine():
435     debugger_flags = ', '.join('{} = {}'.format(i, v) for i, v in enumerate(debugger_list))
436     parser = argparse.ArgumentParser(description='Pico Project generator')
437     parser.add_argument("name", nargs="?", help="Name of the project")
438     parser.add_argument("-t", "--tsv", help="Select an alternative pico_configs.tsv file", default=GetFilePath("pico_configs.tsv"))
439     parser.add_argument("-o", "--output", help="Set an alternative CMakeList.txt filename", default="CMakeLists.txt")
440     parser.add_argument("-x", "--examples", action='store_true', help="Add example code for the Pico standard library")
441     parser.add_argument("-l", "--list", action='store_true', help="List available features")
442     parser.add_argument("-c", "--configs", action='store_true', help="List available project configuration items")
443     parser.add_argument("-f", "--feature", action='append', help="Add feature to generated project")
444     parser.add_argument("-over", "--overwrite", action='store_true', help="Overwrite any existing project AND files")
445     parser.add_argument("-conv", "--convert", action='store_true', help="Convert any existing project - risks data loss")
446     parser.add_argument("-exam", "--example", action='store_true', help="Convert an examples folder to standalone project")
447     parser.add_argument("-b", "--build", action='store_true', help="Build after project created")
448     parser.add_argument("-g", "--gui", action='store_true', help="Run a GUI version of the project generator")
449     parser.add_argument("-p", "--project", action='append', help="Generate projects files for IDE. Options are: vscode")
450     parser.add_argument("-r", "--runFromRAM", action='store_true', help="Run the program from RAM rather than flash")
451     parser.add_argument("-uart", "--uart", action='store_true', default=1, help="Console output to UART (default)")
452     parser.add_argument("-nouart", "--nouart", action='store_true', default=0, help="Disable console output to UART")
453     parser.add_argument("-usb", "--usb", action='store_true', help="Console output to USB (disables other USB functionality")
454     parser.add_argument("-cpp", "--cpp", action='store_true', default=0, help="Generate C++ code")
455     parser.add_argument("-cpprtti", "--cpprtti", action='store_true', default=0, help="Enable C++ RTTI (Uses more memory)")
456     parser.add_argument("-cppex", "--cppexceptions", action='store_true', default=0, help="Enable C++ exceptions (Uses more memory)")
457     parser.add_argument("-d", "--debugger", type=int, help="Select debugger ({})".format(debugger_flags), default=0)
458     parser.add_argument("-board", "--boardtype", action="store", default='pico', help="Select board type (see --boardlist for available boards)")
459     parser.add_argument("-bl", "--boardlist", action="store_true", help="List available board types")
460     parser.add_argument("-cp", "--cpath", help="Override default VSCode compiler path")
461     parser.add_argument("-root", "--projectRoot", help="Override default project root where the new project will be created")
462     parser.add_argument("-sdkVersion", "--sdkVersion", help="Pico SDK version to use (required)")
463     parser.add_argument("-tcVersion", "--toolchainVersion", help="ARM/RISCV Embeded Toolchain version to use (required)")
464     parser.add_argument("-picotoolVersion", "--picotoolVersion", help="Picotool version to use (required)")
465     parser.add_argument("-np", "--ninjaPath", help="Ninja path")
466     parser.add_argument("-cmp", "--cmakePath", help="CMake path")
467     parser.add_argument("-cupy", "--customPython", action='store_true', help="Custom python path used to execute the script.")
468     parser.add_argument("-openOCDVersion", "--openOCDVersion", help="OpenOCD version to use - defaults to 0", default=0)
469     parser.add_argument("-examLibs", "--exampleLibs", action='append', help="Include an examples library in the folder")
470
471     return parser.parse_args()
472
473
474 def GenerateMain(folder, projectName, features, cpp):
475
476     if cpp:
477         filename = Path(folder) / (projectName + '.cpp')
478     else:
479         filename = Path(folder) / (projectName + '.c')
480
481     file = open(filename, 'w')
482
483     main = ('#include <stdio.h>\n'
484             '#include "pico/stdlib.h"\n'
485             )
486     file.write(main)
487
488     if (features):
489
490         # Add any includes
491         for feat in features:
492             if (feat in features_list):
493                 if len(features_list[feat][H_FILE]) == 0:
494                     continue
495                 o = f'#include "{features_list[feat][H_FILE]}"\n'
496                 file.write(o)
497             if (feat in stdlib_examples_list):
498                 if len(stdlib_examples_list[feat][H_FILE]) == 0:
499                     continue
500                 o = f'#include "{stdlib_examples_list[feat][H_FILE]}"\n'
501                 file.write(o)
502             if (feat in picow_options_list):
503                 if len(picow_options_list[feat][H_FILE]) == 0:
504                     continue
505                 o = f'#include "{picow_options_list[feat][H_FILE]}"\n'
506                 file.write(o)
507
508         file.write('\n')
509
510         # Add any defines
511         for feat in features:
512             if (feat in code_fragments_per_feature):
513                 for s in code_fragments_per_feature[feat][DEFINES]:
514                     file.write(s)
515                     file.write('\n')
516                 file.write('\n')
517
518     main = ('\n\n'
519             'int main()\n'
520             '{\n'
521             '    stdio_init_all();\n\n'
522             )
523
524     if any([feat in picow_options_list and feat != "picow_none" for feat in features]):
525         main += (
526             '    // Initialise the Wi-Fi chip\n'
527             '    if (cyw43_arch_init()) {\n'
528             '        printf("Wi-Fi init failed\\n");\n'
529             '        return -1;\n'
530             '    }\n\n')
531
532     if (features):
533         # Add any initialisers
534         indent = 4
535         for feat in features:
536             if (feat in code_fragments_per_feature):
537                 for s in code_fragments_per_feature[feat][INITIALISERS]:
538                     main += (" " * indent)
539                     main += s
540                     main += '\n'
541                 main += '\n'
542
543     main += ('    while (true) {\n'
544              '        printf("Hello, world!\\n");\n'
545              '        sleep_ms(1000);\n'
546              '    }\n'
547              '}\n'
548             )
549
550     file.write(main)
551
552     file.close()
553
554
555 def GenerateCMake(folder, params):
556     filename = Path(folder) / CMAKELIST_FILENAME
557     projectName = params['projectName']
558     board_type = params['boardtype']
559
560     cmake_header1 = (f"# Generated Cmake Pico project file\n\n"
561                  "cmake_minimum_required(VERSION 3.13)\n\n"
562                  "set(CMAKE_C_STANDARD 11)\n"
563                  "set(CMAKE_CXX_STANDARD 17)\n"
564                  "set(CMAKE_EXPORT_COMPILE_COMMANDS ON)\n\n"
565                  "# Initialise pico_sdk from installed location\n"
566                  "# (note this can come from environment, CMake cache etc)\n\n"
567                 )
568
569     # if you change the do never edit headline you need to change the check for it in extension.mts
570     cmake_header_us = (
571                 "# == DO NEVER EDIT THE NEXT LINES for Raspberry Pi Pico VS Code Extension to work ==\n"
572                 "if(WIN32)\n"
573                 "    set(USERHOME $ENV{USERPROFILE})\n"
574                 "else()\n"
575                 "    set(USERHOME $ENV{HOME})\n"
576                 "endif()\n"
577                 f"set(sdkVersion {params['sdkVersion']})\n"
578                 f"set(toolchainVersion {params['toolchainVersion']})\n"
579                 f"set(picotoolVersion {params['picotoolVersion']})\n"
580                 f"set(picoVscode {cmakeIncPath()})\n"
581                 "if (EXISTS ${picoVscode})\n"
582                 "    include(${picoVscode})\n"
583                 "endif()\n"
584                 "# ====================================================================================\n"
585                 )
586
587     cmake_header2 = (
588                  f"set(PICO_BOARD {board_type} CACHE STRING \"Board type\")\n\n"
589                  "# Pull in Raspberry Pi Pico SDK (must be before project)\n"
590                  "include(pico_sdk_import.cmake)\n\n"
591                  f"project({projectName} C CXX ASM)\n"
592                 )
593
594     cmake_header3 = (
595                 "\n# Initialise the Raspberry Pi Pico SDK\n"
596                 "pico_sdk_init()\n\n"
597                 "# Add executable. Default name is the project name, version 0.1\n\n"
598                 )
599
600
601     if params['wantConvert']:
602         with open(filename, 'r+') as file:
603             content = file.read()
604             file.seek(0)
605             lines = file.readlines()
606             file.seek(0)
607             if not params['wantExample']:
608                 # Prexisting CMake configuration - just adding cmake_header_us
609                 file.write(cmake_header_us)
610                 file.write(content)
611             else:
612                 if any(["pico_cyw43_arch_lwip_threadsafe_background" in line for line in lines]):
613                     print("Threadsafe Background")
614                     params["wantThreadsafeBackground"] = True
615                 if any(["pico_cyw43_arch_lwip_poll" in line for line in lines]):
616                     print("Poll")
617                     params["wantPoll"] = True
618                 # Get project name
619                 for line in lines:
620                     if "add_executable" in line:
621                         if params["wantThreadsafeBackground"] or params["wantPoll"]:
622                             newProjectName = line.split('(')[1].split()[0].strip().strip("()")
623                             newProjectName = newProjectName.replace("_background", "")
624                             newProjectName = newProjectName.replace("_poll", "")
625                             print("New project name", newProjectName)
626                             cmake_header2 = cmake_header2.replace(projectName, newProjectName)
627                 # Write all headers
628                 file.write(cmake_header1)
629                 file.write(cmake_header_us)
630                 file.write(cmake_header2)
631                 file.write(cmake_header3)
632                 for lib in params["exampleLibs"]:
633                     file.write(f"add_subdirectory({lib})\n")
634                 file.flush()
635                 # Remove example_auto_set_url
636                 for i, line in enumerate(lines):
637                     if "example_auto_set_url" in line:
638                         lines[i] = ""
639                         print("Removed", line, lines[i])
640                     if "target_link_libraries" in line:
641                         for lib in params["exampleLibs"]:
642                             lines[i] += f"  {lib}\n"
643                 file.writelines(lines)
644         return
645
646
647     file = open(filename, 'w')
648
649     file.write(cmake_header1)
650     file.write(cmake_header_us)
651     file.write(cmake_header2)
652
653     if params['exceptions']:
654         file.write("\nset(PICO_CXX_ENABLE_EXCEPTIONS 1)\n")
655
656     if params['rtti']:
657         file.write("\nset(PICO_CXX_ENABLE_RTTI 1)\n")
658
659     file.write(cmake_header3)
660
661     # add the preprocessor defines for overall configuration
662     if params['configs']:
663         file.write('# Add any PICO_CONFIG entries specified in the Advanced settings\n')
664         for c, v in params['configs'].items():
665             if v == "True":
666                 v = "1"
667             elif v == "False":
668                 v = "0"
669             file.write(f'add_compile_definitions({c} = {v})\n')
670         file.write('\n')
671
672     # No GUI/command line to set a different executable name at this stage
673     executableName = projectName
674
675     if params['wantCPP']:
676         file.write(f'add_executable({projectName} {projectName}.cpp )\n\n')
677     else:
678         file.write(f'add_executable({projectName} {projectName}.c )\n\n')
679
680     file.write(f'pico_set_program_name({projectName} "{executableName}")\n')
681     file.write(f'pico_set_program_version({projectName} "0.1")\n\n')
682
683     if params['wantRunFromRAM']:
684         file.write(f'# no_flash means the target is to run from RAM\n')
685         file.write(f'pico_set_binary_type({projectName} no_flash)\n\n')
686
687     # Add pio output
688     if params['features'] and "pio" in params['features']:
689         file.write(f'# Generate PIO header\n')
690         file.write(f'pico_generate_pio_header({projectName} ${{CMAKE_CURRENT_LIST_DIR}}/blink.pio)\n\n')
691
692     # Console output destinations
693     file.write("# Modify the below lines to enable/disable output over UART/USB\n")
694     if params['wantUART']:
695         file.write(f'pico_enable_stdio_uart({projectName} 1)\n')
696     else:
697         file.write(f'pico_enable_stdio_uart({projectName} 0)\n')
698
699     if params['wantUSB']:
700         file.write(f'pico_enable_stdio_usb({projectName} 1)\n\n')
701     else:
702         file.write(f'pico_enable_stdio_usb({projectName} 0)\n\n')
703
704     # If we need wireless, check for SSID and password
705     # removed for the moment as these settings are currently only needed for the pico-examples
706     # but may be required in here at a later date.
707     if False:
708         if 'ssid' in params or 'password' in params:
709             file.write('# Add any wireless access point information\n')
710             file.write(f'target_compile_definitions({projectName} PRIVATE\n')
711             if 'ssid' in params:
712                 file.write(f'WIFI_SSID=\" {params["ssid"]} \"\n')
713             else:
714                 file.write(f'WIFI_SSID=\"${WIFI_SSID}\"')
715
716             if 'password' in params:
717                 file.write(f'WIFI_PASSWORD=\"{params["password"]}\"\n')
718             else:
719                 file.write(f'WIFI_PASSWORD=\"${WIFI_PASSWORD}\"')
720             file.write(')\n\n')
721
722     # Standard libraries
723     file.write('# Add the standard library to the build\n')
724     file.write(f'target_link_libraries({projectName}\n')
725     file.write("        " + STANDARD_LIBRARIES)
726     file.write(')\n\n')
727
728     # Standard include directories
729     file.write('# Add the standard include files to the build\n')
730     file.write(f'target_include_directories({projectName} PRIVATE\n')
731     file.write("  ${CMAKE_CURRENT_LIST_DIR}\n")
732     file.write("  ${CMAKE_CURRENT_LIST_DIR}/.. # for our common lwipopts or any other standard includes, if required\n")
733     file.write(')\n\n')
734
735     # Selected libraries/features
736     if (params['features']):
737         file.write('# Add any user requested libraries\n')
738         file.write(f'target_link_libraries({projectName} \n')
739         for feat in params['features']:
740             if (feat in features_list):
741                 file.write("        " + features_list[feat][LIB_NAME] + '\n')
742             if (feat in picow_options_list):
743                 file.write("        " + picow_options_list[feat][LIB_NAME] + '\n')
744         file.write('        )\n\n')
745
746     file.write(f'pico_add_extra_outputs({projectName})\n\n')
747
748     file.close()
749
750
751 # Generates the requested project files, if any
752 def generateProjectFiles(projectPath, projectName, sdkPath, projects, debugger, sdkVersion, toolchainVersion, picotoolVersion, ninjaPath, cmakePath, customPython, openOCDVersion):
753
754     oldCWD = os.getcwd()
755
756     os.chdir(projectPath)
757
758     # Add a simple .gitignore file if there isn't one
759     if not os.path.isfile(".gitignore"):
760         file = open(".gitignore", "w")
761         file.write("build\n")
762         file.close()
763
764     debugger = debugger_config_list[debugger]
765
766     if debugger == "raspberrypi-swd.cfg":
767         shutil.copyfile(sourcefolder + "/" +  "raspberrypi-swd.cfg", projectPath / "raspberrypi-swd.cfg")
768
769     # Need to escape windows files paths backslashes
770     # TODO: env in currently not supported in compilerPath var
771     #cPath = f"${{env:PICO_TOOLCHAIN_PATH_{envSuffix}}}" + os.path.sep + os.path.basename(str(compilerPath).replace('\\', '\\\\' ))
772     cPath = compilerPath.as_posix() + (".exe" if isWindows else "")
773
774     # if this is a path in the .pico-sdk homedir tell the settings to use the homevar
775     user_home = os.path.expanduser("~").replace("\\", "/")
776     use_home_var = f"{user_home}/.pico-sdk" in ninjaPath
777
778     openocd_path = ""
779     server_path = "\n            \"serverpath\"" # Because no \ in f-strings
780     openocd_path_os = Path(user_home, relativeOpenOCDPath(openOCDVersion).replace("/", "", 1), "openocd.exe")
781     if os.path.exists(openocd_path_os):
782         openocd_path = f'{codeOpenOCDPath(openOCDVersion)}/openocd.exe'
783
784     for p in projects :
785         if p == 'vscode':
786             launch = f'''{{
787     "version": "0.2.0",
788     "configurations": [
789         {{
790             "name": "Pico Debug (Cortex-Debug)",
791             "cwd": "{"${workspaceRoot}" if not openocd_path else f"{codeOpenOCDPath(openOCDVersion)}/scripts"}",
792             "executable": "${{command:raspberry-pi-pico.launchTargetPath}}",
793             "request": "launch",
794             "type": "cortex-debug",
795             "servertype": "openocd",\
796 {f'{server_path}: "{openocd_path}",' if openocd_path else ""}
797             "gdbPath": "${{command:raspberry-pi-pico.getGDBPath}}",
798             "device": "${{command:raspberry-pi-pico.getChipUppercase}}",
799             "configFiles": [
800                 "{debugger}",
801                 "target/${{command:raspberry-pi-pico.getTarget}}.cfg"
802             ],
803             "svdFile": "{codeSdkPath(sdkVersion)}/src/${{command:raspberry-pi-pico.getChip}}/hardware_regs/${{command:raspberry-pi-pico.getChipUppercase}}.svd",
804             "runToEntryPoint": "main",
805             // Fix for no_flash binaries, where monitor reset halt doesn't do what is expected
806             // Also works fine for flash binaries
807             "overrideLaunchCommands": [
808                 "monitor reset init",
809                 "load \\"${{command:raspberry-pi-pico.launchTargetPath}}\\""
810             ],
811             "openOCDLaunchCommands": [
812                 "adapter speed 5000"
813             ]
814         }},
815         {{
816             "name": "Pico Debug (Cortex-Debug with external OpenOCD)",
817             "cwd": "${{workspaceRoot}}",
818             "executable": "${{command:raspberry-pi-pico.launchTargetPath}}",
819             "request": "launch",
820             "type": "cortex-debug",
821             "servertype": "external",
822             "gdbTarget": "localhost:3333",
823             "gdbPath": "${{command:raspberry-pi-pico.getGDBPath}}",
824             "device": "${{command:raspberry-pi-pico.getChipUppercase}}",
825             "svdFile": "{codeSdkPath(sdkVersion)}/src/${{command:raspberry-pi-pico.getChip}}/hardware_regs/${{command:raspberry-pi-pico.getChipUppercase}}.svd"
826             "runToEntryPoint": "main",
827             // Give restart the same functionality as runToEntryPoint - main
828             "postRestartCommands": [
829                 "break main",
830                 "continue"
831             ]
832         }},
833         {{
834             "name": "Pico Debug (C++ Debugger)",
835             "type": "cppdbg",
836             "request": "launch",
837             "cwd": "${{workspaceRoot}}",
838             "program": "${{command:raspberry-pi-pico.launchTargetPath}}",
839             "MIMode": "gdb",
840             "miDebuggerPath": "${{command:raspberry-pi-pico.getGDBPath}}",
841             "miDebuggerServerAddress": "localhost:3333",
842             "debugServerPath": "{openocd_path if openocd_path else "openocd"}",
843             "debugServerArgs": "-f {debugger} -f target/${{command:raspberry-pi-pico.getTarget}}.cfg -c \\"adapter speed 5000\\"",
844             "serverStarted": "Listening on port .* for gdb connections",
845             "filterStderr": true,
846             "hardwareBreakpoints": {{
847                 "require": true,
848                 "limit": 4
849             }},
850             "preLaunchTask": "Flash",
851             "svdPath": "{codeSdkPath(sdkVersion)}/src/${{command:raspberry-pi-pico.getChip}}/hardware_regs/${{command:raspberry-pi-pico.getChipUppercase}}.svd"
852         }},
853     ]
854 }}
855 '''
856
857             base_headers_folder_name = "pico_base_headers" if semver_compare_ge(sdkVersion, "2.0.0") else "pico_base"
858             properties = f'''{{
859     "configurations": [
860         {{
861             "name": "Pico",
862             "includePath": [
863                 "${{workspaceFolder}}/**",
864                 "{codeSdkPath(sdkVersion)}/**"
865             ],
866             "forcedInclude": [
867                 "{codeSdkPath(sdkVersion)}/src/common/{base_headers_folder_name}/include/pico.h",
868                 "${{workspaceFolder}}/build/generated/pico_base/pico/config_autogen.h"
869             ],
870             "defines": [],
871             "compilerPath": "{cPath}",
872             "compileCommands": "${{workspaceFolder}}/build/compile_commands.json",
873             "cStandard": "c17",
874             "cppStandard": "c++14",
875             "intelliSenseMode": "linux-gcc-arm"
876         }}
877     ],
878     "version": 4
879 }}
880 '''
881
882             pythonExe = sys.executable.replace("\\", "/").replace(user_home, "${HOME}") if use_home_var else sys.executable
883
884             # kits
885             kits = f'''[
886     {{
887         "name": "Pico",
888         "compilers": {{
889             "C": "{cPath}",
890             "CXX": "{cPath}"
891         }},
892         "toolchainFile": "{propertiesSdkPath(sdkVersion)}/cmake/preload/toolchains/{CMAKE_TOOLCHAIN_NAME}",
893         "environmentVariables": {{
894             "PATH": "${{command:raspberry-pi-pico.getEnvPath}};${{env:PATH}}"
895         }},
896         "cmakeSettings": {{
897             "Python3_EXECUTABLE": "${{command:raspberry-pi-pico.getPythonPath}}"
898         }}
899     }}
900 ]'''
901
902             # settings
903             settings = f'''{{
904     "cmake.options.statusBarVisibility": "hidden",
905     "cmake.options.advanced": {{
906         "build": {{
907             "statusBarVisibility": "hidden"
908         }},
909         "launch": {{
910             "statusBarVisibility": "hidden"
911         }},
912         "debug": {{
913             "statusBarVisibility": "hidden"
914         }}
915     }},
916     "cmake.configureOnEdit": false,
917     "cmake.automaticReconfigure": false,
918     "cmake.configureOnOpen": false,
919     "cmake.generator": "Ninja",
920     "cmake.cmakePath": "{cmakePath.replace(user_home, "${userHome}") if use_home_var else cmakePath}",
921     "C_Cpp.debugShortcut": false,
922     "terminal.integrated.env.windows": {{
923         "PICO_SDK_PATH": "{propertiesSdkPath(sdkVersion, force_windows=True)}",
924         "PICO_TOOLCHAIN_PATH": "{propertiesToolchainPath(toolchainVersion, force_windows=True)}",
925         "Path": "\
926 {propertiesToolchainPath(toolchainVersion, force_windows=True)}/bin;\
927 {propertiesPicotoolPath(picotoolVersion, force_windows=True)}/picotool;\
928 {os.path.dirname(cmakePath.replace(user_home, "${env:USERPROFILE}") if use_home_var else cmakePath)};\
929 {os.path.dirname(ninjaPath.replace(user_home, "${env:USERPROFILE}") if use_home_var else ninjaPath)};\
930 ${{env:PATH}}"
931     }},
932     "terminal.integrated.env.osx": {{
933         "PICO_SDK_PATH": "{propertiesSdkPath(sdkVersion, force_non_windows=True)}",
934         "PICO_TOOLCHAIN_PATH": "{propertiesToolchainPath(toolchainVersion, force_non_windows=True)}",
935         "PATH": "\
936 {propertiesToolchainPath(toolchainVersion, force_non_windows=True)}/bin:\
937 {propertiesPicotoolPath(picotoolVersion, force_non_windows=True)}/picotool:\
938 {os.path.dirname(cmakePath.replace(user_home, "${env:HOME}") if use_home_var else cmakePath)}:\
939 {os.path.dirname(ninjaPath.replace(user_home, "${env:HOME}") if use_home_var else ninjaPath)}:\
940 ${{env:PATH}}"
941     }},
942     "terminal.integrated.env.linux": {{
943         "PICO_SDK_PATH": "{propertiesSdkPath(sdkVersion, force_non_windows=True)}",
944         "PICO_TOOLCHAIN_PATH": "{propertiesToolchainPath(toolchainVersion, force_non_windows=True)}",
945         "PATH": "\
946 {propertiesToolchainPath(toolchainVersion, force_non_windows=True)}/bin:\
947 {propertiesPicotoolPath(picotoolVersion, force_non_windows=True)}/picotool:\
948 {os.path.dirname(cmakePath.replace(user_home, "${env:HOME}") if use_home_var else cmakePath)}:\
949 {os.path.dirname(ninjaPath.replace(user_home, "${env:HOME}") if use_home_var else ninjaPath)}:\
950 ${{env:PATH}}"
951     }},
952     "raspberry-pi-pico.cmakeAutoConfigure": true,
953     "raspberry-pi-pico.useCmakeTools": false,
954     "raspberry-pi-pico.cmakePath": "{cmakePath.replace(user_home, "${HOME}") if use_home_var else cmakePath}",
955     "raspberry-pi-pico.ninjaPath": "{ninjaPath.replace(user_home, "${HOME}") if use_home_var else ninjaPath}"'''
956
957             if customPython:
958                 settings += f''',
959     "raspberry-pi-pico.python3Path": "{pythonExe}"'''
960                 
961             settings += '\n}\n'
962
963             # extensions
964             extensions = f'''{{
965     "recommendations": [
966         "marus25.cortex-debug",
967         "ms-vscode.cpptools",
968         "ms-vscode.cpptools-extension-pack",
969         "ms-vscode.vscode-serial-monitor",
970         "raspberry-pi.raspberry-pi-pico",
971     ]
972 }}
973 '''
974             tasks = f'''{{
975     "version": "2.0.0",
976     "tasks": [
977         {{
978             "label": "Compile Project",
979             "type": "process",
980             "isBuildCommand": true,
981             "command": "{ninjaPath.replace(user_home, "${userHome}") if use_home_var else ninjaPath}",
982             "args": ["-C", "${{workspaceFolder}}/build"],
983             "group": "build",
984             "presentation": {{
985                 "reveal": "always",
986                 "panel": "dedicated"
987             }},
988             "problemMatcher": "$gcc",
989             "windows": {{
990                 "command": "{ninjaPath.replace(user_home, "${env:USERPROFILE}") if use_home_var else ninjaPath}.exe"
991             }}
992         }},
993         {{
994             "label": "Run Project",
995             "type": "process",
996             "command": "{propertiesPicotoolPath(picotoolVersion, force_non_windows=True)}/picotool/picotool",
997             "args": [
998                 "load",
999                 "${{command:raspberry-pi-pico.launchTargetPath}}",
1000                 "-fx"
1001             ],
1002             "presentation": {{
1003                 "reveal": "always",
1004                 "panel": "dedicated"
1005             }},
1006             "problemMatcher": [],
1007             "windows": {{
1008                 "command": "{propertiesPicotoolPath(picotoolVersion, force_windows=True)}/picotool/picotool.exe"
1009             }}
1010         }},
1011         {{
1012             "label": "Flash",
1013             "type": "process",
1014             "command": "{openocd_path if openocd_path else "openocd"}",
1015             "args": [
1016                 "-s",
1017                 "{codeOpenOCDPath(openOCDVersion)}/scripts",
1018                 "-f",
1019                 "{debugger}",
1020                 "-f",
1021                 "target/${{command:raspberry-pi-pico.getTarget}}.cfg",
1022                 "-c",
1023                 "adapter speed 5000; program \\"${{command:raspberry-pi-pico.launchTargetPath}}\\" verify reset exit"
1024             ],
1025             "problemMatcher": [],
1026             "windows": {{
1027                 "command": "{openocd_path.replace("${userHome}", "${env:USERPROFILE}") if openocd_path else "openocd"}",
1028             }}
1029         }}
1030     ]
1031 }}
1032 '''
1033
1034             # Create a build folder, and run our cmake project build from it
1035             if not os.path.exists(VSCODE_FOLDER):
1036                 os.mkdir(VSCODE_FOLDER)
1037
1038             os.chdir(VSCODE_FOLDER)
1039
1040             file = open(VSCODE_TASKS_FILENAME, 'w')
1041             file.write(tasks)
1042             file.close()
1043
1044             filename = VSCODE_LAUNCH_FILENAME
1045             file = open(filename, 'w')
1046             file.write(launch)
1047             file.close()
1048
1049             file = open(VSCODE_C_PROPERTIES_FILENAME, 'w')
1050             file.write(properties)
1051             file.close()
1052
1053             file = open(VSCODE_CMAKE_KITS_FILENAME, 'w')
1054             file.write(kits)
1055             file.close()
1056
1057             file = open(VSCODE_SETTINGS_FILENAME, 'w')
1058             file.write(settings)
1059             file.close()
1060
1061             file = open(VSCODE_EXTENSIONS_FILENAME, 'w')
1062             file.write(extensions)
1063             file.close()
1064
1065         else :
1066             print('Unknown project type requested')
1067
1068     os.chdir(oldCWD)
1069
1070
1071 def LoadConfigurations():
1072     try:
1073         with open(args.tsv) as tsvfile:
1074             reader = csv.DictReader(tsvfile, dialect='excel-tab')
1075             for row in reader:
1076                 configuration_dictionary.append(row)
1077     except:
1078         print("No Pico configurations file found. Continuing without")
1079
1080 def LoadBoardTypes(sdkPath):
1081     # Scan the boards folder for all header files, extract filenames, and make a list of the results
1082     # default folder is <PICO_SDK_PATH>/src/boards/include/boards/*
1083     # If the PICO_BOARD_HEADER_DIRS environment variable is set, use that as well
1084
1085     loc = sdkPath / "src/boards/include/boards"
1086     boards=[]
1087     for x in Path(loc).iterdir():
1088         if x.suffix == '.h':
1089             boards.append(x.stem)
1090
1091     loc = os.getenv('PICO_BOARD_HEADER_DIRS')
1092
1093     if loc != None:
1094         for x in Path(loc).iterdir():
1095             if x.suffix == '.h':
1096                 boards.append(x.stem)
1097
1098     return boards
1099
1100 def DoEverything(parent, params):
1101     global CMAKE_TOOLCHAIN_NAME
1102
1103     if not os.path.exists(params['projectRoot']):
1104         print('Invalid project path')
1105         sys.exit(-1)
1106
1107     oldCWD = os.getcwd()
1108     os.chdir(params['projectRoot'])
1109
1110     # Create our project folder as subfolder
1111     os.makedirs(params['projectName'], exist_ok=True)
1112
1113     os.chdir(params['projectName'])
1114
1115     projectPath = params['projectRoot'] / params['projectName']
1116
1117     # First check if there is already a project in the folder
1118     # If there is we abort unless the overwrite flag it set
1119     if os.path.exists(CMAKELIST_FILENAME):
1120         if not (params['wantOverwrite'] or params['wantConvert']):
1121             print('There already appears to be a project in this folder. Use the --overwrite option to overwrite the existing project')
1122             sys.exit(-1)
1123
1124         # We should really confirm the user wants to overwrite
1125         #print('Are you sure you want to overwrite the existing project files? (y/N)')
1126         #c = input().split(" ")[0]
1127         #if c != 'y' and c != 'Y' :
1128         #    sys.exit(0)
1129
1130     # Copy the SDK finder cmake file to our project folder
1131     # Can be found here <PICO_SDK_PATH>/external/pico_sdk_import.cmake
1132     shutil.copyfile(params['sdkPath'] / 'external' / 'pico_sdk_import.cmake', projectPath / 'pico_sdk_import.cmake' )
1133
1134     if params['features']:
1135         features_and_examples = params['features'][:]
1136     else:
1137         features_and_examples= []
1138
1139     if params['wantExamples']:
1140         features_and_examples = list(stdlib_examples_list.keys()) + features_and_examples
1141
1142     if not (params['wantConvert']):
1143         GenerateMain(projectPath, params['projectName'], features_and_examples, params['wantCPP'])
1144
1145         # If we have any ancilliary files, copy them to our project folder
1146         # Currently only the picow with lwIP support needs an extra file, so just check that list
1147         for feat in features_and_examples:
1148             if feat in features_list:
1149                 if features_list[feat][ANCILLARY_FILE] != "":
1150                     shutil.copy(sourcefolder + "/" + features_list[feat][ANCILLARY_FILE], projectPath / features_list[feat][ANCILLARY_FILE])
1151             if feat in picow_options_list:
1152                 if picow_options_list[feat][ANCILLARY_FILE] != "":
1153                     shutil.copy(sourcefolder + "/" + picow_options_list[feat][ANCILLARY_FILE], projectPath / picow_options_list[feat][ANCILLARY_FILE])
1154
1155     GenerateCMake(projectPath, params)
1156
1157     if params['wantExample']:
1158         if params['wantThreadsafeBackground'] or params['wantPoll']:
1159             # Write lwipopts for examples
1160             shutil.copy(sourcefolder + "/" + "lwipopts.h", projectPath / "lwipopts.h")
1161
1162     # Create a build folder, and run our cmake project build from it
1163     if not os.path.exists('build'):
1164         os.mkdir('build')
1165
1166     os.chdir('build')
1167
1168     # If we are overwriting a previous project, we should probably clear the folder, but that might delete something the users thinks is important, so
1169     # for the moment, just delete the CMakeCache.txt file as certain changes may need that to be recreated.
1170
1171     if os.path.exists(CMAKECACHE_FILENAME):
1172         os.remove(CMAKECACHE_FILENAME)
1173
1174     cpus = os.cpu_count()
1175     if cpus == None:
1176         cpus = 1
1177
1178     if isWindows:
1179         if shutil.which("ninja") or (params["ninjaPath"] != None and params["ninjaPath"] != ""):
1180             # When installing SDK version 1.5.0 on windows with installer pico-setup-windows-x64-standalone.exe, ninja is used 
1181             cmakeCmd = params['cmakePath'] + ' -G Ninja ..'
1182             makeCmd = params['ninjaPath'] + ' '        
1183         else:
1184             # Everything else assume nmake
1185             cmakeCmd = params['cmakePath'] + ' -G "NMake Makefiles" ..'
1186             makeCmd = 'nmake '
1187     else:
1188         # Ninja now works OK under Linux, so if installed use it by default. It's faster.
1189         if shutil.which("ninja") or (params["ninjaPath"] != None and params["ninjaPath"] != ""):
1190             cmakeCmd = params['cmakePath'] + ' -G Ninja ..'
1191             makeCmd = params['ninjaPath'] + ' '
1192         else:
1193             cmakeCmd = params['cmakePath'] + ' ..'
1194             makeCmd = 'make -j' + str(cpus)
1195
1196     os.system(cmakeCmd)
1197
1198     # Extract CMake Toolchain File
1199     if os.path.exists(CMAKECACHE_FILENAME):
1200         cacheFile = open(CMAKECACHE_FILENAME, "r")
1201         for line in cacheFile:
1202             if re.search("CMAKE_TOOLCHAIN_FILE:FILEPATH=", line):
1203                 CMAKE_TOOLCHAIN_NAME = line.split("=")[-1].split("/")[-1].strip()
1204
1205     if params['projects']:
1206         generateProjectFiles(
1207             projectPath, 
1208             params['projectName'], 
1209             params['sdkPath'], 
1210             params['projects'], 
1211             params['debugger'], 
1212             params["sdkVersion"], 
1213             params["toolchainVersion"], 
1214             params["picotoolVersion"], 
1215             params["ninjaPath"], 
1216             params["cmakePath"],
1217             params["customPython"],
1218             params["openOCDVersion"])
1219
1220     if params['wantBuild']:
1221         os.system(makeCmd)
1222         print('\nIf the application has built correctly, you can now transfer it to the Raspberry Pi Pico board')
1223
1224     os.chdir(oldCWD)
1225
1226
1227 ###################################################################################
1228 # main execution starteth here
1229
1230 if __name__ == "__main__":
1231     sourcefolder = os.path.dirname(os.path.abspath(__file__))
1232
1233     args = ParseCommandLine()
1234
1235     if args.nouart:
1236         args.uart = False
1237
1238     if args.debugger > len(debugger_list) - 1:
1239         args.debugger = 0
1240
1241     if "RISCV" in args.toolchainVersion:
1242         if "COREV" in args.toolchainVersion:
1243             COMPILER_TRIPLE = COREV_TRIPLE
1244         else:
1245             COMPILER_TRIPLE = RISCV_TRIPLE
1246
1247     # Check we have everything we need to compile etc
1248     c = CheckPrerequisites()
1249
1250     ## TODO Do both warnings in the same error message so user does have to keep coming back to find still more to do
1251
1252     if c == None:
1253         m = f'Unable to find the `{COMPILER_NAME()}` compiler\n'
1254         m +='You will need to install an appropriate compiler to build a Raspberry Pi Pico project\n'
1255         m += 'See the Raspberry Pi Pico documentation for how to do this on your particular platform\n'
1256
1257         print(m)
1258         sys.exit(-1)
1259
1260     if args.name == None and not args.gui and not args.list and not args.configs and not args.boardlist:
1261         print("No project name specfied\n")
1262         sys.exit(-1)
1263
1264     # Check if we were provided a compiler path, and override the default if so
1265     if args.cpath:
1266         compilerPath = Path(args.cpath)
1267     elif args.toolchainVersion:
1268         compilerPath = Path(codeToolchainPath(args.toolchainVersion)+"/bin/"+COMPILER_NAME())
1269     else:
1270         compilerPath = Path(c)
1271
1272     # load/parse any configuration dictionary we may have
1273     LoadConfigurations()
1274
1275     p = CheckSDKPath(args.gui)
1276
1277     if p == None:
1278         sys.exit(-1)
1279
1280     sdkPath = Path(p)
1281
1282     boardtype_list = LoadBoardTypes(sdkPath)
1283     boardtype_list.sort()
1284
1285     projectRoot = Path(os.getcwd()) if not args.projectRoot else Path(args.projectRoot)
1286
1287     if args.list or args.configs or args.boardlist:
1288         if args.list:
1289             print("Available project features:\n")
1290             for feat in features_list:
1291                 print(feat.ljust(6), '\t', features_list[feat][GUI_TEXT])
1292             print('\n')
1293
1294         if args.configs:
1295             print("Available project configuration items:\n")
1296             for conf in configuration_dictionary:
1297                 print(conf['name'].ljust(40), '\t', conf['description'])
1298             print('\n')
1299
1300         if args.boardlist:
1301             print("Available board types:\n")
1302             for board in boardtype_list:
1303                 print(board)
1304             print('\n')
1305
1306         sys.exit(0)
1307     else :
1308         params={
1309             'sdkPath'       : sdkPath,
1310             'projectRoot'   : projectRoot,
1311             'projectName'   : args.name,
1312             'wantGUI'       : False,
1313             'wantOverwrite' : args.overwrite,
1314             'wantConvert'   : args.convert or args.example,
1315             'wantExample'   : args.example,
1316             'wantThreadsafeBackground'  : False,
1317             'wantPoll'                  : False,
1318             'boardtype'     : args.boardtype,
1319             'wantBuild'     : args.build,
1320             'features'      : args.feature,
1321             'projects'      : args.project,
1322             'configs'       : (),
1323             'wantRunFromRAM': args.runFromRAM,
1324             'wantExamples'  : args.examples,
1325             'wantUART'      : args.uart,
1326             'wantUSB'       : args.usb,
1327             'wantCPP'       : args.cpp,
1328             'debugger'      : args.debugger,
1329             'exceptions'    : args.cppexceptions,
1330             'rtti'          : args.cpprtti,
1331             'ssid'          : '',
1332             'password'      : '',
1333             'sdkVersion'    : args.sdkVersion,
1334             'toolchainVersion': args.toolchainVersion,
1335             'picotoolVersion': args.picotoolVersion,
1336             'ninjaPath'     : args.ninjaPath,
1337             'cmakePath'     : args.cmakePath,
1338             'customPython'  : args.customPython,
1339             'openOCDVersion': args.openOCDVersion,
1340             'exampleLibs'   : args.exampleLibs if args.exampleLibs is not None else []
1341             }
1342
1343         DoEverything(None, params)
1344         sys.exit(0)
This page took 0.110352 seconds and 4 git commands to generate.