├── .Zeugwerk └── config.json ├── .github └── workflows │ ├── build.yml │ └── documentation.yml ├── .gitignore ├── LICENSE ├── README.md ├── Twingrind ├── Twingrind.sln ├── Twingrind.tspproj └── Twingrind │ ├── Twingrind.tspproj │ └── Twingrind │ ├── CaptureMode.TcDUT │ ├── FrameData.TcDUT │ ├── FrameMeta.TcDUT │ ├── ParameterList.TcGVL │ ├── Profiler.TcPOU │ ├── ProfilerStackStruct.TcDUT │ └── Twingrind.plcproj ├── images ├── add_library.png ├── add_watch.png ├── demo.png ├── demo1.png ├── demo2.png ├── demo3.png ├── demo4.png ├── demo_struckig.png ├── demo_struckig1.png ├── installation_libraryrepository.png ├── installation_twincatxae.png └── watch.png └── pytwingrind ├── pytwingrind ├── __init__.py ├── __main__.py ├── clean.py ├── common.py ├── fetch.py ├── prepare.py └── reconstruct.py ├── requirements.txt ├── setup.py └── twingrind.py /.Zeugwerk/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "fileversion": 1, 3 | "solution": "Twingrind/Twingrind.sln", 4 | "projects": [ 5 | { 6 | "name": "Twingrind", 7 | "plcs": [ 8 | { 9 | "version": "0.4.1.0", 10 | "name": "Twingrind", 11 | "type": "Library", 12 | "frameworks": {}, 13 | "references": { 14 | "*": [ 15 | "Tc2_Standard=*", 16 | "Tc2_System=*" 17 | ] 18 | }, 19 | "repositories": [], 20 | "bindings": {} 21 | } 22 | ] 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build/Test 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - 'Twingrind/**' 8 | - 'pytwingrind/**' 9 | pull_request: 10 | branches: [ main ] 11 | workflow_dispatch: 12 | jobs: 13 | Build: 14 | name: Build/Test 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Build Twingrind 19 | uses: Zeugwerk/zkbuild-action@1.0.0 20 | with: 21 | username: ${{ secrets.ACTIONS_ZGWK_USERNAME }} 22 | password: ${{ secrets.ACTIONS_ZGWK_PASSWORD }} 23 | - name: Build pytwingrind 24 | run: | 25 | cd pytwingrind 26 | python setup.py bdist_wheel 27 | - uses: actions/upload-artifact@v3 28 | with: 29 | name: Twingrind 30 | path: | 31 | **/*.compiled-library 32 | - uses: actions/upload-artifact@v3 33 | with: 34 | name: pytwingrind 35 | path: | 36 | pytwingrind/dist/*.whl 37 | 38 | -------------------------------------------------------------------------------- /.github/workflows/documentation.yml: -------------------------------------------------------------------------------- 1 | name: Documentation 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - 'documentation/**' 8 | - 'Twingrind/**' 9 | pull_request: 10 | branches: [ main ] 11 | workflow_dispatch: 12 | jobs: 13 | Build: 14 | name: Documentation 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Build 18 | uses: Zeugwerk/zkdoc-action@1.0.0 19 | with: 20 | username: ${{ secrets.ACTIONS_ZGWK_USERNAME }} 21 | password: ${{ secrets.ACTIONS_ZGWK_PASSWORD }} 22 | filepath: "." 23 | - name: Deploy 24 | uses: peaceiris/actions-gh-pages@v3 25 | with: 26 | deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }} 27 | publish_dir: archive/documentation/html 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # python 2 | pytwingrind/build 3 | pytwingrind/dist 4 | *.egg-info 5 | 6 | # TwinCAT files 7 | *.tpy 8 | *.tclrs 9 | *.compiled-library 10 | *.compileinfo 11 | # Don't include the tmc-file rule if either of the following is true: 12 | # 1. You've got TwinCAT C++ projects, as the information in the TMC-file is created manually for the C++ projects (in that case, only (manually) ignore the tmc-files for the PLC projects) 13 | # 2. You've created a standalone PLC-project and added events to it, as these are stored in the TMC-file. 14 | *.tmc 15 | *.tmcRefac 16 | *.bak 17 | *.dbg 18 | *.~u 19 | *.tmcRefac 20 | *.library 21 | *.project.~u 22 | *.tsproj.bak 23 | *.xti.bak 24 | LineIDs.dbg 25 | LineIDs.dbg.bak 26 | _Boot/ 27 | _CompileInfo/ 28 | _Libraries/ 29 | _ModuleInstall/ 30 | 31 | # User-specific files 32 | *.rsuser 33 | *.suo 34 | *.user 35 | *.userosscache 36 | *.sln.docstates 37 | 38 | # User-specific files (MonoDevelop/Xamarin Studio) 39 | *.userprefs 40 | 41 | # Mono auto generated files 42 | mono_crash.* 43 | 44 | # Build results 45 | [Dd]ebug/ 46 | [Dd]ebugPublic/ 47 | [Rr]elease/ 48 | [Rr]eleases/ 49 | x64/ 50 | x86/ 51 | [Ww][Ii][Nn]32/ 52 | [Aa][Rr][Mm]/ 53 | [Aa][Rr][Mm]64/ 54 | bld/ 55 | [Bb]in/ 56 | [Oo]bj/ 57 | [Ll]og/ 58 | [Ll]ogs/ 59 | 60 | # Visual Studio 2015/2017 cache/options directory 61 | .vs/ 62 | # Uncomment if you have tasks that create the project's static files in wwwroot 63 | #wwwroot/ 64 | 65 | # Visual Studio 2017 auto generated files 66 | Generated\ Files/ 67 | 68 | # MSTest test Results 69 | [Tt]est[Rr]esult*/ 70 | [Bb]uild[Ll]og.* 71 | 72 | # NUnit 73 | *.VisualState.xml 74 | TestResult.xml 75 | nunit-*.xml 76 | 77 | # Build Results of an ATL Project 78 | [Dd]ebugPS/ 79 | [Rr]eleasePS/ 80 | dlldata.c 81 | 82 | # Benchmark Results 83 | BenchmarkDotNet.Artifacts/ 84 | 85 | # .NET Core 86 | project.lock.json 87 | project.fragment.lock.json 88 | artifacts/ 89 | 90 | # ASP.NET Scaffolding 91 | ScaffoldingReadMe.txt 92 | 93 | # StyleCop 94 | StyleCopReport.xml 95 | 96 | # Files built by Visual Studio 97 | *_i.c 98 | *_p.c 99 | *_h.h 100 | *.ilk 101 | *.meta 102 | *.obj 103 | *.iobj 104 | *.pch 105 | *.pdb 106 | *.ipdb 107 | *.pgc 108 | *.pgd 109 | *.rsp 110 | *.sbr 111 | *.tlb 112 | *.tli 113 | *.tlh 114 | *.tmp 115 | *.tmp_proj 116 | *_wpftmp.csproj 117 | *.log 118 | *.tlog 119 | *.vspscc 120 | *.vssscc 121 | .builds 122 | *.pidb 123 | *.svclog 124 | *.scc 125 | 126 | # Chutzpah Test files 127 | _Chutzpah* 128 | 129 | # Visual C++ cache files 130 | ipch/ 131 | *.aps 132 | *.ncb 133 | *.opendb 134 | *.opensdf 135 | *.sdf 136 | *.cachefile 137 | *.VC.db 138 | *.VC.VC.opendb 139 | 140 | # Visual Studio profiler 141 | *.psess 142 | *.vsp 143 | *.vspx 144 | *.sap 145 | 146 | # Visual Studio Trace Files 147 | *.e2e 148 | 149 | # TFS 2012 Local Workspace 150 | $tf/ 151 | 152 | # Guidance Automation Toolkit 153 | *.gpState 154 | 155 | # ReSharper is a .NET coding add-in 156 | _ReSharper*/ 157 | *.[Rr]e[Ss]harper 158 | *.DotSettings.user 159 | 160 | # TeamCity is a build add-in 161 | _TeamCity* 162 | 163 | # DotCover is a Code Coverage Tool 164 | *.dotCover 165 | 166 | # AxoCover is a Code Coverage Tool 167 | .axoCover/* 168 | !.axoCover/settings.json 169 | 170 | # Coverlet is a free, cross platform Code Coverage Tool 171 | coverage*.json 172 | coverage*.xml 173 | coverage*.info 174 | 175 | # Visual Studio code coverage results 176 | *.coverage 177 | *.coveragexml 178 | 179 | # NCrunch 180 | _NCrunch_* 181 | .*crunch*.local.xml 182 | nCrunchTemp_* 183 | 184 | # MightyMoose 185 | *.mm.* 186 | AutoTest.Net/ 187 | 188 | # Web workbench (sass) 189 | .sass-cache/ 190 | 191 | # Installshield output folder 192 | [Ee]xpress/ 193 | 194 | # DocProject is a documentation generator add-in 195 | DocProject/buildhelp/ 196 | DocProject/Help/*.HxT 197 | DocProject/Help/*.HxC 198 | DocProject/Help/*.hhc 199 | DocProject/Help/*.hhk 200 | DocProject/Help/*.hhp 201 | DocProject/Help/Html2 202 | DocProject/Help/html 203 | 204 | # Click-Once directory 205 | publish/ 206 | 207 | # Publish Web Output 208 | *.[Pp]ublish.xml 209 | *.azurePubxml 210 | # Note: Comment the next line if you want to checkin your web deploy settings, 211 | # but database connection strings (with potential passwords) will be unencrypted 212 | *.pubxml 213 | *.publishproj 214 | 215 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 216 | # checkin your Azure Web App publish settings, but sensitive information contained 217 | # in these scripts will be unencrypted 218 | PublishScripts/ 219 | 220 | # NuGet Packages 221 | *.nupkg 222 | # NuGet Symbol Packages 223 | *.snupkg 224 | # The packages folder can be ignored because of Package Restore 225 | **/[Pp]ackages/* 226 | # except build/, which is used as an MSBuild target. 227 | !**/[Pp]ackages/build/ 228 | # Uncomment if necessary however generally it will be regenerated when needed 229 | #!**/[Pp]ackages/repositories.config 230 | # NuGet v3's project.json files produces more ignorable files 231 | *.nuget.props 232 | *.nuget.targets 233 | 234 | # Nuget personal access tokens and Credentials 235 | nuget.config 236 | 237 | # Microsoft Azure Build Output 238 | csx/ 239 | *.build.csdef 240 | 241 | # Microsoft Azure Emulator 242 | ecf/ 243 | rcf/ 244 | 245 | # Windows Store app package directories and files 246 | AppPackages/ 247 | BundleArtifacts/ 248 | Package.StoreAssociation.xml 249 | _pkginfo.txt 250 | *.appx 251 | *.appxbundle 252 | *.appxupload 253 | 254 | # Visual Studio cache files 255 | # files ending in .cache can be ignored 256 | *.[Cc]ache 257 | # but keep track of directories ending in .cache 258 | !?*.[Cc]ache/ 259 | 260 | # Others 261 | ClientBin/ 262 | ~$* 263 | *~ 264 | *.dbmdl 265 | *.dbproj.schemaview 266 | *.jfm 267 | *.pfx 268 | *.publishsettings 269 | orleans.codegen.cs 270 | 271 | # Including strong name files can present a security risk 272 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 273 | #*.snk 274 | 275 | # Since there are multiple workflows, uncomment next line to ignore bower_components 276 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 277 | #bower_components/ 278 | 279 | # RIA/Silverlight projects 280 | Generated_Code/ 281 | 282 | # Backup & report files from converting an old project file 283 | # to a newer Visual Studio version. Backup files are not needed, 284 | # because we have git ;-) 285 | _UpgradeReport_Files/ 286 | Backup*/ 287 | UpgradeLog*.XML 288 | UpgradeLog*.htm 289 | ServiceFabricBackup/ 290 | *.rptproj.bak 291 | 292 | # SQL Server files 293 | *.mdf 294 | *.ldf 295 | *.ndf 296 | 297 | # Business Intelligence projects 298 | *.rdl.data 299 | *.bim.layout 300 | *.bim_*.settings 301 | *.rptproj.rsuser 302 | *- [Bb]ackup.rdl 303 | *- [Bb]ackup ([0-9]).rdl 304 | *- [Bb]ackup ([0-9][0-9]).rdl 305 | 306 | # Microsoft Fakes 307 | FakesAssemblies/ 308 | 309 | # GhostDoc plugin setting file 310 | *.GhostDoc.xml 311 | 312 | # Node.js Tools for Visual Studio 313 | .ntvs_analysis.dat 314 | node_modules/ 315 | 316 | # Visual Studio 6 build log 317 | *.plg 318 | 319 | # Visual Studio 6 workspace options file 320 | *.opt 321 | 322 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 323 | *.vbw 324 | 325 | # Visual Studio LightSwitch build output 326 | **/*.HTMLClient/GeneratedArtifacts 327 | **/*.DesktopClient/GeneratedArtifacts 328 | **/*.DesktopClient/ModelManifest.xml 329 | **/*.Server/GeneratedArtifacts 330 | **/*.Server/ModelManifest.xml 331 | _Pvt_Extensions 332 | 333 | # Paket dependency manager 334 | .paket/paket.exe 335 | paket-files/ 336 | 337 | # FAKE - F# Make 338 | .fake/ 339 | 340 | # CodeRush personal settings 341 | .cr/personal 342 | 343 | # Python Tools for Visual Studio (PTVS) 344 | __pycache__/ 345 | *.pyc 346 | 347 | # Cake - Uncomment if you are using it 348 | # tools/** 349 | # !tools/packages.config 350 | 351 | # Tabs Studio 352 | *.tss 353 | 354 | # Telerik's JustMock configuration file 355 | *.jmconfig 356 | 357 | # BizTalk build output 358 | *.btp.cs 359 | *.btm.cs 360 | *.odx.cs 361 | *.xsd.cs 362 | 363 | # OpenCover UI analysis results 364 | OpenCover/ 365 | 366 | # Azure Stream Analytics local run output 367 | ASALocalRun/ 368 | 369 | # MSBuild Binary and Structured Log 370 | *.binlog 371 | 372 | # NVidia Nsight GPU debugger configuration file 373 | *.nvuser 374 | 375 | # MFractors (Xamarin productivity tool) working folder 376 | .mfractor/ 377 | 378 | # Local History for Visual Studio 379 | .localhistory/ 380 | 381 | # BeatPulse healthcheck temp database 382 | healthchecksdb 383 | 384 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 385 | MigrationBackup/ 386 | 387 | # Ionide (cross platform F# VS Code tools) working folder 388 | .ionide/ 389 | 390 | # Fody - auto-generated XML schema 391 | FodyWeavers.xsd 392 | 393 | # VS Code files for those working on multiple tools 394 | .vscode/* 395 | !.vscode/settings.json 396 | !.vscode/tasks.json 397 | !.vscode/launch.json 398 | !.vscode/extensions.json 399 | *.code-workspace 400 | 401 | # Local History for Visual Studio Code 402 | .history/ 403 | 404 | # Windows Installer files from build outputs 405 | *.cab 406 | *.msi 407 | *.msix 408 | *.msm 409 | *.msp 410 | 411 | # JetBrains Rider 412 | .idea/ 413 | *.sln.iml 414 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Twingrind 2 | 3 | This project brings profiling to TwinCAT PLCs. The general idea of this project is as follows. 4 | 5 | 1. Twingrind is a TwinCAT library that includes a program, which is used for profiling. It includes methods to built-up a callstack and some triggers to start profiling. To enable profiling for a PLC the library has to be added to your PLC and a call to the Profiler program it includes has to be made in the task that you want to profile. 6 | 1. pytwingrind a python script that is used to 7 | - **prepare** your PLC for profile by adding some boilerplate code. This code are calls to `Push` and `Pop` methods of the Twincat library, which are needed to record the callstacks. 8 | - **fetch** previously recorded callstacks from the PLC and store it as binary data on our PC. This is not necessarily where the PLC is running. 9 | - **reconstruct** the recorded callstacks to callgrind (http://kcachegrind.sourceforge.net/html/CallgrindFormat.html) for visualization by [qcachegrind](http://kcachegrind.sourceforge.net/html/Home.html). 10 | 11 | The following image shows a visualization of the callstack of example given in the [struckig project](http://github.com/stefanbesler/struckig) for the PLC cycle where the trajectory of the example is calculated. For this example, twingrind profiling was added to the struckig library and also to a PLC, which uses struckig. 12 | 13 |

14 | Callgrind demo 15 |

16 |

17 | Callgrind demo 18 |

19 | 20 | ## Features 21 | 22 | - Profiling for TwinCAT PLCs with free software. 23 | - Selective capturing of callstacks. Threshold can be used to adjust which callstacks should be stored by the profiler. 24 | - Continuous profiling with the following modes 25 | - Only keep "slow" callstacks. This feature is super handy for finding realtime violation issues where the cycletime is exceeded. 26 | - Only keep "fast" callstacks, which is useful for finding issues with the baseline of your PLC. 27 | - Keep all callstacks, overwrite old callstacks in favour of new ones. 28 | - Only keep the first X callstacks. 29 | - Profiling of distinct cycles. 30 | 31 | The core of the implementation was written way before TwinCAT offered any kind of profile mechanism, and I actually had the needs of a profile to find a serious problem in a PLC. Nowadays profiling for TwinCAT is offered by Beckhoff, but is attached with licencing fees and is proprietary. Twingrind instead uses a common fileformat for profiling and is free software. 32 | 33 | **If you are interested to contribute to the project, feel free to write issues or fork the project and create pull requests. I also appreciate [sponsoring](https://github.com/sponsors/stefanbesler) me for creating and maintaining this project.** 34 | 35 | ## Limitations 36 | 37 | The current limitations of the profiler and the topics, which should be looked in, are as follows. 38 | 39 | - [ ] Only PLCs that utilize exactly 1 task can be profiled. 40 | - [ ] Profiling itself adds some overhead to your code, which can not be avoided by this method, but maybe reduced by a fair bit. 41 | - [ ] Files containing non-ST code are skipped. Profiling function blocks **with mixed implementations** (ST and any other IEC 61131-3 language like 42 | SFC, CFC) is not supported. 43 | - [ ] Twingrind focuses on Structured Text (ST), profiling for other languages specified by IEC 61131-3 is not supported. 44 | 45 | 46 | ## Installation 47 | 48 | Twingrind can either be downloaded from Github as or you can clone the [repository](https://github.com/stefanbesler/twingrind) and compile the library yourself. This guide will focus on the former use case. 49 | 50 | First, [get the latest release](https://github.com/stefanbesler/twingrind/releases) of Twingrind, the download will give you a file called "twingrind_0.4.1.0.compiled-library" and a python setup file. Note that the version number may differ from the file you actually downloaded. 51 | 52 | The PLC library can also be installed and updated with [Twinpack, which is a Package Manager for TwinCAT](https://github.com/Zeugwerk/Twinpack). 53 | 54 | ### Twingrind PLC library 55 | 56 | Start the TwinCAT XAE Shell or the Visual Studio Version you are usually using to develop TwinCAT PLCs. Then, in the menubar, select **PLC** and then **Library Repository...** (see figures below) 57 | 58 |

59 | TwinCAT XAE Shell  60 | TwinCAT XAE Shell  61 | Add library 62 |

63 | 64 | In the library-repository dialog, click on **Install** and navigate to the file compiled-library file and select it. Then, click on **Open** to install the Twingrind-plc library into your TwinCAT environment, and you are ready to use it. 65 | 66 | To make the Twingrind library available to the PLC, open the solution, which contains the PLC you want to profile. In the solution explorer, expand the PLC you are interested in and right-click on **References**. Select **Add library**. In the dialog, search for ***Twingrind***, then select the item and click on **Ok** 67 | 68 | ### pytwingrind python-module 69 | 70 | Open a command prompt and navigate to the *pytwingrind-0.4.1-py3-none-any.whl* file. Then use the following command to install the python module on your system. 71 | Make sure that your python environment is reachable in your path variable. 72 | 73 | ``` 74 | pip install pytwingrind-0.4.1-py3-none-any.whl 75 | ``` 76 | 77 | After running the command successfully, the executable `twingrind.exe` should be available in your path. 78 | 79 | ## Preparation 80 | 81 | 82 | ### Backup your source code 83 | 84 | Before profiling you should backup your code by commiting it to your version-control system or at least copy & paste it to a different location. The script will modify your existing source code and although it has been tested thoroughly, it is always better to err on the side of caution. 85 | 86 | ### Prepare your source code 87 | 88 | Use `twingrind.exe prepare` in the folder where your plcproj file is located, to add similar code to additional boilerplate code to your PLC. **Please make sure to use a directory containing your PLC** 89 | 90 | ``` 91 | twingrind prepare -d -m 92 | ``` 93 | 94 | The command transverses through the entire code base located at the given directory. For all calls it adds `Profiler.Push` and `Profiler.Pop` calls. The method calls are identified by id's and can be converted to readable 95 | strings by a hashmap file, which is the output of `twingrind prepare`. The file that is generated by this call is needed subsequently in *reconstruct*. 96 | 97 | If you are using PLC libraries you can reuse the hashmap file and enabling profiling for your libraries as well by a similar call to `twingrind prepare`, make sure to use the **same hashmap** for your libraries and your PLC. 98 | 99 | Most of the profiling boilerplate code is generated by the Twingrind command *prepare*. However, a call to Twingrind.Profiler() has 100 | to be manually inserted as the **first line of the first PLC** in your task. 101 | 102 | ``` 103 | MAIN.PRG 104 | ------------------------------- 105 | 1 Twingrind.Profiler(); // <<<<<< 106 | 2 107 | 3 (* @@ PROFILER @@ *)Twingrind.Profiler.Push(...);(* @@ PROFILER @@ *) 108 | 4 109 | 5 // 110 | 6 // 111 | 7 // 112 | . 113 | . 114 | ``` 115 | 116 | ## Usage 117 | 118 | ### Activate 119 | 120 | You can now activate your PLC on your target and work as you are used to. Note that the Profiler adds some overhead to your code. making execution a bit slower. Usually you should not notice a big impact though. To start profiling, login to your PLC, navigate to your MAIN programm, right click on *Profiler* (In the line you manually inserted in your code) and then click `Add Watch`. 121 | 122 |

123 | Add Watch  124 | Watch 125 |

126 | 127 | Then search for *Twingrind.Profiler* in the Watch panel and expand the node. You can then use the watch window to 128 | - **Capture the callstack** of a single frame of your PLC by a rising edge of *CaptureOnce* 129 | - Run **Captures continuously** by setting *CaptureContinuous=TRUE*. 130 | - You can specify a cpu time threshold such that only frames with a certain percentage-based usage of your CPU are captured (`CaptureCpuTimeLowThreshold`, `Capture CpuTimeHighThreshold`). 131 | - You can use `Mode` to adjust which callstacks are stored by the Profiler. For instance setting `Mode=Slowest` will only keep the slowest callstacks in the storage. 132 | - The library includes a parameter *MAX_FRAMES*, which is used to adjust the maximum amount of recorded frames. If *FrameIndex=MAX_FRAMES* no 133 | new captures will be performed by the Profiler. In order to **reset already taken recordings** you can give a rising edge on *Reset*. This will 134 | internally remove all data and set *FrameIndex=0* again. 135 | 136 | ### Process snapshot 137 | 138 | The *process* command reads all callstacks that have been recorded from the PLC and then reconstructs a callgrind file. Usually this is the command that you want to work with. 139 | 140 | ``` 141 | twingrind process -m hashmap 142 | ``` 143 | 144 | Here `-m hashmap` refers to the hashmap that has been created for your PLC during preparation. Use `twingrind process -h` for a detailed listing of all arguments. Use the following command to delete any previously recorded data (`-r` argument), take the profile of a single cycle (`-s1` argument). 145 | If the command fails with an "RecursionError: maximum recursion depth exceeded" error, try to increase the recursion limit with the "--recursion-limit N" switch, the recursion limit defaults to 2000. 146 | 147 | ``` 148 | twingrind process -m hashmap -rs1 149 | ``` 150 | 151 | ### Optional: Only read out profiling data from the PLC 152 | 153 | Run the following command to only read out all data from your PLC. 154 | 155 | ``` 156 | twingrind fetch 157 | ``` 158 | 159 | to read all recorded frames from the PLC. Capturing of callstacks is temporarily disabled. The resulting data is the output of *fetch* and is stored in 160 | the current directory. Latter files contain base64 encoded information about the callstack and can be 161 | converted to the callgrind format by *reconstruct*. The *fetch* command per default connects to the local target 162 | and with the PLC that is running on port 851. However, the command has several arguments to control its behavior, use 163 | `twingrind fetch -h` for a detailed listing. 164 | 165 | 166 | ### Optional: Convert previously read out data to callgrind 167 | 168 | Use the following command to reconstruct a frame. 169 | 170 | ``` 171 | twingrind reconstruct -m -c 172 | ``` 173 | 174 | Creates a callgrind file in the current directory. This script uses a previously generated hashmap (output of *prepare*) together with a recorded callstack (output of *fetch*). 175 | Run the reconstruct command for all frames that were exported by *fetch*. 176 | You may then open [qcachegrind](http://kcachegrind.sourceforge.net/html/Home.html) to visualize the callstack of your 177 | captured cycles. The command comes with some arguments to control its behavior, for details refer to `twingrind reconstruct -h` 178 | 179 | In the images below the first one shows the overview over a complete cycle. The PLC that I was running when taking this picture didn't use a lot of cpu ticks that is why there is a lot of empty space in *CYCLE::CYCLE*. The second image is zoomed into the MAIN PRG. 180 | If the command fails with an "RecursionError: maximum recursion depth exceeded" error, try to increase the recursion limit with the "--recursion-limit N" switch, the recursion limit defaults to 2000. 181 | 182 |

183 | Callgrind demo  184 | Callgrind demo 185 |

186 | 187 | ## Cleanup 188 | 189 | To cleanup your code from code that was added in the *Prepare* section you can run the *clean* as follows 190 | 191 | ``` 192 | twingrind clean -d 193 | ``` 194 | 195 | The command transverses through the entire code base of the plc located at the given directory. 196 | For all methods, the command removes the header function call and a the footer function call to the profiler 197 | library that were previously generated by using the "prepare". 198 | -------------------------------------------------------------------------------- /Twingrind/Twingrind.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # TcXaeShell Solution File, Format Version 11.00 4 | VisualStudioVersion = 15.0.28307.1300 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{DFBE7525-6864-4E62-8B2E-D530D69D9D96}") = "Twingrind", "Twingrind\Twingrind.tspproj", "{A16004EA-33C0-4358-8B6F-71035443BB89}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|TwinCAT CE7 (ARMV7) = Debug|TwinCAT CE7 (ARMV7) 11 | Debug|TwinCAT OS (ARMT2) = Debug|TwinCAT OS (ARMT2) 12 | Debug|TwinCAT RT (x64) = Debug|TwinCAT RT (x64) 13 | Debug|TwinCAT RT (x86) = Debug|TwinCAT RT (x86) 14 | Release|TwinCAT CE7 (ARMV7) = Release|TwinCAT CE7 (ARMV7) 15 | Release|TwinCAT OS (ARMT2) = Release|TwinCAT OS (ARMT2) 16 | Release|TwinCAT RT (x64) = Release|TwinCAT RT (x64) 17 | Release|TwinCAT RT (x86) = Release|TwinCAT RT (x86) 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT CE7 (ARMV7).ActiveCfg = Debug|TwinCAT CE7 (ARMV7) 21 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT CE7 (ARMV7).Build.0 = Debug|TwinCAT CE7 (ARMV7) 22 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT OS (ARMT2).ActiveCfg = Debug|TwinCAT OS (ARMT2) 23 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT OS (ARMT2).Build.0 = Debug|TwinCAT OS (ARMT2) 24 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT RT (x64).ActiveCfg = Debug|TwinCAT RT (x64) 25 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT RT (x64).Build.0 = Debug|TwinCAT RT (x64) 26 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT RT (x86).ActiveCfg = Debug|TwinCAT RT (x86) 27 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Debug|TwinCAT RT (x86).Build.0 = Debug|TwinCAT RT (x86) 28 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT CE7 (ARMV7).ActiveCfg = Release|TwinCAT CE7 (ARMV7) 29 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT CE7 (ARMV7).Build.0 = Release|TwinCAT CE7 (ARMV7) 30 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT OS (ARMT2).ActiveCfg = Release|TwinCAT OS (ARMT2) 31 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT OS (ARMT2).Build.0 = Release|TwinCAT OS (ARMT2) 32 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT RT (x64).ActiveCfg = Release|TwinCAT RT (x64) 33 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT RT (x64).Build.0 = Release|TwinCAT RT (x64) 34 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT RT (x86).ActiveCfg = Release|TwinCAT RT (x86) 35 | {A16004EA-33C0-4358-8B6F-71035443BB89}.Release|TwinCAT RT (x86).Build.0 = Release|TwinCAT RT (x86) 36 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT CE7 (ARMV7).ActiveCfg = Debug|TwinCAT CE7 (ARMV7) 37 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT CE7 (ARMV7).Build.0 = Debug|TwinCAT CE7 (ARMV7) 38 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT OS (ARMT2).ActiveCfg = Debug|TwinCAT OS (ARMT2) 39 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT OS (ARMT2).Build.0 = Debug|TwinCAT OS (ARMT2) 40 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT RT (x64).ActiveCfg = Debug|TwinCAT RT (x64) 41 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT RT (x64).Build.0 = Debug|TwinCAT RT (x64) 42 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT RT (x86).ActiveCfg = Debug|TwinCAT RT (x86) 43 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Debug|TwinCAT RT (x86).Build.0 = Debug|TwinCAT RT (x86) 44 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT CE7 (ARMV7).ActiveCfg = Release|TwinCAT CE7 (ARMV7) 45 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT CE7 (ARMV7).Build.0 = Release|TwinCAT CE7 (ARMV7) 46 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT OS (ARMT2).ActiveCfg = Release|TwinCAT OS (ARMT2) 47 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT OS (ARMT2).Build.0 = Release|TwinCAT OS (ARMT2) 48 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT RT (x64).ActiveCfg = Release|TwinCAT RT (x64) 49 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT RT (x64).Build.0 = Release|TwinCAT RT (x64) 50 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT RT (x86).ActiveCfg = Release|TwinCAT RT (x86) 51 | {C3E0E12E-171D-4C3C-8375-B12DC038DFE6}.Release|TwinCAT RT (x86).Build.0 = Release|TwinCAT RT (x86) 52 | EndGlobalSection 53 | GlobalSection(SolutionProperties) = preSolution 54 | HideSolutionNode = FALSE 55 | EndGlobalSection 56 | GlobalSection(ExtensibilityGlobals) = postSolution 57 | SolutionGuid = {0DEEEE26-4F96-4C30-B199-81292F2AFAF4} 58 | EndGlobalSection 59 | EndGlobal 60 | -------------------------------------------------------------------------------- /Twingrind/Twingrind.tspproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind.tspproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/CaptureMode.TcDUT: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 15 | 16 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/FrameData.TcDUT: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 15 | 16 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/FrameMeta.TcDUT: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 13 | 14 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/ParameterList.TcGVL: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 9 | 10 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/Profiler.TcPOU: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 46 | 47 | SINT_TO_UDINT(MAX_TASKS) 59 | THEN 60 | Error := TRUE; 61 | ErrorMessage := 'Twingrind only supports PLCs with 1 tasks only!'; 62 | RETURN; 63 | END_IF 64 | 65 | Tasks := UDINT_TO_SINT(TwinCAT_SystemInfoVarList._AppInfo.TaskCnt); 66 | FOR _taskIt:=1 TO TwinCAT_SystemInfoVarList._AppInfo.TaskCnt 67 | DO 68 | CycleTime[_taskIt] := TwinCAT_SystemInfoVarList._TaskInfo[_taskIt].CycleTime; 69 | END_FOR 70 | END_IF 71 | 72 | IF _captureContinuousTrig.Q 73 | THEN 74 | CaptureOnce := 0; 75 | Error := FALSE; 76 | ErrorMessage := ''; 77 | END_IF 78 | 79 | // Logic to only keep frames that satisfy the threshold conditions 80 | IF _frameRecorded.Q 81 | THEN 82 | _meta.Size := _size; 83 | _meta.TotalDuration := _data[_size-1].EndHi - _data[0].StartHi + _data[_size-1].EndLo - _data[0].StartLo; 84 | _currenttask(); 85 | 86 | // Check if the frame that was just recorded should be kept, if so, find the next place in the date structure where 87 | // we can write into 88 | _cycleDuration := 100 * UDINT_TO_LREAL(TwinCAT_SystemInfoVarList._TaskInfo[_currenttask.index].LastExecTime) / UDINT_TO_LREAL(TwinCAT_SystemInfoVarList._TaskInfo[_currenttask.index].CycleTime); 89 | IF (_cycleDuration > CaptureCpuTimeLowThreshold AND_THEN _cycleDuration < CaptureCpuTimeHighThreshold) OR_ELSE 90 | (CaptureCpuTimeLowThreshold = 0 AND_THEN CaptureCpuTimeHighThreshold = 0) 91 | THEN 92 | FrameIndex := NextFrameIndex(); 93 | END_IF 94 | 95 | END_IF 96 | 97 | IF CaptureContinuous 98 | THEN 99 | _enabled := TRUE; 100 | _size := 0; 101 | ELSE 102 | IF _captureOnceTrig.Q 103 | THEN 104 | Error := FALSE; 105 | ErrorMessage := ''; 106 | _enabled := TRUE; 107 | _size := 0; 108 | END_IF 109 | END_IF 110 | 111 | // Delete all Ddata that has already been caputured 112 | IF _resetTrig.Q 113 | THEN 114 | Error := FALSE; 115 | ErrorMessage := ''; 116 | FrameIndex := 0; 117 | MEMSET(ADR(Data), 0, SIZEOF(Data)); 118 | MEMSET(ADR(Meta), 0, SIZEOF(Meta)); 119 | _enabled := FALSE; 120 | END_IF 121 | 122 | // Prepare the current frame 123 | Busy := _enabled; 124 | _depth := 0; 125 | _data REF= Data[FrameIndex, 1]; 126 | _meta REF= Meta[FrameIndex]; 127 | _meta.Id := TwinCAT_SystemInfoVarList._TaskInfo[1].CycleCount; 128 | _frameRecorded(CLK:=_enabled);]]> 129 | 130 | 131 | 137 | 138 | ParameterList.MAX_FRAMES 160 | THEN 161 | NextFrameIndex := 0; 162 | END_IF 163 | 164 | // Find the index of the slowest profile 165 | CaptureMode.Fastest: 166 | duration := 0; 167 | FOR i:=0 TO ParameterList.MAX_FRAMES 168 | DO 169 | IF Meta[i].TotalDuration = 0 170 | THEN 171 | NextFrameIndex := i; 172 | RETURN; 173 | ELSIF Meta[i].TotalDuration > duration OR_ELSE duration = 0 174 | THEN 175 | duration := Meta[i].TotalDuration; 176 | NextFrameIndex := i; 177 | END_IF 178 | END_FOR 179 | 180 | // Only record max_frames, then no further frames are caputured 181 | CaptureMode.FirstOnesOnly: 182 | NextFrameIndex := MIN(FrameIndex + 1, ParameterList.MAX_FRAMES); 183 | 184 | END_CASE]]> 185 | 186 | 187 | 188 | 192 | 193 | _data[_size].EndLo, cpuCntHiDW => _data[_size].EndHi); 204 | 205 | IF _depth < 0 206 | THEN 207 | _enabled := FALSE; 208 | Error := TRUE; 209 | ErrorMessage := 'Pop/Push mismatch!'; 210 | RETURN; 211 | ELSE 212 | _size := _size + 1; 213 | END_IF 214 | 215 | // abort if the stack is getting too big (too many functions were called) 216 | IF _size > ParameterList.MAX_STACKSIZE 217 | THEN 218 | _enabled := FALSE; 219 | Error := TRUE; 220 | ErrorMessage := 'The method stack is too big!'; 221 | END_IF]]> 222 | 223 | 224 | 225 | 231 | 232 | _data[_size].StartLo, cpuCntHiDW => _data[_size].StartHi); 240 | _data[_size].endhi := 0; 241 | _data[_size].endlo := 0; 242 | _size := _size + 1; 243 | _depth := _depth + 1; 244 | 245 | // abort if the stack is getting too big (too many functions were called) 246 | IF _size > ParameterList.MAX_STACKSIZE 247 | THEN 248 | _enabled := FALSE; 249 | Error := TRUE; 250 | ErrorMessage := 'The method stack is too big!'; 251 | END_IF 252 | ]]> 253 | 254 | 255 | 256 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/ProfilerStackStruct.TcDUT: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 15 | 16 | -------------------------------------------------------------------------------- /Twingrind/Twingrind/Twingrind/Twingrind.plcproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 1.0.0.0 6 | 2.0 7 | {c3e0e12e-171d-4c3c-8375-b12dc038dfe6} 8 | True 9 | Twingrind 10 | 3.1.4023.0 11 | {5cb8600d-36c2-4aed-9484-2799a420f128} 12 | {ee1e3ca8-77f5-4cde-9c10-f6855ded4270} 13 | {1c562155-e637-4e3e-83a9-6925d9835630} 14 | {03206031-9847-428b-a9f4-bc7adfe37b16} 15 | {a4e318aa-bf97-40bc-88f0-4821b943304c} 16 | {6cc762c1-16b6-4d36-aa28-1ac36cb62ce1} 17 | false 18 | Stefan Besler 19 | false 20 | Twingrind 21 | 0.4.1.0 22 | Stefan Besler and Contributers 23 | 26 | 27 | 28 | 29 | Code 30 | 31 | 32 | Code 33 | 34 | 35 | Code 36 | true 37 | 38 | 39 | Code 40 | 41 | 42 | Code 43 | 44 | 45 | 46 | 47 | Tc2_Standard, * (Beckhoff Automation GmbH) 48 | Tc2_Standard 49 | 50 | 51 | Tc2_System, * (Beckhoff Automation GmbH) 52 | Tc2_System 53 | 54 | 55 | 56 | 57 | Tc2_Standard, * (Beckhoff Automation GmbH) 58 | 59 | 60 | Tc2_System, * (Beckhoff Automation GmbH) 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | "<ProjectRoot>" 69 | 70 | {192FAD59-8248-4824-A8DE-9177C94C195A} 71 | 72 | "{192FAD59-8248-4824-A8DE-9177C94C195A}" 73 | 74 | 75 | 76 | {246001F4-279D-43AC-B241-948EB31120E1} 77 | 78 | "{246001F4-279D-43AC-B241-948EB31120E1}" 79 | 80 | 81 | GlobalVisuImageFilePath 82 | %APPLICATIONPATH% 83 | 84 | 85 | {F66C7017-BDD8-4114-926C-81D6D687E35F} 86 | 87 | "{F66C7017-BDD8-4114-926C-81D6D687E35F}" 88 | 89 | 90 | 91 | {40450F57-0AA3-4216-96F3-5444ECB29763} 92 | 93 | "{40450F57-0AA3-4216-96F3-5444ECB29763}" 94 | 95 | 96 | ActiveVisuProfile 97 | IR0whWr8bwfwBwAAiD2qpQAAAABVAgAA37x72QAAAAABAAAAAAAAAAEaUwB5AHMAdABlAG0ALgBTAHQAcgBpAG4AZwACTHsAZgA5ADUAYgBiADQAMgA2AC0ANQA1ADIANAAtADQAYgA0ADUALQA5ADQAMAAwAC0AZgBiADAAZgAyAGUANwA3AGUANQAxAGIAfQADCE4AYQBtAGUABDBUAHcAaQBuAEMAQQBUACAAMwAuADEAIABCAHUAaQBsAGQAIAA0ADAAMgA0AC4ANwAFFlAAcgBvAGYAaQBsAGUARABhAHQAYQAGTHsAMQA2AGUANQA1AGIANgAwAC0ANwAwADQAMwAtADQAYQA2ADMALQBiADYANQBiAC0ANgAxADQANwAxADMAOAA3ADgAZAA0ADIAfQAHEkwAaQBiAHIAYQByAGkAZQBzAAhMewAzAGIAZgBkADUANAA1ADkALQBiADAANwBmAC0ANABkADYAZQAtAGEAZQAxAGEALQBhADgAMwAzADUANgBhADUANQAxADQAMgB9AAlMewA5AGMAOQA1ADgAOQA2ADgALQAyAGMAOAA1AC0ANAAxAGIAYgAtADgAOAA3ADEALQA4ADkANQBmAGYAMQBmAGUAZABlADEAYQB9AAoOVgBlAHIAcwBpAG8AbgALBmkAbgB0AAwKVQBzAGEAZwBlAA0KVABpAHQAbABlAA4aVgBpAHMAdQBFAGwAZQBtAE0AZQB0AGUAcgAPDkMAbwBtAHAAYQBuAHkAEAxTAHkAcwB0AGUAbQARElYAaQBzAHUARQBsAGUAbQBzABIwVgBpAHMAdQBFAGwAZQBtAHMAUwBwAGUAYwBpAGEAbABDAG8AbgB0AHIAbwBsAHMAEyhWAGkAcwB1AEUAbABlAG0AcwBXAGkAbgBDAG8AbgB0AHIAbwBsAHMAFCRWAGkAcwB1AEUAbABlAG0AVABlAHgAdABFAGQAaQB0AG8AcgAVIlYAaQBzAHUATgBhAHQAaQB2AGUAQwBvAG4AdAByAG8AbAAWFHYAaQBzAHUAaQBuAHAAdQB0AHMAFwxzAHkAcwB0AGUAbQAYGFYAaQBzAHUARQBsAGUAbQBCAGEAcwBlABkmRABlAHYAUABsAGEAYwBlAGgAbwBsAGQAZQByAHMAVQBzAGUAZAAaCGIAbwBvAGwAGyJQAGwAdQBnAGkAbgBDAG8AbgBzAHQAcgBhAGkAbgB0AHMAHEx7ADQAMwBkADUAMgBiAGMAZQAtADkANAAyAGMALQA0ADQAZAA3AC0AOQBlADkANAAtADEAYgBmAGQAZgAzADEAMABlADYAMwBjAH0AHRxBAHQATABlAGEAcwB0AFYAZQByAHMAaQBvAG4AHhRQAGwAdQBnAGkAbgBHAHUAaQBkAB8WUwB5AHMAdABlAG0ALgBHAHUAaQBkACBIYQBmAGMAZAA1ADQANAA2AC0ANAA5ADEANAAtADQAZgBlADcALQBiAGIANwA4AC0AOQBiAGYAZgBlAGIANwAwAGYAZAAxADcAIRRVAHAAZABhAHQAZQBJAG4AZgBvACJMewBiADAAMwAzADYANgBhADgALQBiADUAYwAwAC0ANABiADkAYQAtAGEAMAAwAGUALQBlAGIAOAA2ADAAMQAxADEAMAA0AGMAMwB9ACMOVQBwAGQAYQB0AGUAcwAkTHsAMQA4ADYAOABmAGYAYwA5AC0AZQA0AGYAYwAtADQANQAzADIALQBhAGMAMAA2AC0AMQBlADMAOQBiAGIANQA1ADcAYgA2ADkAfQAlTHsAYQA1AGIAZAA0ADgAYwAzAC0AMABkADEANwAtADQAMQBiADUALQBiADEANgA0AC0ANQBmAGMANgBhAGQAMgBiADkANgBiADcAfQAmFk8AYgBqAGUAYwB0AHMAVAB5AHAAZQAnVFUAcABkAGEAdABlAEwAYQBuAGcAdQBhAGcAZQBNAG8AZABlAGwARgBvAHIAQwBvAG4AdgBlAHIAdABpAGIAbABlAEwAaQBiAHIAYQByAGkAZQBzACgQTABpAGIAVABpAHQAbABlACkUTABpAGIAQwBvAG0AcABhAG4AeQAqHlUAcABkAGEAdABlAFAAcgBvAHYAaQBkAGUAcgBzACs4UwB5AHMAdABlAG0ALgBDAG8AbABsAGUAYwB0AGkAbwBuAHMALgBIAGEAcwBoAHQAYQBiAGwAZQAsEnYAaQBzAHUAZQBsAGUAbQBzAC1INgBjAGIAMQBjAGQAZQAxAC0AZAA1AGQAYwAtADQAYQAzAGIALQA5ADAANQA0AC0AMgAxAGYAYQA3ADUANgBhADMAZgBhADQALihJAG4AdABlAHIAZgBhAGMAZQBWAGUAcgBzAGkAbwBuAEkAbgBmAG8AL0x7AGMANgAxADEAZQA0ADAAMAAtADcAZgBiADkALQA0AGMAMwA1AC0AYgA5AGEAYwAtADQAZQAzADEANABiADUAOQA5ADYANAAzAH0AMBhNAGEAagBvAHIAVgBlAHIAcwBpAG8AbgAxGE0AaQBuAG8AcgBWAGUAcgBzAGkAbwBuADIMTABlAGcAYQBjAHkAMzBMAGEAbgBnAHUAYQBnAGUATQBvAGQAZQBsAFYAZQByAHMAaQBvAG4ASQBuAGYAbwA0MEwAbwBhAGQATABpAGIAcgBhAHIAaQBlAHMASQBuAHQAbwBQAHIAbwBqAGUAYwB0ADUaQwBvAG0AcABhAHQAaQBiAGkAbABpAHQAeQDQAAIaA9ADAS0E0AUGGgfQBwgaAUUHCQjQAAkaBEUKCwQDAAAABQAAAA0AAAAAAAAA0AwLrQIAAADQDQEtDtAPAS0Q0AAJGgRFCgsEAwAAAAUAAAANAAAAKAAAANAMC60BAAAA0A0BLRHQDwEtENAACRoERQoLBAMAAAAFAAAADQAAAAAAAADQDAutAgAAANANAS0S0A8BLRDQAAkaBEUKCwQDAAAABQAAAA0AAAAUAAAA0AwLrQIAAADQDQEtE9APAS0Q0AAJGgRFCgsEAwAAAAUAAAANAAAAAAAAANAMC60CAAAA0A0BLRTQDwEtENAACRoERQoLBAMAAAAFAAAADQAAAAAAAADQDAutAgAAANANAS0V0A8BLRDQAAkaBEUKCwQDAAAABQAAAA0AAAAAAAAA0AwLrQIAAADQDQEtFtAPAS0X0AAJGgRFCgsEAwAAAAUAAAANAAAAKAAAANAMC60EAAAA0A0BLRjQDwEtENAZGq0BRRscAdAAHBoCRR0LBAMAAAAFAAAADQAAAAAAAADQHh8tINAhIhoCRSMkAtAAJRoFRQoLBAMAAAADAAAAAAAAAAoAAADQJgutAAAAANADAS0n0CgBLRHQKQEtENAAJRoFRQoLBAMAAAADAAAAAAAAAAoAAADQJgutAQAAANADAS0n0CgBLRHQKQEtEJoqKwFFAAEC0AABLSzQAAEtF9AAHy0t0C4vGgPQMAutAQAAANAxC60XAAAA0DIarQDQMy8aA9AwC60CAAAA0DELrQMAAADQMhqtANA0Gq0A0DUarQA= 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | System.Collections.Hashtable 106 | {54dd0eac-a6d8-46f2-8c27-2f43c7e49861} 107 | System.String 108 | 109 | 110 | 111 | 112 | 124 | 125 | -------------------------------------------------------------------------------- /images/add_library.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/add_library.png -------------------------------------------------------------------------------- /images/add_watch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/add_watch.png -------------------------------------------------------------------------------- /images/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo.png -------------------------------------------------------------------------------- /images/demo1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo1.png -------------------------------------------------------------------------------- /images/demo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo2.png -------------------------------------------------------------------------------- /images/demo3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo3.png -------------------------------------------------------------------------------- /images/demo4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo4.png -------------------------------------------------------------------------------- /images/demo_struckig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo_struckig.png -------------------------------------------------------------------------------- /images/demo_struckig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/demo_struckig1.png -------------------------------------------------------------------------------- /images/installation_libraryrepository.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/installation_libraryrepository.png -------------------------------------------------------------------------------- /images/installation_twincatxae.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/installation_twincatxae.png -------------------------------------------------------------------------------- /images/watch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/images/watch.png -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stefanbesler/twingrind/88940b5da9cfb791e779dfedc5e942a5a8f42510/pytwingrind/pytwingrind/__init__.py -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/__main__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | from argparse import ArgumentParser 4 | 5 | prepare_parser = ArgumentParser("""Prepares the source code of a PLC 6 | so that is can be used with Twingrind. The script parses through all source files (*.POU) 7 | and adds boilerplate code to every functionblock, function and method in the PLC. 8 | 9 | The output of this command is a hashmap, which is a mapping between a uniquely generated id and 10 | the functionblock-, function- or methodname, respectively. The hashmap file has to be provided when 11 | reconstructiong the call-graph. 12 | """) 13 | prepare_parser.add_argument("-d", "--directory", help="Directory containing the PLC project and all source files", required=True) 14 | prepare_parser.add_argument("-m", "--hashmap", help="Filepath of a hashmap, if the file does not exist, it will be created", required=True) 15 | 16 | fetch_parser = ArgumentParser("""Reads out all call-graph caputues from a PLC""") 17 | fetch_parser.add_argument("-n", "--netid", help="AMS-NetId of the target machine, defaults to the local machine", default="", required=False) 18 | fetch_parser.add_argument("-p", "--port", help="Port of the PLC", default=851, required=False) 19 | fetch_parser.add_argument("-d", "--directory", help="Output directory", default="./", required=False) 20 | fetch_parser.add_argument("-o", "--outputname", help="Outputname prefix for files that are generated", default="callstack", required=False) 21 | fetch_parser.add_argument("-N", "--namespace", help="Namespace that is used for the Twingrind library, useful if used with TC_SYM_WITH_NAMESPACE", default="Twingrind", required=False) 22 | fetch_parser.add_argument("-r", "--reset", help="Reset the profiler, this action is taken before taken new shots using the shots argument", action='store_true') 23 | fetch_parser.add_argument("-s", "--shots", help="How many single shots should be taken when calling the fetch command", default=0, required=False, type=int) 24 | 25 | reconstruct_parser = ArgumentParser("""Converts a callstack, as it has been read of the fetch command together with the 26 | hashmap that has been created for the PLC with the prepare command, to the callgrind format.""") 27 | reconstruct_parser.add_argument("-m", "--hashmap", help="Hashmap that is created with the prepare command", required=False) 28 | reconstruct_parser.add_argument("-c", "--callstack", help="Callstack that was read out with the fetch command", required=True) 29 | reconstruct_parser.add_argument("-d", "--directory", help="Output directory", default="./", required=False) 30 | reconstruct_parser.add_argument("-q", "--masquarade", help="Obfuscate names of functionblocks, functions and methods", action="store_true", required=False) 31 | reconstruct_parser.add_argument("-o", "--outputname", help="Outputname prefix for files that are generated", default="callstack", required=False) 32 | reconstruct_parser.add_argument("-R", "--recursion-limit", help="Set pythons maximum recursion limit", default=2000, required=False) 33 | 34 | process_parser = ArgumentParser("""Fetches all captures from the PLC and then reconstructs the call-graph. This command 35 | is the same as running fetch and then reconstructing every callstack""") 36 | process_parser.add_argument("-n", "--netid", help="AMS-NetId of the target machine, defaults to the local machine", default="", required=False) 37 | process_parser.add_argument("-p", "--port", help="Port of the PLC", default=851, required=False) 38 | process_parser.add_argument("-d", "--directory", help="Output directory", default="./", required=False) 39 | process_parser.add_argument("-m", "--hashmap", help="Hashmap that is created with the prepare command", required=True) 40 | process_parser.add_argument("-q", "--masquarade", help="Obfuscate names of functionblocks, functions and methods", action="store_true", required=False) 41 | process_parser.add_argument("-o", "--outputname", help="Outputname prefix for files that are generated", default="callstack", required=False) 42 | process_parser.add_argument("-N", "--namespace", help="Namespace that is used for the Twingrind library, useful if used with TC_SYM_WITH_NAMESPACE", default="Twingrind", required=False) 43 | process_parser.add_argument("-r", "--reset", help="Reset the profiler, this action is taken before taken new shots using the shots argument", action='store_true') 44 | process_parser.add_argument("-s", "--shots", help="How many single shots should be taken when calling the fetch command", default=0, required=False, type=int) 45 | process_parser.add_argument("-R", "--recursion-limit", help="Set pythons maximum recursion limit", default=2000, required=False) 46 | 47 | clean_parser = ArgumentParser("""Removes all boilerplate code that has been added the PLC with the prepare command. 48 | Use this command if profiling is no longer needed. 49 | """) 50 | clean_parser.add_argument("-d", "--directory", help="Directory containing the PLC project and all source files", required=True) 51 | 52 | def main(): 53 | logging.basicConfig(level=logging.DEBUG) 54 | cmds = ["prepare", "fetch", "reconstruct", "process", "clean"] 55 | if len(sys.argv) <= 1 or sys.argv[1] not in cmds: 56 | logging.error(f"""Invalid command. The first arugment must be one of the following items {cmds}""") 57 | sys.exit(-1) 58 | 59 | arg = sys.argv[1] 60 | if arg == "prepare": 61 | import pytwingrind.prepare 62 | 63 | parser = prepare_parser 64 | args = vars(parser.parse_args(sys.argv[2::])) 65 | pytwingrind.prepare.run(args["directory"], args["hashmap"]) 66 | 67 | elif arg == "fetch": 68 | import pytwingrind.fetch 69 | 70 | parser = fetch_parser 71 | args = vars(parser.parse_args(sys.argv[2::])) 72 | pytwingrind.fetch.run(args["netid"], int(args["port"]), args["directory"], args["outputname"], args["namespace"], args["reset"], args["shots"]) 73 | 74 | elif arg == "reconstruct": 75 | import pytwingrind.reconstruct 76 | 77 | parser = reconstruct_parser 78 | args = vars(parser.parse_args(sys.argv[2::])) 79 | sys.setrecursionlimit(int(args["recursion_limit"])) 80 | pytwingrind.reconstruct.run(args["hashmap"], args["callstack"], args["directory"], args["outputname"]) 81 | 82 | elif arg == "process": 83 | import pytwingrind.fetch 84 | import pytwingrind.reconstruct 85 | 86 | parser = process_parser 87 | args = vars(parser.parse_args(sys.argv[2::])) 88 | sys.setrecursionlimit(int(args["recursion_limit"])) 89 | callstacks = pytwingrind.fetch.run(args["netid"], int(args["port"]), args["directory"], args["outputname"], args["namespace"], args["reset"], args["shots"]) 90 | 91 | for callstack in callstacks: 92 | pytwingrind.reconstruct.run(args["hashmap"], callstack, args["directory"], "") 93 | 94 | elif arg == "clean": 95 | import pytwingrind.clean 96 | 97 | parser = clean_parser 98 | args = vars(parser.parse_args(sys.argv[2::])) 99 | pytwingrind.clean.run(args["directory"]) 100 | -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/clean.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import re 6 | import logging 7 | from pytwingrind import common 8 | 9 | def remove_guards(filepath: str, fb_name: str): 10 | """remove guards to fb and all methods for this file""" 11 | 12 | encoding = common.detect_encoding(filepath) 13 | with open(filepath, "rt", encoding=encoding) as f: 14 | src = f.read() 15 | src, i = re.subn(r'{tag}Twingrind\.Profiler\.Push.*?{tag}\r?\n'.format(tag=re.escape(common.profiler_tag)), '', src, 0, re.M | re.UNICODE) 16 | src, j = re.subn(r'{tag}Twingrind\.Profiler\.Pop.*?{tag}RETURN'.format(tag=re.escape(common.profiler_tag)), 'RETURN', src, 0, re.M | re.UNICODE) 17 | src, k = re.subn(r'\r?\n{tag}Twingrind\.Profiler\.Pop.*?{tag}'.format(tag=re.escape(common.profiler_tag)), '', src, 0, re.M | re.UNICODE) 18 | logging.debug("{}: removed {} guards".format(fb_name, int(i))) # we should have 2 guards per method 19 | 20 | 21 | with open(filepath, "wt", encoding=encoding) as g: 22 | g.write(src) 23 | 24 | def run(filepath: str): 25 | 26 | for f in common.find_sourcefiles(filepath): 27 | fb_name, _ = os.path.splitext(os.path.basename(f)) 28 | remove_guards(f, fb_name) 29 | -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/common.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import chardet 3 | import os 4 | import re 5 | from dataclasses import dataclass 6 | 7 | profiler_tag = r"(* @@ PROFILER @@ *)" 8 | 9 | @dataclass 10 | class GuardExclusionToken: 11 | token: str 12 | description: str 13 | 14 | file_skip_tokens = [ 15 | GuardExclusionToken(profiler_tag, "Guards already present"), 16 | GuardExclusionToken('', "Sequential function chart detected (SFC)"), 17 | GuardExclusionToken('', "Ladder Logic Diagram detected (LD)"), 18 | GuardExclusionToken('', "Sequential function chart detected (SC)"), 20 | ] 21 | 22 | def detect_encoding(filepath : str): 23 | 24 | with open(filepath, 'rb') as f: 25 | result = chardet.detect(f.read()) 26 | return result['encoding'] 27 | 28 | return 'utf-8' 29 | 30 | def find_sourcefiles(filepath : str): 31 | """walk recursively through folders and look for TwinCat3 source files""" 32 | 33 | for subdir, _, files in os.walk(filepath): 34 | for f in files: 35 | re_source = re.match(".*.tcpou$", f, re.I) 36 | if re_source: 37 | yield os.path.join(subdir, f) 38 | 39 | class Call(ctypes.Structure): 40 | _fields_ = [("hash", ctypes.c_uint32), 41 | ("depth", ctypes.c_int32), 42 | ("startlo", ctypes.c_uint32), 43 | ("starthi", ctypes.c_uint32), 44 | ("endlo", ctypes.c_uint32), 45 | ("endhi", ctypes.c_uint32)] 46 | 47 | def create_stack_class(size : int): 48 | # create global class to keep pickle happy 49 | global Stack 50 | class Stack(ctypes.Structure): 51 | _fields_ = [("calls", Call * (size))] 52 | 53 | class Callstack(object): 54 | def __init__(self, cycletime : int, task : int, size : int, stack : ctypes.Structure): 55 | self.cycletime = cycletime 56 | self.task = task 57 | self.size = size 58 | self.stack = stack 59 | -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/fetch.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import logging 4 | import pyads 5 | import pickle 6 | import ctypes 7 | from pytwingrind import common 8 | 9 | def trigger_edge(plc, symbol: str, pause_duration: float): 10 | plc.write_by_name(symbol, True, pyads.PLCTYPE_BOOL) 11 | time.sleep(pause_duration) 12 | plc.write_by_name(symbol, False, pyads.PLCTYPE_BOOL) 13 | time.sleep(pause_duration) 14 | 15 | def run(netid: str, port: int, directory: str, outputname: str, namespace: str, reset: bool, shots: int): 16 | profiler_symbolname = "Profiler" 17 | parameterlist_symbolname = "ParameterList" 18 | 19 | callstacks = [] 20 | is_capturing = False 21 | logging.info(f"Connecting {netid}:{port}") 22 | if netid == "": 23 | pyads.ads.open_port() 24 | netid = pyads.ads.get_local_address().netid 25 | pyads.ads.close_port() 26 | 27 | plc = pyads.Connection(netid, port) 28 | try: 29 | plc.open() 30 | 31 | for i in range(0, 2): 32 | logging.debug(f"Trying to connect to profiler at {profiler_symbolname}") 33 | try: 34 | plc.read_by_name(f"{profiler_symbolname}.CaptureContinuous", pyads.PLCTYPE_BOOL) 35 | except Exception as e: 36 | if i == 0: 37 | profiler_symbolname = ".".join(filter(None, [namespace, "Profiler"])) 38 | parameterlist_symbolname = ".".join(filter(None, [namespace, "ParameterList"])) 39 | else: 40 | raise Exception(f"Could not resolve entry point for profiler, make sure you PLC running and the Profiler symbol is available at 'Profiler' or '{namespace}.Profiler'") 41 | 42 | # get header data 43 | tasks = plc.read_by_name(f"{profiler_symbolname}.Tasks", pyads.PLCTYPE_SINT) 44 | is_capturing = plc.read_by_name(f"{profiler_symbolname}.CaptureContinuous", pyads.PLCTYPE_BOOL) 45 | capturing_mode = plc.read_by_name(f"{profiler_symbolname}.Mode", pyads.PLCTYPE_INT) 46 | low_threshold = plc.read_by_name(f"{profiler_symbolname}.CaptureCpuTimeLowThreshold", pyads.PLCTYPE_LREAL) 47 | high_threshold = plc.read_by_name(f"{profiler_symbolname}.CaptureCpuTimeHighThreshold", pyads.PLCTYPE_LREAL) 48 | max_cycletime_in_s = max([plc.read_by_name(f"{profiler_symbolname}.CycleTime[{task}]", pyads.PLCTYPE_UDINT) for task in range(1, tasks+1)]) / 10000000.0 49 | pause_duration = 5 * max_cycletime_in_s 50 | 51 | # stop capturing 52 | plc.write_by_name(f"{profiler_symbolname}.CaptureOnce", False, pyads.PLCTYPE_BOOL) 53 | if is_capturing: 54 | plc.write_by_name(f"{profiler_symbolname}.CaptureContinuous", False, pyads.PLCTYPE_BOOL) 55 | logging.info(f"Capturing paused") 56 | 57 | # optionally reset previously taken frames 58 | if reset: 59 | logging.debug(f"Resetting profiler") 60 | trigger_edge(plc, f"{profiler_symbolname}.Reset", pause_duration) 61 | 62 | # optionally capture some frames 63 | if shots > 0: 64 | logging.debug(f"Temporarily configuring profiler for taking singleshots") 65 | plc.write_by_name(f"{profiler_symbolname}.Mode", 0, pyads.PLCTYPE_INT) 66 | plc.write_by_name(f"{profiler_symbolname}.CaptureCpuTimeLowThreshold", 0, pyads.PLCTYPE_LREAL) 67 | plc.write_by_name(f"{profiler_symbolname}.CaptureCpuTimeHighThreshold", 0, pyads.PLCTYPE_LREAL) 68 | time.sleep(pause_duration); 69 | 70 | for i in range(shots): 71 | logging.info(f"Taking snapshot {i+1}/{shots}") 72 | trigger_edge(plc, f"{profiler_symbolname}.CaptureOnce", pause_duration) 73 | 74 | time.sleep(pause_duration); 75 | 76 | # read all the data that the profile already captured 77 | max_stacksize = plc.read_by_name(f"{parameterlist_symbolname}.MAX_STACKSIZE", pyads.PLCTYPE_DINT) 78 | max_frames = plc.read_by_name(f"{parameterlist_symbolname}.MAX_FRAMES", pyads.PLCTYPE_SINT) 79 | frameIndex = plc.read_by_name(f"{profiler_symbolname}.FrameIndex", pyads.PLCTYPE_BYTE) 80 | 81 | logging.info(f"""Fetching callstacks from PLC with 82 | entrypoint = {profiler_symbolname} 83 | max_stacksize = {max_stacksize} 84 | max_frames = {max_frames} 85 | max_cycletime (s) = {max_cycletime_in_s} 86 | tasks = {tasks}""") 87 | 88 | common.create_stack_class(max_stacksize) 89 | counter = 0 90 | for task in range(1, tasks+1): 91 | cycletime = plc.read_by_name(f"{profiler_symbolname}.CycleTime[{task}]", pyads.PLCTYPE_UDINT) 92 | 93 | for frame in range(max_frames): 94 | stacksize = plc.read_by_name(f"{profiler_symbolname}.Meta[{frame}].Size", pyads.PLCTYPE_DINT) 95 | 96 | # abort if we don't get a valid stack out of it 97 | if stacksize > 0 and frame != frameIndex: 98 | stack = plc.read_by_name(f"{profiler_symbolname}.Data[{frame},{task}]", common.Stack) 99 | path = os.path.join(directory, f"{outputname}_frame_{counter}_task_{task}") 100 | callstacks.append(path) 101 | pickle.dump(common.Callstack(cycletime=cycletime, task=task, size=stacksize, stack=stack), open(callstacks[-1], "wb")) 102 | logging.info(f"Fetched Callstack {counter} (Task {task}) with calls {int(stacksize/2)} to {path}") 103 | counter += 1 104 | 105 | except pyads.ADSError as e: 106 | logging.error(e) 107 | finally: 108 | try: 109 | logging.debug(f"Reconfiguring profiler to initial setup") 110 | plc.write_by_name(f"{profiler_symbolname}.Mode", capturing_mode, pyads.PLCTYPE_INT) 111 | plc.write_by_name(f"{profiler_symbolname}.CaptureCpuTimeLowThreshold", low_threshold, pyads.PLCTYPE_LREAL) 112 | plc.write_by_name(f"{profiler_symbolname}.CaptureCpuTimeHighThreshold", high_threshold, pyads.PLCTYPE_LREAL) 113 | plc.write_by_name(f"{profiler_symbolname}.CaptureContinuous", is_capturing, pyads.PLCTYPE_BOOL) 114 | except: 115 | pass 116 | plc.close() 117 | 118 | return callstacks 119 | 120 | 121 | -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/prepare.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import re 6 | import logging 7 | import pickle 8 | from pytwingrind import common 9 | 10 | def create_hash(filepath, fb, method, hashes): 11 | increment = 0 12 | while True: 13 | hstr = filepath + "::" + fb + "::" + method + str(increment) 14 | h = hash(hstr) & 4294967295 15 | if h not in hashes: 16 | hashes[h] = (fb, method) 17 | return h 18 | increment += 1 19 | 20 | def add_guards(filepath, fb_name, hashes): 21 | """add guards to fb and all methods for this file""" 22 | 23 | src = "" 24 | 25 | try: 26 | with open(filepath, "rt", encoding=common.detect_encoding(filepath)) as f: 27 | src = f.read() 28 | 29 | # check if the file should not be guarded due to some token 30 | for t in common.file_skip_tokens: 31 | if t.token in src: 32 | logging.warning(f"Skipping {filepath}, {t.description}") 33 | return 34 | 35 | except UnicodeDecodeError as ex: 36 | print('File {} contains invalid characters, only ascii is supported'.format(filepath)) 37 | raise ex 38 | 39 | nearly = 0 40 | ncallables = 0 41 | 42 | # add guards to functions 43 | functions = re.findall(r'<\/ST>', src, re.S | re.M | re.UNICODE) 44 | if functions: 45 | for m in functions: 46 | function_name = m[1] 47 | body = m[4] 48 | old_body = body 49 | hash = create_hash(filepath, fb_name, function_name, hashes) 50 | 51 | body = '''{tag}Twingrind.Profiler.Push({hash});{tag}\n'''.format(hash=hash, tag=common.profiler_tag) + body 52 | body, i = re.subn(r'RETURN([\s]*?);', 53 | r'''\1{tag}Twingrind.Profiler.Pop({hash});{tag}\1RETURN;'''.format(hash=hash, tag=common.profiler_tag), 54 | body, 0, re.S | re.M | re.UNICODE) 55 | body = body + '''\n{tag}Twingrind.Profiler.Pop({hash});{tag}'''.format(hash=hash, tag=common.profiler_tag) 56 | 57 | nearly += i # two guards are always added 58 | ncallables += 1 59 | 60 | src = src.replace(r''.format(spacer0=m[0], 61 | function_name=function_name, 62 | spacer2=m[2], 63 | spacer3=m[3], 64 | body=old_body), 65 | r''.format(spacer0=m[0], 66 | function_name=function_name, 67 | spacer2=m[2], 68 | spacer3=m[3], 69 | body=body)) 70 | 71 | # add guards to programs 72 | programs = re.findall(r'<\/ST>', src, re.S | re.M | re.UNICODE) 73 | if programs: 74 | for m in programs: 75 | prg_name = m[1] 76 | body = m[4] 77 | old_body = body 78 | hash = create_hash(filepath, fb_name, prg_name, hashes) 79 | 80 | body = '''{tag}Twingrind.Profiler.Push({hash});{tag}\n'''.format(hash=hash, tag=common.profiler_tag) + body 81 | body, i = re.subn(r'RETURN([\s]*?);', 82 | r'''\1{tag}Twingrind.Profiler.Pop({hash});{tag}\1RETURN;'''.format(hash=hash, tag=common.profiler_tag), 83 | body, 0, re.S | re.M | re.UNICODE) 84 | body = body + '''\n{tag}Twingrind.Profiler.Pop({hash});{tag}'''.format(hash=hash, tag=common.profiler_tag) 85 | 86 | nearly += i # two guards are always added 87 | ncallables += 1 88 | 89 | src = src.replace(r''.format(spacer0=m[0], 90 | prg_name=prg_name, 91 | spacer2=m[2], 92 | spacer3=m[3], 93 | body=old_body), 94 | r''.format(spacer0=m[0], 95 | prg_name=prg_name, 96 | spacer2=m[2], 97 | spacer3=m[3], 98 | body=body)) 99 | 100 | # add guards to function blocks 101 | functionblocks = re.findall(r'<\/ST>', src, re.S | re.M | re.UNICODE) 102 | if functionblocks: 103 | for m in functionblocks: 104 | functionblock_name = m[1] 105 | body = m[4] 106 | old_body = body 107 | hash = create_hash(filepath, fb_name, functionblock_name, hashes) 108 | 109 | body = '''{tag}Twingrind.Profiler.Push({hash});{tag}\n'''.format(hash=hash, tag=common.profiler_tag) + body 110 | body, i = re.subn(r'RETURN([\s]*?);', 111 | r'''\1{tag}Twingrind.Profiler.Pop({hash});{tag}RETURN\1;'''.format(hash=hash, tag=common.profiler_tag), 112 | body, 0, re.S | re.M | re.UNICODE) 113 | body = body + '''\n{tag}Twingrind.Profiler.Pop({hash});{tag}'''.format(hash=hash, tag=common.profiler_tag) 114 | 115 | nearly += i # two guards are always added 116 | ncallables += 1 117 | 118 | src = src.replace(r''.format(spacer0=m[0], 119 | functionblock_name=functionblock_name, 120 | spacer2=m[2], 121 | spacer3=m[3], 122 | body=old_body), 123 | r''.format(spacer0=m[0], 124 | functionblock_name=functionblock_name, 125 | spacer2=m[2], 126 | spacer3=m[3], 127 | body=body)) 128 | 129 | # add guards to all methods 130 | methods = re.findall(r'<\/ST>', src, re.S | re.M | re.UNICODE) 131 | if methods: 132 | for m in methods: 133 | if ' ABSTRACT ' in m[2]: 134 | continue 135 | 136 | method_name = m[1] 137 | body = m[3] 138 | old_body = body 139 | hash = create_hash(filepath, fb_name, method_name, hashes) 140 | 141 | body = '''{tag}Twingrind.Profiler.Push({hash});{tag}\n'''.format(hash=hash, tag=common.profiler_tag) + body 142 | body, i = re.subn(r'RETURN([\s]*?);', 143 | r'''\1{tag}Twingrind.Profiler.Pop({hash});{tag}\1RETURN;'''.format(hash=hash, tag=common.profiler_tag), 144 | body, 0, re.S | re.M | re.UNICODE) 145 | body = body + '''\n{tag}Twingrind.Profiler.Pop({hash});{tag}'''.format(hash=hash, tag=common.profiler_tag) 146 | 147 | nearly += i # two guards are always added 148 | ncallables += 1 149 | 150 | src = src.replace(r''.format(spacer0=m[0], 151 | method_name=method_name, 152 | spacer2=m[2], 153 | body=old_body, 154 | fb=fb_name), 155 | r''.format(spacer0=m[0], 156 | method_name=method_name, 157 | spacer2=m[2], 158 | body=body, 159 | fb=fb_name)) 160 | 161 | logging.debug("{}: added {} guards and covered {} paths".format(fb_name, ncallables, nearly+1)) 162 | 163 | with open(filepath, "wt", encoding=common.detect_encoding(filepath)) as g: 164 | g.write(src) 165 | 166 | 167 | 168 | def run(filepath : str, hashmap : str): 169 | hashes = {} 170 | 171 | try: 172 | hashes = pickle.load(open(hashmap, 'rb')) 173 | logging.info('Updating an existing hashfile') 174 | except: 175 | logging.info('Creating a new hashfile') 176 | 177 | for f in common.find_sourcefiles(filepath): 178 | fb_name, _ = os.path.splitext(os.path.basename(f)) 179 | add_guards(f, fb_name, hashes) 180 | 181 | pickle.dump(hashes, open(hashmap, "wb")) 182 | print('Hashmap location={}'.format(hashmap)) 183 | print('Containing {} hashes'.format(len(hashes))) 184 | print('Do not forget to call Twingrind.Profiler() in the *first line* of the *first PRG* in the PLC task!') 185 | print(''' 186 | MAIN.PRG 187 | ------------------------------- 188 | 1 Twingrind.Profiler(); 189 | 2 190 | 3 // 191 | 4 // 192 | 5 // 193 | . 194 | . 195 | ''') 196 | -------------------------------------------------------------------------------- /pytwingrind/pytwingrind/reconstruct.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | import pickle 4 | import inspect 5 | import networkx 6 | import numpy as np 7 | import ctypes 8 | from pytwingrind import common 9 | from enum import IntEnum 10 | from pytwingrind.common import Call 11 | 12 | 13 | class StackRow(IntEnum): 14 | DEPTH = 0 15 | START_100NS = 1 16 | END_100NS = 2 17 | HASH = 3 18 | 19 | 20 | def extract_stack(stack, hashmap): 21 | data = np.zeros((len(stack.calls), 4), dtype=np.uint64) 22 | size = 0 23 | def hilo_to_lword(hi, lo): return ((hi << 32) + lo) 24 | 25 | for call in stack.calls: 26 | data[size] = [call.depth, hilo_to_lword( 27 | call.starthi, call.startlo), hilo_to_lword(call.endhi, call.endlo), call.hash] 28 | 29 | # no more valid timestamps 30 | if np.all(data[size] == 0): 31 | break; 32 | size = size + 1 33 | 34 | logging.info(f"Extracted {int(size/2)} calls") 35 | return data[0:size] 36 | 37 | 38 | def build_graph(network, hashmap, roots, data, sid=-1, eid=-1): 39 | 40 | if sid < 0 and eid < 0: 41 | sid = 0 42 | eid = len(data) 43 | 44 | endid = np.where(np.logical_and(data[sid+1:eid, StackRow.HASH] == data[sid, StackRow.HASH], 45 | data[sid+1:eid, StackRow.DEPTH] == data[sid, StackRow.DEPTH]))[0][0] + sid + 1 46 | dt_100ns = data[endid, StackRow.END_100NS] - data[sid, StackRow.START_100NS] 47 | fb, method = hashmap[data[endid, StackRow.HASH]] if hashmap is not None else (hex(data[endid, StackRow.HASH]), hex(data[endid, StackRow.HASH])) 48 | depth = int(data[endid, StackRow.DEPTH])+1 49 | 50 | roots = roots[0:depth] 51 | parent = roots[-1] 52 | 53 | if network.has_edge(parent, sid): 54 | network[parent][sid]['attr_dict']['calls'] += 1 55 | network[parent][sid]['attr_dict']['dt_100ns'] += [dt_100ns, ] 56 | else: 57 | network.add_edge(parent, sid, attr_dict={ 58 | 'dt_100ns': [dt_100ns, ], 'calls': 1, 'name': '{}::{}'.format(fb, method)}) 59 | if sid+1 != endid: 60 | build_graph(network, hashmap, roots + [sid], data, sid+1, endid) 61 | 62 | if(endid+1 < len(data)) and endid+1 != eid: 63 | build_graph(network, hashmap, roots, data, endid+1, eid) 64 | 65 | 66 | def write_callgrind(network, f, selfcost, node_start="root", node_name=None, depth=0): 67 | 68 | def ch(x, y): return x + '::' + y if len(y) > 0 else x 69 | 70 | # defaulting to cycle time 1 ms if nothing else is specified 71 | if selfcost < 0 and depth == 0: 72 | selfcost = 1000000000 73 | elif selfcost < 0: 74 | raise Exception('selfcost < 0') 75 | 76 | # write header information 77 | if depth == 0: 78 | f.write('events: dt') 79 | f.write('\nfl={}\n'.format(ch('Task', ''))) 80 | f.write('fn={}\n'.format(ch('Task', 'Task'))) 81 | f.write('{} {}\n'.format(1, int(selfcost))) # self cost 82 | 83 | # calculate self costs by substracting the costs of all calls 84 | for _, n in enumerate(network.neighbors(node_start)): 85 | for dt_100ns in network.get_edge_data(node_start, n)['attr_dict']['dt_100ns']: 86 | selfcost -= int(dt_100ns*100) 87 | 88 | if node_name is not None: 89 | node_fb, node_method = node_name.split('::') 90 | f.write('\nfl={}\n'.format(ch(node_fb, ''))) 91 | f.write('fn={}\n'.format(ch(node_fb, node_method))) 92 | f.write('{} {}\n'.format(1, selfcost)) 93 | for i, n in enumerate(network.neighbors(node_start)): 94 | fb, method = network.get_edge_data( 95 | node_start, n)['attr_dict']['name'].split('::') 96 | 97 | calls = network.get_edge_data(node_start, n)['attr_dict']['calls'] 98 | dts = network.get_edge_data(node_start, n)['attr_dict']['dt_100ns'] 99 | 100 | for c in range(calls): 101 | f.write('cfl={}\n'.format(ch(fb, ''))) 102 | f.write('cfn={}\n'.format(ch(fb, method))) 103 | f.write('calls={} {}\n'.format(1, 1)) 104 | f.write('{} {}\n'.format(i, int(dts[c]*100))) 105 | 106 | for i, n in enumerate(network.neighbors(node_start)): 107 | dt_100ns = network.get_edge_data(node_start, n)['attr_dict']['dt_100ns'] 108 | n_name = network.get_edge_data(node_start, n)['attr_dict']['name'] 109 | write_callgrind(network, f, selfcost=int(max(dt_100ns)*100), 110 | node_start=n, node_name=n_name, depth=depth+1) 111 | 112 | 113 | def run(hashmap: str, file: str, dest: str, outputname: str): 114 | 115 | logging.info(f"Reconstructing callstack {file}") 116 | 117 | # unpickling is tricky if the Stack class does not exist yet. The latter 118 | # occurs if we use 'twingrind reconstruct' instead of 'twingrind process'. 119 | # Lets create a "wrong" Stack class that can only hold 1 call, then use 120 | # load the file and use the size, which is stored there, to create 121 | # the correct Stack class 122 | common.create_stack_class(1) 123 | callstack = pickle.load(open(file, 'rb')) 124 | common.create_stack_class(callstack.size) 125 | callstack = pickle.load(open(file, 'rb')) 126 | 127 | logging.debug(f"Callstack size={callstack.size}") 128 | 129 | hm = None 130 | if hashmap is not None: 131 | hm = pickle.load(open(hashmap, 'rb')) 132 | 133 | data = extract_stack(callstack.stack, hm) 134 | n = networkx.DiGraph() 135 | build_graph(n, hm, ['root'], data) 136 | 137 | logging.info(f'Reconstructed {int(len(data) / 2)} calls') 138 | filename = os.path.join( 139 | dest, f"callgrind.{outputname}{os.path.basename(file)}") 140 | with open(filename, 'wt') as f: 141 | write_callgrind(n, f, int(callstack.cycletime * 100)) 142 | logging.info(f'Reconstructed callgrind file to {filename}') 143 | -------------------------------------------------------------------------------- /pytwingrind/requirements.txt: -------------------------------------------------------------------------------- 1 | pyads~=3.3.9 2 | networkx 3 | numpy 4 | chardet 5 | -------------------------------------------------------------------------------- /pytwingrind/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | from os import environ 5 | 6 | setup( 7 | name="pytwingrind", 8 | version=f"0.4.1", 9 | author="Stefan Besler", 10 | author_email="stefan@besler.me", 11 | description="Call-graph profiling for TwinCAT 3.", 12 | long_description="Call-graph profiling for TwinCAT 3.", 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/stefanbesler/twingrind", 15 | packages=find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | ], 19 | python_requires=">=3.8", 20 | entry_points={ 21 | "console_scripts": [ 22 | "twingrind = pytwingrind.__main__:main" 23 | ], 24 | }, 25 | install_requires=list(open('requirements.txt')), 26 | ) 27 | -------------------------------------------------------------------------------- /pytwingrind/twingrind.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from pytwingrind.__main__ import main 4 | 5 | if __name__ == "__main__": 6 | main() --------------------------------------------------------------------------------