├── .gitignore ├── COPYING.GPL3 ├── Readme.md ├── images ├── YAPLCConfig.png ├── YAPLCConfigurableLocation.png ├── YAPLCGroup.png ├── YAPLCPlainLocation.png └── splash.png ├── yaplcconfig ├── YAPLCConfigEditor.py ├── YAPLCConfigFile.py ├── __init__.py ├── yaplcconfig.py ├── yaplcconfig_xsd.xsd └── yaplcparser.py ├── yaplcconnectors ├── YAPLC │ ├── YAPLCObject.py │ ├── YAPLCProto.py │ ├── YaPySerial.py │ └── __init__.py └── __init__.py ├── yaplcext.py ├── yaplcide.py └── yaplctargets ├── XSD_toolchain_yaplc ├── __init__.py ├── __nuc251 ├── XSD ├── __init__.py ├── extensions.cfg └── plc_nuc251_main.c ├── nuc242 ├── XSD ├── __init__.py ├── extensions.cfg └── plc_nuc242_main.c ├── nuc243 ├── XSD ├── __init__.py ├── extensions.cfg └── plc_nuc243_main.c ├── nuc247 ├── XSD ├── __init__.py ├── extensions.cfg └── plc_nuc247_main.c ├── toolchain_yaplc.py ├── toolchain_yaplc_stm32.py └── yaplc ├── XSD ├── __init__.py ├── extensions.cfg └── plc_yaplc_main.c /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | *.pyc 3 | *directory 4 | *~ -------------------------------------------------------------------------------- /COPYING.GPL3: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | Copyright (C) 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | 677 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # YAPLC/IDE 2 | 3 | This is YAPLC IDE based on [Beremiz](www.beremiz.org), it consists of a set of Beremiz extensions and a launcher which adds YAPLC features to Beremiz. 4 | 5 | YAPLC/IDE adds following features: 6 | * a serial port connector for YAPLC, 7 | * a toolchain for YAPLC based on gcc toolchain plugin, 8 | * a configuration plugin, 9 | * a set of target plugins. 10 | 11 | # Contributors 12 | * [Alexander Shaykhrazeev](https://bitbucket.org/aiss83/), 13 | * Paul Beltyukov aka [@shkolnick-kun](https://github.com/shkolnick-kun), 14 | * Radeon Ww . 15 | 16 | -------------------------------------------------------------------------------- /images/YAPLCConfig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nucleron/IDE/c8524faacac9d50cd0376a46dba59792e8978824/images/YAPLCConfig.png -------------------------------------------------------------------------------- /images/YAPLCConfigurableLocation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nucleron/IDE/c8524faacac9d50cd0376a46dba59792e8978824/images/YAPLCConfigurableLocation.png -------------------------------------------------------------------------------- /images/YAPLCGroup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nucleron/IDE/c8524faacac9d50cd0376a46dba59792e8978824/images/YAPLCGroup.png -------------------------------------------------------------------------------- /images/YAPLCPlainLocation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nucleron/IDE/c8524faacac9d50cd0376a46dba59792e8978824/images/YAPLCPlainLocation.png -------------------------------------------------------------------------------- /images/splash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nucleron/IDE/c8524faacac9d50cd0376a46dba59792e8978824/images/splash.png -------------------------------------------------------------------------------- /yaplcconfig/YAPLCConfigEditor.py: -------------------------------------------------------------------------------- 1 | import wx 2 | from editors.ConfTreeNodeEditor import ConfTreeNodeEditor 3 | from editors.CodeFileEditor import VariablesEditor 4 | from controls.VariablePanel import VariablePanel 5 | from PLCControler import LOCATION_CONFNODE, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, \ 6 | LOCATION_VAR_MEMORY 7 | 8 | [ID_YAPLCCONFIGEDITOR, 9 | ] = [wx.NewId() for _init_ctrls in range(1)] 10 | 11 | 12 | class YAPLCConfigEditor(ConfTreeNodeEditor): 13 | ID = ID_YAPLCCONFIGEDITOR 14 | 15 | CODE_EDITOR = None 16 | 17 | CONFNODEEDITOR_TABS = [ 18 | (_("YAPLC Config"), "_create_YAPLCConfigEditor")] 19 | 20 | def _create_YAPLCConfigEditor(self, prnt): 21 | self.ConfigEditor = wx.SplitterWindow(prnt) 22 | self.ConfigEditor.SetMinimumPaneSize(1) 23 | 24 | self.VariablesPanel = VariablesEditor(self.ConfigEditor, 25 | self.ParentWindow, self.Controler) 26 | 27 | if self.CODE_EDITOR is not None: 28 | self.CodeEditor = self.CODE_EDITOR(self.ConfigEditor, 29 | self.ParentWindow, self.Controler) 30 | 31 | self.ConfigEditor.SplitHorizontally(self.VariablesPanel, 32 | self.CodeEditor, 150) 33 | else: 34 | self.ConfigEditor.Initialize(self.VariablesPanel) 35 | 36 | return self.ConfigEditor 37 | 38 | def __init__(self, parent, controler, window): 39 | ConfTreeNodeEditor.__init__(self, parent, controler, window) 40 | 41 | wx.CallAfter(self.ConfigEditor.SetSashPosition, 150) 42 | 43 | def GetBufferState(self): 44 | return self.Controler.GetBufferState() 45 | 46 | def Undo(self): 47 | self.Controler.LoadPrevious() 48 | self.RefreshView() 49 | 50 | def Redo(self): 51 | self.Controler.LoadNext() 52 | self.RefreshView() 53 | 54 | def RefreshView(self): 55 | ConfTreeNodeEditor.RefreshView(self) 56 | 57 | self.VariablesPanel.RefreshView() 58 | 59 | def Find(self, direction, search_params): 60 | pass 61 | -------------------------------------------------------------------------------- /yaplcconfig/YAPLCConfigFile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # This file is part of Beremiz, a Integrated Development Environment for 5 | # programming IEC 61131-3 automates supporting plcopen standard and CanFestival. 6 | # 7 | # Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD 8 | # 9 | # See COPYING file for copyrights details. 10 | # 11 | # This program is free software; you can redistribute it and/or 12 | # modify it under the terms of the GNU General Public License 13 | # as published by the Free Software Foundation; either version 2 14 | # of the License, or (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License 22 | # along with this program; if not, write to the Free Software 23 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 24 | 25 | 26 | import os 27 | import re 28 | import wx 29 | 30 | from copy import deepcopy 31 | from lxml import etree 32 | from xmlclass import GenerateParserFromXSDstring 33 | from PLCControler import UndoBuffer 34 | from ConfigTreeNode import XSDSchemaErrorMessage 35 | from CodeFileTreeNode import CodeFile 36 | from YAPLCConfigEditor import YAPLCConfigEditor 37 | from yaplcparser import YAPLCConfigParser 38 | from yaplcparser import YAPLCParameterType 39 | from PLCControler import LOCATION_CONFNODE, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY, LOCATION_GROUP 40 | from yaplcparser import ParseError 41 | from editors.ConfTreeNodeEditor import ConfTreeNodeEditor 42 | from itertools import product 43 | import shutil 44 | 45 | 46 | def Warn(parent, message, caption='Warning!'): 47 | dlg = wx.MessageDialog(parent, message, caption, wx.OK | wx.ICON_WARNING) 48 | dlg.ShowModal() 49 | dlg.Destroy() 50 | 51 | 52 | class YAPLCTLocation(object): 53 | """ 54 | Represents a location with named parameters 55 | """ 56 | XSD = "" 57 | 58 | EditorType = ConfTreeNodeEditor 59 | 60 | IconFileName = "YAPLCPlainLocation" 61 | 62 | def __init__(self): 63 | pass 64 | 65 | def GetVariableLocationTree(self): 66 | current_location = self.GetCurrentLocation() 67 | 68 | return {"name": self.BaseParams.getName(), 69 | "type": LOCATION_CONFNODE, 70 | "location": "", 71 | "children": [] 72 | } 73 | 74 | def GetIconName(self): 75 | return self.IconFileName 76 | 77 | 78 | """ 79 | Represents locations group with named parameters specified by the user 80 | """ 81 | XSD_LOCATIONS_GROUP = """ 82 | 83 | 84 | 85 | %(attributes)s 86 | 87 | 88 | 89 | """ 90 | 91 | LOC_SECTION_TAG_ELEMENT = "" 92 | LOC_SECTION_RESTRICTION_TAG_ELEMENT = """ 93 | 94 | 95 | 96 | 97 | 98 | 99 | \n""" 100 | LOC_SECTION_ENUMERATION = """\n""" 101 | LOC_SECTION_ENUMERATION_TAG_ELEMENT = """ 102 | 103 | 104 | %(enumerations)s 105 | 106 | 107 | \n""" 108 | 109 | 110 | def PrepareParametrizedXSDNode(name, base, node): 111 | """ 112 | Prepare XSD scheme for location with variable parameters 113 | :param name: Name of the node 114 | :param base: Base class for the node 115 | :param node: Parent node 116 | :return: Prepared XSD node class 117 | """ 118 | params = '' 119 | for p in node.parameters(): 120 | if not p['name']: 121 | continue 122 | 123 | if p['type'] == 'Range': 124 | params += LOC_SECTION_RESTRICTION_TAG_ELEMENT % ({'name': p['name'], 125 | 'opt': 'use="required"', 126 | 'min': p['min'], 127 | 'max': p['max'] 128 | } 129 | ) 130 | 131 | elif p['type'] == 'Items': 132 | enums = "" 133 | for item in p['items']: 134 | enums += LOC_SECTION_ENUMERATION % item 135 | 136 | params += LOC_SECTION_ENUMERATION_TAG_ELEMENT % ({'name': p['name'], 137 | 'opt': 'use="required"', 138 | 'enumerations': enums 139 | }) 140 | 141 | elif p['type'] == 'Number': 142 | params += LOC_SECTION_TAG_ELEMENT % (p['name'], 'xsd:integer', 'use="required"') 143 | 144 | attributes = { 145 | 'name': str(base.__name__), 146 | 'attributes': params 147 | } 148 | 149 | xsd = XSD_LOCATIONS_GROUP % attributes 150 | newNode = type(str(base.__name__) + str(name) + node.name(), (base,), {'XSD': xsd, }) 151 | 152 | return newNode 153 | 154 | 155 | def CreateLocationClass(name, base, node): 156 | """ 157 | Creates location class 158 | :param name: Name of location 159 | :param base: Base class of location 160 | :param node: Parent node of location 161 | :return: Prepared XSD class for location 162 | """ 163 | if node.parametrized(): 164 | newNode = PrepareParametrizedXSDNode(name, base, node) 165 | setattr(newNode, 'IconFileName', 'YAPLCConfigurableLocation') 166 | else: 167 | newNode = None 168 | 169 | return newNode 170 | 171 | 172 | def CreateLocationsGroupClass(name, base, node): 173 | """ 174 | Create group location class 175 | :param name: Name of location group 176 | :param base: Base class of location group 177 | :param node: Parent node of location class 178 | :return: Prepared XSD class for location group 179 | """ 180 | if node and node.parametrized(): 181 | NewGroup = PrepareParametrizedXSDNode(name, base, node) 182 | else: 183 | NewGroup = base 184 | setattr(NewGroup, 'XSD', None) 185 | 186 | return NewGroup 187 | 188 | 189 | def CreateGroupNode(node, group, name): 190 | if group.parametrized() or group.hasParametrized(): 191 | groupClass = CreateLocationsGroupClass(name, YAPLCTLocationsGroup, group) 192 | 193 | if group.parametrized(): 194 | grp = (group.name(), groupClass, group.name()) 195 | if grp not in node.CTNChildrenTypes: 196 | node.CTNChildrenTypes.append(grp) 197 | elif group.hasParametrized(): 198 | params = JoinParameters(group.parameters()) 199 | for s in params: 200 | sName = '%s.%s' % (group.name(), '.'.join(str(x) for x in s)) 201 | grp = (sName, groupClass, sName) 202 | if grp not in node.CTNChildrenTypes: 203 | node.CTNChildrenTypes.append(grp) 204 | 205 | 206 | class YAPLCTLocationsGroup(object): 207 | 208 | EditorType = ConfTreeNodeEditor 209 | 210 | XSD = None 211 | 212 | def __init__(self): 213 | 214 | """ 215 | We are have to use different children for nodes 216 | """ 217 | self.CTNChildrenTypes = [] 218 | name = self.CTNType 219 | 220 | parser = getattr(self.CTNParent, 'YAPLCParser', None) 221 | if parser is not None: 222 | self.YAPLCParser = parser 223 | 224 | # let's parse some staff 225 | if name.find('.') > 0: 226 | group = parser.getgroup(name[:name.find('.')]) 227 | else: 228 | group = parser.getgroup(name) 229 | 230 | if group is None: 231 | raise ParseError("Group %s is None" % name) 232 | 233 | for sg in group.children(): 234 | CreateGroupNode(self, sg, name) 235 | 236 | # fill with locations 237 | for loc in group.locations(): 238 | if loc.parametrized(): 239 | locClass = CreateLocationClass(name, YAPLCTLocation, loc) 240 | if loc.descriptive(): 241 | ll = (loc.descriptive(), locClass, loc.name()) 242 | else: 243 | ll = (loc.name(), locClass, loc.name()) 244 | if ll not in self.CTNChildrenTypes: 245 | self.CTNChildrenTypes.append(ll) 246 | 247 | def GetIconName(self): 248 | return "YAPLCGroup" 249 | 250 | 251 | class YAPLConfigFile(CodeFile): 252 | """ 253 | YAPLC Template Configuration file representation class 254 | Creates instance of root YAPLC node and nested child nodes, that represents groups and locations. 255 | """ 256 | 257 | CODEFILE_NAME = "YAPLCFile" 258 | SECTIONS_NAMES = ["globals", 259 | "locations" 260 | ] 261 | 262 | EditorType = YAPLCConfigEditor 263 | 264 | """ 265 | IEC Types mappings to internal types of YAPLC 266 | """ 267 | IECTypes = {'X': 'BOOL', 268 | 'B': 'BYTE', 269 | 'W': 'WORD', 270 | 'D': 'DWORD', 271 | 'L': 'LWORD', 272 | 'S': 'STRING' 273 | } 274 | 275 | """ 276 | YAPLC Types size conversions 277 | """ 278 | SizeConversion = {'X': 1, 'B': 8, 'W': 16, 'D': 32, 'L': 64} 279 | 280 | """ 281 | YAPLC Locations mapping 282 | """ 283 | LocationTypes = {'I': LOCATION_VAR_INPUT, 284 | 'Q': LOCATION_VAR_OUTPUT, 285 | 'M': LOCATION_VAR_MEMORY 286 | } 287 | 288 | def __init__(self): 289 | 290 | """ 291 | YAPLC SubNodes to ProjectController 292 | """ 293 | self.CTNChildrenTypes = [] 294 | 295 | self.ConfigTemplatePath = None 296 | 297 | CodeFile.__init__(self) 298 | 299 | parent = self.GetCTRoot() 300 | if parent is not None: 301 | target = parent.GetTarget().getcontent().getLocalTag() 302 | base_path = os.path.dirname(__file__) 303 | self.ConfigTemplatePath = os.path.join(base_path, '..', 'yaplctargets', target, 'extensions.cfg') 304 | 305 | if not os.path.isfile(self.ConfigTemplatePath): 306 | Warn(None, _("Target doesn't support YAPLC features."), _("Warning")) 307 | self.GetCTRoot().logger.write_error( 308 | _("Couldn't create %s node.\n") % self.CTNName()) 309 | else: 310 | try: 311 | error = None 312 | # let's add template variables if we start first time 313 | if self.ConfigTemplatePath is not None: 314 | self.YAPLCParser = YAPLCConfigParser() 315 | self.YAPLCParser.fparse(self.ConfigTemplatePath) 316 | self.FillFromTemplate() 317 | else: 318 | self.GetCTRoot().logger.write_error(_("Couldn't load templates path for target %s\n") % 319 | parent.GetTarget().getcontent().getLocalTag()) 320 | except ParseError as pe: 321 | self.GetCTRoot().logger.write_error( 322 | _("Couldn't read %s file because: %s\n") % (self.CTNName(), pe.message())) 323 | error = unicode(pe.message()) 324 | 325 | except Exception, exc: 326 | error = unicode(exc) 327 | 328 | if error is not None: 329 | self.GetCTRoot().logger.write_error( 330 | _("Couldn't import old %s file.") % self.CTNName()) 331 | 332 | def FillFromTemplate(self): 333 | for group in self.YAPLCParser.groups(): 334 | CreateGroupNode(self, group, 'YAPLCTLocationsGroup') 335 | 336 | def GetBaseTypes(self): 337 | return self.GetCTRoot().GetBaseTypes() 338 | 339 | def GetDataTypes(self, basetypes=False): 340 | return self.GetCTRoot().GetDataTypes(basetypes=basetypes) 341 | 342 | def GenerateNewName(self, format, start_idx): 343 | return self.GetCTRoot().GenerateNewName( 344 | None, None, format, start_idx, 345 | dict([(var.getname().upper(), True) 346 | for var in self.CodeFile.variables.getvariable()])) 347 | 348 | def CodeFileName(self): 349 | return os.path.join(self.CTNPath(), "yaplcconfig.xml") 350 | 351 | def FindParametrizedGroupParameters(self, name, baseNode=None): 352 | result = dict() 353 | 354 | if not baseNode: 355 | baseNode = self 356 | 357 | for child in baseNode.IECSortedChildren(): 358 | if child.CTNType == name: 359 | grp = self.YAPLCParser.getgroup(child.CTNType) 360 | if grp is not None: 361 | if grp.parametrized(): 362 | for p in grp.parameters(): 363 | v = getattr(child.YAPLCTLocationsGroup, p['name']) 364 | if v is not None: 365 | result[p['name']] = v 366 | return result 367 | else: 368 | result = self.FindParametrizedGroupParameters(name, child) 369 | 370 | return result 371 | 372 | def GetLocationsForGroup(self, group, parser, parent=None, args=[]): 373 | locations = [] 374 | 375 | for grp in group.children(): 376 | if parent: 377 | if grp.parametrized(): 378 | result = filter(lambda x: x['name'].startswith(grp.name()), parent['children']) 379 | if result: 380 | lst = list(args) 381 | lst.append(result[0]['location']) # Add my current location 382 | result[0]['children'] += self.GetLocationsForGroup(grp, parser, result[0], lst) 383 | else: 384 | combined = JoinParameters(grp.parameters()) 385 | 386 | for line in combined: 387 | groupLocation = '.'.join(str(x) for x in line) 388 | lname = '{0}.{1}'.format(grp.name(), groupLocation) 389 | 390 | result = filter(lambda x: x['name'].startswith(lname), parent['children']) 391 | if result: 392 | lst = list() 393 | lst.append(result[0]['location']) 394 | result[0]['children'] += self.GetLocationsForGroup(grp, parser, result[0], args + lst) 395 | else: 396 | locations.append({ 397 | "name": lname, 398 | "type": LOCATION_GROUP, 399 | "size": 0, 400 | "IEC_type": '', 401 | "var_name": '', 402 | "location": "%s" % groupLocation, 403 | "description": "", 404 | "children": self.GetLocationsForGroup(grp, parser, None, args + list(line))}) 405 | 406 | else: 407 | if grp.parametrized(): # Parametrized groups evaluated here 408 | continue 409 | 410 | combined = JoinParameters(grp.parameters()) 411 | 412 | for line in combined: 413 | groupLocation = '.'.join(str(x) for x in line) 414 | lname = '{0}.{1}'.format(grp.name(), groupLocation) 415 | 416 | locations.append({ 417 | "name": lname, 418 | "type": LOCATION_GROUP, 419 | "size": 0, 420 | "IEC_type": '', 421 | "var_name": '', 422 | "location": "%s" % groupLocation, 423 | "description": "", 424 | "children": self.GetLocationsForGroup(grp, parser, None, args + list(line))}) 425 | 426 | # Locations processing 427 | if group.parametrized() and not parent: 428 | pass 429 | else: 430 | 431 | for loc in group.locations(): 432 | if loc.parametrized(): 433 | continue 434 | 435 | combLocs = JoinParameters(loc.parameters()) 436 | 437 | for line in combLocs: 438 | indexes = args + list(line) 439 | lname = '{0}'.format(loc.name() + '.'.join(str(x) for x in indexes)) 440 | location = lname[1:] 441 | 442 | locations.append({ 443 | "name": '%%%s' % lname, 444 | "type": self.LocationTypes[loc.type()], 445 | "size": self.SizeConversion[loc.datatype()], 446 | "IEC_type": self.IECTypes[loc.datatype()], 447 | "var_name": '_%s' % lname.replace('.', '_'), 448 | "location": location, 449 | "description": "", 450 | "children": []}) 451 | 452 | return locations 453 | 454 | def GetLocationsForNode(self, group, parser, node, args=[]): 455 | locations = [] 456 | 457 | for child in node.IECSortedChildren(): 458 | if child.CTNType.find('.') > 0: 459 | name = child.CTNType[:child.CTNType.find('.')] 460 | suffix = child.CTNType[child.CTNType.find('.') + 1:] 461 | else: 462 | name = child.CTNType 463 | grp = parser.getgroup(name) 464 | if grp: 465 | gids = dict() 466 | if grp.parametrized(): 467 | for p in grp.parameters(): 468 | if not p['name']: 469 | continue 470 | v = getattr(child.YAPLCTLocationsGroup, p['name']) 471 | if v is not None: 472 | gids[p['name']] = v 473 | 474 | if gids: 475 | groups = JoinParameters(grp.parameters(), gids) 476 | else: 477 | groups = list() 478 | groups.append(suffix.split('.')) 479 | 480 | for g in groups: 481 | subLocations = self.GetLocationsForNode(grp, parser, child, args + list(g)) 482 | 483 | if subLocations or grp.parametrized(): 484 | locationString = '%s' % '.'.join(str(x) for x in g) 485 | locations.append({ 486 | "name": '%s.%s' % (name, locationString), 487 | "type": LOCATION_GROUP, 488 | "size": 0, 489 | "IEC_type": '', 490 | "var_name": '', 491 | "location": "%s" % locationString, 492 | "description": "", 493 | "children": subLocations}) 494 | else: 495 | loc = group.getlocation(child.CTNType) 496 | locs = dict() 497 | for p in loc.parameters(): 498 | if p['name']: 499 | v = getattr(child.YAPLCTLocation, p['name']) 500 | locs[p['name']] = v 501 | 502 | params = JoinParameters(loc.parameters(), locs) 503 | 504 | for pp in params: 505 | idx = args + list(pp) 506 | vname = '_%s%s' % (loc.name(), '.'.join(str(x) for x in idx)) 507 | vname = vname.replace('.', '_') 508 | locations.append({ 509 | "name": '%%%s' % (str(loc.name()) + '.'.join(str(x) for x in idx)), 510 | "type": self.LocationTypes[loc.type()], 511 | "size": self.SizeConversion[loc.datatype()], 512 | "IEC_type": self.IECTypes[loc.datatype()], 513 | "var_name": vname, 514 | "location": '%s%s' % (loc.name()[1:], '.'.join(str(x) for x in idx)), 515 | "description": "", 516 | "children": []}) 517 | 518 | return locations 519 | 520 | def GetVariableLocationTree(self): 521 | current_location = self.GetCurrentLocation() 522 | 523 | locations = [] 524 | 525 | if self.YAPLCParser is not None: 526 | parser = self.YAPLCParser 527 | 528 | locations += self.GetLocationsForNode(None, parser, self) 529 | 530 | # extract static locations and groups 531 | for group in parser.groups(): 532 | # if group.parametrized(): 533 | # continue 534 | 535 | result = filter(lambda x: x['name'].startswith(group.name()), locations) 536 | if result: 537 | lst = list() 538 | lst.append(result[0]['location']) 539 | result[0]['children'] += self.GetLocationsForGroup(group, parser, result[0], lst) 540 | else: 541 | groups = JoinParameters(group.parameters()) 542 | 543 | for g in groups: 544 | groupLocation = "%s" % '.'.join(str(x) for x in g) 545 | locations.append({ 546 | "name": group.name() + '.' + groupLocation, 547 | "type": LOCATION_GROUP, 548 | "size": 0, 549 | "IEC_type": '', 550 | "var_name": '', 551 | "location": groupLocation, 552 | "description": "", 553 | "children": self.GetLocationsForGroup(group, parser, None, list(g))}) 554 | 555 | return {"name": self.BaseParams.getName(), 556 | "type": LOCATION_CONFNODE, 557 | "location": ".".join([str(i) for i in current_location]) + ".x", 558 | "children": locations 559 | } 560 | 561 | def SetTextParts(self, parts): 562 | for section in self.SECTIONS_NAMES: 563 | section_code = parts.get(section) 564 | if section_code is not None: 565 | getattr(self.CodeFile, section).setanyText(section_code) 566 | 567 | def GetTextParts(self): 568 | return dict([(section, getattr(self.CodeFile, section).getanyText()) 569 | for section in self.SECTIONS_NAMES]) 570 | 571 | def CTNTestModified(self): 572 | return self.ChangesToSave or not self.CodeFileIsSaved() 573 | 574 | def OnCTNSave(self, from_project_path=None): 575 | filepath = self.CodeFileName() 576 | 577 | xmlfile = open(filepath, "w") 578 | xmlfile.write(etree.tostring( 579 | self.CodeFile, 580 | pretty_print=True, 581 | xml_declaration=True, 582 | encoding='utf-8')) 583 | xmlfile.close() 584 | 585 | self.MarkCodeFileAsSaved() 586 | return True 587 | 588 | def CTNGlobalInstances(self): 589 | variables = self.CodeFileVariables(self.CodeFile) 590 | ret = [(variable.getname(), 591 | variable.gettype(), 592 | variable.getinitial()) 593 | for variable in variables] 594 | ret.extend([("On" + variable.getname() + "Change", "python_poll", "") 595 | for variable in variables 596 | if variable.getonchange()]) 597 | return ret 598 | 599 | # ------------------------------------------------------------------------------- 600 | # Current Buffering Management Functions 601 | # ------------------------------------------------------------------------------- 602 | 603 | """ 604 | Return a copy of the codefile model 605 | """ 606 | 607 | def Copy(self, model): 608 | return deepcopy(model) 609 | 610 | def CreateCodeFileBuffer(self, saved): 611 | self.Buffering = False 612 | self.CodeFileBuffer = UndoBuffer(self.CodeFileParser.Dumps(self.CodeFile), saved) 613 | 614 | def BufferCodeFile(self): 615 | self.CodeFileBuffer.Buffering(self.CodeFileParser.Dumps(self.CodeFile)) 616 | 617 | def StartBuffering(self): 618 | self.Buffering = True 619 | 620 | def EndBuffering(self): 621 | if self.Buffering: 622 | self.CodeFileBuffer.Buffering(self.CodeFileParser.Dumps(self.CodeFile)) 623 | self.Buffering = False 624 | 625 | def MarkCodeFileAsSaved(self): 626 | self.EndBuffering() 627 | self.CodeFileBuffer.CurrentSaved() 628 | 629 | def CodeFileIsSaved(self): 630 | return self.CodeFileBuffer.IsCurrentSaved() and not self.Buffering 631 | 632 | def LoadPrevious(self): 633 | self.EndBuffering() 634 | self.CodeFile = self.CodeFileParser.Loads(self.CodeFileBuffer.Previous()) 635 | 636 | def LoadNext(self): 637 | self.CodeFile = self.CodeFileParser.Loads(self.CodeFileBuffer.Next()) 638 | 639 | def GetBufferState(self): 640 | first = self.CodeFileBuffer.IsFirst() and not self.Buffering 641 | last = self.CodeFileBuffer.IsLast() 642 | return not first, not last 643 | 644 | 645 | def JoinParameters(parameters, args={}): 646 | lists = list() 647 | for p in parameters: 648 | if p['name'] and p['name'] in args: 649 | lst = list() 650 | lst.append(args[p['name']]) 651 | lists.append(lst) 652 | else: 653 | if p['type'] == 'Number': 654 | # add value to all lines 655 | lst = list() 656 | lst.append(p['value']) 657 | lists.append(lst) 658 | 659 | elif p['type'] == 'Range': 660 | lst = list() 661 | for v in range(p['min'], p['max'] + 1): 662 | lst.append(v) 663 | 664 | lists.append(lst) 665 | 666 | elif p['type'] == 'Items': 667 | lst = list() 668 | for v in p['items']: 669 | lst.append(v) 670 | lists.append(lst) 671 | 672 | return product(*lists) 673 | -------------------------------------------------------------------------------- /yaplcconfig/__init__.py: -------------------------------------------------------------------------------- 1 | from yaplcconfig import * 2 | -------------------------------------------------------------------------------- /yaplcconfig/yaplcconfig.py: -------------------------------------------------------------------------------- 1 | from ConfigTreeNode import ConfigTreeNode 2 | from YAPLCConfigFile import YAPLConfigFile 3 | import os, sys, shutil 4 | 5 | 6 | base_folder = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) 7 | 8 | 9 | class YAPLCNodeConfig(YAPLConfigFile): 10 | 11 | def GetIconName(self): 12 | return "YAPLCConfig" 13 | -------------------------------------------------------------------------------- /yaplcconfig/yaplcconfig_xsd.xsd: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | Formatted text according to parts of XHTML 1.1 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /yaplcconfig/yaplcparser.py: -------------------------------------------------------------------------------- 1 | import shlex 2 | import collections 3 | import os 4 | from string import find 5 | from string import split 6 | 7 | """ 8 | TODO: Syntax extensions 9 | 1. Enumerated parameters split by ',' sign placed inside square brackets. 10 | 2. Regions doesn't generate all values when created, but operates with min/max ranges. 11 | 3. Single value parameters interprets like a group id. 12 | 4. Range group parameters interprets like a tuple of groups. 13 | 5. Text labels are enclosed with quotes inside square brackets after value split by a column from value. 14 | 6. Correct group id detection. 15 | 7. Use meta-class to create more accurate and extensible parameters class. 16 | 8. Locations may have descriptive name. Optional for plain locations and required for parametrized. 17 | """ 18 | 19 | """ 20 | YAPLC locations: Input, Memory, Output(Q) 21 | """ 22 | YAPLCLocationTypes = ['I', 'M', 'Q'] 23 | 24 | """ 25 | YAPLC locations data types: bool, byte, word, double-word, long, string 26 | """ 27 | YAPLCLocationDataTypes = ['X', 'B', 'W', 'D', 'L', 'S'] 28 | 29 | """ 30 | YAPLC location parameter types 31 | """ 32 | YAPLCParameterType = {'Number': 0, 'Range': 1, 'Items': 2} 33 | 34 | """ 35 | """ 36 | YAPLCNameIllegal = ['.', ',', '"', '*', ':', '#', '@', '!', '(', ')', '{', '}'] 37 | 38 | 39 | class ParseError(BaseException): 40 | """ Exception reports parsing errors when processing YAPLC template files """ 41 | 42 | def __init__(self, message=None): 43 | self._message = message 44 | 45 | def message(self): 46 | return self._message 47 | 48 | 49 | class YAPLCLocationBase: 50 | 51 | def __init__(self): 52 | self._parameters = list() 53 | self._parametrized = False 54 | 55 | def addParameters(self, values, name=""): 56 | 57 | if find(values, '..') >= 0: 58 | # range of channels 59 | bounds = split(values, '..') 60 | 61 | if len(bounds) != 2: 62 | raise ParseError(_("Wrong range syntax")) 63 | 64 | if not bounds[0].isdigit() or not bounds[1].isdigit(): 65 | raise ParseError(_("Incorrect bounds format %s..%s") % bounds[0] % bounds[1]) 66 | 67 | lbound = int(bounds[0]) 68 | rbound = int(bounds[1]) 69 | 70 | self._parameters.append({"name": name, 71 | "type": 'Range', 72 | "min": lbound, 73 | "max": rbound 74 | }) 75 | 76 | elif find(values, ',') >= 0: 77 | items = split(values, ',') 78 | 79 | self._parameters.append({"name": name, 80 | "type": 'Items', 81 | "items": items 82 | }) 83 | else: 84 | self._parameters.append({"name": name, 85 | "type": 'Number', 86 | "value": values 87 | }) 88 | 89 | def parameters(self): 90 | return self._parameters 91 | 92 | def parametrized(self): 93 | return self._parametrized 94 | 95 | 96 | class YAPLCLocation(YAPLCLocationBase): 97 | """ 98 | YAPLC location abstraction to represent an location described by syntax 99 | """ 100 | 101 | def __init__(self, typestr, group, unique=False, *args): 102 | 103 | YAPLCLocationBase.__init__(self) 104 | 105 | self._descriptive = None 106 | 107 | if len(typestr) != 2: 108 | raise ParseError(_("Incorrect type coding %s") % typestr) 109 | 110 | if typestr[0] not in YAPLCLocationTypes: 111 | raise ParseError(_("Type %s not recognized") % typestr[0]) 112 | else: 113 | self._type = typestr[0] 114 | 115 | if typestr[1] not in YAPLCLocationDataTypes: 116 | raise ParseError(_("Data type %s not recognized") % typestr[1]) 117 | else: 118 | self._datatype = typestr[1] 119 | 120 | for p in args: 121 | if str(p).startswith('['): 122 | # this is named parameter 123 | param = str(p).rstrip(']').lstrip('[') 124 | name, value = param.split(':') 125 | # print name, value 126 | self.addParameters(value, name) 127 | self._parametrized = True 128 | if not self._descriptive: 129 | raise ParseError(_("Parametrized locations requires descriptive name")) 130 | elif str(p).startswith('"'): 131 | # descriptive name of location 132 | self._descriptive = str(p).rstrip('"').lstrip('"') 133 | if any(s in self._descriptive for s in YAPLCNameIllegal): 134 | raise ParseError(_("Illegal symbol in group's name: %s") % self._descriptive) 135 | elif str(p).isdigit(): 136 | self.addParameters(p) 137 | else: 138 | # this is the unnamed range or items 139 | self.addParameters(p) 140 | 141 | self._unique = unique 142 | self._group = group # group to this location 143 | 144 | def type(self): 145 | return self._type 146 | 147 | def datatype(self): 148 | return self._datatype 149 | 150 | def unique(self): 151 | return self._unique 152 | 153 | def descriptive(self): 154 | return self._descriptive 155 | 156 | def __str__(self): 157 | return '{0}{1}'.format(self._type, self._datatype) 158 | 159 | def name(self): 160 | return self.__str__() 161 | 162 | def __repr__(self): 163 | return self.__str__() 164 | 165 | 166 | class YAPLCGroup(YAPLCLocationBase): 167 | """ 168 | YAPLC group abstraction allow to store info about group extracted from DSL 169 | """ 170 | 171 | def __init__(self, name, values=None, unique=False, parent=None, *args): 172 | 173 | YAPLCLocationBase.__init__(self) 174 | 175 | self._name = str(name).rstrip('"').lstrip('"') 176 | 177 | if any(s in self._name for s in YAPLCNameIllegal): 178 | raise ParseError(_("Illegal symbol in group's name: %s") % self._name) 179 | 180 | if len(values) > 1: 181 | raise ParseError(_("Too many parameters for group: %s") % self._name) 182 | 183 | for v in values: 184 | if str(v).startswith('['): 185 | param = str(v).rstrip(']').lstrip('[') 186 | name, value = param.split(':') 187 | self.addParameters(value, name) 188 | self._parametrized = True 189 | else: 190 | self.addParameters(v) 191 | 192 | self._unique = unique 193 | self._locations = list() 194 | self._parent = parent 195 | self._children = list() 196 | 197 | def name(self): 198 | return self._name 199 | 200 | def group(self): 201 | return None 202 | 203 | def append(self, location): 204 | self._locations.append(location) 205 | 206 | def locations(self): 207 | return self._locations 208 | 209 | def getlocation(self, name): 210 | for loc in self._locations: 211 | if loc.name() == name or loc.descriptive() == name: 212 | return loc 213 | 214 | return None 215 | 216 | def children(self): 217 | return self._children 218 | 219 | def unique(self): 220 | return self._unique 221 | 222 | def parent(self): 223 | return self._parent 224 | 225 | def hasParametrized(self): 226 | for child in self._children: 227 | if child.parametrized(): 228 | return True 229 | else: 230 | return child.hasParametrized() 231 | 232 | for loc in self._locations: 233 | if loc.parametrized(): 234 | return True 235 | 236 | return False 237 | 238 | def addsubgroup(self, group): 239 | self._children.append(group) 240 | 241 | 242 | # YAPLC Extensions configuration parser 243 | class YAPLCConfigParser: 244 | 245 | class yaplcparser(shlex.shlex): 246 | 247 | def __init__(self, instream=None, infile=None, posix=False): 248 | shlex.shlex.__init__(self, instream=instream, infile=infile, posix=posix) 249 | # add this tu usual shlex parser 250 | self.brackets = "[]" 251 | 252 | def read_token(self): 253 | quoted = False 254 | enclosed = False 255 | escapedstate = ' ' 256 | while True: 257 | nextchar = self.instream.read(1) 258 | if nextchar == '\n': 259 | self.lineno += 1 260 | if self.debug >= 3: 261 | print "shlex: in state", repr(self.state), \ 262 | "I see character:", repr(nextchar) 263 | if self.state is None: 264 | self.token = '' # past end of file 265 | break 266 | elif self.state == ' ': 267 | if not nextchar: 268 | self.state = None # end of file 269 | break 270 | elif nextchar in self.whitespace: 271 | if self.debug >= 2: 272 | print "shlex: I see whitespace in whitespace state" 273 | if self.token or (self.posix and quoted) or (self.posix and enclosed): 274 | break # emit current token 275 | else: 276 | continue 277 | elif nextchar in self.commenters: 278 | self.instream.readline() 279 | self.lineno += 1 280 | elif self.posix and nextchar in self.escape: 281 | escapedstate = 'a' 282 | self.state = nextchar 283 | elif nextchar in self.wordchars: 284 | self.token = nextchar 285 | self.state = 'a' 286 | elif nextchar in self.quotes: 287 | if not self.posix: 288 | self.token = nextchar 289 | self.state = nextchar 290 | elif self.whitespace_split: 291 | self.token = nextchar 292 | self.state = 'a' 293 | elif nextchar in self.brackets: 294 | self.token = nextchar 295 | self.state = '[' 296 | else: 297 | self.token = nextchar 298 | if self.token or (self.posix and quoted) or (self.posix and enclosed): 299 | break # emit current token 300 | else: 301 | continue 302 | elif self.state in self.quotes: 303 | quoted = True 304 | if not nextchar: # end of file 305 | if self.debug >= 2: 306 | print "shlex: I see EOF in quotes state" 307 | # XXX what error should be raised here? 308 | raise ValueError, "No closing quotation" 309 | if nextchar == self.state: 310 | if not self.posix: 311 | self.token = self.token + nextchar 312 | self.state = ' ' 313 | break 314 | else: 315 | self.state = 'a' 316 | elif self.posix and nextchar in self.escape and \ 317 | self.state in self.escapedquotes: 318 | escapedstate = self.state 319 | self.state = nextchar 320 | else: 321 | self.token = self.token + nextchar 322 | elif self.state in self.brackets: 323 | enclosed = True 324 | if not nextchar: # end of file 325 | if self.debug >= 2: 326 | print "shlex: I see EOF in quotes state" 327 | # XXX what error should be raised here? 328 | raise ValueError, "No closing bracket" 329 | if nextchar == ']': # closing bracket 330 | if not self.posix: 331 | self.token = self.token + nextchar 332 | self.state = ' ' 333 | break 334 | else: 335 | self.state = 'a' 336 | elif self.posix and nextchar in self.escape and \ 337 | self.state in self.escapedquotes: 338 | escapedstate = self.state 339 | self.state = nextchar 340 | else: 341 | self.token = self.token + nextchar 342 | elif self.state in self.escape: 343 | if not nextchar: # end of file 344 | if self.debug >= 2: 345 | print "shlex: I see EOF in escape state" 346 | # XXX what error should be raised here? 347 | raise ValueError, "No escaped character" 348 | # In posix shells, only the quote itself or the escape 349 | # character may be escaped within quotes. 350 | if escapedstate in self.quotes and \ 351 | nextchar != self.state and nextchar != escapedstate: 352 | self.token = self.token + self.state 353 | self.token = self.token + nextchar 354 | self.state = escapedstate 355 | elif self.state == 'a': 356 | if not nextchar: 357 | self.state = None # end of file 358 | break 359 | elif nextchar in self.whitespace: 360 | if self.debug >= 2: 361 | print "shlex: I see whitespace in word state" 362 | self.state = ' ' 363 | if self.token or (self.posix and quoted) or (self.posix and enclosed): 364 | break # emit current token 365 | else: 366 | continue 367 | elif nextchar in self.commenters: 368 | self.instream.readline() 369 | self.lineno += 1 370 | if self.posix: 371 | self.state = ' ' 372 | if self.token or (self.posix and quoted) or (self.posix and enclosed): 373 | break # emit current token 374 | else: 375 | continue 376 | elif self.posix and nextchar in self.quotes: 377 | self.state = nextchar 378 | elif self.posix and nextchar in self.escape: 379 | escapedstate = 'a' 380 | self.state = nextchar 381 | elif nextchar in self.wordchars or nextchar in self.quotes \ 382 | or self.whitespace_split or nextchar in self.brackets: 383 | self.token = self.token + nextchar 384 | else: 385 | self.pushback.appendleft(nextchar) 386 | if self.debug >= 2: 387 | print "shlex: I see punctuation in word state" 388 | self.state = ' ' 389 | if self.token: 390 | break # emit current token 391 | else: 392 | continue 393 | result = self.token 394 | self.token = '' 395 | if self.posix and not quoted and not enclosed and result == '': 396 | result = None 397 | if self.debug > 1: 398 | if result: 399 | print "shlex: raw token=" + repr(result) 400 | else: 401 | print "shlex: raw token=EOF" 402 | return result 403 | 404 | @staticmethod 405 | def parseline(line): 406 | """Parse single line read from settings file 407 | 408 | :param line: Line of text (string) to parse 409 | :return: list of tokens split from line 410 | """ 411 | lexer = YAPLCConfigParser.yaplcparser(line) 412 | lexer.commenters = '#' 413 | lexer.wordchars += '.():,' 414 | 415 | return list(lexer) 416 | 417 | def groups(self): 418 | """Get groups parsed from configuration file 419 | 420 | :return: list of groups keys 421 | """ 422 | return self._groups.values() 423 | 424 | def getgroup(self, name): 425 | 426 | def findgroup(name, group): 427 | if name == group.name(): 428 | return group 429 | 430 | for g in group.children(): 431 | if g.name() == name: 432 | return g 433 | 434 | if len(g.children()) > 0: 435 | return findgroup(name, g) 436 | 437 | return None 438 | 439 | group = None 440 | if name in self._groups: 441 | # in root groups 442 | group = self._groups[name] 443 | else: 444 | # in nested groups 445 | for g in self._groups.values(): 446 | group = findgroup(name, g) 447 | if group is not None: 448 | break 449 | 450 | return group 451 | 452 | def getlocations(self, group): 453 | """Get locations of specified group 454 | 455 | :param group: Group of locations 456 | :return: Locations list 457 | """ 458 | if group in self._groups: 459 | return self._groups[group].locations() 460 | else: 461 | return None 462 | 463 | def addgroup(self, group): 464 | if group not in self._groups: 465 | self._groups[group.name()] = group 466 | 467 | def addlocation(self, group, location): 468 | if group in self._groups: 469 | self._groups.get(group).append(location) 470 | 471 | def __init__(self, dict_type=collections.defaultdict): 472 | self._dict = dict_type 473 | self._groups = self._dict() 474 | 475 | def fparse(self, fileName = None): 476 | if fileName is not None: 477 | try: 478 | with open(fileName) as f: 479 | currentGroup = None 480 | for line in f: 481 | tokens = YAPLCConfigParser.parseline(line) 482 | 483 | if tokens: 484 | if tokens[0] == 'UGRP' or tokens[0] == 'GRP': 485 | rest = [] 486 | 487 | if len(tokens) < 3: 488 | raise ParseError("Arguments number for group less than required") 489 | elif len(tokens) >= 3: 490 | rest = tokens[2:] 491 | 492 | # begin of the unique group/end of previous 493 | if tokens[1] in self._groups: 494 | if self._groups[tokens[1]].unique(): 495 | raise ParseError(_("Has the same unique group %s") % tokens[1]) 496 | 497 | if currentGroup is not None: 498 | grp = YAPLCGroup(tokens[1], rest, (tokens[0] == 'UGRP'), currentGroup) 499 | currentGroup.addsubgroup(grp) 500 | else: 501 | grp = YAPLCGroup(tokens[1], rest, (tokens[0] == 'UGRP'), None) 502 | self.addgroup(grp) # also add to flat root groups table 503 | 504 | currentGroup = grp 505 | 506 | elif tokens[0] == 'LOC' or tokens[0] == 'ULOC': 507 | # non-unique location description 508 | if currentGroup is None: 509 | raise ParseError(_("Location %s without group") % tokens[0]) 510 | if currentGroup.unique(): 511 | loc = YAPLCLocation(tokens[1], currentGroup, 512 | (tokens[0] == 'ULOC'), *tokens[2:]) 513 | else: 514 | # non-unique group could have no GID and parameters only 515 | loc = YAPLCLocation(tokens[1], currentGroup, 516 | (tokens[0] == 'ULOC'), *tokens[2:]) 517 | currentGroup.append(loc) 518 | 519 | elif tokens[0] == 'ENDGRP': 520 | # close current group and try to return to parent group 521 | if currentGroup is None: 522 | raise ParseError(_("Illegal end of group")) 523 | 524 | currentGroup = currentGroup.parent() 525 | 526 | else: 527 | raise ParseError(_("Illegal instruction: %s") % tokens[0]) 528 | 529 | if currentGroup is not None: 530 | raise ParseError(_("Group %s has not been closed properly!") % currentGroup.name()) 531 | 532 | except IOError: 533 | raise ParseError(_("No template file for current target")) 534 | 535 | 536 | if __name__ == '__main__': 537 | parser = YAPLCConfigParser() 538 | path = os.path.join(os.path.dirname(__file__), 539 | '..', 'yaplctargets', 'nuc247', 540 | r'extensions.cfg') 541 | try: 542 | parser.fparse(path) 543 | except ParseError as pe: 544 | print pe.message() 545 | 546 | for grp in parser.groups(): 547 | print grp 548 | print grp.locations() 549 | -------------------------------------------------------------------------------- /yaplcconnectors/YAPLC/YAPLCObject.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # YAPLC connector, based on LPCObject.py and LPCAppObjet.py 5 | # from PLCManager 6 | 7 | 8 | import os 9 | import sys 10 | 11 | if __name__ == "__main__": 12 | __builtins__.BMZ_DBG = True 13 | append_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) 14 | sys.path.append(append_path) 15 | 16 | from threading import Lock 17 | import ctypes 18 | from YAPLCProto import * 19 | from targets.typemapping import LogLevelsCount, TypeTranslator, UnpackDebugBuffer 20 | from util.ProcessLogger import ProcessLogger 21 | 22 | import pdb 23 | 24 | 25 | class YAPLCObject(): 26 | def __init__(self, libfile, confnodesroot, comportstr): 27 | 28 | self.TransactionLock = Lock() 29 | self.PLCStatus = "Disconnected" 30 | self.libfile = libfile 31 | self.confnodesroot = confnodesroot 32 | self.PLCprint = confnodesroot.logger.writeyield 33 | self._Idxs = [] 34 | 35 | self.TransactionLock.acquire() 36 | try: 37 | self.connect(libfile, comportstr, 57600, 20) 38 | except Exception, e: 39 | self.confnodesroot.logger.write_error(str(e) + "\n") 40 | self.SerialConnection = None 41 | self.PLCStatus = None # ProjectController is responsible to set "Disconnected" status 42 | self.TransactionLock.release() 43 | 44 | def connect(self, libfile, comportstr, baud, timeout): 45 | self.SerialConnection = YAPLCProto(libfile, comportstr, baud, timeout) 46 | 47 | def _HandleSerialTransaction(self, transaction, must_do_lock): 48 | res = None 49 | failure = None 50 | # Must acquire the lock 51 | if must_do_lock: 52 | self.TransactionLock.acquire() 53 | if self.SerialConnection is not None: 54 | # Do the job 55 | try: 56 | self.PLCStatus, res = \ 57 | self.SerialConnection.HandleTransaction(transaction) 58 | except YAPLCProtoError, e: 59 | if self.SerialConnection is not None: 60 | self.SerialConnection.Close() 61 | self.SerialConnection = None 62 | failure = str(transaction) + str(e) 63 | self.PLCStatus = None # ProjectController is responsible to set "Disconnected" status 64 | except Exception, e: 65 | failure = str(transaction) + str(e) 66 | # Must release the lock 67 | if must_do_lock: 68 | self.TransactionLock.release() 69 | return res, failure 70 | 71 | def HandleSerialTransaction(self, transaction): 72 | res = None; 73 | failure = None; 74 | res, failure = self._HandleSerialTransaction(transaction, True) 75 | if failure is not None: 76 | print(failure + "\n") 77 | self.confnodesroot.logger.write_warning(failure + "\n") 78 | return res 79 | 80 | def StartPLC(self): 81 | self.HandleSerialTransaction(STARTTransaction()) 82 | 83 | def StopPLC(self): 84 | self.HandleSerialTransaction(STOPTransaction()) 85 | return True 86 | 87 | def NewPLC(self, md5sum, data, extrafiles): 88 | if self.MatchMD5(md5sum) == False: 89 | res = None; 90 | failure = None; 91 | 92 | self.HandleSerialTransaction(SETRTCTransaction()) 93 | 94 | self.confnodesroot.logger.write_warning( 95 | _("Will now upload firmware to PLC.\nThis may take some time, don't close the program.\n")) 96 | self.TransactionLock.acquire() 97 | # Will now boot target 98 | res, failure = self._HandleSerialTransaction(BOOTTransaction(), False) 99 | time.sleep(3) 100 | # Close connection 101 | self.SerialConnection.Close() 102 | # bootloader command 103 | # data contains full command line except serial port string which is passed to % operator 104 | # cmd = data % self.SerialConnection.port 105 | cmd = [token % {"serial_port": self.SerialConnection.port} for token in data] 106 | # wrapper to run command in separate window 107 | cmdhead = [] 108 | cmdtail = [] 109 | if os.name in ("nt", "ce"): 110 | # cmdwrap = "start \"Loading PLC, please wait...\" /wait %s \r" 111 | cmdhead.append("cmd") 112 | cmdhead.append("/c") 113 | cmdhead.append("start") 114 | cmdhead.append("Loading PLC, please wait...") 115 | cmdhead.append("/wait") 116 | else: 117 | # cmdwrap = "xterm -e %s \r" 118 | cmdhead.append("xterm") 119 | cmdhead.append("-e") 120 | # Load a program 121 | # try: 122 | # os.system( cmdwrap % command ) 123 | # except Exception,e: 124 | # failure = str(e) 125 | command = cmdhead + cmd + cmdtail; 126 | status, result, err_result = ProcessLogger(self.confnodesroot.logger, command).spin() 127 | """ 128 | TODO: Process output? 129 | """ 130 | # Reopen connection 131 | self.SerialConnection.Open() 132 | self.TransactionLock.release() 133 | 134 | if failure is not None: 135 | self.confnodesroot.logger.write_warning(failure + "\n") 136 | return False 137 | else: 138 | self.StopPLC(); 139 | return self.PLCStatus == "Stopped" 140 | else: 141 | self.StopPLC(); 142 | return self.PLCStatus == "Stopped" 143 | 144 | def GetPLCstatus(self): 145 | strcounts = self.HandleSerialTransaction(GET_LOGCOUNTSTransaction()) 146 | if strcounts is not None and len(strcounts) == LogLevelsCount * 4: 147 | cstrcounts = ctypes.create_string_buffer(strcounts) 148 | ccounts = ctypes.cast(cstrcounts, ctypes.POINTER(ctypes.c_uint32)) 149 | counts = [int(ccounts[idx]) for idx in xrange(LogLevelsCount)] 150 | else: 151 | counts = [0] * LogLevelsCount 152 | return self.PLCStatus, counts 153 | 154 | def MatchMD5(self, MD5): 155 | self.MatchSwitch = False 156 | data = self.HandleSerialTransaction(GET_PLCIDTransaction()) 157 | self.MatchSwitch = True 158 | if data is not None: 159 | return data[:32] == MD5[:32] 160 | return False 161 | 162 | def SetTraceVariablesList(self, idxs): 163 | """ 164 | Call ctype imported function to append 165 | these indexes to registred variables in PLC debugger 166 | """ 167 | if idxs: 168 | buff = "" 169 | # keep a copy of requested idx 170 | self._Idxs = idxs[:] 171 | for idx, iectype, force in idxs: 172 | idxstr = ctypes.string_at( 173 | ctypes.pointer( 174 | ctypes.c_uint32(idx)), 4) 175 | if force != None: 176 | c_type, unpack_func, pack_func = TypeTranslator.get(iectype, (None, None, None)) 177 | forced_type_size = ctypes.sizeof(c_type) \ 178 | if iectype != "STRING" else len(force) + 1 179 | forced_type_size_str = chr(forced_type_size) 180 | forcestr = ctypes.string_at( 181 | ctypes.pointer( 182 | pack_func(c_type, force)), 183 | forced_type_size) 184 | buff += idxstr + forced_type_size_str + forcestr 185 | else: 186 | buff += idxstr + chr(0) 187 | else: 188 | buff = "" 189 | self._Idxs = [] 190 | self.HandleSerialTransaction(SET_TRACE_VARIABLETransaction(buff)) 191 | 192 | def GetTraceVariables(self): 193 | """ 194 | Return a list of variables, corresponding to the list of required idx 195 | """ 196 | strbuf = self.HandleSerialTransaction(GET_TRACE_VARIABLETransaction()) 197 | TraceVariables = [] 198 | if strbuf is not None and len(strbuf) >= 4 and self.PLCStatus == "Started": 199 | size = len(strbuf) - 4 200 | ctick = ctypes.create_string_buffer(strbuf[:4]) 201 | tick = ctypes.cast(ctick, ctypes.POINTER(ctypes.c_uint32)).contents 202 | if size > 0: 203 | cbuff = ctypes.create_string_buffer(strbuf[4:]) 204 | buff = ctypes.cast(cbuff, ctypes.c_void_p) 205 | TraceBuffer = ctypes.string_at(buff.value, size) 206 | # Add traces 207 | TraceVariables.append((tick.value, TraceBuffer)) 208 | return self.PLCStatus, TraceVariables 209 | 210 | def ResetLogCount(self): 211 | self.HandleSerialTransaction(RESET_LOGCOUNTSTransaction()) 212 | 213 | def GetLogMessage(self, level, msgid): 214 | strbuf = self.HandleSerialTransaction(GET_LOGMSGTransaction(level, msgid)) 215 | if strbuf is not None and len(strbuf) > 12: 216 | cbuf = ctypes.cast( 217 | ctypes.c_char_p(strbuf[:12]), 218 | ctypes.POINTER(ctypes.c_uint32)) 219 | return (strbuf[12:],) + tuple(int(cbuf[idx]) for idx in range(3)) 220 | return None 221 | 222 | def ForceReload(self): 223 | raise YAPLCProtoError("Not implemented") 224 | 225 | def RemoteExec(self, script, **kwargs): 226 | return (-1, "RemoteExec is not supported by YAPLC target!") 227 | 228 | 229 | if __name__ == "__main__": 230 | """ 231 | "C:\Program Files\Beremiz\python\python.exe" YAPLCObject.py 232 | """ 233 | 234 | 235 | class TestLogger(): 236 | def __init__(self): 237 | self.lock = Lock() 238 | 239 | def write(self, v): 240 | self.lock.acquire() 241 | print(v) 242 | self.lock.release() 243 | 244 | def writeyield(self, v): 245 | self.lock.acquire() 246 | print(v) 247 | self.lock.release() 248 | 249 | def write_warning(self, v): 250 | if v is not None: 251 | self.lock.acquire() 252 | msg = "Warning: " + v 253 | print(msg) 254 | self.lock.release() 255 | 256 | def write_error(self, v): 257 | if v is not None: 258 | self.lock.acquire() 259 | msg = "Warning: " + v 260 | print(msg) 261 | self.lock.release() 262 | 263 | 264 | class TestRoot: 265 | def __init__(self): 266 | self.logger = TestLogger() 267 | 268 | 269 | if os.name in ("nt", "ce"): 270 | lib_ext = ".dll" 271 | else: 272 | lib_ext = ".so" 273 | 274 | TstLib = os.path.dirname(os.path.realpath(__file__)) + "/../../../YaPySerial/bin/libYaPySerial" + lib_ext 275 | if (os.name == 'posix' and not os.path.isfile(TstLib)): 276 | TstLib = "libYaPySerial" + lib_ext 277 | 278 | TstRoot = TestRoot() 279 | print "Construct PLC..." 280 | TstPLC = YAPLCObject(TstLib, TstRoot, "COM10") 281 | 282 | print "Start PLC..." 283 | res = TstPLC.StartPLC() 284 | print(res) 285 | 286 | print "Get PLC status..." 287 | res = TstPLC.GetPLCstatus(); 288 | print(res) 289 | 290 | print "MatchMD5..." 291 | res = TstPLC.MatchMD5("aaabbb") 292 | print(res) 293 | 294 | print "MatchMD5..." 295 | res = TstPLC.MatchMD5("2c2700c2c543f64e93747d21277de8fdUnknown#Uncnown#Uncnown") 296 | print(res) 297 | 298 | print "SetTraceVariablesList..." 299 | idxs = [] 300 | idxs.append((0, "BOOL", 1)) 301 | idxs.append((1, "BOOL", 1)) 302 | res = TstPLC.SetTraceVariablesList(idxs) 303 | print(res) 304 | 305 | print "GetTraceVariables..." 306 | res = TstPLC.GetTraceVariables() 307 | print(res) 308 | 309 | print "GetLogMessage..." 310 | res = TstPLC.GetLogMessage(0, 0) 311 | print(res) 312 | 313 | print "ResetLogCount..." 314 | TstPLC.ResetLogCount() 315 | 316 | TstPLC.StopPLC() 317 | 318 | time.sleep(3) 319 | -------------------------------------------------------------------------------- /yaplcconnectors/YAPLC/YAPLCProto.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | #YAPLC connector, based on LPCProto.py and LPCAppProto.py 5 | #from PLCManager 6 | 7 | import ctypes 8 | import exceptions 9 | import time 10 | import datetime 11 | 12 | import YaPySerial 13 | 14 | YAPLC_STATUS={0xaa: "Started", 15 | 0x55: "Stopped"} 16 | 17 | 18 | class YAPLCProtoError(exceptions.Exception): 19 | """Exception class""" 20 | def __init__(self, msg): 21 | self.msg = msg 22 | 23 | def __str__(self): 24 | return "Exception in PLC protocol : " + str(self.msg) 25 | 26 | 27 | class YAPLCProto: 28 | 29 | def __init__(self, libfile, port, baud, timeout): 30 | # serialize access lock 31 | self.port = port 32 | self.baud = baud 33 | self.timeout = timeout 34 | # open serial port 35 | self.SerialPort = YaPySerial.YaPySerial(libfile) 36 | self.Open() 37 | 38 | 39 | def Open(self): 40 | self.SerialPort.Open( self.port, self.baud, "8N1", self.timeout ) 41 | # start with empty buffer 42 | self.SerialPort.Flush() 43 | 44 | 45 | def HandleTransaction(self, transaction): 46 | try: 47 | transaction.SetSerialPort(self.SerialPort) 48 | # send command, wait ack (timeout) 49 | transaction.SendCommand() 50 | current_plc_status = transaction.GetCommandAck() 51 | if current_plc_status is not None: 52 | res = transaction.ExchangeData() 53 | else: 54 | raise YAPLCProtoError("controller did not answer as expected!") 55 | except Exception, e: 56 | msg = "PLC protocol transaction error : "+str(e) 57 | raise YAPLCProtoError( msg ) 58 | return YAPLC_STATUS.get(current_plc_status,"Broken"), res 59 | 60 | 61 | def Close(self): 62 | if self.SerialPort: 63 | try: 64 | self.SerialPort.Close() 65 | except Exception, e: 66 | msg = "PLC protocol transaction error : "+str(e) 67 | raise YAPLCProtoError( msg ) 68 | 69 | def __del__(self): 70 | self.Close() 71 | 72 | 73 | class YAPLCTransaction: 74 | 75 | def __init__(self, command): 76 | self.Command = command 77 | self.SerialPort = None 78 | 79 | 80 | def SetSerialPort(self, SerialPort): 81 | self.SerialPort = SerialPort 82 | 83 | 84 | def SendCommand(self): 85 | # send command thread 86 | self.SerialPort.Write(chr(self.Command)) 87 | 88 | 89 | def GetCommandAck(self): 90 | res = self.SerialPort.Read(2) 91 | if res is None: 92 | return None 93 | if len(res) == 2: 94 | comm_status, current_plc_status = map(ord, res) 95 | else: 96 | raise YAPLCProtoError("YAPLC transaction error - controller did not ack order!") 97 | # LPC returns command itself as an ack for command 98 | if comm_status == self.Command: 99 | return current_plc_status 100 | return None 101 | 102 | 103 | def SendData(self, Data): 104 | return self.SerialPort.Write(Data) 105 | 106 | 107 | def GetData(self): 108 | lengthstr = self.SerialPort.Read(4) 109 | if lengthstr is None: 110 | raise YAPLCProtoError("YAPLC transaction error - can't read data length!") 111 | else: 112 | if len(lengthstr) != 4: 113 | raise YAPLCProtoError("YAPLC transaction error - data length is invalid: " + str(len(lengthstr) + " !")) 114 | 115 | # transform a byte string into length 116 | length = ctypes.cast( 117 | ctypes.c_char_p(lengthstr), 118 | ctypes.POINTER(ctypes.c_uint32) 119 | ).contents.value 120 | if length > 0: 121 | data = self.SerialPort.Read(length) 122 | if data is None: 123 | raise YAPLCProtoError("YAPLC transaction error - can't read data!") 124 | return None 125 | else: 126 | if len(lengthstr) == 0: 127 | raise YAPLCProtoError("YAPLC transaction error - data is invalid!") 128 | return None 129 | return data 130 | else: 131 | return None 132 | 133 | 134 | def ExchangeData(self): 135 | pass 136 | 137 | 138 | class IDLETransaction(YAPLCTransaction): 139 | def __init__(self): 140 | YAPLCTransaction.__init__(self, 0x6a) 141 | #ExchangeData = YAPLCTransaction.GetData 142 | 143 | 144 | class STARTTransaction(YAPLCTransaction): 145 | def __init__(self): 146 | YAPLCTransaction.__init__(self, 0x61) 147 | 148 | 149 | class STOPTransaction(YAPLCTransaction): 150 | def __init__(self): 151 | YAPLCTransaction.__init__(self, 0x62) 152 | 153 | 154 | class BOOTTransaction(YAPLCTransaction): 155 | def __init__(self): 156 | YAPLCTransaction.__init__(self, 0x63) 157 | 158 | 159 | class SET_TRACE_VARIABLETransaction(YAPLCTransaction): 160 | def __init__(self, data): 161 | YAPLCTransaction.__init__(self, 0x64) 162 | length = len(data) 163 | # transform length into a byte string 164 | # we presuppose endianess of LPC same as PC 165 | lengthstr = ctypes.string_at(ctypes.pointer(ctypes.c_uint32(length)),4) 166 | self.Data = lengthstr + data 167 | 168 | def ExchangeData(self): 169 | self.SendData(self.Data) 170 | 171 | 172 | class GET_TRACE_VARIABLETransaction(YAPLCTransaction): 173 | def __init__(self): 174 | YAPLCTransaction.__init__(self, 0x65) 175 | ExchangeData = YAPLCTransaction.GetData 176 | 177 | 178 | class GET_PLCIDTransaction(YAPLCTransaction): 179 | def __init__(self): 180 | YAPLCTransaction.__init__(self, 0x66) 181 | ExchangeData = YAPLCTransaction.GetData 182 | 183 | 184 | class GET_LOGCOUNTSTransaction(YAPLCTransaction): 185 | def __init__(self): 186 | YAPLCTransaction.__init__(self, 0x67) 187 | ExchangeData = YAPLCTransaction.GetData 188 | 189 | 190 | class GET_LOGMSGTransaction(YAPLCTransaction): 191 | def __init__(self,level,msgid): 192 | YAPLCTransaction.__init__(self, 0x68) 193 | msgidstr = ctypes.string_at(ctypes.pointer(ctypes.c_int(msgid)),4) 194 | self.Data = chr(level)+msgidstr 195 | 196 | def ExchangeData(self): 197 | #pass 198 | self.SendData(self.Data) 199 | return self.GetData() 200 | 201 | 202 | class RESET_LOGCOUNTSTransaction(YAPLCTransaction): 203 | def __init__(self): 204 | YAPLCTransaction.__init__(self, 0x69) 205 | 206 | class SETRTCTransaction(YAPLCTransaction): 207 | def __init__(self): 208 | YAPLCTransaction.__init__(self, 0x6b) 209 | dt = datetime.datetime.now() 210 | 211 | year = dt.year%100 212 | year = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(year)) ,1) 213 | mon = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.month)) ,1) 214 | day = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.day)) ,1) 215 | hour = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.hour)) ,1) 216 | minute = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.minute)) ,1) 217 | second = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.second)) ,1) 218 | self.Data = year+mon+day+hour+minute+second 219 | 220 | def ExchangeData(self): 221 | self.SendData(self.Data) 222 | 223 | if __name__ == "__main__": 224 | 225 | import os 226 | __builtins__.BMZ_DBG = True 227 | 228 | """ 229 | "C:\Program Files\Beremiz\python\python.exe" YAPLCProto.py 230 | """ 231 | 232 | if os.name in ("nt", "ce"): 233 | lib_ext = ".dll" 234 | else: 235 | lib_ext = ".so" 236 | 237 | TestLib = os.path.dirname(os.path.realpath(__file__)) + "/../../../YaPySerial/bin/libYaPySerial" + lib_ext 238 | TestConnection = YAPLCProto(TestLib,"COM10",57600,20) 239 | 240 | print "Idle transaction..." 241 | status,res = TestConnection.HandleTransaction(IDLETransaction()) 242 | print status 243 | 244 | print "Start transaction..." 245 | status,res = TestConnection.HandleTransaction(STARTTransaction()) 246 | print status 247 | 248 | print "Set trace vars transaction..." 249 | status,res = TestConnection.HandleTransaction(SET_TRACE_VARIABLETransaction( 250 | "\x00\x00\x00\x00"+ 251 | "\x01" 252 | "\x00" 253 | 254 | "\x01\x00\x00\x00"+ 255 | "\x01" 256 | "\x00" 257 | ) 258 | ) 259 | print status 260 | 261 | print "Get trace vars transaction..." 262 | status,res = TestConnection.HandleTransaction(GET_TRACE_VARIABLETransaction()) 263 | print status 264 | print len(res) 265 | print "GOT : ", map(hex, map(ord, res)) 266 | 267 | print "Get PLCID transaction..." 268 | status,res = TestConnection.HandleTransaction(GET_PLCIDTransaction()) 269 | print status 270 | print len(res) 271 | print "GOT : ", map(hex, map(ord, res)) 272 | 273 | print "Get log counts transaction..." 274 | status,res = TestConnection.HandleTransaction(GET_LOGCOUNTSTransaction()) 275 | print status 276 | print len(res) 277 | print "GOT : ", map(hex, map(ord, res)) 278 | 279 | print "Get log message transaction..." 280 | status,res = TestConnection.HandleTransaction(GET_LOGMSGTransaction(0,0)) 281 | print status 282 | print len(res) 283 | print "GOT : ", map(hex, map(ord, res)) 284 | 285 | print "Stop transaction..." 286 | TestConnection.HandleTransaction(STOPTransaction()) 287 | 288 | time.sleep(3) 289 | -------------------------------------------------------------------------------- /yaplcconnectors/YAPLC/YaPySerial.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import exceptions 5 | from threading import Timer, Thread, Lock, Semaphore 6 | import ctypes, os, commands, types, sys 7 | import time 8 | 9 | if os.name in ("nt", "ce"): 10 | from _ctypes import LoadLibrary as dlopen 11 | from _ctypes import FreeLibrary as dlclose 12 | elif os.name == "posix": 13 | from _ctypes import dlopen, dlclose 14 | 15 | 16 | class YaPySerialError(exceptions.Exception): 17 | """Exception class""" 18 | def __init__(self, msg): 19 | self.msg = msg 20 | 21 | def __str__(self): 22 | return "Exception in YaPySerial : " + str(self.msg) 23 | 24 | 25 | class YaPySerial: 26 | def __init__(self, LibFile): 27 | self.port = None 28 | self._DlibraryHandle = None 29 | self.DlibraryHandle = None 30 | try: 31 | """ 32 | Load library 33 | """ 34 | self._DlibraryHandle = dlopen(LibFile) 35 | self.DlibraryHandle = ctypes.CDLL(LibFile, handle=self._DlibraryHandle) 36 | """ 37 | Attach functions 38 | """ 39 | self._SerialOpen = self.DlibraryHandle.yapy_serial_open; 40 | self._SerialOpen.restype = ctypes.c_int 41 | self._SerialOpen.argtypes = [ctypes.POINTER( ctypes.c_void_p ), ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int] 42 | 43 | self._SerialClose = self.DlibraryHandle.yapy_serial_close; 44 | self._SerialClose.restype = ctypes.c_int 45 | self._SerialClose.argtypes = [ctypes.POINTER( ctypes.c_void_p )] 46 | 47 | self._SerialRead = self.DlibraryHandle.yapy_serial_read; 48 | self._SerialRead.restype = ctypes.c_int 49 | self._SerialRead.argtypes = [ctypes.POINTER( ctypes.c_void_p ), ctypes.c_void_p, ctypes.c_size_t] 50 | 51 | self._SerialWrite = self.DlibraryHandle.yapy_serial_write; 52 | self._SerialWrite.restype = ctypes.c_int 53 | self._SerialWrite.argtypes = [ctypes.POINTER( ctypes.c_void_p ), ctypes.c_void_p, ctypes.c_size_t] 54 | 55 | self._SerialGPIO = self.DlibraryHandle.yapy_serial_gpio; 56 | self._SerialGPIO.restype = ctypes.c_int 57 | self._SerialGPIO.argtypes = [ctypes.POINTER( ctypes.c_void_p ), ctypes.c_int, ctypes.c_int] 58 | except: 59 | raise YaPySerialError("Could'n t load dynamic library!") 60 | 61 | def Open(self, device, baud, modestr, timeout): 62 | self.port = ctypes.c_void_p(0) 63 | try: 64 | res = int( self._SerialOpen( ctypes.byref( self.port ), ctypes.c_char_p( device ), ctypes.c_int( baud ), ctypes.c_char_p( modestr ), ctypes.c_int( timeout ))) 65 | except: 66 | raise YaPySerialError("Runrtime error on serial open!") 67 | if res > 0: 68 | msg = "Couldn't open serial port, error: " + str( res ) + "!" 69 | raise YaPySerialError( msg ) 70 | 71 | def Close(self): 72 | try: 73 | res = int(self._SerialClose( ctypes.byref( self.port ) )) 74 | except: 75 | raise YaPySerialError("Runrtime error on serial close!") 76 | if res > 0: 77 | msg = "Couldn't close serial port, error: " + str( res ) + "!" 78 | raise YaPySerialError( msg ) 79 | self.port = None 80 | 81 | def Read(self, nbytes): 82 | try: 83 | buf = ctypes.create_string_buffer( int(nbytes) ) 84 | res = int(self._SerialRead( ctypes.byref( self.port ), ctypes.cast( buf, ctypes.c_void_p ), ctypes.c_size_t( nbytes ) )) 85 | except: 86 | raise YaPySerialError("Runrtime error on serial read!") 87 | if res > 0: 88 | if res == 2: 89 | return None 90 | else: 91 | msg = "Couldn't read serial port, error: " + str( res ) + "!" 92 | raise YaPySerialError( msg ) 93 | else: 94 | return buf.raw 95 | 96 | def Write(self, buf): 97 | try: 98 | nbytes = len( buf ) 99 | strbuf = ctypes.create_string_buffer( buf ) 100 | res = int(self._SerialWrite( ctypes.byref( self.port ), ctypes.cast( ctypes.byref( strbuf ), ctypes.c_void_p ), ctypes.c_size_t( nbytes ) )) 101 | except: 102 | raise YaPySerialError("Runrtime error on serial write!") 103 | if res > 0: 104 | msg = "Couldn't write to serial port, error: " + str( res ) + "!" 105 | raise YaPySerialError( msg ) 106 | 107 | def Flush(self): 108 | try: 109 | buf = ctypes.create_string_buffer(1); 110 | res = 0 111 | while res == 0: 112 | res = int(self._SerialRead( ctypes.byref( self.port ), ctypes.cast( buf, ctypes.c_void_p ), ctypes.c_size_t(1) )) 113 | except: 114 | raise YaPySerialError("Runrtime error on serial flush!") 115 | if res != 2: 116 | msg = "Couldn't write to serial port, error: " + str( res ) + "!" 117 | raise YaPySerialError( msg ) 118 | 119 | def GPIO(self, n, level): 120 | try: 121 | res = int(self._SerialGPIO( ctypes.byref( self.port ), ctypes.c_int(n), ctypes.c_int( level ) )) 122 | except: 123 | raise YaPySerialError("Runrtime error on serial gpio!") 124 | if res > 0: 125 | msg = "Couldn't write to serial port, error: " + str( res ) + "!" 126 | raise YaPySerialError( msg ) 127 | 128 | def __del__(self): 129 | if self._DlibraryHandle is not None: 130 | if self.port is not None: 131 | try: 132 | self.Close() 133 | except: 134 | raise YaPySerialError("Could'n t close serial port!") 135 | dlclose(self._DlibraryHandle) 136 | self._DlibraryHandle = None 137 | self.DlibraryHandle = None 138 | 139 | if __name__ == "__main__": 140 | 141 | """ 142 | "C:\Program Files\Beremiz\python\python.exe" YaPySerial.py 143 | """ 144 | if os.name in ("nt", "ce"): 145 | lib_ext = ".dll" 146 | else: 147 | lib_ext = ".so" 148 | 149 | TestLib = os.path.dirname(os.path.realpath(__file__)) + "/../../../YaPySerial/bin/libYaPySerial" + lib_ext 150 | if (os.name == 'posix' and not os.path.isfile(TestLib)): 151 | TestLib = "libYaPySerial" + lib_ext 152 | 153 | TestSerial = YaPySerial( TestLib ) 154 | TestSerial.Open( "COM256", 9600, "8N1", 2 ) 155 | 156 | TestSerial.Flush() 157 | 158 | send_str = "Hello World!!!" 159 | TestSerial.Write( send_str ) 160 | 161 | receive_str = TestSerial.Read( len( send_str ) ) 162 | 163 | print( "Received:" ) 164 | print( receive_str ) 165 | 166 | TestSerial.Close() 167 | 168 | time.sleep(1) 169 | -------------------------------------------------------------------------------- /yaplcconnectors/YAPLC/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | #Copyright (C) 2015: Nucleron R&D LLC 5 | # 6 | #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD 7 | # 8 | #See COPYING file for copyrights details. 9 | # 10 | #This library is free software; you can redistribute it and/or 11 | #modify it under the terms of the GNU General Public 12 | #License as published by the Free Software Foundation; either 13 | #version 2.1 of the License, or (at your option) any later version. 14 | # 15 | #This library is distributed in the hope that it will be useful, 16 | #but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 | #General Public License for more details. 19 | # 20 | #You should have received a copy of the GNU General Public 21 | #License along with this library; if not, write to the Free Software 22 | #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 23 | 24 | 25 | def YAPLC_connector_factory(uri, confnodesroot): 26 | """ 27 | This returns the connector to YAPLC style PLCobject 28 | """ 29 | import os 30 | 31 | servicetype, comportstr = uri.split("://") 32 | 33 | confnodesroot.logger.write(_("Connecting to:" + comportstr + "\n")) 34 | 35 | from YAPLCObject import YAPLCObject 36 | 37 | if os.name in ("nt", "ce"): 38 | lib_ext = ".dll" 39 | else: 40 | lib_ext = ".so" 41 | 42 | YaPySerialLib = os.path.dirname(os.path.realpath(__file__)) + "/../../../YaPySerial/bin/libYaPySerial" + lib_ext 43 | if (os.name == 'posix' and not os.path.isfile(YaPySerialLib)): 44 | YaPySerialLib = "libYaPySerial" + lib_ext 45 | 46 | return YAPLCObject(YaPySerialLib,confnodesroot,comportstr) 47 | -------------------------------------------------------------------------------- /yaplcconnectors/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # package initializations 3 | 4 | from os import listdir, path 5 | 6 | 7 | _base_path = path.split(__file__)[0] 8 | 9 | 10 | def _GetLocalConnectorClassFactory(name): 11 | return lambda: getattr(__import__(name, globals(), locals()), name + "_connector_factory") 12 | 13 | connectors = {name: _GetLocalConnectorClassFactory(name) 14 | for name in listdir(_base_path) 15 | if path.isdir(path.join(_base_path, name)) 16 | and not name.startswith("__")} 17 | 18 | 19 | def ConnectorFactory(uri, confnodesroot): 20 | """ 21 | Return a connector corresponding to the URI 22 | or None if cannot connect to URI 23 | """ 24 | servicetype = uri.split("://")[0].upper() 25 | if servicetype == "LOCAL": 26 | # Local is special case 27 | # pyro connection to local runtime 28 | # started on demand, listening on random port 29 | servicetype = "PYRO" 30 | runtime_port = confnodesroot.AppFrame.StartLocalRuntime( 31 | taskbaricon=True) 32 | uri = "PYROLOC://127.0.0.1:" + str(runtime_port) 33 | elif servicetype in connectors: 34 | pass 35 | elif servicetype[-1] == 'S' and servicetype[:-1] in connectors: 36 | servicetype = servicetype[:-1] 37 | else: 38 | return None 39 | 40 | # import module according to uri type 41 | connectorclass = connectors[servicetype]() 42 | return connectorclass(uri, confnodesroot) -------------------------------------------------------------------------------- /yaplcext.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # This file is part of Beremiz, a Integrated Development Environment for 5 | # programming IEC 61131-3 automates supporting plcopen standard and CanFestival. 6 | # 7 | # Copyright (C) 2016 - 2017: Andrey Skvortsov 8 | # 9 | # See COPYING file for copyrights details. 10 | # 11 | # This program is free software; you can redistribute it and/or 12 | # modify it under the terms of the GNU General Public License 13 | # as published by the Free Software Foundation; either version 2 14 | # of the License, or (at your option) any later version. 15 | # 16 | # This program is distributed in the hope that it will be useful, 17 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | # GNU General Public License for more details. 20 | # 21 | # You should have received a copy of the GNU General Public License 22 | # along with this program; if not, write to the Free Software 23 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 24 | 25 | # This is dummy extension file wich never will do something useful. -------------------------------------------------------------------------------- /yaplcide.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | __version__ = "$Revision$" 5 | 6 | import __builtin__ 7 | import gettext 8 | import os 9 | import sys 10 | 11 | gettext.install('yaplcide') # this is a dummy to prevent gettext falling down 12 | 13 | _dist_folder = os.path.split(sys.path[0])[0] 14 | _beremiz_folder = os.path.join(_dist_folder, "beremiz") 15 | #Ensure that Beremiz things are imported before builtins and libs. 16 | sys.path.insert(1,_beremiz_folder) 17 | 18 | from Beremiz import * 19 | 20 | class YAPLCIdeLauncher(BeremizIDELauncher): 21 | """ 22 | YAPLC IDE Launcher class 23 | """ 24 | def __init__(self): 25 | BeremizIDELauncher.__init__(self) 26 | self.yaplc_dir = os.path.dirname(os.path.realpath(__file__)) 27 | self.splashPath = self.YApath("images", "splash.png") 28 | self.extensions.append(self.YApath("yaplcext.py")) 29 | 30 | import features 31 | # Let's import nucleron yaplcconnectors 32 | import yaplcconnectors 33 | import connectors 34 | 35 | connectors.connectors.update(yaplcconnectors.connectors) 36 | 37 | # Import Nucleron yaplctargets 38 | import yaplctargets 39 | import targets 40 | 41 | targets.toolchains.update(yaplctargets.toolchains) 42 | targets.targets.update(yaplctargets.yaplctargets) 43 | 44 | features.libraries = [ 45 | ('Native', 'NativeLib.NativeLibrary')] 46 | 47 | features.catalog.append(('yaplcconfig', 48 | _('YAPLC Configuration Node'), 49 | _('Adds template located variables'), 50 | 'yaplcconfig.yaplcconfig.YAPLCNodeConfig')) 51 | 52 | def YApath(self, *args): 53 | return os.path.join(self.yaplc_dir, *args) 54 | 55 | 56 | # This is where we start our application 57 | if __name__ == '__main__': 58 | beremiz = YAPLCIdeLauncher() 59 | beremiz.Start() 60 | -------------------------------------------------------------------------------- /yaplctargets/XSD_toolchain_yaplc: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /yaplctargets/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Beremiz YAPLC Targets 3 | 4 | - Target are python packages, containing at least one "XSD" file 5 | - Target class may inherit from a toolchain_(toolchainname) 6 | - The target folder's name must match to name define in the XSD for TargetType 7 | """ 8 | 9 | from os import listdir, path 10 | 11 | _base_path = path.split(__file__)[0] 12 | 13 | 14 | def _GetLocalTargetClassFactory(name): 15 | return lambda:getattr(__import__(name,globals(),locals()), name+"_target") 16 | 17 | yaplctargets = dict([(name, {"xsd":path.join(_base_path, name, "XSD"), 18 | "class":_GetLocalTargetClassFactory(name), 19 | "code": { fname: path.join(_base_path, name, fname) 20 | for fname in listdir(path.join(_base_path, name)) 21 | if fname.startswith("plc_%s_main"%name) and 22 | fname.endswith(".c")}}) 23 | for name in listdir(_base_path) 24 | if path.isdir(path.join(_base_path, name)) 25 | and not name.startswith("__")]) 26 | 27 | toolchains = {"yaplc": path.join(_base_path, "XSD_toolchain_yaplc")} 28 | 29 | def GetBuilder(targetname): 30 | return yaplctargets[targetname]["class"]() 31 | 32 | def GetTargetChoices(): 33 | DictXSD_toolchain = {} 34 | targetchoices = "" 35 | 36 | # Get all xsd toolchains 37 | for toolchainname,xsdfilename in toolchains.iteritems() : 38 | if path.isfile(xsdfilename): 39 | DictXSD_toolchain["toolchain_"+toolchainname] = \ 40 | open(xsdfilename).read() 41 | 42 | # Get all xsd yaplctargets 43 | for targetname,nfo in yaplctargets.iteritems(): 44 | xsd_string = open(nfo["xsd"]).read() 45 | targetchoices += xsd_string%DictXSD_toolchain 46 | 47 | return targetchoices 48 | 49 | def GetTargetCode(targetname): 50 | codedesc = yaplctargets[targetname]["code"] 51 | code = "\n".join([open(fpath).read() for fname, fpath in sorted(codedesc.items())]) 52 | return code 53 | 54 | def GetHeader(): 55 | filename = path.join(path.split(__file__)[0],"beremiz.h") 56 | return open(filename).read() 57 | 58 | def GetCode(name): 59 | filename = path.join(path.split(__file__)[0],name) 60 | return open(filename).read() 61 | -------------------------------------------------------------------------------- /yaplctargets/__nuc251/XSD: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %(toolchain_yaplc)s 5 | 6 | 7 | -------------------------------------------------------------------------------- /yaplctargets/__nuc251/__init__.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from yaplctargets.toolchain_yaplc_stm32 import toolchain_yaplc_stm32 3 | from yaplctargets.toolchain_yaplc_stm32 import plc_rt_dir as plc_rt_dir 4 | 5 | class nuc251_target(toolchain_yaplc_stm32): 6 | def __init__(self, CTRInstance): 7 | 8 | toolchain_yaplc_stm32.__init__(self, CTRInstance) 9 | 10 | self.dev_family = "STM32F2" 11 | self.load_addr = "0x08008000" 12 | self.runtime_addr = "0x08000184" 13 | self.linker_script = os.path.join(os.path.join(os.path.join(plc_rt_dir, "bsp"), "nuc-247-1"), "stm32f205xC-app.ld") 14 | -------------------------------------------------------------------------------- /yaplctargets/__nuc251/extensions.cfg: -------------------------------------------------------------------------------- 1 | ################################### Diagnostic info ####################################### 2 | UGRP "Diag" 0 3 | # WCET 4 | UGRP "WCET" 0 5 | LOC MD 6 | ENDGRP 7 | # Inputs 8 | UGRP "HW Failure" 0..1 9 | LOC IX 10 | ENDGRP 11 | # Debug mode (on/off) 12 | UGRP "Debug Mode" 0 13 | LOC QX 14 | ENDGRP 15 | # Outputs 16 | UGRP "Execution status" 1..3 17 | # 1 - User info (on/off), 2 - User warning (on/off), 3 - User critical, stops the program execution!!! 18 | LOC QX 19 | ENDGRP 20 | ENDGRP 21 | ################################### Discrete IO ######################################### 22 | UGRP "Discrete IO" 1 23 | # 12 discrete inputs 24 | GRP "IX" 0..11 25 | LOC IX # values 26 | LOC MB 1 # edge filters 27 | LOC MB 0 # fall filters 28 | ENDGRP 29 | # 8 relay outputs 30 | LOC QX 0..7 31 | ENDGRP 32 | ################################## Modbus slave ######################################## 33 | UGRP "Modbus slave" 2 34 | # Config location 35 | ULOC QX "Configuration" [Addr:1..244] [Baud:1200,2400,4800,9600,19200,38400,57600,115200] [Mode:0..1] # Mode: 0 - RTU, 1 - ASCII 36 | # Holding register 37 | LOC MW 0..31 38 | ENDGRP 39 | ################################## Modbus Master ######################################## 40 | UGRP "Modbus master" 3 41 | # Config location 42 | ULOC QX "Configuration" [Baud:1200,2400,4800,9600,19200,38400,57600,115200] [Mode:0..1] [DelayMs:2..1000]# Mode: 0 - RTU, 1 - ASCII 43 | 44 | #RqID: 0 - read discrete input, 1 - read coils, 2 - read input regs, 3 - read holding regs, 4 - write coils, 5 - write holding regs. 45 | 46 | GRP "WORD RW" [RqID:0..255] 47 | ULOC IB "Request config" [RqType:2,3,5] [SlaveID:1..244] [BaseAddr:0..65471] [PeriodMs:100..3600000] 48 | LOC MW "Word" [Offset:0..63] 49 | ENDGRP 50 | 51 | GRP "BOOL RW" [RqID:0..255] 52 | ULOC IB "Request config" [RqType:0,1,4] [SlaveID:1..244] [BaseAddr:0..65471] [PeriodMs:100..3600000] 53 | LOC MX "Bit" [Offset:0..63] 54 | ENDGRP 55 | 56 | ENDGRP 57 | ###################################### HMI ############################################# 58 | UGRP "HMI LEDs" 4 59 | UGRP "RG" 0..1 60 | # 0 - Red, 1 - Green 61 | LOC QX 62 | ENDGRP 63 | # 4 dots on indicators 64 | UGRP "Dot" 10..13 65 | LOC QX 66 | ENDGRP 67 | #8 LEDS near indicators 68 | UGRP "Other" 2..9 69 | LOC QX 70 | ENDGRP 71 | ENDGRP 72 | 73 | UGRP "HMI Menu" 4 74 | # Menu 75 | LOC QW 0 # Screensaver timer threshold 76 | LOC QB 0 # Screensaver parameter number 77 | LOC IB 0 # Current parameter number 78 | # User menu variables 79 | GRP "Parameter" 0..15 80 | LOC MW "Word" [Mode:0..5] # Mode: 0 - U16 RW, 1 - I16 RW, 2 - HEX RW, 3 - U16 RO, 4 - I16 RO, 5 - HEX RO 81 | # 82 | LOC MX "Bit" [Mode:0..3] # Mode: 0 - True/False RW, 1 - On/Off RW, 2 - True/False RO, 3 - 1 - On/Off RO 83 | ENDGRP 84 | ENDGRP 85 | -------------------------------------------------------------------------------- /yaplctargets/__nuc251/plc_nuc251_main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Newlib stubs. 3 | **/ 4 | 5 | #include 6 | 7 | int _close(int file) 8 | { 9 | (void)file; 10 | return -1; 11 | } 12 | 13 | int _fstat(int file, struct stat *st) 14 | { 15 | (void)file; 16 | st->st_mode = S_IFCHR; 17 | return 0; 18 | } 19 | 20 | int _isatty(int file) 21 | { 22 | (void)file; 23 | return 1; 24 | } 25 | 26 | int _lseek(int file, int ptr, int dir) 27 | { 28 | (void)file; 29 | (void)ptr; 30 | (void)dir; 31 | return 0; 32 | } 33 | 34 | int _open(const char *name, int flags, int mode) 35 | { 36 | (void)name; 37 | (void)flags; 38 | (void)mode; 39 | return -1; 40 | } 41 | 42 | int _read(int file, char *ptr, int len) 43 | { 44 | (void)file; 45 | (void)ptr; 46 | (void)len; 47 | return 0; 48 | } 49 | 50 | char *heap_end = 0; 51 | caddr_t _sbrk(int incr) 52 | { 53 | (void)incr; 54 | return (caddr_t) 0; 55 | } 56 | 57 | int _write(int file, char *ptr, int len) 58 | { 59 | (void)file; 60 | (void)ptr; 61 | (void)len; 62 | return 0; 63 | } 64 | 65 | /** 66 | * YAPLC specific code. 67 | **/ 68 | 69 | #include 70 | #include 71 | #include 72 | 73 | /** 74 | * YAPLC ABI. 75 | **/ 76 | 77 | void fake_start(void) 78 | { 79 | while(1); 80 | } 81 | 82 | /*!< TODO: добавть специальную секцию для 83 | type * name = &(PLC_LOC_BUF(name)); 84 | Чтобы можно было разместть их во flash-памяти. 85 | */ 86 | 87 | #define PLC_LOC_BUF(name) PLC_LOC_CONCAT(name, _BUF) 88 | #define PLC_LOC_ADDR(name) PLC_LOC_CONCAT(name, _ADDR) 89 | #define PLC_LOC_DSC(name) PLC_LOC_CONCAT(name, _LDSC) 90 | 91 | #define __LOCATED_VAR( type, name, lt, lsz, io_proto, ... ) \ 92 | type PLC_LOC_BUF(name); \ 93 | type * name = &(PLC_LOC_BUF(name)); \ 94 | const uint32_t PLC_LOC_ADDR(name)[] = {__VA_ARGS__}; \ 95 | const plc_loc_dsc_t PLC_LOC_DSC(name) = \ 96 | { \ 97 | .v_buf = (void *)&(PLC_LOC_BUF(name)), \ 98 | .v_type = PLC_LOC_TYPE(lt), \ 99 | .v_size = PLC_LOC_SIZE(lsz), \ 100 | .a_size = sizeof(PLC_LOC_ADDR(name))/sizeof(uint32_t), \ 101 | .a_data = &(PLC_LOC_ADDR(name)[0]), \ 102 | .proto = io_proto \ 103 | }; 104 | 105 | #include "LOCATED_VARIABLES.h" 106 | #undef __LOCATED_VAR 107 | 108 | #define __LOCATED_VAR(type, name, ...) &(PLC_LOC_DSC(name)), 109 | plc_loc_tbl_t plc_loc_table[] = 110 | { 111 | #include "LOCATED_VARIABLES.h" 112 | }; 113 | #undef __LOCATED_VAR 114 | 115 | #define PLC_LOC_TBL_SIZE (sizeof(plc_loc_table)/sizeof(plc_loc_dsc_t *)) 116 | 117 | uint32_t plc_loc_weigth[PLC_LOC_TBL_SIZE]; 118 | 119 | #ifndef PLC_MD5 120 | #error "PLC_MD5 must be defined!!!" 121 | #endif 122 | 123 | #define PLC_MD5_STR(a) # a 124 | #define PLC_MD5_STR2(a) PLC_MD5_STR(a) 125 | //App ABI, placed after .plc_app_abi_sec 126 | __attribute__ ((section(".plc_md5_sec"))) char plc_md5[] = PLC_MD5_STR2(PLC_MD5); 127 | //App ABI, placed at the .text end 128 | __attribute__ ((section(".plc_check_sec"))) char plc_check_md5[] = PLC_MD5_STR2(PLC_MD5); 129 | 130 | //Linker added symbols 131 | extern uint32_t _plc_data_loadaddr, _plc_data_start, _plc_data_end, _plc_bss_end, _plc_sstart; 132 | 133 | extern app_fp_t _plc_pa_start, _plc_pa_end; 134 | extern app_fp_t _plc_ia_start, _plc_ia_end; 135 | extern app_fp_t _plc_fia_start,_plc_fia_end; 136 | 137 | extern int startPLC(int argc,char **argv); 138 | extern int stopPLC(); 139 | extern void runPLC(void); 140 | 141 | extern void resumeDebug(void); 142 | extern void suspendDebug(int disable); 143 | 144 | extern void FreeDebugData(void); 145 | extern int GetDebugData(unsigned long *tick, unsigned long *size, void **buffer); 146 | 147 | extern void ResetDebugVariables(void); 148 | extern void RegisterDebugVariable(int idx, void* force); 149 | 150 | extern void ResetLogCount(void); 151 | extern uint32_t GetLogCount(uint8_t level); 152 | extern uint32_t GetLogMessage(uint8_t level, uint32_t msgidx, char* buf, uint32_t max_size, uint32_t* tick, uint32_t* tv_sec, uint32_t* tv_nsec); 153 | 154 | //App ABI, placed at the .text start 155 | __attribute__ ((section(".plc_app_abi_sec"))) plc_app_abi_t plc_yaplc_app = 156 | { 157 | .sstart = (uint32_t *)&_plc_sstart, 158 | .entry = fake_start, 159 | //Startup interface 160 | .data_loadaddr = &_plc_data_loadaddr, 161 | 162 | .data_start = &_plc_data_start, 163 | .data_end = &_plc_data_end, 164 | 165 | .bss_end = &_plc_bss_end, 166 | 167 | .pa_start = &_plc_pa_start, 168 | .pa_end = &_plc_pa_end, 169 | 170 | .ia_start = &_plc_ia_start, 171 | .ia_end = &_plc_ia_end, 172 | 173 | .fia_start = &_plc_fia_start, 174 | .fia_end = &_plc_fia_end, 175 | 176 | .check_id = plc_check_md5, 177 | 178 | //Must be run on compatible RTE 179 | .rte_ver_major = 4, 180 | .rte_ver_minor = 0, 181 | .rte_ver_patch = 0, 182 | 183 | .hw_id = 2470, 184 | //IO manager interface 185 | .l_tab = &plc_loc_table[0], 186 | .w_tab = &plc_loc_weigth[0], 187 | .l_sz = PLC_LOC_TBL_SIZE, 188 | 189 | //App interface 190 | .id = plc_md5, 191 | 192 | .start = startPLC, 193 | .stop = stopPLC, 194 | .run = runPLC, 195 | 196 | .dbg_resume = resumeDebug, 197 | .dbg_suspend = suspendDebug, 198 | 199 | .dbg_data_get = GetDebugData, 200 | .dbg_data_free = FreeDebugData, 201 | 202 | .dbg_vars_reset = ResetDebugVariables, 203 | .dbg_var_register = RegisterDebugVariable, 204 | 205 | .log_cnt_get = GetLogCount, 206 | .log_msg_get = GetLogMessage, 207 | .log_cnt_reset = ResetLogCount, 208 | .log_msg_post = LogMessage 209 | }; 210 | 211 | //Redefine LOG_BUFFER_SIZE 212 | #define LOG_BUFFER_SIZE (1<<10) /*1Ko*/ 213 | #define LOG_BUFFER_ATTRS 214 | 215 | #define PLC_RTE ((plc_rte_abi_t *)(PLC_RTE_ADDR)) 216 | 217 | void PLC_GetTime(IEC_TIME *CURRENT_TIME) 218 | { 219 | PLC_RTE->get_time( CURRENT_TIME ); 220 | } 221 | 222 | void PLC_SetTimer(unsigned long long next, unsigned long long period) 223 | { 224 | PLC_RTE->set_timer( next, period ); 225 | } 226 | 227 | long AtomicCompareExchange(long* atomicvar,long compared, long exchange) 228 | { 229 | /* No need for real atomic op on LPC, 230 | * no possible preemption between debug and PLC */ 231 | long res = *atomicvar; 232 | if(res == compared){ 233 | *atomicvar = exchange; 234 | } 235 | return res; 236 | } 237 | 238 | long long AtomicCompareExchange64(long long* atomicvar,long long compared, long long exchange) 239 | { 240 | /* No need for real atomic op on LPC, 241 | * no possible preemption between debug and PLC */ 242 | long long res = *atomicvar; 243 | if(res == compared){ 244 | *atomicvar = exchange; 245 | } 246 | return res; 247 | } 248 | 249 | static int debug_locked = 0; 250 | static int _DebugDataAvailable = 0; 251 | static unsigned long __debug_tick; 252 | 253 | int TryEnterDebugSection(void) 254 | { 255 | if(!debug_locked && __DEBUG){ 256 | debug_locked = 1; 257 | return 1; 258 | } 259 | return 0; 260 | } 261 | 262 | void LeaveDebugSection(void) 263 | { 264 | debug_locked = 0; 265 | } 266 | 267 | void InitiateDebugTransfer(void) 268 | { 269 | /* remember tick */ 270 | __debug_tick = __tick; 271 | _DebugDataAvailable = 1; 272 | } 273 | 274 | void suspendDebug(int disable) 275 | { 276 | /* Prevent PLC to enter debug code */ 277 | __DEBUG = !disable; 278 | debug_locked = !disable; 279 | } 280 | 281 | void resumeDebug(void) 282 | { 283 | /* Let PLC enter debug code */ 284 | __DEBUG = 1; 285 | debug_locked = 0; 286 | } 287 | 288 | int WaitDebugData(unsigned long *tick) 289 | { 290 | if(_DebugDataAvailable && !debug_locked){ 291 | /* returns 0 on success */ 292 | *tick = __debug_tick; 293 | _DebugDataAvailable = 0; 294 | return 0; 295 | } 296 | return 1; 297 | } 298 | 299 | void ValidateRetainBuffer(void) 300 | { 301 | PLC_RTE->validate_retain_buf(); 302 | } 303 | void InValidateRetainBuffer(void) 304 | { 305 | PLC_RTE->invalidate_retain_buf(); 306 | } 307 | int CheckRetainBuffer(void) 308 | { 309 | return PLC_RTE->check_retain_buf(); 310 | } 311 | 312 | void InitRetain(void) 313 | { 314 | } 315 | 316 | void CleanupRetain(void) 317 | { 318 | } 319 | 320 | void Retain(unsigned int offset, unsigned int count, void *p) 321 | { 322 | PLC_RTE->retain( offset, count, p ); 323 | } 324 | void Remind(unsigned int offset, unsigned int count, void *p) 325 | { 326 | PLC_RTE->remind( offset, count, p ); 327 | } 328 | 329 | int startPLC(int argc,char **argv) 330 | { 331 | if(__init(argc,argv) == 0){ 332 | PLC_SetTimer(0, common_ticktime__); 333 | return 0; 334 | }else{ 335 | return 1; 336 | } 337 | } 338 | 339 | int stopPLC(void) 340 | { 341 | __cleanup(); 342 | return 0; 343 | } 344 | 345 | void runPLC(void) 346 | { 347 | PLC_GetTime( &__CURRENT_TIME ); 348 | __run(); 349 | } 350 | -------------------------------------------------------------------------------- /yaplctargets/nuc242/XSD: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %(toolchain_yaplc)s 5 | 6 | 7 | -------------------------------------------------------------------------------- /yaplctargets/nuc242/__init__.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from yaplctargets.toolchain_yaplc_stm32 import toolchain_yaplc_stm32 3 | from yaplctargets.toolchain_yaplc_stm32 import plc_rt_dir as plc_rt_dir 4 | 5 | class nuc242_target(toolchain_yaplc_stm32): 6 | def __init__(self, CTRInstance): 7 | 8 | toolchain_yaplc_stm32.__init__(self, CTRInstance) 9 | 10 | self.dev_family = "STM32F1" 11 | self.load_addr = "0x08008000" 12 | self.runtime_addr = "0x08000150" 13 | self.linker_script = os.path.join(os.path.join(os.path.join(plc_rt_dir, "bsp"), "nuc-242"), "stm32f103xC-app.ld") 14 | 15 | -------------------------------------------------------------------------------- /yaplctargets/nuc242/extensions.cfg: -------------------------------------------------------------------------------- 1 | ################################### Diagnostic info ####################################### 2 | UGRP "Diag" 0 3 | # WCET 4 | UGRP "WCET" 0 5 | LOC MD 6 | ENDGRP 7 | # Inputs 8 | UGRP "HW Failure" 0..1 9 | LOC IX 10 | ENDGRP 11 | # Debug mode (on/off) 12 | UGRP "Debug Mode" 0 13 | LOC QX 14 | ENDGRP 15 | # Outputs 16 | UGRP "Execution status" 1..3 17 | # 1 - User info (on/off), 2 - User warning (on/off), 3 - User critical, stops the program execution!!! 18 | LOC QX 19 | ENDGRP 20 | ENDGRP 21 | ################################### Discrete IO ######################################### 22 | UGRP "Discrete IO" 1 23 | # 8 discrete inputs 24 | GRP "IX" 0..7 25 | LOC IX # values 26 | LOC MB 1 # edge filters 27 | LOC MB 0 # fall filters 28 | ENDGRP 29 | # 4 relay outputs 30 | LOC QX 0..3 31 | ENDGRP 32 | ################################## Modbus slave ######################################## 33 | UGRP "Modbus slave" 2 34 | # Config locations 35 | ULOC MB "Address" 0 36 | ULOC MB "Baud" 1 37 | ULOC MB "Mode" 2 38 | # Holding register 39 | LOC MW 0..31 40 | ENDGRP 41 | ###################################### HMI ############################################# 42 | UGRP "HMI LEDs" 4 43 | UGRP "RG" 0..1 44 | # 0 - Red, 1 - Green 45 | LOC QX 46 | ENDGRP 47 | ENDGRP 48 | -------------------------------------------------------------------------------- /yaplctargets/nuc242/plc_nuc242_main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Newlib stubs. 3 | **/ 4 | 5 | #include 6 | 7 | int _close(int file) 8 | { 9 | (void)file; 10 | return -1; 11 | } 12 | 13 | int _fstat(int file, struct stat *st) 14 | { 15 | (void)file; 16 | st->st_mode = S_IFCHR; 17 | return 0; 18 | } 19 | 20 | int _isatty(int file) 21 | { 22 | (void)file; 23 | return 1; 24 | } 25 | 26 | int _lseek(int file, int ptr, int dir) 27 | { 28 | (void)file; 29 | (void)ptr; 30 | (void)dir; 31 | return 0; 32 | } 33 | 34 | int _open(const char *name, int flags, int mode) 35 | { 36 | (void)name; 37 | (void)flags; 38 | (void)mode; 39 | return -1; 40 | } 41 | 42 | int _read(int file, char *ptr, int len) 43 | { 44 | (void)file; 45 | (void)ptr; 46 | (void)len; 47 | return 0; 48 | } 49 | 50 | char *heap_end = 0; 51 | caddr_t _sbrk(int incr) 52 | { 53 | (void)incr; 54 | return (caddr_t) 0; 55 | } 56 | 57 | int _write(int file, char *ptr, int len) 58 | { 59 | (void)file; 60 | (void)ptr; 61 | (void)len; 62 | return 0; 63 | } 64 | 65 | /** 66 | * YAPLC specific code. 67 | **/ 68 | 69 | #include 70 | #include 71 | #include 72 | 73 | /** 74 | * YAPLC ABI. 75 | **/ 76 | 77 | void fake_start(void) 78 | { 79 | while(1); 80 | } 81 | 82 | /*!< TODO: добавть специальную секцию для 83 | type * name = &(PLC_LOC_BUF(name)); 84 | Чтобы можно было разместть их во flash-памяти. 85 | */ 86 | 87 | #define PLC_LOC_BUF(name) PLC_LOC_CONCAT(name, _BUF) 88 | #define PLC_LOC_ADDR(name) PLC_LOC_CONCAT(name, _ADDR) 89 | #define PLC_LOC_DSC(name) PLC_LOC_CONCAT(name, _LDSC) 90 | 91 | #define __LOCATED_VAR( type, name, lt, lsz, io_proto, ... ) \ 92 | type PLC_LOC_BUF(name); \ 93 | type * name = &(PLC_LOC_BUF(name)); \ 94 | const uint32_t PLC_LOC_ADDR(name)[] = {__VA_ARGS__}; \ 95 | const plc_loc_dsc_t PLC_LOC_DSC(name) = \ 96 | { \ 97 | .v_buf = (void *)&(PLC_LOC_BUF(name)), \ 98 | .v_type = PLC_LOC_TYPE(lt), \ 99 | .v_size = PLC_LOC_SIZE(lsz), \ 100 | .a_size = sizeof(PLC_LOC_ADDR(name))/sizeof(uint32_t), \ 101 | .a_data = &(PLC_LOC_ADDR(name)[0]), \ 102 | .proto = io_proto \ 103 | }; 104 | 105 | #include "LOCATED_VARIABLES.h" 106 | #undef __LOCATED_VAR 107 | 108 | #define __LOCATED_VAR(type, name, ...) &(PLC_LOC_DSC(name)), 109 | plc_loc_tbl_t plc_loc_table[] = 110 | { 111 | #include "LOCATED_VARIABLES.h" 112 | }; 113 | #undef __LOCATED_VAR 114 | 115 | #define PLC_LOC_TBL_SIZE (sizeof(plc_loc_table)/sizeof(plc_loc_dsc_t *)) 116 | 117 | uint32_t plc_loc_weigth[PLC_LOC_TBL_SIZE]; 118 | 119 | #ifndef PLC_MD5 120 | #error "PLC_MD5 must be defined!!!" 121 | #endif 122 | 123 | #define PLC_MD5_STR(a) # a 124 | #define PLC_MD5_STR2(a) PLC_MD5_STR(a) 125 | //App ABI, placed after .plc_app_abi_sec 126 | __attribute__ ((section(".plc_md5_sec"))) char plc_md5[] = PLC_MD5_STR2(PLC_MD5); 127 | //App ABI, placed at the .text end 128 | __attribute__ ((section(".plc_check_sec"))) char plc_check_md5[] = PLC_MD5_STR2(PLC_MD5); 129 | 130 | //Linker added symbols 131 | extern uint32_t _plc_data_loadaddr, _plc_data_start, _plc_data_end, _plc_bss_end, _plc_sstart; 132 | 133 | extern app_fp_t _plc_pa_start, _plc_pa_end; 134 | extern app_fp_t _plc_ia_start, _plc_ia_end; 135 | extern app_fp_t _plc_fia_start,_plc_fia_end; 136 | 137 | extern int startPLC(int argc,char **argv); 138 | extern int stopPLC(); 139 | extern void runPLC(void); 140 | 141 | extern void resumeDebug(void); 142 | extern void suspendDebug(int disable); 143 | 144 | extern void FreeDebugData(void); 145 | extern int GetDebugData(unsigned long *tick, unsigned long *size, void **buffer); 146 | 147 | extern void ResetDebugVariables(void); 148 | extern void RegisterDebugVariable(int idx, void* force); 149 | 150 | extern void ResetLogCount(void); 151 | extern uint32_t GetLogCount(uint8_t level); 152 | extern uint32_t GetLogMessage(uint8_t level, uint32_t msgidx, char* buf, uint32_t max_size, uint32_t* tick, uint32_t* tv_sec, uint32_t* tv_nsec); 153 | 154 | //App ABI, placed at the .text start 155 | __attribute__ ((section(".plc_app_abi_sec"))) plc_app_abi_t plc_yaplc_app = 156 | { 157 | .sstart = (uint32_t *)&_plc_sstart, 158 | .entry = fake_start, 159 | //Startup interface 160 | .data_loadaddr = &_plc_data_loadaddr, 161 | 162 | .data_start = &_plc_data_start, 163 | .data_end = &_plc_data_end, 164 | 165 | .bss_end = &_plc_bss_end, 166 | 167 | .pa_start = &_plc_pa_start, 168 | .pa_end = &_plc_pa_end, 169 | 170 | .ia_start = &_plc_ia_start, 171 | .ia_end = &_plc_ia_end, 172 | 173 | .fia_start = &_plc_fia_start, 174 | .fia_end = &_plc_fia_end, 175 | 176 | .check_id = plc_check_md5, 177 | 178 | //Must be run on compatible RTE 179 | .rte_ver_major = 4, 180 | .rte_ver_minor = 0, 181 | .rte_ver_patch = 0, 182 | 183 | .hw_id = 242, 184 | //IO manager interface 185 | .l_tab = &plc_loc_table[0], 186 | .w_tab = &plc_loc_weigth[0], 187 | .l_sz = PLC_LOC_TBL_SIZE, 188 | 189 | //App interface 190 | .id = plc_md5, 191 | 192 | .start = startPLC, 193 | .stop = stopPLC, 194 | .run = runPLC, 195 | 196 | .dbg_resume = resumeDebug, 197 | .dbg_suspend = suspendDebug, 198 | 199 | .dbg_data_get = GetDebugData, 200 | .dbg_data_free = FreeDebugData, 201 | 202 | .dbg_vars_reset = ResetDebugVariables, 203 | .dbg_var_register = RegisterDebugVariable, 204 | 205 | .log_cnt_get = GetLogCount, 206 | .log_msg_get = GetLogMessage, 207 | .log_cnt_reset = ResetLogCount, 208 | .log_msg_post = LogMessage 209 | }; 210 | 211 | //Redefine LOG_BUFFER_SIZE 212 | #define LOG_BUFFER_SIZE (1<<10) /*1Ko*/ 213 | #define LOG_BUFFER_ATTRS 214 | 215 | #define PLC_RTE ((plc_rte_abi_t *)(PLC_RTE_ADDR)) 216 | 217 | void PLC_GetTime(IEC_TIME *CURRENT_TIME) 218 | { 219 | PLC_RTE->get_time( CURRENT_TIME ); 220 | } 221 | 222 | void PLC_SetTimer(unsigned long long next, unsigned long long period) 223 | { 224 | PLC_RTE->set_timer( next, period ); 225 | } 226 | 227 | long AtomicCompareExchange(long* atomicvar,long compared, long exchange) 228 | { 229 | /* No need for real atomic op on LPC, 230 | * no possible preemption between debug and PLC */ 231 | long res = *atomicvar; 232 | if(res == compared){ 233 | *atomicvar = exchange; 234 | } 235 | return res; 236 | } 237 | 238 | long long AtomicCompareExchange64(long long* atomicvar,long long compared, long long exchange) 239 | { 240 | /* No need for real atomic op on LPC, 241 | * no possible preemption between debug and PLC */ 242 | long long res = *atomicvar; 243 | if(res == compared){ 244 | *atomicvar = exchange; 245 | } 246 | return res; 247 | } 248 | 249 | static int debug_locked = 0; 250 | static int _DebugDataAvailable = 0; 251 | static unsigned long __debug_tick; 252 | 253 | int TryEnterDebugSection(void) 254 | { 255 | if(!debug_locked && __DEBUG){ 256 | debug_locked = 1; 257 | return 1; 258 | } 259 | return 0; 260 | } 261 | 262 | void LeaveDebugSection(void) 263 | { 264 | debug_locked = 0; 265 | } 266 | 267 | void InitiateDebugTransfer(void) 268 | { 269 | /* remember tick */ 270 | __debug_tick = __tick; 271 | _DebugDataAvailable = 1; 272 | } 273 | 274 | void suspendDebug(int disable) 275 | { 276 | /* Prevent PLC to enter debug code */ 277 | __DEBUG = !disable; 278 | debug_locked = !disable; 279 | } 280 | 281 | void resumeDebug(void) 282 | { 283 | /* Let PLC enter debug code */ 284 | __DEBUG = 1; 285 | debug_locked = 0; 286 | } 287 | 288 | int WaitDebugData(unsigned long *tick) 289 | { 290 | if(_DebugDataAvailable && !debug_locked){ 291 | /* returns 0 on success */ 292 | *tick = __debug_tick; 293 | _DebugDataAvailable = 0; 294 | return 0; 295 | } 296 | return 1; 297 | } 298 | 299 | void ValidateRetainBuffer(void) 300 | { 301 | PLC_RTE->validate_retain_buf(); 302 | } 303 | void InValidateRetainBuffer(void) 304 | { 305 | PLC_RTE->invalidate_retain_buf(); 306 | } 307 | int CheckRetainBuffer(void) 308 | { 309 | return PLC_RTE->check_retain_buf(); 310 | } 311 | 312 | void InitRetain(void) 313 | { 314 | } 315 | 316 | void CleanupRetain(void) 317 | { 318 | } 319 | 320 | void Retain(unsigned int offset, unsigned int count, void *p) 321 | { 322 | PLC_RTE->retain( offset, count, p ); 323 | } 324 | void Remind(unsigned int offset, unsigned int count, void *p) 325 | { 326 | PLC_RTE->remind( offset, count, p ); 327 | } 328 | 329 | int startPLC(int argc,char **argv) 330 | { 331 | if(__init(argc,argv) == 0){ 332 | PLC_SetTimer(0, common_ticktime__); 333 | return 0; 334 | }else{ 335 | return 1; 336 | } 337 | } 338 | 339 | int stopPLC(void) 340 | { 341 | __cleanup(); 342 | return 0; 343 | } 344 | 345 | void runPLC(void) 346 | { 347 | PLC_GetTime( &__CURRENT_TIME ); 348 | __run(); 349 | } 350 | -------------------------------------------------------------------------------- /yaplctargets/nuc243/XSD: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %(toolchain_yaplc)s 5 | 6 | 7 | -------------------------------------------------------------------------------- /yaplctargets/nuc243/__init__.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from yaplctargets.toolchain_yaplc_stm32 import toolchain_yaplc_stm32 3 | from yaplctargets.toolchain_yaplc_stm32 import plc_rt_dir as plc_rt_dir 4 | 5 | class nuc243_target(toolchain_yaplc_stm32): 6 | def __init__(self, CTRInstance): 7 | 8 | toolchain_yaplc_stm32.__init__(self, CTRInstance) 9 | 10 | self.dev_family = "STM32F2" 11 | self.load_addr = "0x08008000" 12 | self.runtime_addr = "0x08000184" 13 | self.linker_script = os.path.join(os.path.join(os.path.join(plc_rt_dir, "bsp"), "nuc-243"), "stm32f205xC-app.ld") 14 | -------------------------------------------------------------------------------- /yaplctargets/nuc243/extensions.cfg: -------------------------------------------------------------------------------- 1 | ################################### Diagnostic info ####################################### 2 | UGRP "Diag" 0 3 | # WCET 4 | UGRP "WCET" 0 5 | LOC MD 6 | ENDGRP 7 | # Inputs 8 | UGRP "HW Failure" 0..1 9 | LOC IX 10 | ENDGRP 11 | # Debug mode (on/off) 12 | UGRP "Debug Mode" 0 13 | LOC QX 14 | ENDGRP 15 | # Outputs 16 | UGRP "Execution status" 1..3 17 | # 1 - User info (on/off), 2 - User warning (on/off), 3 - User critical, stops the program execution!!! 18 | LOC QX 19 | ENDGRP 20 | ENDGRP 21 | ################################### Discrete IO ######################################### 22 | UGRP "Discrete IO" 1 23 | # 8 discrete inputs 24 | GRP "IX" 0..7 25 | LOC IX # values 26 | LOC MB 1 # edge filters 27 | LOC MB 0 # fall filters 28 | ENDGRP 29 | # 6 relay outputs 30 | LOC QX 0..5 31 | ENDGRP 32 | ################################## Modbus slave ######################################## 33 | UGRP "Modbus slave" 2 34 | # Config locations 35 | ULOC MB "Address" 0 36 | ULOC MB "Baud" 1 37 | ULOC MB "Mode" 2 38 | # Holding register 39 | LOC MW 0..31 40 | ENDGRP 41 | ###################################### HMI ############################################# 42 | UGRP "HMI LEDs" 4 43 | UGRP "RG" 0..1 44 | # 0 - Red, 1 - Green 45 | LOC QX 46 | ENDGRP 47 | # 4 dots on indicators 48 | UGRP "Dot" 10..13 49 | LOC QX 50 | ENDGRP 51 | #8 LEDS near indicators 52 | UGRP "Other" 2..9 53 | LOC QX 54 | ENDGRP 55 | ENDGRP 56 | 57 | UGRP "HMI Menu" 4 58 | # Menu 59 | LOC QW 0 # Screensaver timer threshold 60 | LOC QB 0 # Screensaver parameter number 61 | LOC IB 0 # Current parameter number 62 | # User menu variables 63 | GRP "Parameter" 0..15 64 | LOC MW "Word" [Mode:0..5] # Mode: 0 - U16 RW, 1 - I16 RW, 2 - HEX RW, 3 - U16 RO, 4 - I16 RO, 5 - HEX RO 65 | LOC QW 0 # Lower limit 66 | LOC QW 1 # Upper limit 67 | # 68 | LOC MX "Bit" [Mode:0..3] # Mode: 0 - True/False RW, 1 - On/Off RW, 2 - True/False RO, 3 - 1 - On/Off RO 69 | ENDGRP 70 | ENDGRP 71 | ################################ Analog outputs ######################################## 72 | UGRP "Analog outputs" 5 # Analog outputs 73 | LOC QW 0..1 74 | ENDGRP 75 | ################################ Analog inputs ######################################### 76 | UGRP "Analog inputs" 6 77 | GRP "Chanel" 0..3 78 | LOC QB 1 # Mode: 0 - off, 1 - 10V, 2 - 20mA, 3 - 100Ohm, 5 - 4KOhm. 79 | LOC QB 2 # Median filter depth 80 | LOC QB 3 # Aversge filter depth 81 | LOC QW 4 # Poll period 82 | LOC QW 5 # Schmidt trigger low thr 83 | LOC QW 6 # Schmidt trigger high thr 84 | LOC IW 7 # Signal level 85 | LOC IX 8 # Schmidt trigger state 86 | ENDGRP 87 | ENDGRP 88 | -------------------------------------------------------------------------------- /yaplctargets/nuc243/plc_nuc243_main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Newlib stubs. 3 | **/ 4 | 5 | #include 6 | 7 | int _close(int file) 8 | { 9 | (void)file; 10 | return -1; 11 | } 12 | 13 | int _fstat(int file, struct stat *st) 14 | { 15 | (void)file; 16 | st->st_mode = S_IFCHR; 17 | return 0; 18 | } 19 | 20 | int _isatty(int file) 21 | { 22 | (void)file; 23 | return 1; 24 | } 25 | 26 | int _lseek(int file, int ptr, int dir) 27 | { 28 | (void)file; 29 | (void)ptr; 30 | (void)dir; 31 | return 0; 32 | } 33 | 34 | int _open(const char *name, int flags, int mode) 35 | { 36 | (void)name; 37 | (void)flags; 38 | (void)mode; 39 | return -1; 40 | } 41 | 42 | int _read(int file, char *ptr, int len) 43 | { 44 | (void)file; 45 | (void)ptr; 46 | (void)len; 47 | return 0; 48 | } 49 | 50 | char *heap_end = 0; 51 | caddr_t _sbrk(int incr) 52 | { 53 | (void)incr; 54 | return (caddr_t) 0; 55 | } 56 | 57 | int _write(int file, char *ptr, int len) 58 | { 59 | (void)file; 60 | (void)ptr; 61 | (void)len; 62 | return 0; 63 | } 64 | 65 | /** 66 | * YAPLC specific code. 67 | **/ 68 | 69 | #include 70 | #include 71 | #include 72 | 73 | /** 74 | * YAPLC ABI. 75 | **/ 76 | 77 | void fake_start(void) 78 | { 79 | while(1); 80 | } 81 | 82 | /*!< TODO: добавть специальную секцию для 83 | type * name = &(PLC_LOC_BUF(name)); 84 | Чтобы можно было разместть их во flash-памяти. 85 | */ 86 | 87 | #define PLC_LOC_BUF(name) PLC_LOC_CONCAT(name, _BUF) 88 | #define PLC_LOC_ADDR(name) PLC_LOC_CONCAT(name, _ADDR) 89 | #define PLC_LOC_DSC(name) PLC_LOC_CONCAT(name, _LDSC) 90 | 91 | #define __LOCATED_VAR( type, name, lt, lsz, io_proto, ... ) \ 92 | type PLC_LOC_BUF(name); \ 93 | type * name = &(PLC_LOC_BUF(name)); \ 94 | const uint32_t PLC_LOC_ADDR(name)[] = {__VA_ARGS__}; \ 95 | const plc_loc_dsc_t PLC_LOC_DSC(name) = \ 96 | { \ 97 | .v_buf = (void *)&(PLC_LOC_BUF(name)), \ 98 | .v_type = PLC_LOC_TYPE(lt), \ 99 | .v_size = PLC_LOC_SIZE(lsz), \ 100 | .a_size = sizeof(PLC_LOC_ADDR(name))/sizeof(uint32_t), \ 101 | .a_data = &(PLC_LOC_ADDR(name)[0]), \ 102 | .proto = io_proto \ 103 | }; 104 | 105 | #include "LOCATED_VARIABLES.h" 106 | #undef __LOCATED_VAR 107 | 108 | #define __LOCATED_VAR(type, name, ...) &(PLC_LOC_DSC(name)), 109 | plc_loc_tbl_t plc_loc_table[] = 110 | { 111 | #include "LOCATED_VARIABLES.h" 112 | }; 113 | #undef __LOCATED_VAR 114 | 115 | #define PLC_LOC_TBL_SIZE (sizeof(plc_loc_table)/sizeof(plc_loc_dsc_t *)) 116 | 117 | uint32_t plc_loc_weigth[PLC_LOC_TBL_SIZE]; 118 | 119 | #ifndef PLC_MD5 120 | #error "PLC_MD5 must be defined!!!" 121 | #endif 122 | 123 | #define PLC_MD5_STR(a) # a 124 | #define PLC_MD5_STR2(a) PLC_MD5_STR(a) 125 | //App ABI, placed after .plc_app_abi_sec 126 | __attribute__ ((section(".plc_md5_sec"))) char plc_md5[] = PLC_MD5_STR2(PLC_MD5); 127 | //App ABI, placed at the .text end 128 | __attribute__ ((section(".plc_check_sec"))) char plc_check_md5[] = PLC_MD5_STR2(PLC_MD5); 129 | 130 | //Linker added symbols 131 | extern uint32_t _plc_data_loadaddr, _plc_data_start, _plc_data_end, _plc_bss_end, _plc_sstart; 132 | 133 | extern app_fp_t _plc_pa_start, _plc_pa_end; 134 | extern app_fp_t _plc_ia_start, _plc_ia_end; 135 | extern app_fp_t _plc_fia_start,_plc_fia_end; 136 | 137 | extern int startPLC(int argc,char **argv); 138 | extern int stopPLC(); 139 | extern void runPLC(void); 140 | 141 | extern void resumeDebug(void); 142 | extern void suspendDebug(int disable); 143 | 144 | extern void FreeDebugData(void); 145 | extern int GetDebugData(unsigned long *tick, unsigned long *size, void **buffer); 146 | 147 | extern void ResetDebugVariables(void); 148 | extern void RegisterDebugVariable(int idx, void* force); 149 | 150 | extern void ResetLogCount(void); 151 | extern uint32_t GetLogCount(uint8_t level); 152 | extern uint32_t GetLogMessage(uint8_t level, uint32_t msgidx, char* buf, uint32_t max_size, uint32_t* tick, uint32_t* tv_sec, uint32_t* tv_nsec); 153 | 154 | //App ABI, placed at the .text start 155 | __attribute__ ((section(".plc_app_abi_sec"))) plc_app_abi_t plc_yaplc_app = 156 | { 157 | .sstart = (uint32_t *)&_plc_sstart, 158 | .entry = fake_start, 159 | //Startup interface 160 | .data_loadaddr = &_plc_data_loadaddr, 161 | 162 | .data_start = &_plc_data_start, 163 | .data_end = &_plc_data_end, 164 | 165 | .bss_end = &_plc_bss_end, 166 | 167 | .pa_start = &_plc_pa_start, 168 | .pa_end = &_plc_pa_end, 169 | 170 | .ia_start = &_plc_ia_start, 171 | .ia_end = &_plc_ia_end, 172 | 173 | .fia_start = &_plc_fia_start, 174 | .fia_end = &_plc_fia_end, 175 | 176 | .check_id = plc_check_md5, 177 | 178 | //Must be run on compatible RTE 179 | .rte_ver_major = 4, 180 | .rte_ver_minor = 0, 181 | .rte_ver_patch = 0, 182 | 183 | .hw_id = 243, 184 | //IO manager interface 185 | .l_tab = &plc_loc_table[0], 186 | .w_tab = &plc_loc_weigth[0], 187 | .l_sz = PLC_LOC_TBL_SIZE, 188 | 189 | //App interface 190 | .id = plc_md5, 191 | 192 | .start = startPLC, 193 | .stop = stopPLC, 194 | .run = runPLC, 195 | 196 | .dbg_resume = resumeDebug, 197 | .dbg_suspend = suspendDebug, 198 | 199 | .dbg_data_get = GetDebugData, 200 | .dbg_data_free = FreeDebugData, 201 | 202 | .dbg_vars_reset = ResetDebugVariables, 203 | .dbg_var_register = RegisterDebugVariable, 204 | 205 | .log_cnt_get = GetLogCount, 206 | .log_msg_get = GetLogMessage, 207 | .log_cnt_reset = ResetLogCount, 208 | .log_msg_post = LogMessage 209 | }; 210 | 211 | //Redefine LOG_BUFFER_SIZE 212 | #define LOG_BUFFER_SIZE (1<<10) /*1Ko*/ 213 | #define LOG_BUFFER_ATTRS 214 | 215 | #define PLC_RTE ((plc_rte_abi_t *)(PLC_RTE_ADDR)) 216 | 217 | void PLC_GetTime(IEC_TIME *CURRENT_TIME) 218 | { 219 | PLC_RTE->get_time( CURRENT_TIME ); 220 | } 221 | 222 | void PLC_SetTimer(unsigned long long next, unsigned long long period) 223 | { 224 | PLC_RTE->set_timer( next, period ); 225 | } 226 | 227 | long AtomicCompareExchange(long* atomicvar,long compared, long exchange) 228 | { 229 | /* No need for real atomic op on LPC, 230 | * no possible preemption between debug and PLC */ 231 | long res = *atomicvar; 232 | if(res == compared){ 233 | *atomicvar = exchange; 234 | } 235 | return res; 236 | } 237 | 238 | long long AtomicCompareExchange64(long long* atomicvar,long long compared, long long exchange) 239 | { 240 | /* No need for real atomic op on LPC, 241 | * no possible preemption between debug and PLC */ 242 | long long res = *atomicvar; 243 | if(res == compared){ 244 | *atomicvar = exchange; 245 | } 246 | return res; 247 | } 248 | 249 | static int debug_locked = 0; 250 | static int _DebugDataAvailable = 0; 251 | static unsigned long __debug_tick; 252 | 253 | int TryEnterDebugSection(void) 254 | { 255 | if(!debug_locked && __DEBUG){ 256 | debug_locked = 1; 257 | return 1; 258 | } 259 | return 0; 260 | } 261 | 262 | void LeaveDebugSection(void) 263 | { 264 | debug_locked = 0; 265 | } 266 | 267 | void InitiateDebugTransfer(void) 268 | { 269 | /* remember tick */ 270 | __debug_tick = __tick; 271 | _DebugDataAvailable = 1; 272 | } 273 | 274 | void suspendDebug(int disable) 275 | { 276 | /* Prevent PLC to enter debug code */ 277 | __DEBUG = !disable; 278 | debug_locked = !disable; 279 | } 280 | 281 | void resumeDebug(void) 282 | { 283 | /* Let PLC enter debug code */ 284 | __DEBUG = 1; 285 | debug_locked = 0; 286 | } 287 | 288 | int WaitDebugData(unsigned long *tick) 289 | { 290 | if(_DebugDataAvailable && !debug_locked){ 291 | /* returns 0 on success */ 292 | *tick = __debug_tick; 293 | _DebugDataAvailable = 0; 294 | return 0; 295 | } 296 | return 1; 297 | } 298 | 299 | void ValidateRetainBuffer(void) 300 | { 301 | PLC_RTE->validate_retain_buf(); 302 | } 303 | void InValidateRetainBuffer(void) 304 | { 305 | PLC_RTE->invalidate_retain_buf(); 306 | } 307 | int CheckRetainBuffer(void) 308 | { 309 | return PLC_RTE->check_retain_buf(); 310 | } 311 | 312 | void InitRetain(void) 313 | { 314 | } 315 | 316 | void CleanupRetain(void) 317 | { 318 | } 319 | 320 | void Retain(unsigned int offset, unsigned int count, void *p) 321 | { 322 | PLC_RTE->retain( offset, count, p ); 323 | } 324 | void Remind(unsigned int offset, unsigned int count, void *p) 325 | { 326 | PLC_RTE->remind( offset, count, p ); 327 | } 328 | 329 | int startPLC(int argc,char **argv) 330 | { 331 | if(__init(argc,argv) == 0){ 332 | PLC_SetTimer(0, common_ticktime__); 333 | return 0; 334 | }else{ 335 | return 1; 336 | } 337 | } 338 | 339 | int stopPLC(void) 340 | { 341 | __cleanup(); 342 | return 0; 343 | } 344 | 345 | void runPLC(void) 346 | { 347 | PLC_GetTime( &__CURRENT_TIME ); 348 | __run(); 349 | } 350 | -------------------------------------------------------------------------------- /yaplctargets/nuc247/XSD: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %(toolchain_yaplc)s 5 | 6 | 7 | -------------------------------------------------------------------------------- /yaplctargets/nuc247/__init__.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from yaplctargets.toolchain_yaplc_stm32 import toolchain_yaplc_stm32 3 | from yaplctargets.toolchain_yaplc_stm32 import plc_rt_dir as plc_rt_dir 4 | 5 | class nuc247_target(toolchain_yaplc_stm32): 6 | def __init__(self, CTRInstance): 7 | 8 | toolchain_yaplc_stm32.__init__(self, CTRInstance) 9 | 10 | self.dev_family = "STM32F2" 11 | self.load_addr = "0x08008000" 12 | self.runtime_addr = "0x08000184" 13 | self.linker_script = os.path.join(os.path.join(os.path.join(plc_rt_dir, "bsp"), "nuc-247-0"), "stm32f205xC-app.ld") 14 | -------------------------------------------------------------------------------- /yaplctargets/nuc247/extensions.cfg: -------------------------------------------------------------------------------- 1 | ################################### Diagnostic info ####################################### 2 | UGRP "Diag" 0 3 | # WCET 4 | UGRP "WCET" 0 5 | LOC MD 6 | ENDGRP 7 | # Inputs 8 | UGRP "HW Failure" 0..1 9 | LOC IX 10 | ENDGRP 11 | # Debug mode (on/off) 12 | UGRP "Debug Mode" 0 13 | LOC QX 14 | ENDGRP 15 | # Outputs 16 | UGRP "Execution status" 1..3 17 | # 1 - User info (on/off), 2 - User warning (on/off), 3 - User critical, stops the program execution!!! 18 | LOC QX 19 | ENDGRP 20 | ENDGRP 21 | ################################### Discrete IO ######################################### 22 | UGRP "Discrete IO" 1 23 | # 12 discrete inputs 24 | GRP "IX" 0..11 25 | LOC IX # values 26 | LOC MB 1 # edge filters 27 | LOC MB 0 # fall filters 28 | ENDGRP 29 | # 8 relay outputs 30 | LOC QX 0..7 31 | ENDGRP 32 | ################################## Modbus slave ######################################## 33 | UGRP "Modbus slave" 2 34 | # Config locations 35 | ULOC MB "Address" 0 36 | ULOC MB "Baud" 1 37 | ULOC MB "Mode" 2 38 | # Holding register 39 | LOC MW 0..31 40 | ENDGRP 41 | ###################################### HMI ############################################# 42 | UGRP "HMI LEDs" 4 43 | UGRP "RG" 0..1 44 | # 0 - Red, 1 - Green 45 | LOC QX 46 | ENDGRP 47 | # 4 dots on indicators 48 | UGRP "Dot" 10..13 49 | LOC QX 50 | ENDGRP 51 | #8 LEDS near indicators 52 | UGRP "Other" 2..9 53 | LOC QX 54 | ENDGRP 55 | ENDGRP 56 | 57 | UGRP "HMI Menu" 4 58 | # Menu 59 | LOC QW 0 # Screensaver timer threshold 60 | LOC QB 0 # Screensaver parameter number 61 | LOC IB 0 # Current parameter number 62 | # User menu variables 63 | GRP "Parameter" 0..15 64 | LOC MW "Word" [Mode:0..5] # Mode: 0 - U16 RW, 1 - I16 RW, 2 - HEX RW, 3 - U16 RO, 4 - I16 RO, 5 - HEX RO 65 | # 66 | LOC MX "Bit" [Mode:0..3] # Mode: 0 - True/False RW, 1 - On/Off RW, 2 - True/False RO, 3 - 1 - On/Off RO 67 | ENDGRP 68 | ENDGRP 69 | -------------------------------------------------------------------------------- /yaplctargets/nuc247/plc_nuc247_main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Newlib stubs. 3 | **/ 4 | 5 | #include 6 | 7 | int _close(int file) 8 | { 9 | (void)file; 10 | return -1; 11 | } 12 | 13 | int _fstat(int file, struct stat *st) 14 | { 15 | (void)file; 16 | st->st_mode = S_IFCHR; 17 | return 0; 18 | } 19 | 20 | int _isatty(int file) 21 | { 22 | (void)file; 23 | return 1; 24 | } 25 | 26 | int _lseek(int file, int ptr, int dir) 27 | { 28 | (void)file; 29 | (void)ptr; 30 | (void)dir; 31 | return 0; 32 | } 33 | 34 | int _open(const char *name, int flags, int mode) 35 | { 36 | (void)name; 37 | (void)flags; 38 | (void)mode; 39 | return -1; 40 | } 41 | 42 | int _read(int file, char *ptr, int len) 43 | { 44 | (void)file; 45 | (void)ptr; 46 | (void)len; 47 | return 0; 48 | } 49 | 50 | char *heap_end = 0; 51 | caddr_t _sbrk(int incr) 52 | { 53 | (void)incr; 54 | return (caddr_t) 0; 55 | } 56 | 57 | int _write(int file, char *ptr, int len) 58 | { 59 | (void)file; 60 | (void)ptr; 61 | (void)len; 62 | return 0; 63 | } 64 | 65 | /** 66 | * YAPLC specific code. 67 | **/ 68 | 69 | #include 70 | #include 71 | #include 72 | 73 | /** 74 | * YAPLC ABI. 75 | **/ 76 | 77 | void fake_start(void) 78 | { 79 | while(1); 80 | } 81 | 82 | /*!< TODO: добавть специальную секцию для 83 | type * name = &(PLC_LOC_BUF(name)); 84 | Чтобы можно было разместть их во flash-памяти. 85 | */ 86 | 87 | #define PLC_LOC_BUF(name) PLC_LOC_CONCAT(name, _BUF) 88 | #define PLC_LOC_ADDR(name) PLC_LOC_CONCAT(name, _ADDR) 89 | #define PLC_LOC_DSC(name) PLC_LOC_CONCAT(name, _LDSC) 90 | 91 | #define __LOCATED_VAR( type, name, lt, lsz, io_proto, ... ) \ 92 | type PLC_LOC_BUF(name); \ 93 | type * name = &(PLC_LOC_BUF(name)); \ 94 | const uint32_t PLC_LOC_ADDR(name)[] = {__VA_ARGS__}; \ 95 | const plc_loc_dsc_t PLC_LOC_DSC(name) = \ 96 | { \ 97 | .v_buf = (void *)&(PLC_LOC_BUF(name)), \ 98 | .v_type = PLC_LOC_TYPE(lt), \ 99 | .v_size = PLC_LOC_SIZE(lsz), \ 100 | .a_size = sizeof(PLC_LOC_ADDR(name))/sizeof(uint32_t), \ 101 | .a_data = &(PLC_LOC_ADDR(name)[0]), \ 102 | .proto = io_proto \ 103 | }; 104 | 105 | #include "LOCATED_VARIABLES.h" 106 | #undef __LOCATED_VAR 107 | 108 | #define __LOCATED_VAR(type, name, ...) &(PLC_LOC_DSC(name)), 109 | plc_loc_tbl_t plc_loc_table[] = 110 | { 111 | #include "LOCATED_VARIABLES.h" 112 | }; 113 | #undef __LOCATED_VAR 114 | 115 | #define PLC_LOC_TBL_SIZE (sizeof(plc_loc_table)/sizeof(plc_loc_dsc_t *)) 116 | 117 | uint32_t plc_loc_weigth[PLC_LOC_TBL_SIZE]; 118 | 119 | #ifndef PLC_MD5 120 | #error "PLC_MD5 must be defined!!!" 121 | #endif 122 | 123 | #define PLC_MD5_STR(a) # a 124 | #define PLC_MD5_STR2(a) PLC_MD5_STR(a) 125 | //App ABI, placed after .plc_app_abi_sec 126 | __attribute__ ((section(".plc_md5_sec"))) char plc_md5[] = PLC_MD5_STR2(PLC_MD5); 127 | //App ABI, placed at the .text end 128 | __attribute__ ((section(".plc_check_sec"))) char plc_check_md5[] = PLC_MD5_STR2(PLC_MD5); 129 | 130 | //Linker added symbols 131 | extern uint32_t _plc_data_loadaddr, _plc_data_start, _plc_data_end, _plc_bss_end, _plc_sstart; 132 | 133 | extern app_fp_t _plc_pa_start, _plc_pa_end; 134 | extern app_fp_t _plc_ia_start, _plc_ia_end; 135 | extern app_fp_t _plc_fia_start,_plc_fia_end; 136 | 137 | extern int startPLC(int argc,char **argv); 138 | extern int stopPLC(); 139 | extern void runPLC(void); 140 | 141 | extern void resumeDebug(void); 142 | extern void suspendDebug(int disable); 143 | 144 | extern void FreeDebugData(void); 145 | extern int GetDebugData(unsigned long *tick, unsigned long *size, void **buffer); 146 | 147 | extern void ResetDebugVariables(void); 148 | extern void RegisterDebugVariable(int idx, void* force); 149 | 150 | extern void ResetLogCount(void); 151 | extern uint32_t GetLogCount(uint8_t level); 152 | extern uint32_t GetLogMessage(uint8_t level, uint32_t msgidx, char* buf, uint32_t max_size, uint32_t* tick, uint32_t* tv_sec, uint32_t* tv_nsec); 153 | 154 | //App ABI, placed at the .text start 155 | __attribute__ ((section(".plc_app_abi_sec"))) plc_app_abi_t plc_yaplc_app = 156 | { 157 | .sstart = (uint32_t *)&_plc_sstart, 158 | .entry = fake_start, 159 | //Startup interface 160 | .data_loadaddr = &_plc_data_loadaddr, 161 | 162 | .data_start = &_plc_data_start, 163 | .data_end = &_plc_data_end, 164 | 165 | .bss_end = &_plc_bss_end, 166 | 167 | .pa_start = &_plc_pa_start, 168 | .pa_end = &_plc_pa_end, 169 | 170 | .ia_start = &_plc_ia_start, 171 | .ia_end = &_plc_ia_end, 172 | 173 | .fia_start = &_plc_fia_start, 174 | .fia_end = &_plc_fia_end, 175 | 176 | .check_id = plc_check_md5, 177 | 178 | //Must be run on compatible RTE 179 | .rte_ver_major = 4, 180 | .rte_ver_minor = 0, 181 | .rte_ver_patch = 0, 182 | 183 | .hw_id = 2470, 184 | //IO manager interface 185 | .l_tab = &plc_loc_table[0], 186 | .w_tab = &plc_loc_weigth[0], 187 | .l_sz = PLC_LOC_TBL_SIZE, 188 | 189 | //App interface 190 | .id = plc_md5, 191 | 192 | .start = startPLC, 193 | .stop = stopPLC, 194 | .run = runPLC, 195 | 196 | .dbg_resume = resumeDebug, 197 | .dbg_suspend = suspendDebug, 198 | 199 | .dbg_data_get = GetDebugData, 200 | .dbg_data_free = FreeDebugData, 201 | 202 | .dbg_vars_reset = ResetDebugVariables, 203 | .dbg_var_register = RegisterDebugVariable, 204 | 205 | .log_cnt_get = GetLogCount, 206 | .log_msg_get = GetLogMessage, 207 | .log_cnt_reset = ResetLogCount, 208 | .log_msg_post = LogMessage 209 | }; 210 | 211 | //Redefine LOG_BUFFER_SIZE 212 | #define LOG_BUFFER_SIZE (1<<10) /*1Ko*/ 213 | #define LOG_BUFFER_ATTRS 214 | 215 | #define PLC_RTE ((plc_rte_abi_t *)(PLC_RTE_ADDR)) 216 | 217 | void PLC_GetTime(IEC_TIME *CURRENT_TIME) 218 | { 219 | PLC_RTE->get_time( CURRENT_TIME ); 220 | } 221 | 222 | void PLC_SetTimer(unsigned long long next, unsigned long long period) 223 | { 224 | PLC_RTE->set_timer( next, period ); 225 | } 226 | 227 | long AtomicCompareExchange(long* atomicvar,long compared, long exchange) 228 | { 229 | /* No need for real atomic op on LPC, 230 | * no possible preemption between debug and PLC */ 231 | long res = *atomicvar; 232 | if(res == compared){ 233 | *atomicvar = exchange; 234 | } 235 | return res; 236 | } 237 | 238 | long long AtomicCompareExchange64(long long* atomicvar,long long compared, long long exchange) 239 | { 240 | /* No need for real atomic op on LPC, 241 | * no possible preemption between debug and PLC */ 242 | long long res = *atomicvar; 243 | if(res == compared){ 244 | *atomicvar = exchange; 245 | } 246 | return res; 247 | } 248 | 249 | static int debug_locked = 0; 250 | static int _DebugDataAvailable = 0; 251 | static unsigned long __debug_tick; 252 | 253 | int TryEnterDebugSection(void) 254 | { 255 | if(!debug_locked && __DEBUG){ 256 | debug_locked = 1; 257 | return 1; 258 | } 259 | return 0; 260 | } 261 | 262 | void LeaveDebugSection(void) 263 | { 264 | debug_locked = 0; 265 | } 266 | 267 | void InitiateDebugTransfer(void) 268 | { 269 | /* remember tick */ 270 | __debug_tick = __tick; 271 | _DebugDataAvailable = 1; 272 | } 273 | 274 | void suspendDebug(int disable) 275 | { 276 | /* Prevent PLC to enter debug code */ 277 | __DEBUG = !disable; 278 | debug_locked = !disable; 279 | } 280 | 281 | void resumeDebug(void) 282 | { 283 | /* Let PLC enter debug code */ 284 | __DEBUG = 1; 285 | debug_locked = 0; 286 | } 287 | 288 | int WaitDebugData(unsigned long *tick) 289 | { 290 | if(_DebugDataAvailable && !debug_locked){ 291 | /* returns 0 on success */ 292 | *tick = __debug_tick; 293 | _DebugDataAvailable = 0; 294 | return 0; 295 | } 296 | return 1; 297 | } 298 | 299 | void ValidateRetainBuffer(void) 300 | { 301 | PLC_RTE->validate_retain_buf(); 302 | } 303 | void InValidateRetainBuffer(void) 304 | { 305 | PLC_RTE->invalidate_retain_buf(); 306 | } 307 | int CheckRetainBuffer(void) 308 | { 309 | return PLC_RTE->check_retain_buf(); 310 | } 311 | 312 | void InitRetain(void) 313 | { 314 | } 315 | 316 | void CleanupRetain(void) 317 | { 318 | } 319 | 320 | void Retain(unsigned int offset, unsigned int count, void *p) 321 | { 322 | PLC_RTE->retain( offset, count, p ); 323 | } 324 | void Remind(unsigned int offset, unsigned int count, void *p) 325 | { 326 | PLC_RTE->remind( offset, count, p ); 327 | } 328 | 329 | int startPLC(int argc,char **argv) 330 | { 331 | if(__init(argc,argv) == 0){ 332 | PLC_SetTimer(0, common_ticktime__); 333 | return 0; 334 | }else{ 335 | return 1; 336 | } 337 | } 338 | 339 | int stopPLC(void) 340 | { 341 | __cleanup(); 342 | return 0; 343 | } 344 | 345 | void runPLC(void) 346 | { 347 | PLC_GetTime( &__CURRENT_TIME ); 348 | __run(); 349 | } 350 | -------------------------------------------------------------------------------- /yaplctargets/toolchain_yaplc.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from util.ProcessLogger import ProcessLogger 3 | from targets.toolchain_gcc import toolchain_gcc 4 | 5 | toolchain_dir = os.path.dirname(os.path.realpath(__file__)) 6 | base_dir = os.path.join(os.path.join(toolchain_dir, ".."), "..") 7 | plc_rt_dir = os.path.join(os.path.join(base_dir, "RTE"), "src") 8 | if (os.name == 'posix' and not os.path.isfile(plc_rt_dir)): 9 | plc_rt_dir = os.environ["HOME"]+"/YAPLC/RTE/src" 10 | 11 | class toolchain_yaplc(toolchain_gcc): 12 | def __init__(self, CTRInstance): 13 | self.dev_family = "NO_DEVICE" 14 | self.load_addr = "0" 15 | self.runtime_addr = "0" 16 | self.base_flags = ["-mthumb", "-mcpu=cortex-m3", "-g3"] 17 | 18 | if os.name in ("nt", "ce"): 19 | prefix_dir = os.path.join(os.path.join(base_dir, "gnu-arm-embedded"), "bin") 20 | self.toolchain_prefix = prefix_dir + "\\arm-none-eabi-" 21 | else: 22 | self.toolchain_prefix = "arm-none-eabi-" 23 | 24 | self.linker_script = "" 25 | self.extension = ".elf" 26 | toolchain_gcc.__init__(self, CTRInstance) 27 | 28 | def getBuilderCFLAGS(self): 29 | """ 30 | Returns list of builder specific CFLAGS 31 | """ 32 | flags = self.base_flags 33 | flags += ["-std=gnu90", "-Wall", "-fdata-sections", "-ffunction-sections", "-fno-strict-aliasing"] 34 | flags += ["-D"+ self.dev_family] 35 | flags += ["-I\"" + plc_rt_dir + "\""] 36 | flags += ["-DPLC_RTE_ADDR=" + self.runtime_addr] 37 | flags += self.cflags 38 | return flags + [self.CTRInstance.GetTarget().getcontent().getCFLAGS()] 39 | 40 | def getBuilderLDFLAGS(self): 41 | """ 42 | Returns list of builder specific LDFLAGS 43 | """ 44 | flags = self.base_flags 45 | flags += ["-Xlinker", "-T \"" + self.linker_script + "\""] 46 | flags += ["-Wl,--gc-sections", "-nostartfiles"] 47 | #flags += ["-Wl,-Map=\"" + self.exe_path + ".map\""] 48 | return flags + [self.CTRInstance.GetTarget().getcontent().getLDFLAGS()] 49 | 50 | def getCompiler(self): 51 | """ 52 | Returns compiler 53 | """ 54 | return self.toolchain_prefix + "gcc" 55 | 56 | def getLinker(self): 57 | """ 58 | Returns linker 59 | """ 60 | return self.toolchain_prefix + "g++" 61 | 62 | def calc_md5(self): 63 | return toolchain_gcc.calc_source_md5(self) 64 | 65 | def build(self): 66 | 67 | #Build project 68 | self.cflags = ["-DPLC_MD5=" + self.calc_md5()] 69 | 70 | if toolchain_gcc.build(self): 71 | #Run objcopy on success 72 | self.CTRInstance.logger.write(" [OBJCOPY] " + self.exe +" -> " + self.exe + ".hex\n") 73 | 74 | objcpy = [self.toolchain_prefix + "objcopy", "--change-address", self.load_addr, "-O", "ihex", self.exe_path, self.exe_path + ".hex"] 75 | ProcessLogger( self.CTRInstance.logger, objcpy).spin() 76 | 77 | self.CTRInstance.logger.write("Output size:\n") 78 | 79 | size = [self.toolchain_prefix + "size", self.exe_path] 80 | ProcessLogger( self.CTRInstance.logger, size).spin() 81 | 82 | return True 83 | 84 | return False 85 | -------------------------------------------------------------------------------- /yaplctargets/toolchain_yaplc_stm32.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from toolchain_yaplc import toolchain_yaplc 3 | from toolchain_yaplc import plc_rt_dir as plc_rt_dir 4 | 5 | toolchain_dir = os.path.dirname(os.path.realpath(__file__)) 6 | base_dir = os.path.join(os.path.join(toolchain_dir, ".."), "..") 7 | 8 | class toolchain_yaplc_stm32(toolchain_yaplc): 9 | 10 | def GetBinaryCode(self): 11 | if os.path.exists(self.exe_path): 12 | yaplc_boot_loader = os.path.join(os.path.join(base_dir, "stm32flash"), "stm32flash") 13 | if (os.name == 'posix' and not os.path.isfile(yaplc_boot_loader)): 14 | yaplc_boot_loader = "stm32flash" 15 | command = [yaplc_boot_loader, "-w", self.exe_path + ".hex", "-v", "-g", "0x0", "-S", self.load_addr, "%(serial_port)s"] 16 | return command 17 | else: 18 | return None 19 | -------------------------------------------------------------------------------- /yaplctargets/yaplc/XSD: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %(toolchain_yaplc)s 5 | 6 | 7 | -------------------------------------------------------------------------------- /yaplctargets/yaplc/__init__.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from yaplctargets.toolchain_yaplc_stm32 import toolchain_yaplc_stm32 3 | from yaplctargets.toolchain_yaplc_stm32 import plc_rt_dir as plc_rt_dir 4 | 5 | class yaplc_target(toolchain_yaplc_stm32): 6 | def __init__(self, CTRInstance): 7 | 8 | toolchain_yaplc_stm32.__init__(self, CTRInstance) 9 | 10 | self.dev_family = "STM32F4" 11 | self.load_addr = "0x08008000" 12 | self.runtime_addr = "0x080001ac" 13 | self.base_flags = ["-mthumb", "-mcpu=cortex-m4", "-mfpu=fpv4-sp-d16", "-mfloat-abi=hard", "-g3", "-DARM_MATH_CM4", "-D__FPU_USED"] 14 | self.linker_script = os.path.join(os.path.join(os.path.join(plc_rt_dir, "bsp"), "nuc-227-dev"), "stm32f4disco-app.ld") 15 | -------------------------------------------------------------------------------- /yaplctargets/yaplc/extensions.cfg: -------------------------------------------------------------------------------- 1 | ################################### Diagnostic info ####################################### 2 | UGRP "Diag" 0 3 | # WCET 4 | UGRP "WCET" 0 5 | LOC MD 6 | ENDGRP 7 | # Inputs 8 | UGRP "HW Failure" 0..1 9 | LOC IX 10 | ENDGRP 11 | # Debug mode (on/off) 12 | UGRP "Debug Mode" 0 13 | LOC QX 14 | ENDGRP 15 | # Outputs 16 | UGRP "Execution status" 1..3 17 | # 1 - User info (on/off), 2 - User warning (on/off), 3 - User critical, stops the program execution!!! 18 | LOC QX 19 | ENDGRP 20 | ENDGRP 21 | ################################### Discrete IO ######################################### 22 | UGRP "Discrete IO" 1 23 | # 8 discrete inputs 24 | GRP "IX" 1..8 25 | LOC IX # values 26 | LOC MB 1 # edge filters 27 | LOC MB 0 # fall filters 28 | ENDGRP 29 | # 4 relay outputs 30 | LOC QX 1..4 31 | ENDGRP 32 | -------------------------------------------------------------------------------- /yaplctargets/yaplc/plc_yaplc_main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Newlib stubs. 3 | **/ 4 | 5 | #include 6 | 7 | int _close(int file) 8 | { 9 | (void)file; 10 | return -1; 11 | } 12 | 13 | int _fstat(int file, struct stat *st) 14 | { 15 | (void)file; 16 | st->st_mode = S_IFCHR; 17 | return 0; 18 | } 19 | 20 | int _isatty(int file) 21 | { 22 | (void)file; 23 | return 1; 24 | } 25 | 26 | int _lseek(int file, int ptr, int dir) 27 | { 28 | (void)file; 29 | (void)ptr; 30 | (void)dir; 31 | return 0; 32 | } 33 | 34 | int _open(const char *name, int flags, int mode) 35 | { 36 | (void)name; 37 | (void)flags; 38 | (void)mode; 39 | return -1; 40 | } 41 | 42 | int _read(int file, char *ptr, int len) 43 | { 44 | (void)file; 45 | (void)ptr; 46 | (void)len; 47 | return 0; 48 | } 49 | 50 | char *heap_end = 0; 51 | caddr_t _sbrk(int incr) 52 | { 53 | (void)incr; 54 | return (caddr_t) 0; 55 | } 56 | 57 | int _write(int file, char *ptr, int len) 58 | { 59 | (void)file; 60 | (void)ptr; 61 | (void)len; 62 | return 0; 63 | } 64 | 65 | /** 66 | * YAPLC specific code. 67 | **/ 68 | 69 | #include 70 | #include 71 | #include 72 | 73 | /** 74 | * YAPLC ABI. 75 | **/ 76 | 77 | void fake_start(void) 78 | { 79 | while(1); 80 | } 81 | 82 | /*!< TODO: добавть специальную секцию для 83 | type * name = &(PLC_LOC_BUF(name)); 84 | Чтобы можно было разместть их во flash-памяти. 85 | */ 86 | 87 | #define PLC_LOC_BUF(name) PLC_LOC_CONCAT(name, _BUF) 88 | #define PLC_LOC_ADDR(name) PLC_LOC_CONCAT(name, _ADDR) 89 | #define PLC_LOC_DSC(name) PLC_LOC_CONCAT(name, _LDSC) 90 | 91 | #define __LOCATED_VAR( type, name, lt, lsz, io_proto, ... ) \ 92 | type PLC_LOC_BUF(name); \ 93 | type * name = &(PLC_LOC_BUF(name)); \ 94 | const uint32_t PLC_LOC_ADDR(name)[] = {__VA_ARGS__}; \ 95 | const plc_loc_dsc_t PLC_LOC_DSC(name) = \ 96 | { \ 97 | .v_buf = (void *)&(PLC_LOC_BUF(name)), \ 98 | .v_type = PLC_LOC_TYPE(lt), \ 99 | .v_size = PLC_LOC_SIZE(lsz), \ 100 | .a_size = sizeof(PLC_LOC_ADDR(name))/sizeof(uint32_t), \ 101 | .a_data = &(PLC_LOC_ADDR(name)[0]), \ 102 | .proto = io_proto \ 103 | }; 104 | 105 | #include "LOCATED_VARIABLES.h" 106 | #undef __LOCATED_VAR 107 | 108 | #define __LOCATED_VAR(type, name, ...) &(PLC_LOC_DSC(name)), 109 | plc_loc_tbl_t plc_loc_table[] = 110 | { 111 | #include "LOCATED_VARIABLES.h" 112 | }; 113 | #undef __LOCATED_VAR 114 | 115 | #define PLC_LOC_TBL_SIZE (sizeof(plc_loc_table)/sizeof(plc_loc_dsc_t *)) 116 | 117 | uint32_t plc_loc_weigth[PLC_LOC_TBL_SIZE]; 118 | 119 | #ifndef PLC_MD5 120 | #error "PLC_MD5 must be defined!!!" 121 | #endif 122 | 123 | #define PLC_MD5_STR(a) # a 124 | #define PLC_MD5_STR2(a) PLC_MD5_STR(a) 125 | //App ABI, placed after .plc_app_abi_sec 126 | __attribute__ ((section(".plc_md5_sec"))) char plc_md5[] = PLC_MD5_STR2(PLC_MD5); 127 | //App ABI, placed at the .text end 128 | __attribute__ ((section(".plc_check_sec"))) char plc_check_md5[] = PLC_MD5_STR2(PLC_MD5); 129 | 130 | //Linker added symbols 131 | extern uint32_t _plc_data_loadaddr, _plc_data_start, _plc_data_end, _plc_bss_end, _plc_sstart; 132 | 133 | extern app_fp_t _plc_pa_start, _plc_pa_end; 134 | extern app_fp_t _plc_ia_start, _plc_ia_end; 135 | extern app_fp_t _plc_fia_start,_plc_fia_end; 136 | 137 | extern int startPLC(int argc,char **argv); 138 | extern int stopPLC(); 139 | extern void runPLC(void); 140 | 141 | extern void resumeDebug(void); 142 | extern void suspendDebug(int disable); 143 | 144 | extern void FreeDebugData(void); 145 | extern int GetDebugData(unsigned long *tick, unsigned long *size, void **buffer); 146 | 147 | extern void ResetDebugVariables(void); 148 | extern void RegisterDebugVariable(int idx, void* force); 149 | 150 | extern void ResetLogCount(void); 151 | extern uint32_t GetLogCount(uint8_t level); 152 | extern uint32_t GetLogMessage(uint8_t level, uint32_t msgidx, char* buf, uint32_t max_size, uint32_t* tick, uint32_t* tv_sec, uint32_t* tv_nsec); 153 | 154 | //App ABI, placed at the .text start 155 | __attribute__ ((section(".plc_app_abi_sec"))) plc_app_abi_t plc_yaplc_app = 156 | { 157 | .sstart = (uint32_t *)&_plc_sstart, 158 | .entry = fake_start, 159 | //Startup interface 160 | .data_loadaddr = &_plc_data_loadaddr, 161 | 162 | .data_start = &_plc_data_start, 163 | .data_end = &_plc_data_end, 164 | 165 | .bss_end = &_plc_bss_end, 166 | 167 | .pa_start = &_plc_pa_start, 168 | .pa_end = &_plc_pa_end, 169 | 170 | .ia_start = &_plc_ia_start, 171 | .ia_end = &_plc_ia_end, 172 | 173 | .fia_start = &_plc_fia_start, 174 | .fia_end = &_plc_fia_end, 175 | 176 | .check_id = plc_check_md5, 177 | 178 | //Must be run on compatible RTE 179 | .rte_ver_major = 2, 180 | .rte_ver_minor = 0, 181 | .rte_ver_patch = 0, 182 | 183 | .hw_id = 227, 184 | //IO manager interface 185 | .l_tab = &plc_loc_table[0], 186 | .w_tab = &plc_loc_weigth[0], 187 | .l_sz = PLC_LOC_TBL_SIZE, 188 | 189 | //App interface 190 | .id = plc_md5, 191 | 192 | .start = startPLC, 193 | .stop = stopPLC, 194 | .run = runPLC, 195 | 196 | .dbg_resume = resumeDebug, 197 | .dbg_suspend = suspendDebug, 198 | 199 | .dbg_data_get = GetDebugData, 200 | .dbg_data_free = FreeDebugData, 201 | 202 | .dbg_vars_reset = ResetDebugVariables, 203 | .dbg_var_register = RegisterDebugVariable, 204 | 205 | .log_cnt_get = GetLogCount, 206 | .log_msg_get = GetLogMessage, 207 | .log_cnt_reset = ResetLogCount, 208 | .log_msg_post = LogMessage 209 | }; 210 | 211 | //Redefine LOG_BUFFER_SIZE 212 | #define LOG_BUFFER_SIZE (1<<10) /*1Ko*/ 213 | #define LOG_BUFFER_ATTRS 214 | 215 | #define PLC_RTE ((plc_rte_abi_t *)(PLC_RTE_ADDR)) 216 | 217 | void PLC_GetTime(IEC_TIME *CURRENT_TIME) 218 | { 219 | PLC_RTE->get_time( CURRENT_TIME ); 220 | } 221 | 222 | void PLC_SetTimer(unsigned long long next, unsigned long long period) 223 | { 224 | PLC_RTE->set_timer( next, period ); 225 | } 226 | 227 | long AtomicCompareExchange(long* atomicvar,long compared, long exchange) 228 | { 229 | /* No need for real atomic op on LPC, 230 | * no possible preemption between debug and PLC */ 231 | long res = *atomicvar; 232 | if(res == compared){ 233 | *atomicvar = exchange; 234 | } 235 | return res; 236 | } 237 | 238 | long long AtomicCompareExchange64(long long* atomicvar,long long compared, long long exchange) 239 | { 240 | /* No need for real atomic op on LPC, 241 | * no possible preemption between debug and PLC */ 242 | long long res = *atomicvar; 243 | if(res == compared){ 244 | *atomicvar = exchange; 245 | } 246 | return res; 247 | } 248 | 249 | static int debug_locked = 0; 250 | static int _DebugDataAvailable = 0; 251 | static unsigned long __debug_tick; 252 | 253 | int TryEnterDebugSection(void) 254 | { 255 | if(!debug_locked && __DEBUG){ 256 | debug_locked = 1; 257 | return 1; 258 | } 259 | return 0; 260 | } 261 | 262 | void LeaveDebugSection(void) 263 | { 264 | debug_locked = 0; 265 | } 266 | 267 | void InitiateDebugTransfer(void) 268 | { 269 | /* remember tick */ 270 | __debug_tick = __tick; 271 | _DebugDataAvailable = 1; 272 | } 273 | 274 | void suspendDebug(int disable) 275 | { 276 | /* Prevent PLC to enter debug code */ 277 | __DEBUG = !disable; 278 | debug_locked = !disable; 279 | } 280 | 281 | void resumeDebug(void) 282 | { 283 | /* Let PLC enter debug code */ 284 | __DEBUG = 1; 285 | debug_locked = 0; 286 | } 287 | 288 | int WaitDebugData(unsigned long *tick) 289 | { 290 | if(_DebugDataAvailable && !debug_locked){ 291 | /* returns 0 on success */ 292 | *tick = __debug_tick; 293 | _DebugDataAvailable = 0; 294 | return 0; 295 | } 296 | return 1; 297 | } 298 | 299 | void ValidateRetainBuffer(void) 300 | { 301 | PLC_RTE->validate_retain_buf(); 302 | } 303 | void InValidateRetainBuffer(void) 304 | { 305 | PLC_RTE->invalidate_retain_buf(); 306 | } 307 | int CheckRetainBuffer(void) 308 | { 309 | return PLC_RTE->check_retain_buf(); 310 | } 311 | 312 | void InitRetain(void) 313 | { 314 | } 315 | 316 | void CleanupRetain(void) 317 | { 318 | } 319 | 320 | void Retain(unsigned int offset, unsigned int count, void *p) 321 | { 322 | PLC_RTE->retain( offset, count, p ); 323 | } 324 | void Remind(unsigned int offset, unsigned int count, void *p) 325 | { 326 | PLC_RTE->remind( offset, count, p ); 327 | } 328 | 329 | int startPLC(int argc,char **argv) 330 | { 331 | if(__init(argc,argv) == 0){ 332 | PLC_SetTimer(0, common_ticktime__); 333 | return 0; 334 | }else{ 335 | return 1; 336 | } 337 | } 338 | 339 | int stopPLC(void) 340 | { 341 | __cleanup(); 342 | return 0; 343 | } 344 | 345 | void runPLC(void) 346 | { 347 | PLC_GetTime( &__CURRENT_TIME ); 348 | __run(); 349 | } 350 | --------------------------------------------------------------------------------