├── .editorconfig ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .vscode └── extensions.json ├── CPPLINT.cfg ├── LICENSE ├── README.md ├── assets ├── banner.png ├── esp-modbus-mqtt.social.png └── esp-modbus-mqtt.svg ├── examples ├── README.md └── telegraf_diematic.conf ├── include └── README ├── lib ├── README └── Url │ ├── Url.cpp │ └── Url.h ├── platformio.ini.dist ├── src ├── cert.h ├── esp_base.cpp ├── esp_base.h ├── main.cpp ├── main.h ├── modbus_base.cpp ├── modbus_base.h └── modbus_registers.h └── test ├── README └── test_url.cpp /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # http://editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | indent_style = space 9 | indent_size = 2 10 | end_of_line = lf 11 | charset = utf-8 12 | trim_trailing_whitespace = true 13 | insert_final_newline = true 14 | max_line_length = 120 15 | 16 | [{*.md,*.rst}] 17 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | env: 6 | PIO_FIRMWARE_URL: "http://foo.bar/firmware.com" 7 | PIO_MQTT_HOST_IP: 127.0.0.1 8 | PIO_MQTT_PORT: 1883 9 | PIO_MQTT_TOPIC: topic 10 | 11 | jobs: 12 | test: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - name: Set up Python 17 | uses: actions/setup-python@v5 18 | with: 19 | python-version: '3.11' 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip setuptools wheel cpplint platformio 23 | cp platformio.ini.dist platformio.ini 24 | pio pkg update 25 | - name: Lint 26 | run: cpplint --recursive src include lib 27 | - name: Compile 28 | run: platformio run 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | platformio.ini 2 | .pio 3 | .vscode/.browse.c_cpp.db* 4 | .vscode/c_cpp_properties.json 5 | .vscode/launch.json 6 | .vscode/tasks.json 7 | .vscode/settings.json 8 | .vscode/ipch 9 | .env 10 | venv/ 11 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "mine.cpplint", 6 | "ms-vscode.cpptools", 7 | "platformio.platformio-ide" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /CPPLINT.cfg: -------------------------------------------------------------------------------- 1 | filter=-build/include_subdir 2 | linelength=120 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![esp-modbus-mqtt: A Modbus RTU (RS-485) to MQTT Gateway (based on ESP32)](./assets/banner.png) 2 | 3 | ![CI workflow](https://github.com/gmasse/esp-modbus-mqtt/actions/workflows/ci.yml/badge.svg) 4 | 5 | ## Circuit 6 | 7 | Auto-switching UART-to-RS485 converter: 8 | ``` 9 | 10 | VCC ---------------+ 11 | | 12 | +-------x-------+ 13 | (PIN27) RXD <------| RX | 14 | | UART B|----------<> B 15 | (PIN26) TXD ------>| TX TO | 16 | ESP32 | RS-485 | RS485 bus side 17 | | | 18 | | A|----------<> A 19 | | | 20 | +-------x-------+ 21 | | 22 | GND 23 | ``` 24 | Manual switching UART-to-RS485 converter: 25 | ``` 26 | VCC ---------------+ 27 | | 28 | +-------x-------+ 29 | (PIN27) RXD <------| R | 30 | | UART B|----------<> B 31 | (PIN26) TXD ------>| D TO | 32 | ESP32 | RS-485 | RS485 bus side 33 | (PIN25) RTS --+--->| DE | 34 | | | A|----------<> A 35 | +----| /RE | 36 | +-------x-------+ 37 | | 38 | GND 39 | ``` 40 | NB: ESP32 pins are configurable at compilation time. 41 | 42 | ## Modbus 43 | 44 | Device acts as Modbus Master, regurlaly polling a list of registers from a Modbus Slave. 45 | 46 | List of Modbus parameters (in `platformio.ini` file): 47 | - `modbus_rxd`: RX/R pin number (default: `27`) 48 | - `modbus_txd`: TX/D pin number (default: `26`) 49 | - `modbus_rts`: DE/RE pin number (default: `25`). If you don't need RTS, use `NOT_A_PIN` value. 50 | - `modbus_baudrate` (default: `9600`) 51 | - `modbus_unit`: Modbus Slave ID (default: `10`); 52 | - `modbus_retries`: if a Modbus request fails, number of retries before passing to the next register (default: `2`) 53 | - `modbus_scanrate`: the device will attempt to poll the slave every XX seconds (default: `30`) 54 | 55 | Registers list is defined by the array `registers[]` in `src/modbus_registers.h`. 56 | A very simple example would be: 57 | ``` 58 | const modbus_register_t registers[] = { 59 | { 123, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "value_123" }, 60 | { 124, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "value_124" } 61 | }; 62 | ``` 63 | Where: 64 | - `123` and `124` are register address to read, 65 | - `MODBUS_TYPE_HOLDING` is the Modbus object type to read, 66 | - `REGISTER_TYPE_U16` is the expected format of the returned value, 67 | - `value_123` and `value_124` are the name in the JSON MQTT message 68 | 69 | #### Supported Modbus objects: 70 | - `HOLDING` type is supported and has been tested 71 | - `INPUT`, `COIL`, `DISCRETE` and `COUNT` has not been tested but should work 72 | 73 | #### Supported returned Value: 74 | - `REGISTER_TYPE_U16`: unsigned 16-bit integer 75 | - `REGISTER_TYPE_BITFIELD`: a sequence of 16 (or less) single bits; the first item maps the least significant bit 76 | - `REGISTER_TYPE_DIEMATIC_ONE_DECIMAL`: a specific De-Dietrich signed decimal implementation 77 | - `REGISTER_TYPE_DEBUG`: hexadecimal value only visible in INFO logs (not sent in MQTT message) 78 | - other types are not supported (TODO src/modbus_base.cpp:readModbusRegisterToJson) 79 | 80 | ## MQTT 81 | 82 | MQTT parameters are passed through environment variables: 83 | - `PIO_MQTT_HOST_IP`: MQTT broker IPv4 84 | - `PIO_MQTT_PORT`: MQTT broker port 85 | - `PIO_MQTT_TOPIC`: root prefix of the published topic 86 | 87 | With `PIO_MQTT_TOPIC=MyTopic`, based on the register list example above, the published MQTT message will be: 88 | ``` 89 | Topic: MyTopic/ESP-MM-ABCDEF012345/data 90 | Message: {"value_123":0,"value_124":65536} 91 | ``` 92 | Where `ABCDEF012345` is the ESP unique Chip ID. 93 | 94 | ## Compilation 95 | 96 | ``` 97 | git clone https://github.com/gmasse/esp-modbus-mqtt.git 98 | cd esp-modbus-mqtt 99 | python3 -m venv venv 100 | source venv/bin/activate 101 | pip install -U platformio 102 | hash -r 103 | cp platformio.ini.dist platformio.ini 104 | (edit platformio.ini if needed) 105 | export PIO_FIRMWARE_URL="http://domain.com/firmware.bin" 106 | export PIO_MQTT_HOST_IP=11.22.33.44 107 | export PIO_MQTT_PORT=1883 108 | export PIO_MQTT_TOPIC=mytopic 109 | platformio run 110 | ``` 111 | 112 | Built firmware will be at `.pio/build/fm-devkit/firmware.bin` 113 | You can upload to ESP with: `platformio run upload` 114 | 115 | ## TODO 116 | 117 | - [ ] Configuration (Wifi credentials) Reset 118 | - [ ] Factory Firmware (https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/bootloader.html) 119 | - [ ] Secure Boot 120 | - [ ] Moving to ESP-IDF Framework 121 | - [ ] Log level update at runtime 122 | 123 | ## FAQ 124 | #### Passing environment variables via VS Code 125 | Edit `.vscode/settings.json` and add the following lines: 126 | ``` 127 | "terminal.integrated.env.osx": { 128 | "PIO_FIRMWARE_URL": "https://url/firmware.bin", 129 | "PIO_MQTT_HOST_IP": "11.22.33.44", 130 | "PIO_MQTT_PORT": "1883", 131 | "PIO_MQTT_TOPIC": "mytopic" 132 | }, 133 | ``` 134 | 135 | #### Flashing firmware 136 | ``` 137 | cp .plateformio/packages/framework-arduinoespressif32/tools/sdk/bin/bootloader_dio_40m.bin . 138 | cp .platformio/packages/framework-arduinoespressif32/tools/partitions/default.bin . 139 | 140 | esptool.py --chip esp32 --port /dev/ttyUSB1 --baud 460800 \ 141 | --before default_reset --after hard_reset write_flash -z \ 142 | --flash_mode dio --flash_freq 40m --flash_size detect \ 143 | 0x1000 bootloader_dio_40m.bin 0x8000 default.bin 0x10000 firmware.bin 144 | ``` 145 | -------------------------------------------------------------------------------- /assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gmasse/esp-modbus-mqtt/3b40d27a4b5e009e65fc5cdee6fa1c3a16e056cd/assets/banner.png -------------------------------------------------------------------------------- /assets/esp-modbus-mqtt.social.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gmasse/esp-modbus-mqtt/3b40d27a4b5e009e65fc5cdee6fa1c3a16e056cd/assets/esp-modbus-mqtt.social.png -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # MQTT + InfluxDB backend (Ubuntu) 2 | ``` 3 | curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add - 4 | source /etc/lsb-release 5 | echo "deb https://repos.influxdata.com/ubuntu ${DISTRIB_CODENAME} stable" | sudo tee /etc/apt/sources.list.d/influxdb.list 6 | sudo apt update 7 | sudo apt-get install influxdb telegraf mosquitto mosquitto-clients 8 | # bind to 127.0.0.1:8086 in /etc/influxdb/influxdb.conf 9 | sudo systemctl start influxd 10 | # create user, database and retention policies 11 | # copy telegraph custom configuration 12 | sudo systemctl start telegraf 13 | ``` 14 | 15 | ``` 16 | wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add - 17 | sudo add-apt-repository "deb https://packages.grafana.com/oss/deb stable main" 18 | sudo apt-get update 19 | sudo apt-get install grafana 20 | sudo /bin/systemctl daemon-reload 21 | sudo /bin/systemctl enable grafana-server 22 | sudo /bin/systemctl start grafana-server 23 | ``` 24 | 25 | ### Troubleshooting 26 | ``` 27 | mosquitto_sub -t "#" 28 | ``` 29 | -------------------------------------------------------------------------------- /examples/telegraf_diematic.conf: -------------------------------------------------------------------------------- 1 | # Read metrics from MQTT topic(s) 2 | [[inputs.mqtt_consumer]] 3 | ## MQTT broker URLs to be used. The format should be scheme://host:port, 4 | ## schema can be tcp, ssl, or ws. 5 | servers = ["tcp://127.0.0.1:1883"] 6 | 7 | ## Topics that will be subscribed to. 8 | topics = [ 9 | "diematic/+/data", 10 | ] 11 | 12 | ## The message topic will be stored in a tag specified by this value. If set 13 | ## to the empty string no topic tag will be created. 14 | topic_tag = "topic" 15 | 16 | ## Data format to consume. 17 | ## Each data format has its own unique set of configuration options, read 18 | ## more about them here: 19 | ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md 20 | data_format = "json" 21 | 22 | 23 | # Configuration for sending metrics to InfluxDB 24 | [[outputs.influxdb]] 25 | ## The full HTTP or UDP URL for your InfluxDB instance. 26 | ## 27 | ## Multiple URLs can be specified for a single cluster, only ONE of the 28 | ## urls will be written to each interval. 29 | urls = ["http://127.0.0.1:8086"] 30 | 31 | ## The target database for metrics; will be created as needed. 32 | ## For UDP url endpoint database needs to be configured on server side. 33 | database = "diematic" 34 | 35 | ## If true, the database tag will not be added to the metric. 36 | exclude_database_tag = false 37 | 38 | ## If true, no CREATE DATABASE queries will be sent. Set to true when using 39 | ## Telegraf with a user without permissions to create databases or when the 40 | ## database already exists. 41 | skip_database_creation = true 42 | 43 | ## HTTP Basic Auth 44 | username = "diematic" 45 | password = "mySecurePas$w0rd" 46 | -------------------------------------------------------------------------------- /include/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project header files. 3 | 4 | A header file is a file containing C declarations and macro definitions 5 | to be shared between several project source files. You request the use of a 6 | header file in your project source file (C, C++, etc) located in `src` folder 7 | by including it, with the C preprocessing directive `#include'. 8 | 9 | ```src/main.c 10 | 11 | #include "header.h" 12 | 13 | int main (void) 14 | { 15 | ... 16 | } 17 | ``` 18 | 19 | Including a header file produces the same results as copying the header file 20 | into each source file that needs it. Such copying would be time-consuming 21 | and error-prone. With a header file, the related declarations appear 22 | in only one place. If they need to be changed, they can be changed in one 23 | place, and programs that include the header file will automatically use the 24 | new version when next recompiled. The header file eliminates the labor of 25 | finding and changing all the copies as well as the risk that a failure to 26 | find one copy will result in inconsistencies within a program. 27 | 28 | In C, the usual convention is to give header files names that end with `.h'. 29 | It is most portable to use only letters, digits, dashes, and underscores in 30 | header file names, and at most one dot. 31 | 32 | Read more about using header files in official GCC documentation: 33 | 34 | * Include Syntax 35 | * Include Operation 36 | * Once-Only Headers 37 | * Computed Includes 38 | 39 | https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html 40 | -------------------------------------------------------------------------------- /lib/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for project specific (private) libraries. 3 | PlatformIO will compile them to static libraries and link into executable file. 4 | 5 | The source code of each library should be placed in a an own separate directory 6 | ("lib/your_library_name/[here are source files]"). 7 | 8 | For example, see a structure of the following two libraries `Foo` and `Bar`: 9 | 10 | |--lib 11 | | | 12 | | |--Bar 13 | | | |--docs 14 | | | |--examples 15 | | | |--src 16 | | | |- Bar.c 17 | | | |- Bar.h 18 | | | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html 19 | | | 20 | | |--Foo 21 | | | |- Foo.c 22 | | | |- Foo.h 23 | | | 24 | | |- README --> THIS FILE 25 | | 26 | |- platformio.ini 27 | |--src 28 | |- main.c 29 | 30 | and a contents of `src/main.c`: 31 | ``` 32 | #include 33 | #include 34 | 35 | int main (void) 36 | { 37 | ... 38 | } 39 | 40 | ``` 41 | 42 | PlatformIO Library Dependency Finder will find automatically dependent 43 | libraries scanning project source files. 44 | 45 | More information about PlatformIO Library Dependency Finder 46 | - https://docs.platformio.org/page/librarymanager/ldf.html 47 | -------------------------------------------------------------------------------- /lib/Url/Url.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Url.cpp - URL parsing class 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include "Url.h" 20 | 21 | #include 22 | 23 | Url::Url(const String& url_s) { 24 | // check for :// 25 | int index = url_s.indexOf("://"); 26 | if (index < 0) { 27 | ESP_LOGV(TAG, "failed to parse protocol"); 28 | } 29 | 30 | this->Protocol = url_s.substring(0, index); 31 | this->Protocol.toLowerCase(); 32 | 33 | this->Path = url_s.substring(index + 3); // after :// 34 | 35 | index = this->Path.indexOf('/'); // looking for the first / 36 | this->Host = this->Path.substring(0, index); 37 | this->Path.remove(0, index); // removing host part 38 | 39 | // remove Authorization part from host 40 | index = this->Host.indexOf('@'); 41 | if (index >= 0) { 42 | // auth info 43 | this->Host.remove(0, index + 1); // remove auth part including @ 44 | } 45 | 46 | // get port 47 | index = this->Host.indexOf(':'); 48 | // TODO(gmasse): support IPv6 like [1234:abcd::1234]:8888 49 | if (index >= 0) { 50 | this->Port = this->Host.substring(index + 1); 51 | this->Host.remove(index, this->Port.length() + 1); // remove : + port 52 | } 53 | 54 | // get query 55 | index = this->Path.indexOf('?'); 56 | if (index >= 0) { 57 | this->Query = this->Path.substring(index + 1); 58 | this->Path.remove(index); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /lib/Url/Url.h: -------------------------------------------------------------------------------- 1 | /* 2 | Url.h - URL parsing class headers 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef LIB_URL_URL_H_ 20 | #define LIB_URL_URL_H_ 21 | 22 | #include 23 | 24 | class Url { 25 | public: 26 | explicit Url(const String& url_s); // omitted copy, ==, accessors, ... 27 | String Query, Path, Protocol, Host, Port; 28 | 29 | // private: 30 | // void Parse(const String& url_s); 31 | }; 32 | 33 | #endif // LIB_URL_URL_H_ 34 | -------------------------------------------------------------------------------- /platformio.ini.dist: -------------------------------------------------------------------------------- 1 | ;PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [common] 12 | lib_deps_external = 13 | 4-20ma/ModbusMaster@~2.0.1 14 | marvinroger/AsyncMqttClient@~0.9.0 15 | bblanchon/ArduinoJson@~7.0.4 16 | https://github.com/tzapu/WiFiManager.git#v2.0.17 17 | 18 | [extra] 19 | monitor_speed = 115200 20 | firmware_url = ${sysenv.PIO_FIRMWARE_URL} 21 | modbus_rxd = 27 22 | modbus_txd = 26 23 | modbus_rts = 25 24 | ; if there is no flow control pin 25 | ; modbus_rts = NOT_A_PIN 26 | modbus_baudrate = 9600 27 | modbus_unit = 10 28 | modbus_retries = 2 29 | modbus_scanrate = 30 30 | mqtt_host_ip = ${sysenv.PIO_MQTT_HOST_IP} 31 | mqtt_port = ${sysenv.PIO_MQTT_PORT} 32 | mqtt_topic = ${sysenv.PIO_MQTT_TOPIC} 33 | 34 | [env:fm-devkit] 35 | platform = espressif32 36 | board = fm-devkit 37 | framework = arduino 38 | ;upload_port = /dev/tty.SLAB_USBtoUART 39 | ;monitor_port = /dev/tty.SLAB_USBtoUART 40 | upload_port = /dev/ttyUSB0 41 | monitor_port = /dev/ttyUSB0 42 | test_port = /dev/ttyUSB0 43 | monitor_speed = ${extra.monitor_speed} 44 | build_flags = 45 | ; '-DMODBUS_DISABLED' 46 | '-DCORE_DEBUG_LEVEL=3' 47 | '-DFIRMWARE_URL="${extra.firmware_url}"' 48 | '-DMONITOR_SPEED=${extra.monitor_speed}' 49 | '-DRXD=${extra.modbus_rxd}' 50 | '-DTXD=${extra.modbus_txd}' 51 | '-DRTS=${extra.modbus_rts}' 52 | '-DMODBUS_BAUDRATE=${extra.modbus_baudrate}' 53 | '-DMODBUS_UNIT=${extra.modbus_unit}' 54 | '-DMODBUS_RETRIES=${extra.modbus_retries}' 55 | '-DMODBUS_SCANRATE=${extra.modbus_scanrate}' 56 | '-DMQTT_HOST_IP="${extra.mqtt_host_ip}"' 57 | '-DMQTT_PORT=${extra.mqtt_port}' 58 | '-DMQTT_TOPIC="${extra.mqtt_topic}"' 59 | lib_deps = 60 | ${common.lib_deps_external} 61 | -------------------------------------------------------------------------------- /src/cert.h: -------------------------------------------------------------------------------- 1 | /* 2 | cert.h - Root SSL Certificate 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef SRC_CERT_H_ 20 | #define SRC_CERT_H_ 21 | 22 | // curl --silent https://letsencrypt.org/certs/letsencryptauthorityx3.pem.txt | sed 's/^\(.*\)$/"\1\\n" \\/' 23 | static const char* rootCACertificate = \ 24 | "-----BEGIN CERTIFICATE-----\n" \ 25 | "MIIFjTCCA3WgAwIBAgIRANOxciY0IzLc9AUoUSrsnGowDQYJKoZIhvcNAQELBQAw\n" \ 26 | "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" \ 27 | "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTYxMDA2MTU0MzU1\n" \ 28 | "WhcNMjExMDA2MTU0MzU1WjBKMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg\n" \ 29 | "RW5jcnlwdDEjMCEGA1UEAxMaTGV0J3MgRW5jcnlwdCBBdXRob3JpdHkgWDMwggEi\n" \ 30 | "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCc0wzwWuUuR7dyXTeDs2hjMOrX\n" \ 31 | "NSYZJeG9vjXxcJIvt7hLQQWrqZ41CFjssSrEaIcLo+N15Obzp2JxunmBYB/XkZqf\n" \ 32 | "89B4Z3HIaQ6Vkc/+5pnpYDxIzH7KTXcSJJ1HG1rrueweNwAcnKx7pwXqzkrrvUHl\n" \ 33 | "Npi5y/1tPJZo3yMqQpAMhnRnyH+lmrhSYRQTP2XpgofL2/oOVvaGifOFP5eGr7Dc\n" \ 34 | "Gu9rDZUWfcQroGWymQQ2dYBrrErzG5BJeC+ilk8qICUpBMZ0wNAxzY8xOJUWuqgz\n" \ 35 | "uEPxsR/DMH+ieTETPS02+OP88jNquTkxxa/EjQ0dZBYzqvqEKbbUC8DYfcOTAgMB\n" \ 36 | "AAGjggFnMIIBYzAOBgNVHQ8BAf8EBAMCAYYwEgYDVR0TAQH/BAgwBgEB/wIBADBU\n" \ 37 | "BgNVHSAETTBLMAgGBmeBDAECATA/BgsrBgEEAYLfEwEBATAwMC4GCCsGAQUFBwIB\n" \ 38 | "FiJodHRwOi8vY3BzLnJvb3QteDEubGV0c2VuY3J5cHQub3JnMB0GA1UdDgQWBBSo\n" \ 39 | "SmpjBH3duubRObemRWXv86jsoTAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js\n" \ 40 | "LnJvb3QteDEubGV0c2VuY3J5cHQub3JnMHIGCCsGAQUFBwEBBGYwZDAwBggrBgEF\n" \ 41 | "BQcwAYYkaHR0cDovL29jc3Aucm9vdC14MS5sZXRzZW5jcnlwdC5vcmcvMDAGCCsG\n" \ 42 | "AQUFBzAChiRodHRwOi8vY2VydC5yb290LXgxLmxldHNlbmNyeXB0Lm9yZy8wHwYD\n" \ 43 | "VR0jBBgwFoAUebRZ5nu25eQBc4AIiMgaWPbpm24wDQYJKoZIhvcNAQELBQADggIB\n" \ 44 | "ABnPdSA0LTqmRf/Q1eaM2jLonG4bQdEnqOJQ8nCqxOeTRrToEKtwT++36gTSlBGx\n" \ 45 | "A/5dut82jJQ2jxN8RI8L9QFXrWi4xXnA2EqA10yjHiR6H9cj6MFiOnb5In1eWsRM\n" \ 46 | "UM2v3e9tNsCAgBukPHAg1lQh07rvFKm/Bz9BCjaxorALINUfZ9DD64j2igLIxle2\n" \ 47 | "DPxW8dI/F2loHMjXZjqG8RkqZUdoxtID5+90FgsGIfkMpqgRS05f4zPbCEHqCXl1\n" \ 48 | "eO5HyELTgcVlLXXQDgAWnRzut1hFJeczY1tjQQno6f6s+nMydLN26WuU4s3UYvOu\n" \ 49 | "OsUxRlJu7TSRHqDC3lSE5XggVkzdaPkuKGQbGpny+01/47hfXXNB7HntWNZ6N2Vw\n" \ 50 | "p7G6OfY+YQrZwIaQmhrIqJZuigsrbe3W+gdn5ykE9+Ky0VgVUsfxo52mwFYs1JKY\n" \ 51 | "2PGDuWx8M6DlS6qQkvHaRUo0FMd8TsSlbF0/v965qGFKhSDeQoMpYnwcmQilRh/0\n" \ 52 | "ayLThlHLN81gSkJjVrPI0Y8xCVPB4twb1PFUd2fPM3sA1tJ83sZ5v8vgFv2yofKR\n" \ 53 | "PB0t6JzUA81mSqM3kxl5e+IZwhYAyO0OTg3/fs8HqGTNKd9BqoUwSRBzp06JMg5b\n" \ 54 | "rUCGwbCUDI0mxadJ3Bz4WxR6fyNpBK2yAinWEsikxqEt\n" \ 55 | "-----END CERTIFICATE-----\n"; 56 | 57 | #endif // SRC_CERT_H_ 58 | -------------------------------------------------------------------------------- /src/esp_base.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | esp_base.cpp - ESP core functions 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include "esp_base.h" 20 | 21 | #include "Arduino.h" 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | #include "cert.h" 28 | 29 | static const char *VERSION_HEADER = "X-Object-Meta-Version"; 30 | 31 | static const char __attribute__((__unused__)) *TAG = "ESP_base"; 32 | 33 | 34 | bool _httpRequest(HTTPClient *http_client, const String& url_s) { 35 | bool ret = false; 36 | Url url(url_s); 37 | if (url.Protocol == "https") { 38 | const uint16_t port = (url.Port.isEmpty() ? 443 : url.Port.toInt()); 39 | ret = http_client->begin(url.Host, port, url.Path, rootCACertificate); 40 | } else if (url.Protocol == "http") { 41 | const uint16_t port = (url.Port.isEmpty() ? 80 : url.Port.toInt()); 42 | ret = http_client->begin(url.Host, port, url.Path); 43 | } else { 44 | ESP_LOGE(TAG, "Unsupported protocol: %s", url.Protocol.c_str()); 45 | return false; 46 | } 47 | 48 | if (ret) { 49 | int httpCode = http_client->GET(); 50 | 51 | // httpCode will be negative on error 52 | if (httpCode > 0) { 53 | // HTTP header has been send and Server response header has been handled 54 | ESP_LOGV(TAG, "HTTP GET... code: %d", httpCode); 55 | 56 | // file found at server 57 | if (httpCode == HTTP_CODE_OK) { 58 | return true; 59 | } else if (httpCode == HTTP_CODE_MOVED_PERMANENTLY || httpCode == HTTP_CODE_FOUND 60 | || httpCode == HTTP_CODE_TEMPORARY_REDIRECT || httpCode == HTTP_CODE_PERMANENT_REDIRECT ) { 61 | ESP_LOGE(TAG, "HTTP redirection not supported (yet): %d", httpCode); 62 | } else { 63 | ESP_LOGE(TAG, "Unsupported HTTP response code: %d", httpCode); 64 | } 65 | } else { 66 | ESP_LOGE(TAG, "HTTP GET... failed, error: %s", http_client->errorToString(httpCode).c_str()); 67 | } 68 | } 69 | return false; 70 | } 71 | 72 | String _requestFirmwareVersion(const String &url_s) { 73 | ESP_LOGD(TAG, "Requesting firmware from url=%s", url_s.c_str()); 74 | String firmware_version = ""; 75 | HTTPClient client; 76 | const char* headers_list[] = { VERSION_HEADER, "Content-Type" }; 77 | client.collectHeaders(headers_list, sizeof(headers_list)/sizeof(headers_list[0])); 78 | if (_httpRequest(&client, url_s)) { 79 | ESP_LOGV(TAG, "Header %s=%s", VERSION_HEADER, client.header(VERSION_HEADER).c_str()); 80 | ESP_LOGV(TAG, "Header %s=%s", "Content-Type", client.header("Content-Type").c_str()); 81 | if (client.header("Content-Type") == "application/octet-stream") { 82 | firmware_version = client.header(VERSION_HEADER); 83 | } else { 84 | ESP_LOGE(TAG, "Invalid Content-Type: %s", client.header("Content-Type").c_str()); 85 | } 86 | } 87 | client.end(); 88 | return firmware_version; 89 | } 90 | 91 | bool checkFirmwareUpdate(const String& url_s, const String& current_version) { 92 | ESP_LOGD(TAG, "Checking firmware version=%s from url=%s", current_version.c_str(), url_s.c_str()); 93 | 94 | const String remote_version = _requestFirmwareVersion(url_s); 95 | if (remote_version.isEmpty()) { 96 | ESP_LOGW(TAG, "Remote firmware not found"); 97 | } else if (remote_version > current_version) { 98 | ESP_LOGI(TAG, "New firmware version detected: %s", remote_version.c_str()); 99 | return true; 100 | } else { 101 | ESP_LOGD(TAG, "Firmware remote version: %s", remote_version.c_str()); 102 | ESP_LOGI(TAG, "Firmware is already up to date (version %s)", current_version.c_str()); 103 | } 104 | return false; 105 | } 106 | 107 | bool updateOTA(const String& url_s) { 108 | HTTPClient client; 109 | if (_httpRequest(&client, url_s)) { 110 | int len = client.getSize(); 111 | WiFiClient *tcp = client.getStreamPtr(); 112 | 113 | // check whether we have everything for OTA update 114 | if (len) { 115 | if (Update.begin(len)) { 116 | ESP_LOGW(TAG, "Starting Over-The-Air update. This may take some time to complete ..."); 117 | size_t written = Update.writeStream(*tcp); 118 | 119 | if (written == len) { 120 | ESP_LOGD(TAG, "Written: %d successfully", written); 121 | } else { 122 | ESP_LOGE(TAG, "Written only: %d/%d. Retry?", written, len); 123 | // Retry?? 124 | } 125 | 126 | if (Update.end()) { 127 | if (Update.isFinished()) { 128 | ESP_LOGW(TAG, "OTA update has successfully completed. Reboot needed..."); 129 | client.end(); 130 | return true; 131 | } else { 132 | ESP_LOGE(TAG, "Something went wrong! OTA update hasn't been finished properly."); 133 | } 134 | } else { 135 | ESP_LOGE(TAG, "An error Occurred. Error #: %d", Update.getError()); 136 | } 137 | } else { 138 | ESP_LOGE(TAG, "There isn't enough space to start OTA update"); 139 | } 140 | } else { 141 | ESP_LOGE(TAG, "Invalid content-length received from server"); 142 | } 143 | } else { 144 | ESP_LOGE(TAG, "Unable to connect to server"); 145 | } 146 | client.end(); 147 | return false; 148 | } 149 | -------------------------------------------------------------------------------- /src/esp_base.h: -------------------------------------------------------------------------------- 1 | /* 2 | esp_base.h - ESP core functions headers 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef SRC_ESP_BASE_H_ 20 | #define SRC_ESP_BASE_H_ 21 | 22 | #include "Arduino.h" 23 | 24 | bool checkFirmwareUpdate(const String& url_s, const String& current_version); 25 | bool updateOTA(const String& url_s); 26 | 27 | #endif // SRC_ESP_BASE_H_ 28 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | main.cpp - esp-modbus-mqtt 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include "main.h" 20 | 21 | #include 22 | #include 23 | #if defined(ARDUINO_ARCH_ESP32) 24 | #include 25 | #include 26 | // #include "esp32-hal-log.h" 27 | #elif defined(ARDUINO_ARCH_ESP8266) 28 | // TODO(gmasse): test ESP8266 #include 29 | // TODO(gmasse): test ESP8266 #include 30 | #endif 31 | extern "C" { 32 | #include "freertos/FreeRTOS.h" 33 | #include "freertos/timers.h" 34 | #include "freertos/task.h" 35 | } 36 | 37 | #include 38 | #include 39 | #include 40 | 41 | #include 42 | #include "esp_base.h" 43 | #ifndef MODBUS_DISABLED 44 | #include 45 | #endif // MODBUS_DISABLED 46 | 47 | static char HOSTNAME[24] = "ESP-MM-FFFFFFFFFFFFFFFF"; 48 | static const char __attribute__((__unused__)) *TAG = "Main"; 49 | 50 | // static const char *FIRMWARE_URL = "https://domain.com/path/file.bin"; 51 | static const char *FIRMWARE_VERSION = "000.000.024"; 52 | 53 | // instanciate WiFiManager object 54 | WiFiManager wifiManager; 55 | 56 | // instanciate AsyncMqttClient object 57 | AsyncMqttClient mqtt_client; 58 | 59 | // instanciate timers 60 | TimerHandle_t mqtt_reconnect_timer; 61 | TimerHandle_t wifi_reconnect_timer; 62 | TimerHandle_t modbus_poller_timer; 63 | bool modbus_poller_inprogress = false; 64 | 65 | // instanciate task handlers 66 | TaskHandle_t modbus_poller_task_handler = NULL; 67 | TaskHandle_t ota_update_task_handler = NULL; 68 | 69 | 70 | void resetWiFi() { 71 | // Set WiFi to station mode 72 | // and disconnect from an AP if it was previously connected 73 | ESP_LOGD(TAG, "Resetting Wifi"); 74 | WiFi.mode(WIFI_STA); 75 | WiFi.disconnect(); 76 | } 77 | 78 | void connectToWifi() { 79 | ESP_LOGD(TAG, "Connecting to '%s'", WIFI_SSID); 80 | WiFi.begin(); 81 | } 82 | 83 | void connectToMqtt() { 84 | ESP_LOGD(TAG, "Connecting to MQTT"); 85 | mqtt_client.connect(); 86 | } 87 | 88 | void wiFiEvent(WiFiEvent_t event) { 89 | ESP_LOGD(TAG, "WiFi event: %d", event); 90 | switch (event) { 91 | case SYSTEM_EVENT_STA_GOT_IP: 92 | ESP_LOGI(TAG, "WiFi connected with IP address: %s", WiFi.localIP().toString().c_str()); 93 | if (!MDNS.begin(HOSTNAME)) { // init mdns 94 | ESP_LOGW(TAG, "Error setting up MDNS responder"); 95 | } 96 | configTime(0, 0, "pool.ntp.org"); // init UTC time 97 | struct tm now; 98 | if (getLocalTime(&now)) { 99 | ESP_LOGI(TAG, "Time: %4d-%02d-%02d %02d:%02d:%02d", 100 | now.tm_year+1900, now.tm_mon+1, now.tm_mday, 101 | now.tm_hour, now.tm_min, now.tm_sec); 102 | } else { 103 | ESP_LOGW(TAG, "Failed to obtain time"); 104 | } 105 | connectToMqtt(); 106 | break; 107 | case SYSTEM_EVENT_STA_DISCONNECTED: 108 | ESP_LOGW(TAG, "WiFi lost connection"); 109 | xTimerStop(mqtt_reconnect_timer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi 110 | xTimerStart(wifi_reconnect_timer, 0); 111 | break; 112 | default: 113 | break; 114 | } 115 | } 116 | 117 | void onMqttConnect(bool sessionPresent) { 118 | ESP_LOGI(TAG, "Connected to MQTT"); 119 | ESP_LOGD(TAG, "Session present: %s", sessionPresent ? "true" : "false"); 120 | 121 | String mqtt_topic = MQTT_TOPIC; 122 | mqtt_topic += "/" + String(HOSTNAME) + "/action/#"; 123 | ESP_LOGI(TAG, "Subscribing at %s", mqtt_topic.c_str()); 124 | // uint16_t packetIdSub = mqtt_client.subscribe(mqtt_topic.c_str(), 1); 125 | mqtt_client.subscribe(mqtt_topic.c_str(), 1); 126 | } 127 | 128 | void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { 129 | ESP_LOGW(TAG, "Disconnected from MQTT"); 130 | 131 | if (WiFi.isConnected()) { 132 | xTimerStart(mqtt_reconnect_timer, 0); 133 | } 134 | } 135 | 136 | void onMqttSubscribe(uint16_t packetId, uint8_t qos) { 137 | ESP_LOGD(TAG, "Subscribe acknowledged for packetId: %d qos: %d", packetId, qos); 138 | } 139 | 140 | void onMqttUnsubscribe(uint16_t packetId) { 141 | ESP_LOGD(TAG, "Unsubscribe acknowledged for packetId: %d", packetId); 142 | } 143 | 144 | void onMqttMessage(char *topic, char *payload, 145 | AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { 146 | ESP_LOGV(TAG, "Message received (topic=%s, qos=%d, dup=%d, retain=%d, len=%d, index=%d, total=%d): %s", 147 | topic, properties.qos, properties.dup, properties.retain, len, index, total, payload); 148 | 149 | String suffix = String(topic).substring(strlen(MQTT_TOPIC) + strlen(HOSTNAME) + 9); 150 | // substring(1 + strlen(MQTT_TOPIC) + strlen("/") + strlen(HOSTNAME) + strlen("/") + strlen("action")) 151 | ESP_LOGV(TAG, "MQTT topic suffix=%s", suffix.c_str()); 152 | 153 | if (suffix == "upgrade") { 154 | ESP_LOGD(TAG, "MQTT OTA update requested"); 155 | vTaskResume(ota_update_task_handler); 156 | return; 157 | /* 158 | // TODO(gmasse): fix esp_log_level_set 159 | } else if (suffix == "loglevel") { 160 | ESP_LOGD(TAG, "MQTT log level update requested"); 161 | uint8_t log_level_nb; 162 | if (sscanf(payload, "%hhu", &log_level_nb) == 1) { 163 | switch (log_level_nb) { 164 | case 0: 165 | esp_log_level_set("*", ESP_LOG_NONE); 166 | ESP_LOGI(TAG, "Log level changed to %#x", ESP_LOG_NONE); 167 | break; 168 | case 1: 169 | esp_log_level_set("*", ESP_LOG_ERROR); 170 | ESP_LOGI(TAG, "Log level changed to %#x", ESP_LOG_ERROR); 171 | break; 172 | case 2: 173 | esp_log_level_set("*", ESP_LOG_WARN); 174 | ESP_LOGI(TAG, "Log level changed to %#x", ESP_LOG_WARN); 175 | break; 176 | case 3: 177 | esp_log_level_set("*", ESP_LOG_INFO); 178 | ESP_LOGI(TAG, "Log level changed to %#x", ESP_LOG_INFO); 179 | break; 180 | case 4: 181 | esp_log_level_set("*", ESP_LOG_DEBUG); 182 | ESP_LOGI(TAG, "Log level changed to %#x", ESP_LOG_DEBUG); 183 | break; 184 | case 5: 185 | esp_log_level_set("*", ESP_LOG_VERBOSE); 186 | ESP_LOGI(TAG, "Log level changed to %#x", ESP_LOG_VERBOSE); 187 | break; 188 | default: 189 | ESP_LOGE(TAG, "MQTT Invalid requested log level: %s (expected 0 to 5)", payload); 190 | break; 191 | } 192 | } 193 | */ 194 | } else { 195 | ESP_LOGW(TAG, "Unknow MQTT topic received: %s", topic); 196 | } 197 | } 198 | 199 | void onMqttPublish(uint16_t packetId) { 200 | ESP_LOGD(TAG, "Publish acknowledged for packetId: %d", packetId); 201 | } 202 | 203 | void runOtaUpdateTask(void * pvParameters) { 204 | UBaseType_t __attribute__((__unused__)) uxHighWaterMark; 205 | /* Inspect our own high water mark on entering the task. */ 206 | uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL); 207 | ESP_LOGV(TAG, "Entering OTA task. Unused stack size: %d", uxHighWaterMark); 208 | 209 | for (;;) { 210 | uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL); 211 | ESP_LOGV(TAG, "Suspending OTA task. Unused stack size: %d", uxHighWaterMark); 212 | vTaskSuspend(NULL); // Task is suspended by default 213 | 214 | ESP_LOGV(TAG, "Resuming OTA task..."); 215 | ESP_LOGI(TAG, "Checking if new firmware is available"); 216 | if (checkFirmwareUpdate(FIRMWARE_URL, FIRMWARE_VERSION)) { 217 | ESP_LOGI(TAG, "New firmware found"); 218 | ESP_LOGV(TAG, "Suspending modbus poller"); 219 | if (xTimerStop(modbus_poller_timer, 10) == pdFAIL) { 220 | ESP_LOGW(TAG, "Unable to stop Modbus Poller timer for OTA update"); 221 | } 222 | vTaskSuspend(modbus_poller_task_handler); 223 | 224 | if (updateOTA(FIRMWARE_URL)) { 225 | // Update is done. Rebooting... 226 | uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL); 227 | ESP_LOGV(TAG, "Rebooting. Unused stack size: %d", uxHighWaterMark); 228 | ESP_LOGI(TAG, "************************ REBOOT IN PROGRESS *************************"); 229 | ESP.restart(); 230 | } else { 231 | ESP_LOGV(TAG, "OTA update failed. Restarting Modbus Poller"); 232 | // TODO(gmasse): retry? 233 | vTaskResume(modbus_poller_task_handler); 234 | if (xTimerStart(modbus_poller_timer, 10) == pdFAIL) { 235 | ESP_LOGE(TAG, "Unable to restart Modbus Poller timer after OTA update failure."); 236 | uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL); 237 | ESP_LOGV(TAG, "Rebooting. Unused stack size: %d", uxHighWaterMark); 238 | ESP_LOGI(TAG, "************************ REBOOT IN PROGRESS *************************"); 239 | ESP.restart(); 240 | } 241 | } 242 | } 243 | } 244 | } 245 | 246 | void runModbusPollerTask(void * pvParameters) { 247 | #ifndef MODBUS_DISABLED 248 | UBaseType_t __attribute__((__unused__)) uxHighWaterMark; 249 | /* Inspect our own high water mark on entering the task. */ 250 | uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL); 251 | ESP_LOGV(TAG, "Entering Modbus Poller task. Unused stack size: %d", uxHighWaterMark); 252 | 253 | for (;;) { 254 | uxHighWaterMark = uxTaskGetStackHighWaterMark(NULL); 255 | ESP_LOGV(TAG, "Suspending Modbus Poller task. Unused stack size: %d", uxHighWaterMark); 256 | vTaskSuspend(NULL); // Task is suspended by default 257 | 258 | ESP_LOGV(TAG, "Resuming Modbus Poller task"); 259 | if (modbus_poller_inprogress) { // not sure if needed 260 | ESP_LOGV(TAG, "Modbus polling in already progress. Waiting for next cycle."); 261 | return; 262 | } 263 | 264 | StaticJsonDocument<2000> json_doc; // instanciate JSON storage 265 | parseModbusToJson(json_doc.to()); 266 | 267 | char buffer[1600]; 268 | size_t n = serializeJson(json_doc, buffer); 269 | ESP_LOGD(TAG, "JSON serialized: %s", buffer); 270 | if (mqtt_client.connected()) { 271 | String mqtt_topic = MQTT_TOPIC; 272 | mqtt_topic += "/" + String(HOSTNAME) + "/data"; 273 | ESP_LOGI(TAG, "MQTT Publishing data to topic: %s", mqtt_topic.c_str()); 274 | mqtt_client.publish(mqtt_topic.c_str(), 0, true, buffer, n); 275 | } 276 | } 277 | #endif // MODBUS_DISABLED 278 | } 279 | 280 | void runModbusPollerTimer() { 281 | ESP_LOGV(TAG, "Time to resume Modbus Poller"); 282 | vTaskResume(modbus_poller_task_handler); 283 | ESP_LOGV(TAG, "Modbus Poller resume done"); 284 | } 285 | 286 | void setup() { 287 | // debug comm 288 | Serial.begin(MONITOR_SPEED); 289 | while (!Serial) continue; 290 | Serial.setDebugOutput(true); 291 | /* 292 | // TODO(gmasse): fix esp_log_level_set 293 | esp_log_level_set("*", ESP_LOG_VERBOSE); 294 | esp_log_level_set("ESP_base", ESP_LOG_INFO); 295 | esp_log_level_set("Modbus_base", ESP_LOG_INFO); 296 | esp_log_level_set("Main", ESP_LOG_INFO); 297 | ESP_LOGE("Main", "Error"); 298 | ESP_LOGW("Main", "Warning"); 299 | ESP_LOGI("Main", "Info"); 300 | ESP_LOGD("Main", "Debug"); 301 | ESP_LOGV("Main", "Verbose"); 302 | esp_log_level_set(TAG, ESP_LOG_INFO); 303 | ESP_LOGE(TAG, "Error"); 304 | ESP_LOGW(TAG, "Warning"); 305 | ESP_LOGI(TAG, "Info"); 306 | ESP_LOGD(TAG, "Debug"); 307 | ESP_LOGV(TAG, "Verbose"); 308 | */ 309 | 310 | snprintf(HOSTNAME, sizeof(HOSTNAME), "ESP-MM-%llX", ESP.getEfuseMac()); // setting hostname 311 | 312 | ESP_LOGI(TAG, "*********************************************************************"); 313 | ESP_LOGI(TAG, "Firmware version %s (compiled at %s %s)", FIRMWARE_VERSION, __DATE__, __TIME__); 314 | ESP_LOGV(TAG, "Watchdog time-out: %ds", CONFIG_TASK_WDT_TIMEOUT_S); 315 | ESP_LOGI(TAG, "Hostname: %s", HOSTNAME); 316 | 317 | mqtt_reconnect_timer = xTimerCreate("mqtt_timer", pdMS_TO_TICKS(2000), pdFALSE, 318 | NULL, reinterpret_cast(connectToMqtt)); 319 | wifi_reconnect_timer = xTimerCreate("wifi_timer", pdMS_TO_TICKS(2000), pdFALSE, 320 | NULL, reinterpret_cast(connectToWifi)); 321 | 322 | WiFi.onEvent(wiFiEvent); 323 | 324 | mqtt_client.onConnect(onMqttConnect); 325 | mqtt_client.onDisconnect(onMqttDisconnect); 326 | mqtt_client.onSubscribe(onMqttSubscribe); 327 | mqtt_client.onUnsubscribe(onMqttUnsubscribe); 328 | mqtt_client.onMessage(onMqttMessage); 329 | mqtt_client.onPublish(onMqttPublish); 330 | 331 | IPAddress mqtt_ip; 332 | mqtt_ip.fromString(MQTT_HOST_IP); 333 | mqtt_client.setServer(mqtt_ip, MQTT_PORT); 334 | 335 | wifiManager.autoConnect(); 336 | 337 | #ifndef MODBUS_DISABLED 338 | initModbus(); 339 | 340 | xTaskCreate(runModbusPollerTask, "modbus_poller", 5900, NULL, 1, &modbus_poller_task_handler); 341 | configASSERT(modbus_poller_task_handler); 342 | 343 | modbus_poller_timer = xTimerCreate("modbus_poller_timer", pdMS_TO_TICKS(MODBUS_SCANRATE*1000), pdTRUE, NULL, 344 | reinterpret_cast(runModbusPollerTimer)); 345 | if (modbus_poller_timer == NULL) { 346 | // The timer was not created 347 | } else { 348 | if (xTimerStart(modbus_poller_timer, 0) != pdPASS) { 349 | // The timer could not be set into the Active state 350 | } 351 | } 352 | #endif // MODBUS_DISABLED 353 | 354 | xTaskCreate(runOtaUpdateTask, "ota_update", 4500, NULL, 2, &ota_update_task_handler); 355 | configASSERT(ota_update_task_handler); 356 | } 357 | 358 | void loop() { 359 | } 360 | -------------------------------------------------------------------------------- /src/main.h: -------------------------------------------------------------------------------- 1 | /* 2 | main.h - esp-modbus-mqtt 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef SRC_MAIN_H_ 20 | #define SRC_MAIN_H_ 21 | 22 | #endif // SRC_MAIN_H_ 23 | -------------------------------------------------------------------------------- /src/modbus_base.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | modbus_base.cpp - Modbus functions 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include "modbus_base.h" 20 | #include "modbus_registers.h" 21 | 22 | #include "Arduino.h" 23 | #include 24 | #include 25 | 26 | 27 | static const char __attribute__((__unused__)) *TAG = "Modbus_base"; 28 | 29 | /* The following symbols are passed via BUILD parameters 30 | #define RXD 27 // aka R0 31 | #define TXD 26 // aka DI 32 | #define RTS 25 // aka DE and /RE 33 | //if there is no flow control PIN 34 | //#define RTS NOT_A_PIN 35 | 36 | #define MODBUS_BAUDRATE 9600 37 | #define MODBUS_UNIT 10 38 | #define MODBUS_RETRIES 2 39 | #define MODBUS_SCANRATE 30 // in seconds 40 | */ 41 | 42 | // instantiate ModbusMaster object 43 | ModbusMaster modbus_client; 44 | 45 | void preTransmission() { 46 | digitalWrite(RTS, 1); 47 | } 48 | 49 | void postTransmission() { 50 | digitalWrite(RTS, 0); 51 | } 52 | 53 | void initModbus() { 54 | Serial2.begin(MODBUS_BAUDRATE, SERIAL_8N1, RXD, TXD); // Using ESP32 UART2 for Modbus 55 | modbus_client.begin(MODBUS_UNIT, Serial2); 56 | 57 | // do we have a flow control pin? 58 | if (RTS != NOT_A_PIN) { 59 | // Init in receive mode 60 | pinMode(RTS, OUTPUT); 61 | digitalWrite(RTS, 0); 62 | 63 | // Callbacks allow us to configure the RS485 transceiver correctly 64 | modbus_client.preTransmission(preTransmission); 65 | modbus_client.postTransmission(postTransmission); 66 | } 67 | } 68 | 69 | bool _getModbusResultMsg(ModbusMaster *node, uint8_t result) { 70 | String tmpstr2 = ""; 71 | switch (result) { 72 | case node->ku8MBSuccess: 73 | return true; 74 | break; 75 | case node->ku8MBIllegalFunction: 76 | tmpstr2 += "Illegal Function"; 77 | break; 78 | case node->ku8MBIllegalDataAddress: 79 | tmpstr2 += "Illegal Data Address"; 80 | break; 81 | case node->ku8MBIllegalDataValue: 82 | tmpstr2 += "Illegal Data Value"; 83 | break; 84 | case node->ku8MBSlaveDeviceFailure: 85 | tmpstr2 += "Slave Device Failure"; 86 | break; 87 | case node->ku8MBInvalidSlaveID: 88 | tmpstr2 += "Invalid Slave ID"; 89 | break; 90 | case node->ku8MBInvalidFunction: 91 | tmpstr2 += "Invalid Function"; 92 | break; 93 | case node->ku8MBResponseTimedOut: 94 | tmpstr2 += "Response Timed Out"; 95 | break; 96 | case node->ku8MBInvalidCRC: 97 | tmpstr2 += "Invalid CRC"; 98 | break; 99 | default: 100 | tmpstr2 += "Unknown error: " + String(result); 101 | break; 102 | } 103 | ESP_LOGV(TAG, "%s", tmpstr2.c_str()); 104 | return false; 105 | } 106 | 107 | bool _getModbusValue(uint16_t register_id, modbus_entity_t modbus_entity, uint16_t *value_ptr) { 108 | ESP_LOGD(TAG, "Requesting data"); 109 | for (uint8_t i = 1; i <= MODBUS_RETRIES + 1; ++i) { 110 | ESP_LOGV(TAG, "Trial %d/%d", i, MODBUS_RETRIES + 1); 111 | switch (modbus_entity) { 112 | case MODBUS_TYPE_HOLDING: 113 | uint8_t result; 114 | result = modbus_client.readHoldingRegisters(register_id, 1); 115 | if (_getModbusResultMsg(&modbus_client, result)) { 116 | *value_ptr = modbus_client.getResponseBuffer(0); 117 | ESP_LOGV(TAG, "Data read: %x", *value_ptr); 118 | return true; 119 | } 120 | break; 121 | default: 122 | ESP_LOGW(TAG, "Unsupported Modbus entity type"); 123 | value_ptr = nullptr; 124 | return false; 125 | break; 126 | } 127 | } 128 | // Time-out 129 | ESP_LOGW(TAG, "Time-out"); 130 | value_ptr = nullptr; 131 | return false; 132 | } 133 | 134 | String _toBinary(uint16_t input) { 135 | String output; 136 | while (input != 0) { 137 | output = (input % 2 == 0 ? "0" : "1") + output; 138 | input /= 2; 139 | } 140 | return output; 141 | } 142 | 143 | bool _decodeDiematicDecimal(uint16_t int_input, int8_t decimals, float *value_ptr) { 144 | ESP_LOGV(TAG, "Decoding %#x with %d decimal(s)", int_input, decimals); 145 | if (int_input == 65535) { 146 | value_ptr = nullptr; 147 | return false; 148 | } else { 149 | uint16_t masked_input = int_input & 0x7FFF; 150 | float output = static_cast(masked_input); 151 | if (int_input >> 15 == 1) { 152 | output = -output; 153 | } 154 | *value_ptr = output / pow(10, decimals); 155 | ESP_LOGV(TAG, "Decoded value: %f", *value_ptr); 156 | return true; 157 | } 158 | } 159 | 160 | void readModbusRegisterToJson(uint16_t register_id, ArduinoJson::JsonVariant variant) { 161 | // searchin for register matching register_id 162 | const uint8_t item_nb = sizeof(registers) / sizeof(modbus_register_t); 163 | for (uint8_t i = 0; i < item_nb; ++i) { 164 | if (registers[i].id != register_id) { 165 | // not this one 166 | continue; 167 | } else { 168 | // register found 169 | ESP_LOGD(TAG, "Register id=%d type=0x%x name=%s", registers[i].id, registers[i].type, registers[i].name); 170 | uint16_t raw_value; 171 | if (_getModbusValue(registers[i].id, registers[i].modbus_entity, &raw_value)) { 172 | ESP_LOGV(TAG, "Raw value: %s=%#06x", registers[i].name, raw_value); 173 | switch (registers[i].type) { 174 | case REGISTER_TYPE_U16: 175 | ESP_LOGV(TAG, "Value: %u", raw_value); 176 | variant[registers[i].name] = raw_value; 177 | break; 178 | case REGISTER_TYPE_DIEMATIC_ONE_DECIMAL: 179 | float final_value; 180 | if (_decodeDiematicDecimal(raw_value, 1, &final_value)) { 181 | ESP_LOGV(TAG, "Value: %.1f", final_value); 182 | variant[registers[i].name] = final_value; 183 | } else { 184 | ESP_LOGD(TAG, "Value: Invalid Diematic value"); 185 | } 186 | break; 187 | case REGISTER_TYPE_BITFIELD: 188 | for (uint8_t j = 0; j < 16; ++j) { 189 | const char *bit_varname = registers[i].optional_param.bitfield[j]; 190 | if (bit_varname == nullptr) { 191 | ESP_LOGV(TAG, " [bit%02d] end of bitfield reached", j); 192 | break; 193 | } 194 | const uint8_t bit_value = raw_value >> j & 1; 195 | ESP_LOGV(TAG, " [bit%02d] %s=%d", j, bit_varname, bit_value); 196 | variant[bit_varname] = bit_value; 197 | } 198 | break; 199 | case REGISTER_TYPE_DEBUG: 200 | ESP_LOGI(TAG, "Raw DEBUG value: %s=%#06x %s", registers[i].name, raw_value, _toBinary(raw_value).c_str()); 201 | break; 202 | default: 203 | // Unsupported type 204 | ESP_LOGW(TAG, "Unsupported register type"); 205 | break; 206 | } 207 | } else { 208 | ESP_LOGW(TAG, "Request failed!"); 209 | } 210 | return; // break the loop and exit the function 211 | } 212 | } 213 | // register not found 214 | } 215 | 216 | void parseModbusToJson(ArduinoJson::JsonVariant variant) { 217 | ESP_LOGI(TAG, "Parsing all Modbus registers (Logging Tag: %s)", TAG); 218 | uint8_t item_nb = sizeof(registers) / sizeof(modbus_register_t); 219 | for (uint8_t i = 0; i < item_nb; ++i) { 220 | readModbusRegisterToJson(registers[i].id, variant); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /src/modbus_base.h: -------------------------------------------------------------------------------- 1 | /* 2 | modbus_base.h - Modbus functions headers 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef SRC_MODBUS_BASE_H_ 20 | #define SRC_MODBUS_BASE_H_ 21 | 22 | #include 23 | #include 24 | 25 | void preTransmission(); 26 | void postTransmission(); 27 | void initModbus(); 28 | void readModbusRegisterToJson(uint16_t register_id, ArduinoJson::JsonVariant variant); 29 | void parseModbusToJson(ArduinoJson::JsonVariant variant); 30 | 31 | #endif // SRC_MODBUS_BASE_H_ 32 | -------------------------------------------------------------------------------- /src/modbus_registers.h: -------------------------------------------------------------------------------- 1 | /* 2 | modbus_registers.h - Modbus Registers Structure 3 | Copyright (C) 2020 Germain Masse 4 | 5 | This program is free software: you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef SRC_MODBUS_REGISTERS_H_ 20 | #define SRC_MODBUS_REGISTERS_H_ 21 | 22 | #include "Arduino.h" 23 | 24 | typedef enum { 25 | MODBUS_TYPE_HOLDING = 0x00, /*!< Modbus Holding register. */ 26 | // MODBUS_TYPE_INPUT, /*!< Modbus Input register. */ 27 | // MODBUS_TYPE_COIL, /*!< Modbus Coils. */ 28 | // MODBUS_TYPE_DISCRETE, /*!< Modbus Discrete bits. */ 29 | // MODBUS_TYPE_COUNT, 30 | // MODBUS_TYPE_UNKNOWN = 0xFF 31 | } modbus_entity_t; 32 | 33 | typedef enum { 34 | // REGISTER_TYPE_U8 = 0x00, /*!< Unsigned 8 */ 35 | REGISTER_TYPE_U16 = 0x01, /*!< Unsigned 16 */ 36 | // REGISTER_TYPE_U32 = 0x02, /*!< Unsigned 32 */ 37 | // REGISTER_TYPE_FLOAT = 0x03, /*!< Float type */ 38 | // REGISTER_TYPE_ASCII = 0x04, /*!< ASCII type */ 39 | REGISTER_TYPE_DIEMATIC_ONE_DECIMAL = 0x05, 40 | REGISTER_TYPE_BITFIELD = 0x06, 41 | REGISTER_TYPE_DEBUG = 0x07 42 | } register_type_t; 43 | 44 | typedef union { 45 | const char* bitfield[16]; 46 | } optional_param_t; 47 | 48 | typedef struct { 49 | uint16_t id; 50 | modbus_entity_t modbus_entity; /*!< Type of modbus parameter */ 51 | register_type_t type; /*!< Float, U8, U16, U32, ASCII, etc. */ 52 | const char* name; 53 | optional_param_t optional_param; 54 | } modbus_register_t; 55 | 56 | const modbus_register_t registers[] = { 57 | { 251, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "pulse_1_1" }, 58 | { 252, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_1_1" }, 59 | { 253, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "pulse_1_2" }, 60 | { 254, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_1_2" }, 61 | { 255, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "pulse_2_1" }, 62 | { 256, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_2_1" }, 63 | { 257, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "pulse_2_2" }, 64 | { 258, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_2_2" }, 65 | { 259, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "pulse_3_1" }, 66 | { 260, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_3_1" }, 67 | { 261, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "pulse_3_2" }, 68 | { 262, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_3_2" }, 69 | { 474, MODBUS_TYPE_HOLDING, REGISTER_TYPE_BITFIELD, "bits_primary_status", { .bitfield = { 70 | "io_burner_1", 71 | "io_burner_2", 72 | "io_valve_isolation_open", 73 | "io_valve_isolation_closed", 74 | "io_pump_boiler" 75 | } } }, 76 | { 475, MODBUS_TYPE_HOLDING, REGISTER_TYPE_BITFIELD, "bits_secondary_status", { .bitfield = { 77 | "io_pump_dhw", // Domestic Hot Water 78 | "io_pump_a", 79 | "io_valve_a_open", 80 | "io_valve_a_closed", 81 | "io_pump_b", 82 | "io_valve_b_open", 83 | "io_valve_b_closed", 84 | "io_pump_c", 85 | "io_valve_c_open", 86 | "io_valve_c_closed", 87 | "io_pump_aux_1", 88 | "io_pump_aux_2", 89 | "io_pump_aux_3" 90 | } } }, 91 | { 500, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "alarm_critical" }, // red 92 | { 501, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "alarm_major" }, // orange 93 | { 502, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "alarm_minor" }, // momentary 94 | { 503, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "power_instantaneous" }, // ##.# kW 95 | { 504, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "power_average" }, // ##.# kW/h 96 | { 505, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "power_average_dhw" }, // ##.# kW/h 97 | { 507, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "pulse_unit" }, 98 | { 508, MODBUS_TYPE_HOLDING, REGISTER_TYPE_U16, "pulse_ten" }, 99 | { 509, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_unit" }, 100 | { 510, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DEBUG, "operating_ten" }, 101 | { 601, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_external" }, 102 | { 602, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_boiler" }, 103 | { 603, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_tank" }, 104 | { 605, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_circuit_b" }, 105 | { 606, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_circuit_c" }, 106 | { 610, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "pressure" }, 107 | { 614, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_ambiant_circuit_a" }, 108 | { 615, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_computed_circuit_a" }, 109 | { 616, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_ambiant_circuit_b" }, 110 | { 617, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_computed_circuit_b" }, 111 | { 618, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_ambiant_circuit_c" }, 112 | { 619, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_computed_circuit_c" }, 113 | { 620, MODBUS_TYPE_HOLDING, REGISTER_TYPE_DIEMATIC_ONE_DECIMAL, "temperature_computed_boiler" }, 114 | { 700, MODBUS_TYPE_HOLDING, REGISTER_TYPE_BITFIELD, "bits_base", { .bitfield = { 115 | "io_pump_aux", 116 | "io_pump_boiler_1", 117 | "io_burner_1_2", 118 | "io_burner_1_1", 119 | "io_pump_a_xxx", 120 | "io_pump_dhw_xxx", 121 | "io_alarm_burner_1", 122 | "io_diematic", 123 | "io_valve_isolation_1", 124 | "io_boiler_mod_1", 125 | "io_burner_6_2", 126 | "io_burner_6_1", 127 | "io_burner_5_2", 128 | "io_burner_5_1", 129 | "io_burner_4_2", 130 | "io_burner_4_1" 131 | } } }, 132 | { 701, MODBUS_TYPE_HOLDING, REGISTER_TYPE_BITFIELD, "bits_terminal_2", { .bitfield = { 133 | "io_burner_2_1", 134 | "io_burner_2_2", 135 | "io_pump_boiler_2", 136 | "io_alarm_burner_2", 137 | "io_duration_2_1", 138 | "io_duration_2_2", 139 | "io_duration_1_1", 140 | "io_board_detected_k11", 141 | "io_valve_isolation_2", 142 | "io_boiler_mod_2", 143 | "io_burner_9_2", 144 | "io_burner_9_1", 145 | "io_burner_8_2", 146 | "io_burner_8_1", 147 | "io_burner_7_2", 148 | "io_burner_7_1" 149 | } } } 150 | }; 151 | 152 | #endif // SRC_MODBUS_REGISTERS_H_ 153 | -------------------------------------------------------------------------------- /test/README: -------------------------------------------------------------------------------- 1 | 2 | This directory is intended for PIO Unit Testing and project tests. 3 | 4 | Unit Testing is a software testing method by which individual units of 5 | source code, sets of one or more MCU program modules together with associated 6 | control data, usage procedures, and operating procedures, are tested to 7 | determine whether they are fit for use. Unit testing finds problems early 8 | in the development cycle. 9 | 10 | More information about PIO Unit Testing: 11 | - https://docs.platformio.org/page/plus/unit-testing.html 12 | -------------------------------------------------------------------------------- /test/test_url.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | void test_url_1(void) { 6 | Url url("http://userid:password@example.com:8080/blah_(wikipedia)_blah#cite-1?q=Test%20URL-encoded%20stuff"); 7 | TEST_ASSERT_EQUAL_STRING("http", url.Protocol.c_str()); 8 | TEST_ASSERT_EQUAL_STRING("example.com", url.Host.c_str()); 9 | TEST_ASSERT_EQUAL_STRING("8080", url.Port.c_str()); 10 | TEST_ASSERT_EQUAL_STRING("/blah_(wikipedia)_blah#cite-1", url.Path.c_str()); 11 | TEST_ASSERT_EQUAL_STRING("q=Test%20URL-encoded%20stuff", url.Query.c_str()); 12 | } 13 | 14 | void process() { 15 | UNITY_BEGIN(); 16 | RUN_TEST(test_url_1); 17 | UNITY_END(); 18 | } 19 | 20 | #ifdef ARDUINO 21 | 22 | #include 23 | void setup() { 24 | // NOTE!!! Wait for >2 secs 25 | // if board doesn't support software reset via Serial.DTR/RTS 26 | delay(2000); 27 | 28 | process(); 29 | } 30 | 31 | void loop() { 32 | } 33 | 34 | #else 35 | 36 | int main(int argc, char **argv) { 37 | process(); 38 | return 0; 39 | } 40 | 41 | #endif 42 | --------------------------------------------------------------------------------