├── .gitignore ├── .idea ├── .gitignore ├── misc.xml ├── vcs.xml ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── modules.xml └── CubeProgrammer_API.iml ├── CppExample ├── .gitignore ├── Example2.cpp ├── DisplayManager.h ├── Example.sln ├── Example1.cpp ├── DisplayManager.cpp ├── Example2.vcxproj └── Example1.vcxproj ├── api ├── came-from.lnk ├── CubeProgrammer_API.dll ├── lib │ └── CubeProgrammer_API.lib └── include │ ├── DeviceDataStructure.h │ └── CubeProgrammer_API.h ├── CubeProgrammer_API.cp310-win_amd64.pyd ├── run_setup.py ├── Start-Python-IDE.py ├── setup.py ├── TestHotPlug.py ├── runme.py ├── README.md ├── CubeProgrammer_API.pyx └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /CubeProgrammer_API.cpp 3 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /CppExample/.gitignore: -------------------------------------------------------------------------------- 1 | /*.vcxproj.filters 2 | /*.vcxproj.user 3 | /x64 4 | /.vs 5 | -------------------------------------------------------------------------------- /api/came-from.lnk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jimfred/PyCubeProgrammer_API/HEAD/api/came-from.lnk -------------------------------------------------------------------------------- /api/CubeProgrammer_API.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jimfred/PyCubeProgrammer_API/HEAD/api/CubeProgrammer_API.dll -------------------------------------------------------------------------------- /api/lib/CubeProgrammer_API.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jimfred/PyCubeProgrammer_API/HEAD/api/lib/CubeProgrammer_API.lib -------------------------------------------------------------------------------- /CubeProgrammer_API.cp310-win_amd64.pyd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jimfred/PyCubeProgrammer_API/HEAD/CubeProgrammer_API.cp310-win_amd64.pyd -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /run_setup.py: -------------------------------------------------------------------------------- 1 | # Executes 'python setup.py build_ext --inplace' 2 | 3 | import subprocess 4 | cmd = 'python setup.py build_ext --inplace' 5 | x = subprocess.run(cmd.split()) 6 | print('ok' if 0 == x.returncode else 'fail') 7 | # input("Press Enter to continue...") # pause to see result when launched from FileExplorer. 8 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/CubeProgrammer_API.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Start-Python-IDE.py: -------------------------------------------------------------------------------- 1 | #!"python.exe" 2 | ''' 3 | Start app asynchronously and briefly display a message. 4 | 'duration_sec' will linger so that CMD window can be read for debug purposes. 5 | ''' 6 | 7 | import subprocess 8 | import time 9 | import glob 10 | import os 11 | 12 | def find_app(app_path_name_pattern: str): 13 | apps = glob.glob(app_path_name_pattern) 14 | qty = len(apps) 15 | if 1 == qty: 16 | return apps[0] 17 | raise NameError(f'Found {qty}, {apps} but expected just 1') 18 | 19 | 20 | app = find_app('C:/Program Files/JetBrains/**/bin/pycharm64.exe') 21 | duration_sec=9 22 | 23 | print(f'Start {app}\nhere {os.getcwd()}') 24 | subprocess.Popen([app, "./"]) 25 | 26 | for i in range(duration_sec, 0, -1): 27 | print(f'{i}', end='\r'); 28 | time.sleep(1) 29 | 30 | 31 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | from distutils.extension import Extension 3 | from Cython.Build import cythonize 4 | 5 | extensions = [ 6 | Extension( 7 | "CubeProgrammer_API", 8 | ["CubeProgrammer_API.pyx"], 9 | libraries=["CubeProgrammer_API"], language="c++", 10 | library_dirs=['./api/lib/'], 11 | ) 12 | ] 13 | setup( 14 | name="CubeProgrammer_API", 15 | version='0.1', 16 | description='CubeProgrammer_API.py', 17 | author='Jim Fred', 18 | author_email='jimfred@jimfred.org', 19 | ext_modules=cythonize( 20 | extensions, 21 | compiler_directives={ 22 | 'language_level': "3", 23 | 'always_allow_keywords': True # https://github.com/cython/cython/issues/2881 24 | }), 25 | requires=['Cython'] 26 | ) -------------------------------------------------------------------------------- /TestHotPlug.py: -------------------------------------------------------------------------------- 1 | 2 | import time 3 | 4 | api_dll_and_loader_path = 'C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeProgrammer/api/lib/' # Directory containing DLLs, ExternalLoader and FlashLoader. 5 | import os # noqa: E402 6 | os.add_dll_directory(api_dll_and_loader_path) # Path to DLLs before importing CubeProgrammer_API. https://stackoverflow.com/a/67437837/101252 7 | # noinspection PyUnresolvedReferences 8 | import CubeProgrammer_API # noqa: E402 9 | 10 | api = CubeProgrammer_API.CubeProgrammer_API() 11 | 12 | api.setLoadersPath(api_dll_and_loader_path) 13 | api.set_default_log_message_verbosity(0) 14 | 15 | while True: 16 | time.sleep(1) 17 | 18 | api.connection_update() 19 | 20 | print(f'stlink qty={len(api.stlink_list)}, stlink_connected={api.stlink_connected}, device_connected={api.device_connected}') 21 | 22 | 23 | -------------------------------------------------------------------------------- /CppExample/Example2.cpp: -------------------------------------------------------------------------------- 1 | // Example2.cpp : This file contains the 'main' function. Program execution begins and ends there. 2 | // 3 | 4 | #include 5 | 6 | int main() 7 | { 8 | std::cout << "Hello World!\n"; 9 | } 10 | 11 | // Run program: Ctrl + F5 or Debug > Start Without Debugging menu 12 | // Debug program: F5 or Debug > Start Debugging menu 13 | 14 | // Tips for Getting Started: 15 | // 1. Use the Solution Explorer window to add/manage files 16 | // 2. Use the Team Explorer window to connect to source control 17 | // 3. Use the Output window to see build output and other messages 18 | // 4. Use the Error List window to view errors 19 | // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project 20 | // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file 21 | -------------------------------------------------------------------------------- /CppExample/DisplayManager.h: -------------------------------------------------------------------------------- 1 | 2 | #define BLACK 0 3 | #define BLUE 1 4 | #define GREEN 2 5 | #define CYAN 3 6 | #define RED 4 7 | #define MAGENTA 5 8 | #define BROWN 6 9 | #define LIGHTGREY 7 10 | #define DARKGREY 8 11 | #define LIGHTBLUE 9 12 | #define LIGHTGREEN 10 13 | #define LIGHTCYAN 11 14 | #define LIGHTRED 12 15 | #define LIGHTMAGENTA 13 16 | #define YELLOW 14 17 | #define WHITE 15 18 | #define BLINK 128 19 | 20 | 21 | typedef enum verbosity 22 | { 23 | VERBOSITY_LEVEL_0 = 0, 24 | VERBOSITY_LEVEL_1 = 1, 25 | VERBOSITY_LEVEL_2 = 2, 26 | VERBOSITY_LEVEL_3 = 3 27 | }verbosity; 28 | 29 | enum MSGTYPE 30 | { 31 | Normal, 32 | Info, 33 | GreenInfo, 34 | Title, 35 | Warning, 36 | Error, 37 | Verbosity_1, 38 | Verbosity_2, 39 | Verbosity_3, 40 | GreenInfoNoPopup, 41 | WarningNoPopup, 42 | ErrorNoPopup 43 | }; 44 | 45 | void InitPBar(); 46 | void lBar(int x, int n); 47 | void DisplayMessage(int msgType, const wchar_t* str); 48 | void logMessage(int msgType, const char* str,...); -------------------------------------------------------------------------------- /CppExample/Example.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31424.327 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Example2", "Example2.vcxproj", "{67946BF0-0CDE-4E99-A380-AB92924FEE74}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Example1", "Example1.vcxproj", "{AF2B6C20-3080-43F3-92FD-AF3879C6F23B}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|x64 = Debug|x64 13 | Debug|x86 = Debug|x86 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Debug|x64.ActiveCfg = Debug|x64 19 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Debug|x64.Build.0 = Debug|x64 20 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Debug|x86.ActiveCfg = Debug|Win32 21 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Release|x64.ActiveCfg = Release|x64 22 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Release|x64.Build.0 = Release|x64 23 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Release|x86.ActiveCfg = Release|Win32 24 | {67946BF0-0CDE-4E99-A380-AB92924FEE74}.Release|x86.Build.0 = Release|Win32 25 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Debug|x64.ActiveCfg = Debug|x64 26 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Debug|x64.Build.0 = Debug|x64 27 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Debug|x86.ActiveCfg = Debug|Win32 28 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Debug|x86.Build.0 = Debug|Win32 29 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Release|x64.ActiveCfg = Release|x64 30 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Release|x64.Build.0 = Release|x64 31 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Release|x86.ActiveCfg = Release|Win32 32 | {AF2B6C20-3080-43F3-92FD-AF3879C6F23B}.Release|x86.Build.0 = Release|Win32 33 | EndGlobalSection 34 | GlobalSection(SolutionProperties) = preSolution 35 | HideSolutionNode = FALSE 36 | EndGlobalSection 37 | GlobalSection(ExtensibilityGlobals) = postSolution 38 | SolutionGuid = {265B0C23-9A69-4C82-8331-7A617E877954} 39 | EndGlobalSection 40 | EndGlobal 41 | -------------------------------------------------------------------------------- /runme.py: -------------------------------------------------------------------------------- 1 | 2 | api_dll_and_loader_path = 'C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeProgrammer/api/lib/' # Directory containing DLLs, ExternalLoader and FlashLoader. 3 | import os # noqa: E402 4 | os.add_dll_directory(api_dll_and_loader_path) # Path to DLLs before importing CubeProgrammer_API. https://stackoverflow.com/a/67437837/101252 5 | # noinspection PyUnresolvedReferences 6 | import CubeProgrammer_API # noqa: E402 7 | 8 | 9 | def init_progress_bar(): 10 | print(f'InitProgressBar') 11 | 12 | 13 | def log_message(msgType : int, str): 14 | if msgType < 22: 15 | # print(f'{msgType}, {str}') 16 | print(f'{str}') 17 | 18 | 19 | def load_bar(curr_progress: int, total: int): 20 | print(f'{100 * curr_progress / total}%') 21 | 22 | 23 | api = CubeProgrammer_API.CubeProgrammer_API() 24 | 25 | api.setDisplayCallbacks( 26 | initProgressBar=init_progress_bar, 27 | logMessage=log_message, 28 | loadBar=load_bar) 29 | 30 | api.setLoadersPath(api_dll_and_loader_path) 31 | 32 | 33 | def check_connection(): 34 | x = api.checkDeviceConnection() 35 | str = 'Connected' if 1==x else 'Not connected' 36 | print(f'checkDeviceConnection: {str}') 37 | 38 | 39 | check_connection() 40 | 41 | list = api.getStLinkList() 42 | print(f'list: {list}') 43 | 44 | if len(list) == 1: 45 | x = api.connectStLink() 46 | if x < 0: 47 | api.disconnect() 48 | quit() 49 | 50 | check_connection() 51 | 52 | genInfo = api.getDeviceGeneralInf() 53 | print(f'genInfo: {genInfo}') 54 | 55 | resetFlag = api.reset(0) 56 | 57 | if resetFlag != 0: 58 | api.disconnect() 59 | quit() 60 | 61 | if False: # switch to enable downloads. 62 | isVerify = 1 # add verification step 63 | isSkipErase = 0 # no skip erase 64 | filePath = r'C:\Users\james.frederick\src\uctq_Sandbox\E102878-Qx\QuadRfDriverFirmware\Debug\QuadRfDriverFirmware.elf' 65 | downloadFileFlag = api.downloadFile(filePath) #, 0x08000000, isSkipErase, isVerify, "") 66 | if downloadFileFlag != 0: 67 | api.disconnect() 68 | quit() 69 | 70 | size = 64 71 | startAddress = 0x08000000 72 | data = api.readMemory(address=startAddress, byte_qty=size) 73 | 74 | print(f'data: {data}') 75 | 76 | print(f'\nReading 32-bit memory content') 77 | print(f' Size : {size} Bytes') 78 | print(f' Address: : 0x{startAddress:08X}') 79 | 80 | i = 0 81 | 82 | while i < size: 83 | col = 0 84 | print(f'\n@0x{startAddress + i:08X}:', end="") 85 | while (col < 4) and (i < size): 86 | # print(f' {data[i+3]:02X}{data[i+2]:02X}{data[i+1]:02X}{data[i]:02X} ', end="") 87 | u32 = int.from_bytes(data[i:i + 4], byteorder='little', signed=False) 88 | print(f' {u32:08X} ', end="") 89 | 90 | col += 1 91 | i += 4 92 | print() 93 | 94 | # Run application 95 | executeFlag = api.execute() 96 | if executeFlag != 0: 97 | api.disconnect() 98 | quit() 99 | 100 | api.disconnect() 101 | 102 | 103 | # input("Press Enter to continue...") # pause to see result -------------------------------------------------------------------------------- /api/include/DeviceDataStructure.h: -------------------------------------------------------------------------------- 1 | #ifndef DEVICEDATASTRUCTURE 2 | #define DEVICEDATASTRUCTURE 3 | 4 | 5 | #ifdef __cplusplus 6 | extern "C" { 7 | #endif 8 | 9 | #define R_ACCESS 0x0 10 | #define W_ACCESS 0x1 11 | #define RW_ACCESS 0x2 12 | #define RWE_ACCESS 0x3 13 | 14 | 15 | /* -------------------------------------------------------------------------------------------- */ 16 | /* OB Data Structures */ 17 | /* -------------------------------------------------------------------------------------------- */ 18 | 19 | 20 | /** 21 | * \struct bankSector. 22 | * \brief This stucture indicates the sectors parameters. 23 | */ 24 | typedef struct bankSector 25 | { 26 | unsigned int index ; /**< Index of the sector. */ 27 | unsigned int size ; /**< Sector size. */ 28 | unsigned int address ; /**< Sector starting address. */ 29 | }bankSector; 30 | 31 | 32 | /** 33 | * \struct deviceBank. 34 | * \brief This stucture defines the memory sectors for each bank. 35 | */ 36 | typedef struct deviceBank 37 | { 38 | unsigned int sectorsNumber; /**< Number of sectors of the considered bank. */ 39 | bankSector* sectors; /**< Sectors specifications #Bank_Sector. */ 40 | }deviceBank; 41 | 42 | 43 | /** 44 | * \struct storageStructure. 45 | * \brief This stucture describes sotrage characterization. 46 | */ 47 | typedef struct storageStructure 48 | { 49 | unsigned int banksNumber; /**< Number of exsisted banks. */ 50 | deviceBank* banks; /**< Banks sectors definition #Device_Bank. */ 51 | }storageStructure; 52 | 53 | 54 | /** 55 | * \struct bitCoefficient_C. 56 | * \brief This stucture indicates the coefficients to access to the adequate option bit. 57 | */ 58 | typedef struct bitCoefficient_C 59 | { 60 | unsigned int multiplier; /**< Bit multiplier. */ 61 | unsigned int offset; /**< Bit offset. */ 62 | }bitCoefficient_C; 63 | 64 | 65 | /** 66 | * \struct bitValue_C. 67 | * \brief This stucture describes the option Bit value. 68 | */ 69 | typedef struct bitValue_C 70 | { 71 | unsigned int value; /**< Option bit value. */ 72 | char description[200]; /**< Option bit description. */ 73 | }bitValue_C; 74 | 75 | 76 | /** 77 | * \struct bit_C. 78 | * \brief This stucture will be filled by values which characterize the device's option bytes. 79 | * \note See product reference manual for more details. 80 | */ 81 | typedef struct bit_C 82 | { 83 | char name[32]; /**< Bit name such as RDP, BOR_LEV, nBOOT0... */ 84 | char description[300]; /**< Config description. */ 85 | unsigned int wordOffset; /**< Word offset. */ 86 | unsigned int bitOffset; /**< Bit offset. */ 87 | unsigned int bitWidth; /**< Number of bits build the option. */ 88 | unsigned char access; /**< Access Read/Write. */ 89 | unsigned int valuesNbr; /**< Number of possible values. */ 90 | bitValue_C** values; /**< Bits value, #BitValue_C. */ 91 | bitCoefficient_C equation; /**< Bits equation, #BitCoefficient_C. */ 92 | unsigned char* reference; 93 | unsigned int bitValue; 94 | }bit_C; 95 | 96 | 97 | /** 98 | * \struct category_C 99 | * \brief Get option bytes banks categories descriptions. 100 | */ 101 | typedef struct category_C 102 | { 103 | char name[100]; /**< Get category name such as Read Out Protection, BOR Level... */ 104 | unsigned int bitsNbr; /**< Get bits number of the considered category. */ 105 | bit_C** bits; /**< Get internal bits descriptions. */ 106 | }category_C; 107 | 108 | 109 | /** 110 | * \struct bank_C 111 | * \brief Get option bytes banks internal descriptions. 112 | * \note STLINK and Bootloader interfaces have different addresses to access to option bytes registres. 113 | */ 114 | typedef struct bank_C 115 | { 116 | unsigned int size; /**< Bank size. */ 117 | unsigned int address; /**< Bank starting address. */ 118 | unsigned char access; /**< Bank access Read/Write. */ 119 | unsigned int categoriesNbr; /**< Number of option bytes categories. */ 120 | category_C** categories; /**< Get bank categories descriptions #Category_C. */ 121 | }bank_C; 122 | 123 | 124 | /** 125 | * \struct peripheral_C 126 | * \brief Get peripheral option bytes general informations. 127 | */ 128 | typedef struct peripheral_C 129 | { 130 | char name[32]; /**< Peripheral name. */ 131 | char description[200]; /**< Peripheral description. */ 132 | unsigned int banksNbr; /**< Number of existed banks. */ 133 | bank_C** banks; /**< Get banks descriptions #Bank_C. */ 134 | }peripheral_C; 135 | 136 | 137 | 138 | #ifdef __cplusplus 139 | } 140 | #endif 141 | 142 | 143 | #endif // DEVICEDATASTRUCTURE 144 | 145 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyCubeProgrammer_API 2 | 3 | Use your Python app to create a customized live-watch window for your firmware by talking over SWD. 4 | 5 | This is a Python wrapper for STM32 CubeProgrammer_API. It uses Cython, resulting in a .pyd python-DLL file that is imported by a user's Python program. 6 | 7 | [](https://mermaid-js.github.io/mermaid-live-editor/edit/#eyJjb2RlIjoiZ3JhcGggVEQ7XG5cdFx0Y2xhc3NEZWYgR3JlZW5GaWxsIGZpbGw6IzdmNztcbiAgICBzdWJncmFwaCBXaW5kb3dzXG5cdFx0XHR1c2VyUHl0aG9uW3VzZXIgUHl0aG9uXSAtLT4gUHlDdWJlUHJvZ3JhbW1lcl9BUElbQ3ViZVByb2dyYW1tZXJfQVBJLnB5ZDxicj50aGluIFB5dGhvbiB3cmFwcGVyXTo6OkdyZWVuRmlsbDtcbiAgICAgIFB5Q3ViZVByb2dyYW1tZXJfQVBJIC0tPiBDdWJlUHJvZ3JhbW1lcl9BUEk7XG4gICAgICBDdWJlUHJvZ3JhbW1lcl9BUElbQ3ViZVByb2dyYW1tZXJfQVBJPGJyPkRMTHMgYW5kIGRyaXZlcnNdXG5cdFx0ZW5kXG5cbiAgICBDdWJlUHJvZ3JhbW1lcl9BUEkgLS0-fFVTQnwgU1RMaW5rW1NULUxpbmsgZG9uZ2xlXVxuXHQgIFNUTGluayAtLT58U1dEIG9yIEpUQUd8IFNUTTMyW1NUTTMyIE1pY3JvQ29udHJvbGxlcl1cbiAgICBodHRwczovL3d3dy5zdC5jb20vZW4vZGV2ZWxvcG1lbnQtdG9vbHMvc3RtMzJjdWJlcHJvZy5odG1sIC0tLS0-fGRvd25sb2FkL2luc3RhbGx8IEN1YmVQcm9ncmFtbWVyX0FQSVxuICAgIGh0dHBzOi8vZ2l0aHViLmNvbS9qaW1mcmVkL1B5Q3ViZVByb2dyYW1tZXJfQVBJIC0tLS0-fGRvd25sb2FkL2NvcHl8IFB5Q3ViZVByb2dyYW1tZXJfQVBJIiwibWVybWFpZCI6IntcbiAgXCJ0aGVtZVwiOiBcImRlZmF1bHRcIlxufSIsInVwZGF0ZUVkaXRvciI6ZmFsc2UsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjpmYWxzZX0) 8 | 9 | The STM32 CubeProgrammer_API is a C-library, created by ST for ST-Link access to micro-controllers for the purpose of flash downloads or general memory access. The CubeProgrammer is required, including its drivers, and can be downloaded from st.com and installed. 10 | 11 | This has been tested on Windows and although CubeProgrammer is available for other OS's. The main focus so far is USB-to-SWD access. 12 | 13 | Two examples are included: 14 | - TestHotPlug.py - a console app that gracefully recovers from a hot-plug of either end of an ST-Link (USB end or the SWD end). 15 | - runme.py - based loosely on C examples included in the CubeProgrammer_API. 16 | 17 | ## Why would anybody want this? 18 | Firmware rarely remains isolated in it's own little CPU. It needs to interact with people and processes, at least during testing and development. That's what communication protocols are for, right? Yes, but with SWD (or JTAG), the firmware needs no communication protocols. SWD is used anyway for firmware download. While it's there, plugged in, it's available for things like reading and writing of data. It's like a live-watch debug window to read and write data except it can be orchestrated by Python and leverage Python's GUI capabilities. And how does Python know how to access data? The same way a debugger does - by interrogating the .elf file to determine data structures and their locations. This capability is useful for R&D development, production testing and beyond. All the necessary drivers for various OS's are handled by others and the firmware doesn't need to implement any communications protocols to open a huge window to the outside world for human interaction. 19 | 20 | ## Installation 21 | copy CubeProgrammer_API.cp39-win_amd64.pyd locally. It's assumed that CubeProgrammer has been installed (`C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeProgrammer/api/lib/`) and has all the necessary DLLs required by the CubeProgrammer_API .pyd file. See the top of the examples for code to reference the location of those DLLs. 22 | 23 | ## Usage 24 | In a Python application, reference the API's DLLs with a statement like... 25 | ```os.add_dll_directory('C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeProgrammer/api/lib/')``` 26 | The `os` will, of course need an `import os` 27 | 28 | Then import the .PYD extension like this... 29 | `import CubeProgrammer_API` 30 | The import needs to be done after the `add_dll_directory()`. 31 | 32 | This Cython/Python wrapper performs default initialization that the C-API omitted such as initialization of callbacks. This default initialization will prevent faults/exceptions that halt/crash the application without diagnostic information. 33 | 34 | 35 | ## Development 36 | - setup.py and run_setup.py are used to compile the Cython .pyx file to a .dll with the .pyd extension. 37 | - CppExample is a Visual Studio project that uses the CubeProgrammer_API, used only to isolate C-vs-Python issues. 38 | - CubeProgrammer_API.cpp is a temporary intermediate file used by Cython to generate the .pyd file. 39 | 40 | ## Other similar projects: 41 | - pyOCD 42 | - PyStLink 43 | - OpenOcd 44 | 45 | Although there are several other libraries that provide debug interfaces to ARM micro-controllers, some with Python bindings, this PyCubeProgrammer_API is intended to leverage ST's support for driver installation and support for new chip variants. 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /CppExample/Example1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file Example1.cpp 3 | * This example allows to execute some operations to the internal STM32 Flash memory. \n 4 | * 1. Detect connected ST-LINK and display them. \n 5 | * 2. Loop on each ST-LINK probes and execute the following operations: \n 6 | * - Mass erase. 7 | * - Single word edition (-w32). 8 | * - Read 64 bytes from 0x08000000. 9 | * - Sector erase. 10 | * - Read 64 bytes from 0x08000000 . 11 | * - System Reset. \n 12 | *. 13 | *Go to the source code : \ref STLINK_Example1 14 | * \example STLINK_Example1 15 | * This example allows to execute some operations to the internal STM32 Flash memory. \n 16 | * 1. Detect connected ST-LINK and display them. \n 17 | * 2. Loop on each St-LINK probes and execute the following operations: \n 18 | * - Mass erase. 19 | * - Single word edition (-w32). 20 | * - Read 64 bytes from 0x08000000. 21 | * - Sector erase. 22 | * - Read 64 bytes from 0x08000000 . 23 | * - System Reset. \n 24 | * \code{.cpp} 25 | **/ 26 | 27 | #include 28 | #include 29 | #include "DisplayManager.h" 30 | 31 | #include 32 | #pragma comment(lib, "CubeProgrammer_API.lib") 33 | // Prerequisites for CubeProgrammer_API compile & link: 34 | // - Include path needs $(ProjectDir)..\api\include or 35 | // - Lib path needs $(ProjectDir)..\api\lib 36 | // Prerequisites for CubeProgrammer_API debug/execution: 37 | // - debuger environment needs: PATH=C:\Program Files\STMicroelectronics\STM32Cube\STM32CubeProgrammer\api\lib;%PATH% 38 | 39 | extern unsigned int verbosityLevel; 40 | 41 | int Example1(void) { 42 | 43 | logMessage(Title, "\n+++ Example 1 +++\n\n"); 44 | 45 | debugConnectParameters* stLinkList; 46 | debugConnectParameters debugParameters; 47 | generalInf* genInfo; 48 | 49 | int getStlinkListNb = getStLinkList(&stLinkList, 0); 50 | 51 | if (getStlinkListNb == 0) 52 | { 53 | logMessage(Error, "No STLINK available\n"); 54 | return 0; 55 | } 56 | else { 57 | logMessage(Title, "\n-------- Connected ST-LINK Probes List --------"); 58 | for (int i = 0; i < getStlinkListNb; i++) 59 | { 60 | logMessage(Normal, "\nST-LINK Probe %d :\n", i); 61 | logMessage(Info, " ST-LINK SN : %s \n", stLinkList[i].serialNumber); 62 | logMessage(Info, " ST-LINK FW : %s \n", stLinkList[i].firmwareVersion); 63 | } 64 | logMessage(Title, "-----------------------------------------------\n\n"); 65 | } 66 | 67 | for (int index = 0; index < getStlinkListNb; index++) { 68 | 69 | logMessage(Title, "\n--------------------- "); 70 | logMessage(Title, "\n ST-LINK Probe : %d ", index); 71 | logMessage(Title, "\n--------------------- \n\n"); 72 | 73 | debugParameters = stLinkList[index]; 74 | debugParameters.connectionMode = HOTPLUG_MODE; // UNDER_RESET_MODE; 75 | debugParameters.shared = 0; 76 | 77 | /* Target connect */ 78 | int connectStlinkFlag = connectStLink(debugParameters); 79 | if (connectStlinkFlag != 0) { 80 | logMessage(Error, "Establishing connection with the device failed\n"); 81 | disconnect(); 82 | continue; 83 | } 84 | else { 85 | logMessage(GreenInfo, "\n--- Device %d Connected --- \n", index); 86 | } 87 | 88 | /* Display device informations */ 89 | genInfo = getDeviceGeneralInf(); 90 | logMessage(Normal, "\nDevice name : %s ", genInfo->name); 91 | logMessage(Normal, "\nDevice type : %s ", genInfo->type); 92 | logMessage(Normal, "\nDevice CPU : %s \n", genInfo->cpu); 93 | 94 | /* Reading 64 bytes from 0x08000000 */ 95 | unsigned char* dataStruct = 0; 96 | int size = 64; 97 | int startAddress = 0x08000000; 98 | 99 | int readMemoryFlag = readMemory(startAddress, &dataStruct, size); 100 | if (readMemoryFlag != 0) 101 | { 102 | disconnect(); 103 | continue; 104 | } 105 | 106 | logMessage(Normal, "\nReading 32-bit memory content\n"); 107 | logMessage(Normal, " Size : %d Bytes\n", size); 108 | logMessage(Normal, " Address: : 0x%08X\n", startAddress); 109 | 110 | int i = 0, col = 0; 111 | 112 | while ((i < size)) 113 | { 114 | col = 0; 115 | logMessage(Normal, "\n0x%08X :", startAddress + i); 116 | while ((col < 4) && (i < size)) 117 | { 118 | logMessage(Info, " %08X ", *(unsigned int*)(dataStruct + i)); 119 | col++; 120 | i += 4; 121 | } 122 | 123 | } 124 | logMessage(Normal, "\n"); 125 | 126 | /* Process successfully Done */ 127 | disconnect(); 128 | } 129 | 130 | deleteInterfaceList(); 131 | return 1; 132 | 133 | } 134 | 135 | int main() 136 | { 137 | int x = checkDeviceConnection(); 138 | 139 | int ret = 0; 140 | const char* loaderPath = "C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeProgrammer/api/lib/"; // reference directory that has ExternalLoader and FlashLoader. 141 | displayCallBacks vsLogMsg; 142 | 143 | /* Set device loaders path that contains FlashLoader and ExternalLoader folders*/ 144 | setLoadersPath(loaderPath); 145 | 146 | /* Set the progress bar and message display functions callbacks */ 147 | vsLogMsg.logMessage = DisplayMessage; 148 | vsLogMsg.initProgressBar = InitPBar; 149 | vsLogMsg.loadBar = lBar; 150 | setDisplayCallbacks(vsLogMsg); 151 | 152 | /* Set DLL verbosity level */ 153 | //setVerbosityLevel(verbosityLevel = VERBOSITY_LEVEL_1); 154 | 155 | ret = Example1(); 156 | //ret = Example2(); 157 | //ret = Example3(); 158 | //ret = Example_WB(); 159 | //ret = I2C_Example(); 160 | //ret = CAN_Example(); 161 | //ret = SPI_Example(); 162 | //ret = UART_Example(); 163 | //ret = USB_Example(); 164 | //ret = USB_Example_WB(); 165 | //ret = TSV_Flashing(); 166 | 167 | std::cout << "\n" << "Press enter to continue..."; 168 | std::cin.get(); 169 | return ret; 170 | } 171 | 172 | 173 | /** \endcode **/ 174 | -------------------------------------------------------------------------------- /CppExample/DisplayManager.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * \file DisplayManager.cpp 3 | * This example of functions allows to personalize the display messages. \n 4 | * - Implement Init Progress Bar function to add a progress bar. 5 | * - Implement load Bar function to animate the loading process 0% to 100%. 6 | * - Implement DisplayMessage function to ensure the display of internal DLL messages. 7 | * - Implement logMessage function to personalize the display (user messages). 8 | *. 9 | * Go to the source code : \ref DisplayManager 10 | \example DisplayManager 11 | * This example of functions allows to personalize the display messages. \n 12 | * - Implement Init Progress Bar function to add a progress bar. 13 | * - Implement load Bar function to animate the loading process 0% to 100%. 14 | * - Implement DisplayMessage function to ensure the display of internal DLL messages. 15 | * - Implement logMessage function to personalize the display (user messages). 16 | * \code{.cpp} 17 | **/ 18 | 19 | #define _CRT_SECURE_NO_WARNINGS // will disable warnings to use vsprintf instead vsprintf_s 20 | 21 | #include 22 | #include "DisplayManager.h" 23 | #include 24 | #include 25 | #include 26 | 27 | #ifdef _WIN32 28 | #include 29 | HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);; 30 | CONSOLE_SCREEN_BUFFER_INFO SBInfo, CurSBInfo; 31 | #endif 32 | 33 | #define WIDH 50 34 | using namespace std; 35 | 36 | unsigned int verbosityLevel; 37 | unsigned int Progress = 0; 38 | 39 | 40 | void InitPBar() 41 | { 42 | #ifdef _WIN32 43 | if (verbosityLevel == VERBOSITY_LEVEL_1) 44 | { 45 | for (int idx = 0; idx < WIDH; idx++) 46 | { 47 | console = GetStdHandle(STD_OUTPUT_HANDLE); 48 | SetConsoleTextAttribute(console, LIGHTGREY); 49 | putc(177, stdout); 50 | } 51 | GetConsoleScreenBufferInfo(console, &SBInfo); 52 | printf(" %d%c", Progress,'%'); 53 | SetConsoleTextAttribute(console, LIGHTCYAN); 54 | putc('\r', stdout); 55 | Progress = 0; 56 | } 57 | #endif 58 | } 59 | 60 | void lBar(int currProgress, int total) 61 | { 62 | unsigned int alreadyLoaded = 0; 63 | if (total == 0) return; 64 | if (currProgress > total) 65 | currProgress = total; 66 | 67 | /*Calculuate the ratio of complete-to-incomplete.*/ 68 | float ratio = currProgress / (float)total; 69 | unsigned int counter = (unsigned int)ratio * WIDH; 70 | 71 | if ((counter > alreadyLoaded) && (verbosityLevel == VERBOSITY_LEVEL_1)) 72 | { 73 | #ifdef _WIN32 74 | SetConsoleTextAttribute(console, FOREGROUND_GREEN); 75 | 76 | for (DWORD Idx = Progress; Idx < (counter - alreadyLoaded); Idx++) 77 | { 78 | putc(219, stdout); 79 | } 80 | Progress = counter; 81 | GetConsoleScreenBufferInfo(console, &CurSBInfo); 82 | SetConsoleCursorPosition(console, SBInfo.dwCursorPosition); 83 | 84 | printf(" %d%%", (int)(ratio * 100)); 85 | SetConsoleCursorPosition(console, CurSBInfo.dwCursorPosition); 86 | #else 87 | 88 | printf("\033[00;32m"); 89 | printf("["); 90 | for (int i = 0; i < counter; i++) 91 | { 92 | printf("="); 93 | } 94 | for (int i = counter; i < WIDH; i++) 95 | { 96 | printf(" "); 97 | } 98 | // draw the percentage progress 99 | 100 | printf("] %3d%% \r", (int)(ratio * 100)); /* Move to the first column*/ 101 | printf("\033[39;49m"); 102 | #endif 103 | } 104 | alreadyLoaded = counter; 105 | } 106 | 107 | 108 | void DisplayMessage(int msgType, const wchar_t* str) 109 | { 110 | 111 | #ifdef _WIN32 112 | switch (msgType) 113 | { 114 | default: 115 | case Normal: 116 | SetConsoleTextAttribute(console, WHITE); 117 | break; 118 | case GreenInfo: 119 | SetConsoleTextAttribute(console, GREEN); 120 | break; 121 | case Info: 122 | SetConsoleTextAttribute(console, LIGHTGREY); 123 | break; 124 | case Title: 125 | SetConsoleTextAttribute(console, LIGHTCYAN); 126 | break; 127 | case Error: 128 | SetConsoleTextAttribute(console, RED); 129 | break; 130 | case Warning: 131 | SetConsoleTextAttribute(console, YELLOW); 132 | break; 133 | case ErrorNoPopup: 134 | SetConsoleTextAttribute(console, RED); 135 | break; 136 | case WarningNoPopup: 137 | SetConsoleTextAttribute(console, YELLOW); 138 | break; 139 | case Verbosity_1: 140 | SetConsoleTextAttribute(console, CYAN); 141 | break; 142 | case Verbosity_2: 143 | SetConsoleTextAttribute(console, CYAN); 144 | break; 145 | case Verbosity_3: 146 | SetConsoleTextAttribute(console, CYAN); 147 | break; 148 | } 149 | 150 | if ((msgType != Verbosity_1 && msgType != Verbosity_2 && msgType != Verbosity_3) || ((msgType == Verbosity_1 && verbosityLevel >= VERBOSITY_LEVEL_1) || (msgType == Verbosity_2 && verbosityLevel >= VERBOSITY_LEVEL_2) || (msgType == Verbosity_3 && verbosityLevel == VERBOSITY_LEVEL_3))) { 151 | 152 | wprintf(L"%s\n", str); 153 | } 154 | SetConsoleTextAttribute(console, WHITE); 155 | #else 156 | if (verbosityLevel == VERBOSITY_LEVEL_1) 157 | { 158 | if ((msgType == Verbosity_1 && verbosityLevel >= 1)) 159 | printf("\033[39;36m"); 160 | if ((msgType == Verbosity_2 && verbosityLevel >= 2)) 161 | printf("\033[39;36m"); 162 | if ((msgType == Verbosity_3 && verbosityLevel >= 3)) 163 | printf("\033[39;36m"); 164 | 165 | switch (msgType) 166 | { 167 | case GreenInfo: 168 | printf("\033[00;32m"); 169 | break; 170 | case Info: 171 | printf("\e[90m"); 172 | break; 173 | case Normal: 174 | printf("\033[39;49m"); 175 | break; 176 | case Warning: 177 | printf("\033[00;33m"); 178 | break; 179 | case Error: 180 | printf("\033[00;31m"); 181 | break; 182 | case Title: 183 | printf("\e[36m\033[01m"); 184 | break; 185 | } 186 | } 187 | if ((msgType != Verbosity_1 && msgType != Verbosity_2 && msgType != Verbosity_3) || ((msgType == Verbosity_1 && verbosityLevel >= 1) || (msgType == Verbosity_2 && verbosityLevel >= 2) || (msgType == Verbosity_3 && verbosityLevel == 3))) 188 | { 189 | std::wcout << str << std::endl; 190 | } 191 | printf("\033[39;49m"); 192 | #endif 193 | } 194 | 195 | void logMessage(int msgType, const char* str, ...) 196 | { 197 | #ifdef _WIN32 198 | switch (msgType) 199 | { 200 | default: 201 | case Normal: 202 | SetConsoleTextAttribute(console, WHITE); 203 | break; 204 | case GreenInfo: 205 | SetConsoleTextAttribute(console, GREEN); 206 | break; 207 | case Info: 208 | SetConsoleTextAttribute(console, LIGHTGREY); 209 | break; 210 | case Title: 211 | SetConsoleTextAttribute(console, LIGHTCYAN); 212 | break; 213 | case Error: 214 | SetConsoleTextAttribute(console, RED); 215 | break; 216 | case Warning: 217 | SetConsoleTextAttribute(console, YELLOW); 218 | break; 219 | case ErrorNoPopup: 220 | SetConsoleTextAttribute(console, RED); 221 | break; 222 | case WarningNoPopup: 223 | SetConsoleTextAttribute(console, YELLOW); 224 | break; 225 | case Verbosity_1: 226 | SetConsoleTextAttribute(console, CYAN); 227 | break; 228 | case Verbosity_2: 229 | SetConsoleTextAttribute(console, CYAN); 230 | break; 231 | case Verbosity_3: 232 | SetConsoleTextAttribute(console, CYAN); 233 | break; 234 | } 235 | #else 236 | switch (msgType) 237 | { 238 | case GreenInfo: 239 | printf("\033[00;32m"); 240 | break; 241 | case Info: 242 | printf("\e[90m"); 243 | break; 244 | case Normal: 245 | printf("\033[39;49m"); 246 | break; 247 | case Warning: 248 | printf("\033[00;33m"); 249 | break; 250 | case Error: 251 | printf("\033[00;31m"); 252 | break; 253 | case Title: 254 | printf("\e[36m\033[01m"); 255 | break; 256 | } 257 | #endif 258 | va_list args; 259 | va_start(args, str); 260 | char buffer[256]; 261 | vsprintf(buffer, str, args); 262 | printf("%s", buffer); 263 | va_end(args); 264 | 265 | #ifdef _WIN32 266 | SetConsoleTextAttribute(console, WHITE); 267 | #else 268 | printf("\033[39;49m"); 269 | #endif 270 | } 271 | 272 | /** \endcode **/ 273 | -------------------------------------------------------------------------------- /CppExample/Example2.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {67946bf0-0cde-4e99-a380-ab92924fee74} 25 | Example2 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v142 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v142 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v142 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v142 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | true 75 | 76 | 77 | false 78 | 79 | 80 | true 81 | 82 | 83 | false 84 | ..\api\include;$(IncludePath) 85 | ..\api\lib\x64;$(LibraryPath) 86 | 87 | 88 | 89 | Level3 90 | true 91 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 92 | true 93 | 94 | 95 | Console 96 | true 97 | 98 | 99 | 100 | 101 | Level3 102 | true 103 | true 104 | true 105 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | 108 | 109 | Console 110 | true 111 | true 112 | true 113 | 114 | 115 | 116 | 117 | Level3 118 | true 119 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | 122 | 123 | Console 124 | true 125 | 126 | 127 | 128 | 129 | Level3 130 | true 131 | true 132 | true 133 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 134 | true 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | %(AdditionalLibraryDirectories) 142 | CubeProgrammer_API.lib;%(AdditionalDependencies) 143 | $(ProjectDir)..\$(TargetName)$(TargetExt) 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /CppExample/Example1.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {af2b6c20-3080-43f3-92fd-af3879c6f23b} 25 | Example1 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v142 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v142 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v142 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v142 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | true 75 | 76 | 77 | false 78 | 79 | 80 | true 81 | $(ProjectDir)..\api\include;$(IncludePath) 82 | $(ProjectDir)..\api\lib;$(IncludePath);$(LibraryPath) 83 | $(ExecutablePath) 84 | 85 | 86 | false 87 | ..\api\include;$(IncludePath) 88 | ..\api\lib\x64;$(LibraryPath) 89 | 90 | 91 | 92 | Level3 93 | true 94 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 95 | true 96 | 97 | 98 | Console 99 | true 100 | 101 | 102 | 103 | 104 | Level3 105 | true 106 | true 107 | true 108 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 109 | true 110 | 111 | 112 | Console 113 | true 114 | true 115 | true 116 | 117 | 118 | 119 | 120 | Level3 121 | true 122 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 123 | true 124 | 125 | 126 | Console 127 | true 128 | 129 | 130 | 131 | 132 | Level3 133 | true 134 | true 135 | true 136 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 137 | true 138 | 139 | 140 | Console 141 | true 142 | true 143 | true 144 | %(AdditionalLibraryDirectories) 145 | CubeProgrammer_API.lib;%(AdditionalDependencies) 146 | $(ProjectDir)..\$(TargetName)$(TargetExt) 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /CubeProgrammer_API.pyx: -------------------------------------------------------------------------------- 1 | """ 2 | Define thin Python wrapper for CubeProgrammer_API using Cython. 3 | This generates a .PYD python extension. 4 | Members added to read and write symbols e.g., floats etc. 5 | """ 6 | 7 | import struct 8 | 9 | cdef extern from "stddef.h": 10 | ctypedef void wchar_t 11 | 12 | from cpython.ref cimport PyObject 13 | cdef extern from "Python.h": 14 | PyObject* PyUnicode_FromWideChar(wchar_t *w, Py_ssize_t size) 15 | wchar_t* PyUnicode_AsWideCharString(object, Py_ssize_t*) except NULL 16 | 17 | 18 | # Tell Cython what C constructs we wish to use from this C header file 19 | cdef extern from "./api/include/CubeProgrammer_API.h": 20 | 21 | cdef enum cubeProgrammerError: 22 | CUBEPROGRAMMER_NO_ERROR = 0, # Success (no error) 23 | CUBEPROGRAMMER_ERROR_NOT_CONNECTED = -1, # Device not connected 24 | CUBEPROGRAMMER_ERROR_NO_DEVICE = -2, # Device not found 25 | CUBEPROGRAMMER_ERROR_CONNECTION = -3, # Device connection error 26 | CUBEPROGRAMMER_ERROR_NO_FILE = -4, # No such file 27 | CUBEPROGRAMMER_ERROR_NOT_SUPPORTED = -5, # Operation not supported or unimplemented on this interface 28 | CUBEPROGRAMMER_ERROR_INTERFACE_NOT_SUPPORTED = -6, # Interface not supported or unimplemented on this plateform 29 | CUBEPROGRAMMER_ERROR_NO_MEM = -7, # Insufficient memory 30 | CUBEPROGRAMMER_ERROR_WRONG_PARAM = -8, # Wrong parameters 31 | CUBEPROGRAMMER_ERROR_READ_MEM = -9, # Memory read failure 32 | CUBEPROGRAMMER_ERROR_WRITE_MEM = -10, # Memory write failure 33 | CUBEPROGRAMMER_ERROR_ERASE_MEM = -11, # Memory erase failure 34 | CUBEPROGRAMMER_ERROR_UNSUPPORTED_FILE_FORMAT = -12, # File format not supported for this kind of device 35 | CUBEPROGRAMMER_ERROR_REFRESH_REQUIRED = -13, # Refresh required 36 | CUBEPROGRAMMER_ERROR_NO_SECURITY = -14, # Refresh required 37 | CUBEPROGRAMMER_ERROR_CHANGE_FREQ = -15, # Changing frequency problem 38 | CUBEPROGRAMMER_ERROR_RDP_ENABLED = -16, # RDP Enabled error 39 | CUBEPROGRAMMER_ERROR_OTHER = -99, # Other error 40 | 41 | cdef enum debugConnectMode: 42 | NORMAL_MODE = 0, # Connect with normal mode, the target is reset then halted while the type of reset is selected using the [debugResetMode]. 43 | HOTPLUG_MODE, # Connect with hotplug mode, this option allows the user to connect to the target without halt or reset. 44 | UNDER_RESET_MODE, # Connect with under reset mode, option allows the user to connect to the target using a reset vector catch before executing any instruction. 45 | POWER_DOWN_MODE, # Connect with power down mode. 46 | PRE_RESET_MODE # Connect with pre reset mode. 47 | 48 | cdef enum debugPort: 49 | JTAG = 0, 50 | SWD = 1, 51 | 52 | cdef enum debugResetMode: 53 | SOFTWARE_RESET, # Apply a reset by the software. 54 | HARDWARE_RESET, # Apply a reset by the hardware. 55 | CORE_RESET # Apply a reset by the internal core peripheral. 56 | 57 | cdef struct frequencies: 58 | unsigned int jtagFreq[12] # JTAG frequency. 59 | unsigned int jtagFreqNumber # Get JTAG supported frequencies. 60 | unsigned int swdFreq[12] # SWD frequency. 61 | unsigned int swdFreqNumber # Get SWD supported frequencies. 62 | 63 | # https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html#styles-of-struct-union-and-enum-declaration 64 | cdef struct debugConnectParameters: 65 | debugPort dbgPort # Select the type of debug interface #debugPort. 66 | int index # Select one of the debug ports connected. 67 | char serialNumber[33] # ST-LINK serial number. 68 | char firmwareVersion[20] # Firmware version. 69 | char targetVoltage[5] # Operate voltage. 70 | int accessPortNumber # Number of available access port. 71 | int accessPort # Select access port controller. 72 | debugConnectMode connectionMode # Select the debug CONNECT mode #debugConnectMode. 73 | debugResetMode resetMode # Select the debug RESET mode #debugResetMode. 74 | int isOldFirmware # Check Old ST-LINK firmware version. 75 | frequencies freq # Supported frequencies #frequencies. 76 | int frequency # Select specific frequency. 77 | int isBridge # Indicates if it's Bridge device or not. 78 | int shared # Select connection type, if it's shared, use ST-LINK Server. 79 | char board[100] # board Name 80 | int DBG_Sleep 81 | 82 | # define C typedefs for 3 callback functions. 83 | ctypedef void (*PCCbInitProgressBar)() 84 | ctypedef void (*PCCbLogMessage)(int msgType, const wchar_t* str) 85 | ctypedef void (*PCCbLoadBar)(int x, int n) 86 | 87 | cdef struct displayCallBacks: 88 | PCCbInitProgressBar initProgressBar # Add a progress bar. 89 | PCCbLogMessage logMessage # Display internal messages according to verbosity level. 90 | PCCbLoadBar loadBar # Display the loading of read/write process. 91 | 92 | cdef struct generalInf: 93 | unsigned short deviceId; # Device ID. 94 | int flashSize; # Flash memory size. 95 | int bootloaderVersion; # Bootloader version 96 | char type[4]; # Device MCU or MPU. 97 | char cpu[20]; # Cortex CPU. 98 | char name[100]; # Device name. 99 | char series[100]; # Device serie. 100 | char description[150]; # Take notice. 101 | char revisionId[100]; # Revision ID. 102 | char board[100]; # Board Rpn. 103 | 104 | int api_checkDeviceConnection "checkDeviceConnection" () 105 | int api_getStLinkList "getStLinkList" (debugConnectParameters** stLinkList, int shared) 106 | int api_connectStLink "connectStLink" (debugConnectParameters debugParameters) 107 | int api_readMemory "readMemory" (unsigned int address, unsigned char** data, unsigned int byte_qty) 108 | int api_writeMemory "writeMemory" (unsigned int address, char* data, unsigned int byte_qty) 109 | void api_disconnect "disconnect" () 110 | generalInf * api_getDeviceGeneralInf "getDeviceGeneralInf" () 111 | int api_downloadFile "downloadFile" (const wchar_t* filePath, unsigned int address, unsigned int skipErase, unsigned int verify, const wchar_t* binPath) 112 | int api_execute "execute" (unsigned int address) 113 | int api_reset "reset" (debugResetMode rstMode) 114 | 115 | void api_setDisplayCallbacks "setDisplayCallbacks" (displayCallBacks c) 116 | void api_setLoadersPath "setLoadersPath" (const char* path) 117 | 118 | 119 | cdef class CubeProgrammer_API: 120 | cdef int c_stlink_connected 121 | cdef int c_device_connected 122 | py_stlink_list: [] 123 | 124 | @property 125 | def stlink_list(self): 126 | return self.py_stlink_list 127 | 128 | @property 129 | def stlink_connected(self): 130 | return self.c_stlink_connected != 0 131 | 132 | @property 133 | def device_connected(self): 134 | return self.c_device_connected != 0 135 | 136 | def __init__(self): 137 | cdef const char* path = "./" 138 | api_setLoadersPath(path) 139 | 140 | global display_cb_struct 141 | api_setDisplayCallbacks(display_cb_struct) 142 | 143 | self.c_stlink_connected = False 144 | self.c_device_connected = False 145 | self.py_stlink_list = None 146 | 147 | def setDisplayCallbacks(self, initProgressBar, logMessage, loadBar): 148 | global py_cb_InitProgressBar, py_cb_LogMessage, py_cb_LoadBar 149 | 150 | py_cb_InitProgressBar = initProgressBar 151 | py_cb_LogMessage = logMessage 152 | py_cb_LoadBar = loadBar 153 | 154 | def setLoadersPath(self, path): 155 | str = f'setLoadersPath({path})' 156 | c_cb_LogMessage(4, PyUnicode_AsWideCharString(str, NULL)) 157 | cdef bytes x = path.encode() 158 | api_setLoadersPath(x) 159 | 160 | def checkDeviceConnection(self): 161 | return api_checkDeviceConnection() 162 | 163 | def getStLinkList(self): 164 | global stLinkList 165 | stLinkListLen = api_getStLinkList(&stLinkList, 0) 166 | self.py_stlink_list = [stLinkList[i] for i in range(stLinkListLen)] 167 | return self.py_stlink_list 168 | 169 | def connectStLink(self, int index=0) -> int : 170 | if index >= len(self.py_stlink_list): 171 | return -1 172 | # print(stLinkList[index]) 173 | if 0 == stLinkList[index].accessPortNumber: # assume this is an indication that the ST-Link is disconnected from the target. 174 | return -1 175 | cdef int err = api_connectStLink(stLinkList[index]) 176 | # print(f'connectStLink: {err}') 177 | return err 178 | 179 | def readMemory(self, unsigned int address, unsigned int byte_qty) -> bytearray: 180 | cdef unsigned char * data 181 | cdef int err = api_readMemory(address, &data, byte_qty) 182 | if err: 183 | return None 184 | bytes = bytearray() 185 | for i in range(byte_qty): 186 | bytes.append(data[i]) 187 | return bytes 188 | 189 | def disconnect(self): 190 | api_disconnect() 191 | 192 | def getDeviceGeneralInf(self): 193 | cdef generalInf * p_general_inf = 0 194 | p_general_inf = api_getDeviceGeneralInf() 195 | return p_general_inf[0] 196 | 197 | def downloadFile(self, filePath, unsigned int address=0x08000000, unsigned int skipErase=0, unsigned int verify=1, binPath=''): 198 | cdef wchar_t* wfilePath = PyUnicode_AsWideCharString(filePath, NULL) 199 | cdef wchar_t* wbinPath = PyUnicode_AsWideCharString(binPath, NULL) 200 | # print(f'downloadFile, filePath: {filePath}, address: {address}, skipErase: {skipErase}, verify: {verify}') 201 | return api_downloadFile(wfilePath, address, skipErase, verify, wbinPath) 202 | 203 | def reset(self, debugResetMode rstMode): 204 | return api_reset(rstMode) 205 | 206 | def execute(self, unsigned int address=0x08000000): 207 | return api_execute(address) 208 | 209 | def set_default_log_message_verbosity(self, val): 210 | global default_log_message_verbosity 211 | default_log_message_verbosity = val 212 | 213 | ''' 214 | Check connection, USB and SWD, to microcontroller. 215 | Updates device_connected and stlink_connected 216 | ''' 217 | def connection_update(self): 218 | 219 | self.c_device_connected = 1 == self.checkDeviceConnection() 220 | 221 | if not self.c_device_connected: 222 | self.disconnect() 223 | self.py_stlink_list = None 224 | self.c_stlink_connected = False 225 | 226 | if self.py_stlink_list is None: 227 | self.getStLinkList() 228 | self.c_stlink_connected = len(self.py_stlink_list) > 0 229 | 230 | if len(self.py_stlink_list) == 1 and not self.c_device_connected: 231 | self.connectStLink() 232 | 233 | self.c_device_connected = 1 == self.checkDeviceConnection() 234 | 235 | def read_u8(self, adr_arg): 236 | cdef unsigned char * bytes 237 | cdef int err = api_readMemory(adr_arg, &bytes, 1) 238 | return None if err else int(bytes[0]) 239 | 240 | def read_u16(self, adr_arg): 241 | cdef unsigned char * bytes 242 | cdef int err = api_readMemory(adr_arg, &bytes, 2) 243 | return None if err else int.from_bytes(bytes[0:2], byteorder='little', signed=False) 244 | 245 | def read_u32(self, adr_arg): 246 | cdef unsigned char * bytes 247 | cdef int err = api_readMemory(adr_arg, &bytes, 4) 248 | return None if err else int.from_bytes(bytes[0:4], byteorder='little', signed=False) 249 | 250 | def write_u8(self, adr_arg, val_arg: int): 251 | cdef unsigned char[4] bytes = int.to_bytes(val_arg, length=4, byteorder='little', signed=False) 252 | # cast required because writeMemory takes a char which is inconsistent with readMemory that takes unsigned char. 253 | cdef int err = api_writeMemory(adr_arg, &bytes[0], 1) 254 | 255 | def write_u16(self, adr_arg, val_arg: int): 256 | cdef unsigned char[4] bytes = int.to_bytes(val_arg, length=4, byteorder='little', signed=False) 257 | # cast required because writeMemory takes a char which is inconsistent with readMemory that takes unsigned char. 258 | cdef int err = api_writeMemory(adr_arg, &bytes[0], 2) 259 | 260 | def write_u32(self, adr_arg, val_arg): 261 | cdef unsigned char[4] bytes = int.to_bytes(val_arg, length=4, byteorder='little', signed=False) 262 | cdef int err = api_writeMemory(adr_arg, &bytes[0], 4) 263 | 264 | def read_str(self, adr_arg, char_qty): 265 | cdef unsigned char * bytes 266 | cdef int err = api_readMemory(adr_arg, &bytes, char_qty) 267 | return None if err else bytes.decode('iso-8859-1') # 'utf-8') 268 | 269 | def read_f32(self, adr_arg): 270 | """ 271 | Read float, single-precision, 4-bytes. 272 | """ 273 | cdef unsigned char * bytes 274 | cdef int err = api_readMemory(adr_arg, &bytes, 4) 275 | return None if err else struct.unpack('py_cb_InitProgressBar)() 283 | else: 284 | str = f'InitProgressBar' 285 | size = len(str) 286 | c_cb_LogMessage(4, PyUnicode_AsWideCharString(str, &size)) 287 | 288 | # C variant of LogMessage will call the Python variant if it's been set. 289 | @staticmethod 290 | cdef void c_cb_LogMessage(int msgType, const wchar_t* str): 291 | s = PyUnicode_FromWideChar(str, -1) # https://stackoverflow.com/a/16526775/101252 292 | global py_cb_LogMessage 293 | if py_cb_LogMessage is not None: 294 | (py_cb_LogMessage)(msgType, s) 295 | else: 296 | global default_log_message_verbosity 297 | if default_log_message_verbosity > msgType: 298 | print(f'msgType: {msgType}, {s}') 299 | 300 | @staticmethod 301 | cdef void c_cb_LoadBar(int x, int n): 302 | global py_cb_LoadBar 303 | if py_cb_LoadBar is not None: 304 | (py_cb_LoadBar)(x, n) 305 | else: 306 | str = f'lBar, x: {x}, n: {n} {(x * 100) / n:.2f}%' 307 | size = len(str) 308 | c_cb_LogMessage(4, PyUnicode_AsWideCharString(str, &size)) 309 | 310 | 311 | # Globals 312 | cdef displayCallBacks display_cb_struct = displayCallBacks(logMessage = c_cb_LogMessage, initProgressBar = c_cb_InitProgressBar, loadBar = c_cb_LoadBar) 313 | cdef debugConnectParameters * stLinkList = 0 314 | cdef object py_cb_InitProgressBar = None 315 | cdef object py_cb_LogMessage = None 316 | cdef object py_cb_LoadBar = None 317 | cdef int default_log_message_verbosity = 3 318 | 319 | 320 | 321 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /api/include/CubeProgrammer_API.h: -------------------------------------------------------------------------------- 1 | 2 | /******************************************************************************* 3 | * 4 | * Copyright (C) 2021 STMicroelectronics - All rights reserved 5 | * 6 | * This file is part of STM32CubeProgrammer project. 7 | * 8 | * Unauthorized copying of this file, via any medium is strictly prohibited 9 | * Proprietary and confidential 10 | * 11 | ******************************************************************************/ 12 | /* doxygen documentation */ 13 | /*! 14 | * \file CubeProgrammer_API.h 15 | * \mainpage STM32CubeProgrammer API Documentation 16 | * \section intro1 Introduction 17 | * In addition to the graphical user interface and the commandline interface, STM32CubeProgrammer offers a C++ API 18 | * that you could use to develop your own application and benefit of wide range 19 | * of features to program STM32 microcontrollers memories (such as Flash, RAM, and OTP) 20 | * either over debug interface or bootloder interface (USB DFU, UART, I²C, SPI and CAN). 21 | * 22 | * This documentation details all types and functions API to use STM32CubeProgrammer functionalities. \n 23 | * 24 | * \section include STM32CubeProgrammer API package 25 | * The API package is based on the following resources that are ready for use : \n 26 | * 27 | * File Description 28 | * CubeProgrammer_API.h header file contains functions declarations and macro definitions to be used by the CubeProgrammer_API.dll. 29 | * DeviceDataStructure.h header file contains macro definitions to be shared between several functions. 30 | * CubeProgrammer_API.dll/.so/.dylib Dynamic Link Library file contains a library of functions and other informations that can be accessed by windows, linux and MacOs programs. 31 | * CubeProgrammer_API.lib import library for use with MSVC compiler. 32 | * 33 | * 34 | * \section app Application System requirements 35 | * We offer various examples developed for use with Visual Studio and Qt Creator IDEs: 36 | * - Visual Studio project for windows applications under MSVC compiler. 37 | * - Qt project for Windows, Linux and MacOs applications under MinGW compiler. 38 | * \note The attached examples are tested on STM32F429, STM32L4R9 and STM32L452RE Nucleo Boards. 39 | * 40 | * \subsection windows Windows build settings 41 | * To ensure the correct environment for the provided examples, some constraints must be taken into account\n 42 | * 43 | * \subsubsection vs Visual studio 44 | * The code was developed with Microsoft Visual Studio Community 2017 version 15.6.6 with Windows SDK version : 10.0.16299.0 45 | * and it was tested also on Microsoft Visual Studio 2010 \n 46 | * - Verify that the api's lib directory is the default working directory. 47 | * - The debug command is to execute the application that is resided in the output directory. 48 | * - Insert the Additional Include Directories:\n 49 | * 50 | * \image html link1.jpg \n 51 | * 52 | * - Indicate the output name and path. \n 53 | * - Insert the Additional Library Directories. \n 54 | * - Insert the Additional Dependencies, The CubeProgrammer_API import library "CubeProgrammer_API.lib" must be added to Linker input\n 55 | * 56 | * \image html link2.jpg \n 57 | * 58 | * \note The provided Visual studio project is already configured like the description above and you can change it carefully according to your use case. 59 | * \subsubsection qt Qt creator 60 | * The Qt projects are developed with Qt Creator 4.7.1, Qt 5.11.2 and MinGW 32 bit compiler and also it can be compiled by MinGW x64.\n 61 | * The shadow build option must be disable to inform Qt that the build should be located in the original Qt project directory. 62 | * \note Verify that the following DLLs are placed to /lib in the api package directory : 63 | * 64 | * CubeProgrammer_API.dll FileManager.dll STLinkUSBDriver.dll 65 | * HSM_P11_Lib.dll libeay32.dll libgcc_s_dw2-1.dll 66 | * stlibp11_SAM.dll libstdc++-6.dll libwinpthread-1.dll 67 | * mfc120.dll msvcp120.dll msvcr120.dll 68 | * Qt5Core.dll Qt5SerialPort.dll Qt5Xml.dll 69 | * 70 | * 71 | * \subsection qtlinux Linux build settings 72 | * To correctly build the Qt project in linux platform, you should follow the next 3 steps: 73 | * 1. Select the build configuration in Projects field of the main view. \n 74 | * 2. Disable the Shadow build option. \n 75 | * 3. Go to build environment, add the System Environment variable LD_LIBRARY_PATH and set the path to ../../../../lib \n 76 | * 77 | * \image html LdLibraryPath.png \n 78 | * 79 | * * \note Verify that the following Shared Objects are placed to /lib in the STM32CubeProgrammer package directory : 80 | * 81 | * libCubeProgrammer_API.so libCubeProgrammer_API.so.1 libSTLinkUSBDriver.so libFileManager.so.1 82 | * libhsmp11.so libQt5SerialPort.so.5 libQtXml.so.5 libQt5Core.so.5 83 | * libicudata.so.56 libicui18n.so.56 libicuuc.so.56 - 84 | * 85 | * 86 | * \subsection qtMacOS MacOS buiild settings 87 | * To get the default api folder that is integrated into the STM32CubeProgrammer package already installed, go to \n 88 | * /Application/STMicroelectronics/STM32Cube/STM32CubeProgrammer/STM32CubeProgrammer.app/contents/MacOs/api 89 | * \note Verify that the following Mach Objects are placed to /Application/STMicroelectronics/STM32Cube/STM32CubeProgrammer/STM32CubeProgrammer.app/contents/MacOs/bin in the STM32CubeProgrammer package directory: 90 | * 91 | * libCubeProgrammer_API.dylib libCubeProgrammer_API.1.dylib libCubeProgrammer_API.1.0.dylib libCubeProgrammer_API.1.0.0.dylib 92 | * libFileManager.dylib libFileManager.1.dylib libFileManager.1.0.dylib libFileManager.1.0.0.dylib 93 | * libSTLinkUSBDriver.dylib libhsmp11.dylib libstP11_SAM.dylib libusb-1.0.0.dylib 94 | * QtSerialPort.framework QtXml.framework QtCore.framework - 95 | * 96 | */ 97 | 98 | 99 | #ifndef CUBEPROGRAMMER_API_H 100 | #define CUBEPROGRAMMER_API_H 101 | 102 | #ifdef __cplusplus 103 | extern "C" { 104 | #endif 105 | 106 | #include 107 | #include "DeviceDataStructure.h" 108 | 109 | #if (defined WIN32 || defined _WIN32 || defined WINCE) 110 | # define CP_EXPORTS __declspec(dllexport) 111 | #else 112 | # define CP_EXPORTS 113 | #endif 114 | 115 | 116 | /* -------------------------------------------------------------------------------------------- */ 117 | /* Errors Enumerations */ 118 | /* -------------------------------------------------------------------------------------------- */ 119 | 120 | /** 121 | * \enum cubeProgrammerVerbosityLevel 122 | * \brief List of verbosity levels. 123 | */ 124 | enum cubeProgrammerVerbosityLevel { 125 | /** no messages ever printed by the library */ 126 | CUBEPROGRAMMER_VER_LEVEL_NONE = 0, 127 | 128 | /** warning, error and success messages are printed (default) */ 129 | CUBEPROGRAMMER_VER_LEVEL_ONE = 1, 130 | 131 | /** error roots informational messages are printed */ 132 | CUBEPROGRAMMER_VER_LEVEL_TWO = 2, 133 | 134 | /** debug and informational messages are printed */ 135 | CUBEPROGRAMMER_VER_LEVEL_DEBUG = 3, 136 | 137 | /** no progress bar is printed in the output of the library */ 138 | CUBEPROGRAMMER_NO_PROGRESS_BAR = 4, /* progress bars are printed only with verbosity level one */ 139 | }; 140 | 141 | 142 | /** 143 | * \enum cubeProgrammerError 144 | * \brief List of errors that can be occured. 145 | */ 146 | enum cubeProgrammerError { 147 | /** Success (no error) */ 148 | CUBEPROGRAMMER_NO_ERROR = 0, 149 | 150 | /** Device not connected */ 151 | CUBEPROGRAMMER_ERROR_NOT_CONNECTED = -1, 152 | 153 | /** Device not found */ 154 | CUBEPROGRAMMER_ERROR_NO_DEVICE = -2, 155 | 156 | /** Device connection error */ 157 | CUBEPROGRAMMER_ERROR_CONNECTION = -3, 158 | 159 | /** No such file */ 160 | CUBEPROGRAMMER_ERROR_NO_FILE = -4, 161 | 162 | /** Operation not supported or unimplemented on this interface */ 163 | CUBEPROGRAMMER_ERROR_NOT_SUPPORTED = -5, 164 | 165 | /** Interface not supported or unimplemented on this plateform */ 166 | CUBEPROGRAMMER_ERROR_INTERFACE_NOT_SUPPORTED = -6, 167 | 168 | /** Insufficient memory */ 169 | CUBEPROGRAMMER_ERROR_NO_MEM = -7, 170 | 171 | /** Wrong parameters */ 172 | CUBEPROGRAMMER_ERROR_WRONG_PARAM = -8, 173 | 174 | /** Memory read failure */ 175 | CUBEPROGRAMMER_ERROR_READ_MEM = -9, 176 | 177 | /** Memory write failure */ 178 | CUBEPROGRAMMER_ERROR_WRITE_MEM = -10, 179 | 180 | /** Memory erase failure */ 181 | CUBEPROGRAMMER_ERROR_ERASE_MEM = -11, 182 | 183 | /** File format not supported for this kind of device */ 184 | CUBEPROGRAMMER_ERROR_UNSUPPORTED_FILE_FORMAT = -12, 185 | 186 | /** Refresh required **/ 187 | CUBEPROGRAMMER_ERROR_REFRESH_REQUIRED = -13, 188 | 189 | /** Refresh required **/ 190 | CUBEPROGRAMMER_ERROR_NO_SECURITY = -14, 191 | 192 | /** Changing frequency problem **/ 193 | CUBEPROGRAMMER_ERROR_CHANGE_FREQ = -15, 194 | 195 | /** RDP Enabled error **/ 196 | CUBEPROGRAMMER_ERROR_RDP_ENABLED = -16, 197 | 198 | /* NB: Remember to update CUBEPROGRAMMER_ERROR_COUNT below. */ 199 | 200 | /** Other error */ 201 | CUBEPROGRAMMER_ERROR_OTHER = -99, 202 | }; 203 | 204 | /* -------------------------------------------------------------------------------------------- */ 205 | /* Flash Size Structures and Enumerations */ 206 | /* -------------------------------------------------------------------------------------------- */ 207 | 208 | enum flashSize { 209 | Flash_Size_1KB = (1024), 210 | Flash_Size_512KB = (512*1024), 211 | Flash_Size_256KB = (256*1024), 212 | 213 | }; 214 | 215 | /* -------------------------------------------------------------------------------------------- */ 216 | /* STM32WB Structures and Enumerations */ 217 | /* -------------------------------------------------------------------------------------------- */ 218 | 219 | enum wbFunctionArguments { 220 | FIRST_INSTALL_ACTIVE = 1, 221 | FIRST_INSTALL_NOT_ACTIVE = 0, 222 | START_STACK_ACTIVE=1, 223 | START_STACK_NOT_ACTIVE=1, 224 | VERIFY_FILE_DOWLOAD_FILE=1, 225 | DO_NOT_VERIFY_DOWLOAD_FILE=0, 226 | }; 227 | 228 | /* -------------------------------------------------------------------------------------------- */ 229 | /* Bootloader Data Structures and Enumerations */ 230 | /* -------------------------------------------------------------------------------------------- */ 231 | 232 | /** 233 | * \enum usartParity 234 | * \brief The parity bit in the data frame of the USART communication tells the receiving device if there is any error in the data bits. 235 | */ 236 | typedef enum usartParity 237 | { 238 | EVEN = 0, /**< Even parity bit. */ 239 | ODD = 1, /**< Odd parity bit. */ 240 | NONE = 2, /**< No check parity. */ 241 | }usartParity; 242 | 243 | 244 | /** 245 | * \enum usartFlowControl 246 | * \brief UART Flow Control is a method for devices to communicate with each other over UART without the risk of losing data. 247 | */ 248 | typedef enum usartFlowControl 249 | { 250 | OFF = 0, /**< No flow control. */ 251 | HARDWARE = 1, /**< Hardware flow control : RTS/CTS. */ 252 | SOFTWARE = 2, /**< Software flow control : Transmission is started and stopped by sending special characters. */ 253 | }usartFlowControl; 254 | 255 | 256 | /** 257 | * \struct dfuDeviceInfo 258 | * \brief Get DFU device informations . 259 | */ 260 | typedef struct dfuDeviceInfo 261 | { 262 | char usbIndex[10]; /**< USB index. */ 263 | int busNumber; /**< Bus number. */ 264 | int addressNumber; /**< Address number. */ 265 | char productId[100]; /**< Product number. */ 266 | char serialNumber[100]; /**< Serial number. */ 267 | unsigned int dfuVersion; /**< DFU version. */ 268 | }dfuDeviceInfo; 269 | 270 | /** 271 | * \struct usartConnectParameters 272 | * \brief Specify the USART connect parameters. 273 | */ 274 | typedef struct usartConnectParameters 275 | { 276 | char portName[100]; /**< Interface identifier: COM1, COM2, /dev/ttyS0...*/ 277 | unsigned int baudrate; /**< Speed transmission: 115200, 9600... */ 278 | usartParity parity; /**< Parity bit: value in usartParity. */ 279 | unsigned char dataBits; /**< Data bit: value in {6, 7, 8}. */ 280 | float stopBits; /**< Stop bit: value in {1, 1.5, 2}. */ 281 | usartFlowControl flowControl; /**< Flow control: value in usartFlowControl. */ 282 | int statusRTS; /**< RTS: Value in {0,1}. */ 283 | int statusDTR; /**< DTR: Value in {0,1}. */ 284 | unsigned char noinitBits; /**< Set No Init bits: value in {0,1}. */ 285 | char rdu; /**< request a read unprotect: value in {0,1}.*/ 286 | }usartConnectParameters; 287 | 288 | /** 289 | * \struct dfuConnectParameters 290 | * \brief Specify the USB DFU connect parameters. 291 | */ 292 | typedef struct dfuConnectParameters 293 | { 294 | char *usb_index; 295 | char rdu; /**< request a read unprotect: value in {0,1}.*/ 296 | }dfuConnectParameters; 297 | 298 | 299 | /** 300 | * \struct spiConnectParameters 301 | * \brief Specify the SPI connect parameters. 302 | * \note Recommended SPI parameters : baudrate=375, crcPol=7, direction=0, cpha=0, cpol=0, crc=0, firstBit=1, frameFormat=0, dataSize=1, mode=1, nss=1, nssPulse=1, delay=1 303 | */ 304 | typedef struct spiConnectParameters 305 | { 306 | uint32_t baudrate ; /**< Speed transmission 187, 375, 750, 1500, 3000, 6000, 12000 KHz. */ 307 | uint16_t crcPol ; /**< crc polynom value. */ 308 | int direction ; /**< 2LFullDuplex/2LRxOnly/1LRx/1LTx. */ 309 | int cpha ; /**< 1Edge or 2Edge. */ 310 | int cpol ; /**< LOW or HIGH. */ 311 | int crc ; /**< DISABLE or ENABLE. */ 312 | int firstBit ; /**< First bit: LSB or MSB. */ 313 | int frameFormat ; /**< Frame format: Motorola or TI. */ 314 | int dataSize ; /**< Size of frame data: 16bit or 8bit . */ 315 | int mode ; /**< Operating mode: Slave or Master. */ 316 | int nss ; /**< Selection: Soft or Hard. */ 317 | int nssPulse ; /**< NSS pulse: No Pulse or Pulse. */ 318 | int delay ; /**< Delay of few microseconds, No Delay or Delay, at least 4us delay is inserted */ 319 | 320 | } spiConnectParameters; 321 | 322 | 323 | /** 324 | * \struct canConnectParameters 325 | * \brief Specify the CAN connect parameters. 326 | * \note Not all configurations are supported by STM32 Bootloader, such as CAN type is STANDARD and the filter should be always activated. 327 | * \note Recommended CAN parameters : br=125000, mode=0, ide=0, rtr=0, fifo=0, fm=0, fs=1, fe=1, fbn=0 328 | */ 329 | typedef struct canConnectParameters 330 | { 331 | int br ; /**< Baudrate and speed transmission 125KHz, 250KHz, 500KHz... */ 332 | int mode ; /**< CAN mode: NORMAL, LOOPBACK..., */ 333 | int ide ; /**< CAN type: STANDARD or EXTENDED. */ 334 | int rtr ; /**< Frame format: DATA or REMOTE. */ 335 | int fifo ; /**< Memory of received messages: FIFO0 or FIFO1. */ 336 | int fm ; /**< Filter mode: MASK or LIST. */ 337 | int fs ; /**< Filter scale: 16 or 32. */ 338 | int fe ; /**< Filter activation: DISABLE or ENABLE. */ 339 | char fbn ; /**< Filter bank number: 0 to 13. */ 340 | 341 | } canConnectParameters; 342 | 343 | 344 | /** 345 | * \struct i2cConnectParameters 346 | * \brief Specify the I2C connect parameters. 347 | * \warning The Bootloader Slave address varies depending on the device (see AN2606). 348 | * \note Not all configurations are supported by STM32 Bootloader, such as address in 7 bits form, analog filter: ENABLE, digital filter: DISABLE. 349 | * \note Recommended I2C parameters : add=0x??, br=400, sm=1, am=0, af=1, df=0, dnf=0, rt=0, ft=0 350 | */ 351 | typedef struct i2cConnectParameters 352 | { 353 | int add ; /**< Device address in hex format. */ 354 | int br ; /**< Baudrate and speed transmission : 100 or 400 KHz. */ 355 | int sm ; /**< Speed Mode: STANDARD or FAST. */ 356 | int am ; /**< Address Mode: 7 or 10 bits. */ 357 | int af ; /**< Analog filter: DISABLE or ENABLE. */ 358 | int df ; /**< Digital filter: DISABLE or ENABLE. */ 359 | char dnf ; /**< Digital noise filter: 0 to 15. */ 360 | int rt ; /**< Rise time: 0-1000 for STANDARD speed mode and 0-300 for FAST. */ 361 | int ft ; /**< Fall time: 0-300 for STANDARD speed mode and 0-300 for FAST. */ 362 | 363 | } i2cConnectParameters; 364 | 365 | 366 | /* -------------------------------------------------------------------------------------------- */ 367 | /* STLINK Data Structures and Enumerations */ 368 | /* -------------------------------------------------------------------------------------------- */ 369 | 370 | /** 371 | * \enum debugResetMode 372 | * \brief Choose the way to apply a system reset. 373 | */ 374 | typedef enum debugResetMode 375 | { 376 | SOFTWARE_RESET, /**< Apply a reset by the software. */ 377 | HARDWARE_RESET, /**< Apply a reset by the hardware. */ 378 | CORE_RESET /**< Apply a reset by the internal core peripheral. */ 379 | }debugResetMode; 380 | 381 | 382 | /** 383 | * \enum debugConnectMode 384 | * \brief Choose the appropriate mode for connection. 385 | */ 386 | typedef enum debugConnectMode 387 | { 388 | NORMAL_MODE, /**< Connect with normal mode, the target is reset then halted while the type of reset is selected using the [debugResetMode]. */ 389 | HOTPLUG_MODE, /**< Connect with hotplug mode, this option allows the user to connect to the target without halt or reset. */ 390 | UNDER_RESET_MODE, /**< Connect with under reset mode, option allows the user to connect to the target using a reset vector catch before executing any instruction. */ 391 | POWER_DOWN_MODE, /**< Connect with power down mode. */ 392 | PRE_RESET_MODE /**< Connect with pre reset mode. */ 393 | }debugConnectMode; 394 | 395 | 396 | /** 397 | * \enum debugPort 398 | * \brief Select the debug port interface for connection. 399 | */ 400 | typedef enum debugPort 401 | { 402 | JTAG = 0, /**< JTAG debug port. */ 403 | SWD = 1, /**< SWD debug port. */ 404 | }debugPort; 405 | 406 | 407 | /** 408 | * \struct frequencies 409 | * \brief Get supported frequencies for JTAG and SWD ineterfaces. 410 | */ 411 | typedef struct frequencies 412 | { 413 | unsigned int jtagFreq[12]; /**< JTAG frequency. */ 414 | unsigned int jtagFreqNumber; /**< Get JTAG supported frequencies. */ 415 | unsigned int swdFreq[12]; /**< SWD frequency. */ 416 | unsigned int swdFreqNumber; /**< Get SWD supported frequencies. */ 417 | }frequencies; 418 | 419 | 420 | /** 421 | * \struct debugConnectParameters 422 | * \brief Get device characterization and specify connection parameters through ST-LINK interface. 423 | */ 424 | typedef struct debugConnectParameters 425 | { 426 | debugPort dbgPort; /**< Select the type of debug interface #debugPort. */ 427 | int index; /**< Select one of the debug ports connected. */ 428 | char serialNumber[33]; /**< ST-LINK serial number. */ 429 | char firmwareVersion[20]; /**< Firmware version. */ 430 | char targetVoltage[5]; /**< Operate voltage. */ 431 | int accessPortNumber; /**< Number of available access port. */ 432 | int accessPort; /**< Select access port controller. */ 433 | debugConnectMode connectionMode; /**< Select the debug CONNECT mode #debugConnectMode. */ 434 | debugResetMode resetMode; /**< Select the debug RESET mode #debugResetMode. */ 435 | int isOldFirmware; /**< Check Old ST-LINK firmware version. */ 436 | frequencies freq; /**< Supported frequencies #frequencies. */ 437 | int frequency; /**< Select specific frequency. */ 438 | int isBridge; /**< Indicates if it's Bridge device or not. */ 439 | int shared; /**< Select connection type, if it's shared, use ST-LINK Server. */ 440 | char board[100]; /**< board Name */ 441 | int DBG_Sleep ; 442 | }debugConnectParameters; 443 | 444 | 445 | /* -------------------------------------------------------------------------------------------- */ 446 | /* General Data Structures and Enumerations */ 447 | /* -------------------------------------------------------------------------------------------- */ 448 | 449 | /** 450 | * \enum targetInterfaceType 451 | * \brief Indicates the supported interfaces. 452 | */ 453 | typedef enum targetInterfaceType 454 | { 455 | STLINK_INTERFACE = 0, /**< STLINK used as connection interface. */ 456 | USART_INTERFACE = 1, /**< USART used as connection interface. */ 457 | USB_INTERFACE = 2, /**< USB DFU used as connection interface. */ 458 | SPI_INTERFACE = 3, /**< SPI used as connection interface. */ 459 | I2C_INTERFACE = 4, /**< I2C used as connection interface. */ 460 | CAN_INTERFACE = 5 /**< CAN used as connection interface. */ 461 | }targetInterfaceType; 462 | 463 | 464 | /** 465 | * \struct displayCallBacks 466 | * \brief Functions must be implemented to personalize the display of messages. 467 | */ 468 | typedef struct displayCallBacks 469 | { 470 | void (*initProgressBar)(); /**< Add a progress bar. */ 471 | void (*logMessage)(int msgType, const wchar_t* str); /**< Display internal messages according to verbosity level. */ 472 | void (*loadBar)(int x, int n); /**< Display the loading of read/write process. */ 473 | } displayCallBacks; 474 | 475 | 476 | typedef struct segmentData_C 477 | { 478 | int address; /**< Segment start address. */ 479 | int size; /**< Memory segment size. */ 480 | unsigned char* data; /**< Memory segment data. */ 481 | }segmentData_C ; 482 | 483 | 484 | /** 485 | * \struct FileData_C 486 | * \brief Get file required informations. 487 | */ 488 | typedef struct fileData_C 489 | { 490 | int Type; /**< File extension type. */ 491 | int segmentsNbr; /**< Number of required segments. */ 492 | segmentData_C* segments; /**< Segments description. */ 493 | }fileData_C ; 494 | 495 | 496 | /** 497 | * \struct GeneralInf 498 | * \brief Get device general informations. 499 | */ 500 | typedef struct generalInf 501 | { 502 | unsigned short deviceId; /**< Device ID. */ 503 | int flashSize; /**< Flash memory size. */ 504 | int bootloaderVersion; /**< Bootloader version */ 505 | char type[4]; /**< Device MCU or MPU. */ 506 | char cpu[20]; /**< Cortex CPU. */ 507 | char name[100]; /**< Device name. */ 508 | char series[100]; /**< Device serie. */ 509 | char description[150]; /**< Take notice. */ 510 | char revisionId[100]; /**< Revision ID. */ 511 | char board[100]; /**< Board Rpn. */ 512 | }generalInf ; 513 | 514 | 515 | /* -------------------------------------------------------------------------------------------- */ 516 | /* Loaders Data Structures */ 517 | /* -------------------------------------------------------------------------------------------- */ 518 | 519 | 520 | /** 521 | * \struct deviceSector 522 | * \brief Get device sectors basic informations. 523 | */ 524 | typedef struct deviceSector 525 | { 526 | uint32_t sectorNum; /**< Number of Sectors. */ 527 | uint32_t sectorSize; /**< Sector Size in BYTEs. */ 528 | }deviceSector; 529 | 530 | 531 | /** 532 | * \struct externalLoader 533 | * \brief Get external Loader parameters to launch the process of programming an external flash memory. 534 | */ 535 | typedef struct externalLoader{ 536 | char filePath[200]; /**< FlashLoader file path. */ 537 | char deviceName[100]; /**< Device Name and Description. */ 538 | int deviceType; /**< Device Type: ONCHIP, EXT8BIT, EXT16BIT, ... */ 539 | uint32_t deviceStartAddress; /**< Default Device Start Address. */ 540 | uint32_t deviceSize; /**< Total Size of Device. */ 541 | uint32_t pageSize; /**< Programming Page Size. */ 542 | // unsigned char EraseValue; /**< Content of Erased Memory. */ 543 | uint32_t sectorsTypeNbr; /**< Type number. */ 544 | deviceSector* sectors; /**< Device sectors. */ 545 | }externalLoader; 546 | 547 | 548 | /** 549 | * \struct externalStorageInfo 550 | * \brief Get external storage informations useful for external Loader. 551 | */ 552 | typedef struct externalStorageInfo 553 | { 554 | unsigned int externalLoaderNbr; 555 | externalLoader* externalLoader; 556 | }externalStorageInfo; 557 | 558 | 559 | /* -------------------------------------------------------------------------------------------- */ 560 | /* STLINK functions */ 561 | /* -------------------------------------------------------------------------------------------- */ 562 | 563 | /*! \addtogroup STLINK 564 | * STLINK module groups debug ports JTAG/SWD functions together. 565 | * @{ 566 | */ 567 | 568 | /** 569 | * \brief This routine allows to get ST-LINK conneted probe(s). 570 | * \param stLinkList : Filled with the connected ST-LINK list and its default configurations. 571 | * \param shared : Enable shared mode allowing connection of two or more instances to the same ST-LINK probe. 572 | * \return Number of the ST-LINK probes already exists. 573 | * \warning The Share option is useful only with ST-LINK Server. 574 | * \note At the end of usage, #deleteInterfaceList must have been called. 575 | */ 576 | int getStLinkList(debugConnectParameters** stLinkList, int shared); 577 | 578 | 579 | /** 580 | * \brief This routine allows to start connection to device through SWD or JTAG interfaces. 581 | * \param debugParameters : Indicates customized configuration for ST-LINK connection, 582 | * It is recommended to check [debugConnectParameters] fields before connection. 583 | * \return 0 if the connection successfully established, otherwise an error occurred. 584 | */ 585 | int connectStLink(debugConnectParameters debugParameters); 586 | 587 | 588 | /** 589 | * \brief This routine used to apply a target reset. 590 | * \note Reset operation is only available with JTAG/SWD debug interface. 591 | * \param rstMode : Indicates the reset type Soft/Hard/Core #debugResetMode. \n 592 | * \return 0 if the reset operation finished successfully, otherwise an error occurred. 593 | */ 594 | int reset(debugResetMode rstMode) ; 595 | 596 | /*! @} */ 597 | 598 | 599 | /* -------------------------------------------------------------------------------------------- */ 600 | /* Bootloader functions */ 601 | /* -------------------------------------------------------------------------------------------- */ 602 | 603 | /*! \addtogroup Bootloader 604 | * Bootloader module is a way to group Serial interfaces USB/UART/SPI/I2C/CAN functions together. 605 | * @{ 606 | */ 607 | 608 | /** 609 | * \brief This routine allows to get connected serial ports. 610 | * \param usartList : Receive serial ports list and its default configurations. 611 | * \return Number of serial ports already connected. 612 | * \note At the end of usage, #deleteInterfaceList must have been called. 613 | */ 614 | int getUsartList(usartConnectParameters** usartList); 615 | 616 | 617 | /** 618 | * \brief This routine allows to start connection to device through USART interface. 619 | * \param usartParameters : Indicates customized configuration for USART connection. 620 | * \return 0 if the connection successfully established, otherwise an error occurred. 621 | */ 622 | int connectUsartBootloader(usartConnectParameters usartParameters); 623 | 624 | 625 | /** 626 | * \brief This routine allows to send a single byte through the USART interface. 627 | * \param byte : The data to be written 628 | * \return 0 if the sending operation correctly achieved, otherwise an error occurred. 629 | */ 630 | int sendByteUart(int byte); 631 | 632 | 633 | /** 634 | * \brief This routine allows to get connected DFU devices. 635 | * \param dfuList : Receive DFU devices list and its default configurations. 636 | * \param iPID : Indicate the Product ID to be used for DFU interface. 637 | * \param iVID : Indicate the Vendor ID to be used for DFU interface. 638 | * \return Number of DFU devices already connected. 639 | * \note At the end of usage, #deleteInterfaceList must have been called. 640 | */ 641 | int getDfuDeviceList(dfuDeviceInfo** dfuList,int iPID, int iVID); 642 | 643 | 644 | /** 645 | * \brief This routine allows to start a simple connection through USB DFU interface. 646 | * \param usbIndex : Indicates the index of DFU ports already connected. 647 | * \return 0 if the connection successfully established, otherwise an error occurred. 648 | */ 649 | int connectDfuBootloader(char* usbIndex); 650 | 651 | /** 652 | * \brief This routine allows to start connection to device through USB DFU interface. 653 | * \param dfuConnectParameters : Indicates the dfu connection parameters 654 | * \return 0 if the connection successfully established, otherwise an error occurred. 655 | * \note It's recommanded to use this routine to disable readout protection when connecting a MCU based device. 656 | */ 657 | int connectDfuBootloader2(dfuConnectParameters dfuParameters); 658 | 659 | /** 660 | * \brief This routine allows to start connection to device through SPI interface. 661 | * \param spiParameters : Indicates customized configuration for SPI connection 662 | * \return 0 if the connection successfully established, otherwise an error occurred. 663 | */ 664 | int connectSpiBootloader(spiConnectParameters spiParameters); 665 | 666 | 667 | /** 668 | * \brief This routine allows to start connection to device through CAN interface. 669 | * \param canParameters : Indicates customized configuration for CAN connection 670 | * \return 0 if the connection successfully established, otherwise an error occurred. 671 | * \warning To have CAN full support, you must have St-Link firmware version at least v3JxMxB2. 672 | */ 673 | int connectCanBootloader(canConnectParameters canParameters); 674 | 675 | 676 | /** 677 | * \brief This routine allows to start connection to device through I2C interface. 678 | * \param i2cParameters : Indicates customized configuration for I2C connection 679 | * \return 0 if the connection successfully established, otherwise an error occurred. 680 | */ 681 | int connectI2cBootloader(i2cConnectParameters i2cParameters); 682 | 683 | /*! @} */ 684 | 685 | 686 | /* -------------------------------------------------------------------------------------------- */ 687 | /* General purposes functions */ 688 | /* -------------------------------------------------------------------------------------------- */ 689 | 690 | /*! \addtogroup General 691 | * General module groups general purposes functions used by any interface. 692 | * @{ 693 | */ 694 | 695 | /** 696 | * \brief This routine allows to choose your custom display. 697 | * \param c : Fill the struct to customize the display tool. 698 | * \note This function must be called first of all to ensure the display management. 699 | */ 700 | void setDisplayCallbacks(displayCallBacks c); 701 | 702 | 703 | /** 704 | * \brief This routine allows to choose the verbosity level for display. 705 | * \param level : Indicates the verbosity number 0, 1 or 3. 706 | */ 707 | void setVerbosityLevel(int level); 708 | 709 | 710 | /** 711 | * \brief This routine allows to check connection status [maintained or lost]. 712 | * \return 1 if the device is already connected, otherwise the connection to device is lost. 713 | */ 714 | int checkDeviceConnection(); 715 | 716 | 717 | /** 718 | * \brief This routine allows to get general device informations. 719 | * \return Structure #GeneralInf in which the informations are stored. 720 | */ 721 | generalInf* getDeviceGeneralInf(); 722 | 723 | 724 | /** 725 | * \brief This routine allows to receive memory data on the used interface with the configration already initialized. 726 | * \param address : The address to start reading from. 727 | * \param data : Pointer to the data buffer. 728 | * \param size : It indicates the size for read data. 729 | * \return 0 if the reading operation correctly finished, otherwise an error occurred. 730 | * \warning Unlike ST-LINK interface, the Bootloader interface can access only to some specific memory regions. 731 | */ 732 | int readMemory(unsigned int address, unsigned char** data, unsigned int size); 733 | 734 | 735 | /** 736 | * \brief This routine allows to write memory data on the user interface with the configration already initialized. 737 | * \param address : The address to start writing from. 738 | * \param data : Pointer to the data buffer. 739 | * \param size : It indicates the size for write data. 740 | * \return 0 if the writing operation correctly finished, otherwise an error occurred. 741 | * \warning Unlike ST-LINK interface, the Bootloader interface can access only to some specific memory regions. 742 | */ 743 | int writeMemory(unsigned int address, char* data, unsigned int size); 744 | 745 | 746 | /** 747 | * \brief This routine allows to download data from a file to the memory. 748 | * File formats that are supported : hex, bin, srec, tsv, elf, axf, out, stm32, ext 749 | * \param filePath : Indicates the full path of the considered file. 750 | * \param address : The address to start downloading from. 751 | * \param skipErase : In case to win in term time and if we have a blank device, we can skip erasing memory before programming [skipErase=0]. 752 | * \param verify : To add verification step after downloading. 753 | * \param binPath : Path of the binary file. 754 | * \return 0 if the downloading operation correctly finished, otherwise an error occurred. 755 | */ 756 | int downloadFile(const wchar_t* filePath, unsigned int address, unsigned int skipErase, unsigned int verify, const wchar_t* binPath); 757 | 758 | 759 | /** 760 | * \brief This routine allows to run the application. 761 | * \param address : The address to start executing from. 762 | * In most cases, the program will run from the Flash memory starting from 0x08000000. 763 | * \return 0 if the execution correctly started, otherwise an error occurred. 764 | */ 765 | int execute(unsigned int address); 766 | 767 | 768 | /*! 769 | * \brief This routine allows to erase the whole Flash memory. 770 | * \return 0 if the operation finished successfully, otherwise an error was occurred. 771 | * \note Depending on the device, this routine can take a particular period of time. 772 | */ 773 | int massErase(char* sFlashMemName = nullptr); 774 | 775 | 776 | /** 777 | * \brief This routine allows to erase specific sectors of the Flash memory. 778 | * \param sectors : Indicates the indexs of the specific sectors to be erased. 779 | * \param sectorNbr : The number of chosen sectors. 780 | * \return 0 if the operation finished successfully, otherwise an error occurred. 781 | * \note Each circuit has a specific number of Flash memory sectors. 782 | */ 783 | int sectorErase(unsigned int sectors[],unsigned int sectorNbr, char* sFlashMemName = nullptr); 784 | 785 | 786 | 787 | /** 788 | * \brief This routine allows to disable the readout protection. 789 | * If the memory is not protected, a message appears to indicate that the device is not 790 | * under Readout protection and the command has no effects. 791 | * \return 0 if the disabling correctly accomplished, otherwise an error occurred. 792 | * \note Depending on the device used, this routine take a specific time. 793 | */ 794 | int readUnprotect(); 795 | 796 | 797 | /** 798 | * \brief This routine allows to know the interface what is in use. 799 | * \return The target interface type #targetInterfaceType, otherwise -1. 800 | */ 801 | int getTargetInterfaceType(); 802 | 803 | 804 | /** 805 | * \brief This routine allows to drop the current read/write operation. 806 | * \return 0 if there is no call for stop operation, otherwise 1. 807 | */ 808 | volatile int* getCancelPointer(); 809 | 810 | 811 | /** 812 | * \brief This routine allows to open and get data from any supported file extension. 813 | * \param filePath : Indicates the full path of the considered file. 814 | * \return Pointer to #fileData_C if the file has hex, bin, srec or elf as extension, otherwise a null pointer to indicate that the file type is not supported. 815 | */ 816 | void *fileOpen(const wchar_t* filePath); 817 | 818 | 819 | /** 820 | * \brief This routine allows to clean up the handled file data. 821 | * \param data 822 | */ 823 | void freeFileData(fileData_C* data); 824 | 825 | 826 | /** 827 | * \brief This routine allows to diplay the Option bytes 828 | */ 829 | int obDisplay(); 830 | 831 | /** 832 | * \brief This routine allows to verfiy if the indicated file data is identical to Flash memory content. 833 | * \param fileData : Input file name. 834 | * \param address : The address to start verifying from, it's considered only if the file has .bin or .binary as extension. 835 | * \return 0 if the file data matching Flash memory content, otherwise an error occurred or the data is mismatched. 836 | */ 837 | int verify(fileData_C* fileData, unsigned int address); 838 | 839 | 840 | /** 841 | * \brief This routine allows to save the data file content to another file. 842 | * \param fileData : Input file name. 843 | * \param sFileName : Output file name. 844 | * \return 0 if the output file was created successfully, otherwise an error occurred. 845 | */ 846 | int saveFileToFile(fileData_C *fileData, const wchar_t* sFileName); 847 | 848 | 849 | /** 850 | * \brief This routine allows to save Flash memory content to file. 851 | * \param address : The address to start saving from. 852 | * \param size : Data size to be saved. 853 | * \param sFileName : Indicates the file name. 854 | * \return 0 if the data copy was acheived successfully, otherwise an error occurred. 855 | * \note The file name must finish with an extension ".hex", ".bin" or ".srec" 856 | */ 857 | int saveMemoryToFile(int address, int size, const wchar_t* sFileName); 858 | 859 | 860 | /** 861 | * \brief This routine allows to clean up and disconnect the current connected target. 862 | * \note This routine disconnect the target and delete the loaded Flash Loaders. 863 | */ 864 | void disconnect(); 865 | 866 | 867 | /** 868 | * \brief This routine allows to clear the list of each created interface. 869 | * \note The list is filled by #getStlinkList, #getDfuDeviceList or #getUsartList. 870 | */ 871 | void deleteInterfaceList(); 872 | 873 | 874 | /** 875 | * \brief This routine allows to enter and make an automatic process for memory management through JTAG/SWD, UART, DFU, SPI, CAN and I²C interfaces. 876 | * \param filePath : Indicates the full file path. 877 | * \param address : The address to start downloading from. 878 | * \param skipErase : If we have a blank device, we can skip erasing memory before programming [skipErase=0]. 879 | * \param verify : Add verification step after downloading. 880 | * \param isMassErase : Erase the whole Flash memory. 881 | * \param obCommand : Indicates the option bytes commands to be loaded "-ob [optionbyte=value] [optionbyte=value]..." 882 | * \param run : Start the application. 883 | * \warning Connection to target must be established before performing automatic mode. 884 | */ 885 | void automaticMode(const wchar_t* filePath, unsigned int address, unsigned int skipErase, unsigned int verify, int isMassErase, char* obCommand, int run); 886 | 887 | 888 | /** 889 | * \brief This routine allows to get Flash storage information. 890 | * \param deviceStorageStruct : The data strcurure to load memory sectors information. 891 | * \return 0 if the operation was acheived successfully, otherwise an error occurred. 892 | */ 893 | int getStorageStructure(storageStructure** deviceStorageStruct); 894 | 895 | /*! @} */ 896 | 897 | 898 | /* -------------------------------------------------------------------------------------------- */ 899 | /* Option Bytes functions */ 900 | /* -------------------------------------------------------------------------------------------- */ 901 | 902 | /*! \addtogroup OB 903 | * OB module groups option bytes functions used by any interface. 904 | * @{ 905 | */ 906 | 907 | 908 | /** 909 | * \brief This routine allows program the given Option Byte. 910 | * The option bytes are configured by the end user depending on the application requirements. 911 | * \param command : Indicates the command to execute. 912 | * \return 0 if the programming Option Byte correctly executed, otherwise an error occurred. 913 | * \note The command must written as: -ob [optionbyte=value] [optionbyte=value] ... 914 | * \code 915 | * int ob = sendOptionBytesCmd("–ob rdp=0x0 BOR_LEV=0"); 916 | * \endcode 917 | */ 918 | int sendOptionBytesCmd(char* command); 919 | 920 | 921 | /** 922 | * \brief This routine allows to get option bytes values of the connected target. 923 | * \return Structure #Peripheral_C in which the option bytes descriptions are stored. 924 | */ 925 | peripheral_C* initOptionBytesInterface(); 926 | 927 | 928 | /** 929 | * \brief This routine allows to diplay the Option bytes. 930 | * \return 0 if the programming display correctly done, otherwise an error occurred. 931 | */ 932 | int obDisplay(); 933 | 934 | /*! @} */ 935 | 936 | 937 | /* -------------------------------------------------------------------------------------------- */ 938 | /* Loaders functions */ 939 | /* -------------------------------------------------------------------------------------------- */ 940 | 941 | 942 | /*! \addtogroup Loaders 943 | * Loaders module groups loaders functions. 944 | * @{ 945 | */ 946 | 947 | 948 | /** 949 | * \brief This routine allows to specify the location of Flash Loader. 950 | * \param path : Indicates the full path of the considered folder. 951 | */ 952 | void setLoadersPath(const char* path); 953 | 954 | 955 | /** 956 | * \brief This routine allows to specify the path of the external Loaders to be loaded. 957 | * \param path : Indicates the full path of the folder containing external Loaders. 958 | * \param externalLoaderInfo : Structure in which the external Loaders informations are stored. 959 | */ 960 | void setExternalLoaderPath(const char* path, externalLoader** externalLoaderInfo); 961 | 962 | 963 | /** 964 | * \brief This routine allows to get available external Loaders in th mentioned path. 965 | * \param path : Indicates the full path of the external Loader file ready for loading. 966 | * \param externalStorageNfo : Structure in which we get storage information. 967 | * \return 1 if the External loaders cannot be loaded from the path, otherwise 0. 968 | * \warning All external Loader files should have the extension "stldr". 969 | */ 970 | int getExternalLoaders(const char* path, externalStorageInfo** externalStorageNfo); 971 | 972 | 973 | 974 | /** 975 | * \brief This routine allows to unload an external Loaders. 976 | * \param path : Indicates the full path of the external Loader file ready for unloading. 977 | */ 978 | void removeExternalLoader(const char* path); 979 | /** 980 | * \brief This routine allows to delete all target Flash Loaders. 981 | */ 982 | void deleteLoaders(); 983 | 984 | /*! @} */ 985 | 986 | /* -------------------------------------------------------------------------------------------- */ 987 | /* STM32WB specific functions */ 988 | /* -------------------------------------------------------------------------------------------- */ 989 | 990 | /*! \addtogroup STM32WB 991 | * Specific APIs used exclusively for STM32WB series to manage BLE Stack and they are available only through USB DFU and UART bootloader interfaces, 992 | * except for the “firmwareDelete" and the “firmwareUpgrade", available through USB DFU, UART and SWD interfaces. 993 | * Connection under Reset is mandatory. 994 | * @{ 995 | */ 996 | 997 | /** 998 | * \brief This routine allows to read the device unique identifier. 999 | * \param data : Pointer to the data buffer. 1000 | */ 1001 | int getUID64(unsigned char** data); 1002 | 1003 | 1004 | /** 1005 | * \brief This routine allows to erase the BLE stack firmware. 1006 | * \return 0 if the operation was acheived successfully, otherwise an error occurred. 1007 | */ 1008 | int firmwareDelete(); 1009 | 1010 | /** 1011 | * \brief This routine allows to make upgrade of BLE stack firmware or FUS firmware. 1012 | * \param filePath : Indicates the full path of the firmware to be programmed. 1013 | * \param address : Start address of download. 1014 | * \param firstInstall : 1 if it is the first installation, otherwise 0, to ignore the firmware delete operation. 1015 | * \param startStack : Starts the stack after programming. 1016 | * \param verify : Verify if the download operation is achieved successfully before starting the upgrade. 1017 | * \return true if the operation was acheived successfully, otherwise an error occurred. 1018 | */ 1019 | int firmwareUpgrade(const wchar_t* filePath, unsigned int address, unsigned int firstInstall, unsigned int startStack, unsigned int verify); 1020 | 1021 | 1022 | /** 1023 | * \brief This routine allows to start the programmed Stack. 1024 | * \return true if the Stack was started successfully, otherwise an error occurred. 1025 | */ 1026 | int startWirelessStack(); 1027 | 1028 | 1029 | /** 1030 | * \brief This routine allows to start the programmed Stack. 1031 | * \param filePath : Indicates the full path of the key file. 1032 | * \note This is the public key generated by STM32TrustedPackageCreator when signing the firmware using -sign command. 1033 | * \return true if the update was performed successfully, otherwise an error occurred. 1034 | */ 1035 | int updateAuthKey(const wchar_t* filePath); 1036 | 1037 | 1038 | /** 1039 | * \brief This routine allows to lock the authentication key and once locked, it is no longer possible to change it. 1040 | * \return 0 if the lock step was performed successfully, otherwise an error occurred. 1041 | */ 1042 | int authKeyLock(); 1043 | 1044 | 1045 | /** 1046 | * \brief This routine allows to write a customized user key. 1047 | * \param filePath : Indicates the full path of the key file. 1048 | * \param keyType : String indicating the key type to be used "Simple", "Master", "Encrypted". 1049 | * \return 0 if the write was performed successfully, otherwise an error occurred. 1050 | */ 1051 | int writeUserKey(const wchar_t* filePath, unsigned char keyType); 1052 | 1053 | 1054 | /** 1055 | * \brief This routine allows to activate the AntiRollBack. 1056 | * \return true if the activation was done successfully, otherwise an error occurred. 1057 | */ 1058 | int antiRollBack(); 1059 | 1060 | 1061 | /** 1062 | * \brief This routine allows to start and establish a communication with the FUS operator. 1063 | * \return true if the FUS operator was started successfully, otherwise an error occurred. 1064 | * \note Availbale only for ST-LINK interfaces. 1065 | */ 1066 | int startFus(); 1067 | 1068 | /*! @} */ 1069 | 1070 | #ifdef __cplusplus 1071 | } 1072 | #endif 1073 | 1074 | 1075 | 1076 | #endif // CUBEPROGRAMMER_API_H 1077 | --------------------------------------------------------------------------------