├── .github └── workflows │ └── stale.yml ├── LICENSE ├── README.md ├── mqtt2sql.conf ├── mqtt2sql.py ├── mysql.sql ├── requirements.txt └── sqlite.sql /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. 2 | # 3 | # You can adjust the behavior by modifying this file. 4 | # For more information, see: 5 | # https://github.com/actions/stale 6 | name: Mark stale issues and pull requests 7 | 8 | on: 9 | schedule: 10 | - cron: "00 17 * * *" 11 | 12 | jobs: 13 | stale: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/stale@v6.0.1 17 | with: 18 | repo-token: ${{ secrets.GITHUB_TOKEN }} 19 | days-before-stale: 25 20 | days-before-close: 5 21 | stale-issue-message: "This issue has been automatically marked as stale because it hasn't any activity in last few weeks. It will be closed if no further activity occurs. Thank you for your contributions." 22 | stale-pr-message: "This PR has been automatically marked as stale because it hasn't any activity in last few weeks. It will be closed if no further activity occurs. Thank you for your contributions." 23 | close-issue-message: "This issue was automatically closed because of being stale. Feel free to open a new one if you still experience this problem." 24 | close-pr-message: "This PR was automatically closed because of being stale." 25 | stale-pr-label: "stale" 26 | stale-issue-label: "stale" 27 | exempt-issue-labels: "bug,enhancement,pinned,security" 28 | exempt-pr-labels: "bug,enhancement,pinned,security" 29 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | # mqtt2sql 2 | 3 | This [python](#deprecated) program creates copies of MQTT broker/server payloads into a SQL database (currently supports MySQL5.x-8.x/MariaDB 10.x and SQLite 3). 4 | 5 | [![master](https://img.shields.io/badge/master-v3.0.2-blue.svg)](https://github.com/curzon01/mqtt2sql/tree/master) 6 | [![License](https://img.shields.io/github/license/curzon01/mqtt2sql.svg)](LICENSE) 7 | 8 | If you like **mqtt2sql** give it a star or fork it: 9 | 10 | [![GitHub stars](https://img.shields.io/github/stars/curzon01/mqtt2sql.svg?style=social&label=Star)](https://github.com/curzon01/mqtt2sql/stargazers) 11 | [![GitHub forks](https://img.shields.io/github/forks/curzon01/mqtt2sql.svg?style=social&label=Fork)](https://github.com/curzon01/mqtt2sql/network) 12 | 13 | The MQTT data are provided in the following tables/view: 14 | 15 | * Table `mqtt` 16 | contains the last MQTT copied payload for the subcribed topic 17 | * Table `mqtt_history` 18 | contains the payloads history from `mqtt`. History data can be disabled by topic or in general (see [History control](#history-control)). 19 | * View `mqtt_history_view` 20 | contains data from `mqtt_history` with readable topics and timestamps (see [History view](#history-view)) 21 | 22 |
23 | Contents 24 | 25 | * [Installation](#installation) 26 | * [Python prerequisites](#python-prerequisites) 27 | * [MySQL prerequisites](#mysql-prerequisites) 28 | * [Copy the program](#copy-the-program) 29 | * [Create database objects](#create-database-objects) 30 | * [Usage](#usage) 31 | * [Start from command line](#start-from-command-line) 32 | * [Start as systemd manager daemon](#start-as-systemd-manager-daemon) 33 | * [History data](#history-data) 34 | * [History control](#history-control) 35 | * [History view](#history-view) 36 | * [Localized timestamps](#localized-timestamps) 37 | * [Deprecated](#deprecated) 38 | * [Deprecated program arguments](#deprecated-program-arguments) 39 |
40 | 41 | ## Installation 42 | 43 | During the installation we 44 | 45 | * create a usable [Python 3.x](https://www.python.org/downloads/) environment 46 | * create the necessary databases and objects 47 | * test the program 48 | * and if desired, create a system daemon 49 | 50 | ### Python prerequisites 51 | 52 | If not already done, install a working [Python 3.x](https://www.python.org/downloads/) environment described there. 53 | 54 | **Note**: Due to the [Python 2.7 EOL](https://github.com/python/devguide/pull/344) in Jan 2020 Python 2.x is no longer supported. 55 | 56 | Install Pip, Paho MQTT and MySQLdb lib to your python environment use 57 | 58 | ```bash 59 | sudo apt install python3 python3-pip libmysqlclient-dev 60 | python -m pip install -r requirements.txt 61 | ``` 62 | 63 | **Check** that Python 3.x is installed e.g. 64 | 65 | ```bash 66 | $ python --version 67 | Python 3.10.6 68 | ``` 69 | 70 | **Check** that pip installed **pao-mqtt greater or equal version 1.2.3**, e.g. 71 | 72 | ```bash 73 | $ python -m pip show paho-mqtt 74 | ... 75 | Name: paho-mqtt 76 | Version: 1.6.1 77 | ... 78 | ``` 79 | 80 | ### MySQL prerequisites 81 | 82 | In order for MySQL to handle time zones correctly, make sure that the [MySQL Server Time Zone Support](https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html) is set up correctly (see also [Populating the Time Zone Tables](https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html#time-zone-installation)). 83 | 84 | ### Copy the program 85 | 86 | Copy repository using git and make the program executable: 87 | 88 | ```bash 89 | git clone https://github.com/curzon01/mqtt2sql 90 | cd mqtt2sql 91 | chmod +x mqtt2sql.py 92 | ``` 93 | 94 | ### Create database objects 95 | 96 | > the sql scripts we use here for MySQL and SQLite are creating all neccessary databases and objects. The default database is `mqtt` and the tables are `mqtt_history` with history data enabled. If you want to use different namings or existing databases, edit the top of the related *sql script before using it. 97 | 98 | #### Using MySQL 99 | 100 | ```bash 101 | mysql --host localhost < mysql.sql 102 | ``` 103 | 104 | If a username and password is set on your server, use 105 | 106 | ```bash 107 | mysql --host localhost -u -p < mysql.sql 108 | ``` 109 | 110 | #### Using SQLite3 111 | 112 | ```bash 113 | sqlite3 mqtt.db Change parameter to your needs 131 | 132 | ```bash 133 | ./mqtt2sql.py --mqtt mqtt://mqttuser:mqttpasswd@localhost/mytopic/# \ 134 | --sql-type mysql --sql-host localhost --sql-username sqluser --sql-password 'sqlpasswd' --sql-db mqtt -v 135 | ``` 136 | 137 | #### Run program using SQLite3 138 | 139 | > Change parameter to your needs 140 | 141 | ```bash 142 | ./mqtt2sql.py --mqtt mqtt://mqttuser:mqttpasswd@localhost/mytopic/# \ 143 | --sql-type sqlite --sql-db mqtt.db -v 144 | ``` 145 | 146 | ### Start as systemd manager daemon 147 | 148 | The program allows the entire program parameters to be transferred in a configuration file instead of as individual program parameters. 149 | For the following service file we use a copy of the configuration file [mqtt2sql.conf](https://github.com/curzon01/mqtt2sql/blob/master/mqtt2sql.conf) for parameterization and chnage it to our needs. This means that we do not have to edit the service file in the case of changes. 150 | 151 | #### Make a copy of the program and configuration file and edit the parameter 152 | 153 | ```bash 154 | sudo mkdir -p /usr/local/bin/ 155 | sudo cp mqtt2sql.py /usr/local/bin/ 156 | sudo mkdir -p /usr/local/etc/ 157 | sudo cp mqtt2sql.conf /usr/local/etc/ 158 | sudo nano /usr/local/etc/mqtt2sql.conf 159 | ``` 160 | 161 | edit the configuration parameter for your needs and save it with `Ctrl+o` `Ctrl+x`. 162 | 163 | #### Create mqtt2sql.service 164 | 165 | ```bash 166 | sudo nano /etc/systemd/system/mqtt2sql.service 167 | ``` 168 | 169 | Insert the following lines 170 | 171 | ```conf 172 | Description=MQTT2SQL 173 | After=local-fs.target network.target mysql.service 174 | 175 | [Service] 176 | Type=simple 177 | Restart=always 178 | RestartSec=10 179 | ExecStart=/usr/local/bin/mqtt2sql.py --configfile /usr/local/etc/mqtt2sql.conf 180 | 181 | [Install] 182 | WantedBy=multi-user.target 183 | ``` 184 | 185 | #### Reload systemd manager, restart daemon and check success 186 | 187 | ```bash 188 | sudo systemctl daemon-reload 189 | sudo systemctl restart mqtt2sql 190 | sudo systemctl status mqtt2sql 191 | ``` 192 | 193 | #### Finally enable the service 194 | 195 | ```bash 196 | sudo systemctl enable mqtt2sql 197 | ``` 198 | 199 | ## History data 200 | 201 | Table `mqtt_history` contains data history from table `mqtt` changes received by the MQTT subscription. The default setup is storing only changed values within `mqtt_history`. 202 | 203 | Database objects created by this scripts enables history data as default. 204 | 205 | ### History control 206 | 207 | History data creation depends on two columns for topics in `mqtt` table: 208 | 209 | * column `history_enable` indicates whether topic payload is saved in `mqtt_history` (1) or not (0). 210 | * column `history_diffonly` indicates whether topic payload is saved in `mqtt_history` only if payload is different to previously (1) or always (0). Note: this setting is ignored if `history_enable` is 0. 211 | 212 | #### Change history control for exiting records 213 | 214 | For existing `mqtt` table records use the UPDATE command, e.g. `UPDATE mqtt SET history_enable=0` to disable history saving for all existing topic records (accordingly same sing column `history_diffonly`) 215 | 216 | #### Change history control for newly created records 217 | 218 | For newly created `mqtt` table records change the default of the related column using the ALTER command, e.g. 219 | 220 | ```sql 221 | ALTER TABLE `mqtt` 222 | CHANGE COLUMN `history_enable` 223 | `history_enable` TINYINT(4) NOT NULL DEFAULT 0;` 224 | ``` 225 | 226 | set the same as above (disable history saving for topic records) for newly created topics. 227 | 228 | ### History view 229 | 230 | The view `mqtt_history_view` can be used to get the history data with human readable topics instead of foreign keys from original table `mqtt_history`. The view has also two timestamp columns: 231 | 232 | * `ts` is the timestamp from lastest insert into the `mqtt_history` table 233 | * `ts_last` is the timestamp from lastest change 234 | 235 | If `history_diffonly` is enabled (1), `ts` shows the timestamp of the last payload change where the `ts_last` shows the latest recevied timestamp (independent if the last recevied payload has change or not). 236 | 237 | ### Localized timestamps 238 | 239 | Since *mqtt2sql* v3.0.0, timestamps are saved using [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) by default. This is the best way to avoid time duplicates during the change from e. g. daylight saving time (DST) to standard time. 240 | 241 | #### SQLite 242 | 243 | To process timestamps under `SQLite` using your local time, convert them when reading the database (e.g. `SELECT DATETIME(ts, 'localtime'`). 244 | 245 | #### MySQL 246 | 247 | When using `MySQL` you do not need to perform an explicit conversion when reading table. `MySQL` continues to use the `TIMESTAMP` data type for timestamps, which always stores timestamps in UTC and automatically converts them to the local time zone of the client connection when they are returned. For this purpose, *mqtt2sql* uses the same time zone setting for the connection to the MySQL server as the value that is saved when insert the data. 248 | 249 | Leave the setting for `--sql-timezone` at the default value `UTC`, because Python handles the time conversion from local time to UTC without errors, while MySQL works incorrectly. 250 | 251 | If you want to use local timestamps for any reason, use the optional parameter `--sql-timezone ` (possible time zones can be displayed using `--sql-timezone help`). But be aware that this will result in ambiguous records regarding the time stamps during the changeover from summer to standard time. In this case, you can recognize the duplicate timestamps by the table `mqtt_history.id`, which are in ascending order. 252 | 253 | ## Deprecated 254 | 255 | Due to the [Python 2.7 EOL](https://github.com/python/devguide/pull/344) in Jan 2020 Python 2.x is no longer supported. 256 | 257 | ### Deprecated program arguments 258 | 259 | The following program arguments are deprecated but still valid and working for backwards compatibility. 260 | However, these should no longer be used, as they could be omitted in the future. 261 | 262 | #### Deprecated MQTT arguments 263 | 264 | These deprecated parameters override MQTT URL components: 265 | 266 | `--mqtt-host`, `--mqtthost` 267 | `--mqtt-port`, `--mqttport` 268 | `--mqtt-username`, `--mqttusername` 269 | `--mqtt-password` , `--mqttpassword` 270 | -------------------------------------------------------------------------------- /mqtt2sql.conf: -------------------------------------------------------------------------------- 1 | # Optional configuration file for mqtt2sql 2 | # 3 | # Use it with parameter -c or --configfile, e.g. 4 | # mqtt2sql.py -c my.conf 5 | # 6 | # Allowed parameters: 7 | # All parameter starting with double dashes '--' from command line 8 | # see mqtt2sql -h for details 9 | # 10 | # Parameter given here can be overwritten by command line parameters. 11 | # Parameter grouping by [] are optional for better reading and ignored. 12 | # 13 | # For detailed configuration file syntax: 14 | # see https://pypi.python.org/pypi/ConfigArgParse 15 | 16 | 17 | [DEFAULT] 18 | # optional logfile [string] 19 | #logfile = /var/log/mqtt2sql.log 20 | 21 | # debug output 22 | #debug 23 | 24 | # verbose output 25 | #verbose 26 | 27 | 28 | [MQTT] 29 | # MQTT conection URL [string] 30 | mqtt = mqtt://mqttusername:mqttpassword@localhost:1883/# 31 | 32 | # MQTT topics subscribe to [string] or [array] 33 | #mqtt-topic = [topic1/#, topic2/+/sub/#, topic3/#] 34 | 35 | # MQTT cafile [string] 36 | # if MQTT server uses an official cert you can use an official ca 37 | #mqtt-cafile = /etc/ssl/certs/ISRG_Root_X1.pem 38 | 39 | # MQTT certfile [string] 40 | #mqtt-certfile = 41 | 42 | # MQTT keyfile [string] 43 | #mqtt-keyfile = 44 | 45 | # MQTT suppress TLS verification (default False) [bool] 46 | #mqtt-insecure 47 | 48 | # MQTT keepalive timeout for the client (default 60) [integer] 49 | #mqtt-keepalive = 60 50 | 51 | # MQTT timeout for mqtt connection in ms (default 500) [integer] 52 | #mqtt-connect-timeout = 500 53 | 54 | [SQL] 55 | # SQL server type ['mysql', 'sqlite'] (default 'mysql') [string] 56 | sql-type = mysql 57 | 58 | # SQL host to connect (default localhost) [string] 59 | sql-host = localhost 60 | 61 | # SQL port to connect (default 3306) [integer] 62 | #sql-port = 3306 63 | 64 | # SQL username [string] 65 | sql-username = sqlusername 66 | 67 | # SQL password [string] 68 | sql-password = sqlpassword 69 | 70 | # SQL database to use [string] 71 | sql-db = mqtt 72 | 73 | # SQL table to use (default 'mqtt') [string] 74 | sql-table = mqtt 75 | 76 | # SQL maximum number of simultaneous connections (default 50) [integer] 77 | #sql-max-connection = 50 78 | 79 | # maximum number of SQL connection retries on error [integer] 80 | #sql-connection-retry = 10 81 | 82 | # start delay between SQL reconnect retry (default 1) [float] 83 | # is doubled after each occurrence 84 | #sql-connection-retry-start-delay = 1 85 | 86 | # maximum number of SQL transaction retry on error (default 10) [integer] 87 | #sql-transaction-retry = 10 88 | -------------------------------------------------------------------------------- /mqtt2sql.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # pylint: disable=line-too-long 4 | VER = '3.0.2' 5 | 6 | """ 7 | mqtt2mysql.py - Copy MQTT topic payloads to MySQL/SQLite database 8 | 9 | Copyright (C) 2022 Norbert Richter 10 | 11 | This program is free software: you can redistribute it and/or modify 12 | it under the terms of the GNU General Public License as published by 13 | the Free Software Foundation, either version 3 of the License, or 14 | (at your option) any later version. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | GNU General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License 22 | along with this program. If not, see . 23 | 24 | 25 | Requirements: 26 | Python, pip and modules: 27 | > apt install python3 python3-pip 28 | > python -m pip install -r requirements.txt 29 | 30 | Usage: 31 | See README.md for more details how to install and use 32 | https://github.com/curzon01/mqtt2sql#mqtt2sql 33 | 34 | """ 35 | 36 | class ExitCode: 37 | """ 38 | Program return codes 39 | """ 40 | OK = 0 41 | MISSING_MODULE = 1 42 | MQTT_CONNECTION_ERROR = 2 43 | SQL_CONNECTION_ERROR = 3 44 | 45 | def module_import_error(module): 46 | """ 47 | Print suggestion for import failures 48 | 49 | @param module: import module name 50 | """ 51 | err_str = str(module) 52 | print("{}. Try 'python -m pip install {}' to install".format(err_str, err_str.split(' ')[len(err_str.split(' '))-1])) 53 | sys.exit(9) 54 | 55 | # pylint: disable=wrong-import-position 56 | import os 57 | import sys 58 | try: 59 | import paho.mqtt.client as mqtt 60 | import time 61 | import datetime 62 | import zoneinfo 63 | import signal 64 | import logging 65 | import configargparse 66 | import urllib 67 | import re 68 | from threading import get_ident, Thread, BoundedSemaphore 69 | from random import random 70 | except ImportError as err: 71 | module_import_error(err) 72 | try: 73 | import ssl 74 | MODULE_SSL_AVAIL = True 75 | except ImportError: 76 | MODULE_SSL_AVAIL = False 77 | try: 78 | import MySQLdb 79 | MODULE_MYSQLDB_AVAIL = True 80 | except ImportError: 81 | MODULE_MYSQLDB_AVAIL = False 82 | try: 83 | import sqlite3 84 | MODULE_SQLITE3_AVAIL = True 85 | except ImportError: 86 | MODULE_SQLITE3_AVAIL = False 87 | # pylint: enable=wrong-import-position 88 | 89 | SCRIPTNAME = os.path.basename(sys.argv[0]) 90 | SCRIPTPID = os.getpid() 91 | SQLTYPES = {'mysql':'MySQL', 'sqlite':'SQLite'} 92 | ARGS = {} 93 | DEFAULTS = { 94 | 'configfile': None, 95 | 'logfile': None, 96 | 'debug': None, 97 | 'verbose': None, 98 | 99 | 'mqtt-url': 'mqtt://localhost/#', 100 | 'mqtt-username': None, 101 | 'mqtt-password': None, 102 | 'mqtt-host': 'localhost', 103 | 'mqtt-topic': None, 104 | 'mqtt-exclude-topic': None, 105 | 'mqtt-cafile': None, 106 | 'mqtt-certfile': None, 107 | 'mqtt-keyfile': None, 108 | 'mqtt-insecure': False, 109 | 'mqtt-keepalive': 60, 110 | 'mqtt-connect-timeout':500, 111 | 112 | 'sql-type': 'mysql' if MODULE_MYSQLDB_AVAIL else ('sqlite' if MODULE_SQLITE3_AVAIL else None), 113 | 'sql-host': 'localhost', 114 | 'sql-port': 3306, 115 | 'sql-username': None, 116 | 'sql-password': None, 117 | 'sql-db': None, 118 | 'sql-table': 'mqtt', 119 | 'sql-max-connection': 50, 120 | 'sql-connection-retry': 10, 121 | 'sql-connection-retry-start-delay': 1, 122 | 'sql-transaction-retry': 10, 123 | 'sql-timezone': 'UTC' 124 | } 125 | 126 | DEFAULT_PORT_MQTT = 1883 127 | DEFAULT_PORT_MQTTS = 8883 128 | DEFAULT_PORT_MYSQL = 3306 129 | 130 | def parseargs(): 131 | """ 132 | Program argument parser 133 | 134 | @return: 135 | configargparse.parse_args() result 136 | """ 137 | # pylint: disable=global-statement 138 | global VER 139 | global DEFAULTS 140 | global MODULE_SSL_AVAIL 141 | global MODULE_MYSQLDB_AVAIL 142 | global MODULE_SQLITE3_AVAIL 143 | # pylint: enable=global-statement 144 | 145 | class SmartFormatter(configargparse.HelpFormatter): 146 | def _split_lines(self, text, width): 147 | if text.startswith('R|'): 148 | return text[2:].splitlines() 149 | return configargparse.HelpFormatter._split_lines(self, text, width) 150 | 151 | parser = configargparse.ArgumentParser(\ 152 | description='MQTT to MySQL bridge. Subscribes to MQTT broker topic(s) and write values into a database.', 153 | epilog="There are no required arguments, defaults are displayed using --help.", 154 | formatter_class=SmartFormatter 155 | ) 156 | parser.add_argument( 157 | '-c', '--configfile', 158 | metavar="", 159 | dest='configfile', 160 | is_config_file=True, 161 | default=DEFAULTS['configfile'], 162 | help="Config file, can be used instead of command parameter (default {})".format(DEFAULTS['configfile']) 163 | ) 164 | 165 | mqtt_group = parser.add_argument_group('MQTT Options') 166 | mqtt_group.add_argument( 167 | '--mqtt', 168 | metavar='', 169 | dest='mqtt_url', 170 | default=DEFAULTS['mqtt-url'], 171 | help="R|Specify specify user, password, hostname, port and topic at once as a URL (default '{}').\n" 172 | "The URL must be in the form:\n" 173 | "mqtt(s)://[username[:password]@]host[:port][/topic]".format(DEFAULTS['mqtt-url']) 174 | ) 175 | mqtt_group.add_argument('--mqtt-host',dest='mqtt_host', help=configargparse.SUPPRESS) 176 | mqtt_group.add_argument('--mqtthost', '--host', dest='mqtt_host', help=configargparse.SUPPRESS) 177 | mqtt_group.add_argument('--mqtt-port', dest='mqtt_port', type=int, help=configargparse.SUPPRESS) 178 | mqtt_group.add_argument('--mqttport', '--port', dest='mqtt_port', type=int, help=configargparse.SUPPRESS) 179 | mqtt_group.add_argument('--mqtt-username', dest='mqtt_username', help=configargparse.SUPPRESS) 180 | mqtt_group.add_argument('--mqttusername', '--username', dest='mqtt_username', help=configargparse.SUPPRESS) 181 | mqtt_group.add_argument('--mqtt-password', dest='mqtt_password',help=configargparse.SUPPRESS) 182 | mqtt_group.add_argument('--mqttpassword', '--password', dest='mqtt_password', help=configargparse.SUPPRESS) 183 | mqtt_group.add_argument( 184 | '--mqtt-topic', 185 | metavar='', 186 | dest='mqtt_topic', 187 | nargs='*', 188 | default=DEFAULTS['mqtt-topic'], 189 | help="optional: topic(s) to use (default {}).".format(DEFAULTS['mqtt-topic'])) 190 | mqtt_group.add_argument('--topic', dest='mqtt_topic', nargs='*', help=configargparse.SUPPRESS) 191 | mqtt_group.add_argument( 192 | '--mqtt-exclude-topic', 193 | metavar='', 194 | dest='mqtt_exclude_topic', 195 | nargs='*', 196 | default=DEFAULTS['mqtt-exclude-topic'], 197 | help="optional: topic(s) to exclude (default {}).".format(DEFAULTS['mqtt-exclude-topic'])) 198 | mqtt_group.add_argument( 199 | '--mqtt-cafile', 200 | metavar='', 201 | dest='mqtt_cafile', 202 | default=DEFAULTS['mqtt-cafile'], 203 | help="cafile (default {})".format(DEFAULTS['mqtt-cafile']) if MODULE_SSL_AVAIL else configargparse.SUPPRESS) 204 | mqtt_group.add_argument('--cafile', dest='mqtt_cafile', help=configargparse.SUPPRESS) 205 | mqtt_group.add_argument( 206 | '--mqtt-certfile', 207 | metavar='', 208 | dest='mqtt_certfile', 209 | default=DEFAULTS['mqtt-certfile'], 210 | help="certfile (default {})".format(DEFAULTS['mqtt-certfile']) if MODULE_SSL_AVAIL else configargparse.SUPPRESS) 211 | mqtt_group.add_argument('--certfile', dest='mqtt_certfile', help=configargparse.SUPPRESS) 212 | mqtt_group.add_argument( 213 | '--mqtt-keyfile', 214 | metavar='', 215 | dest='mqtt_keyfile', 216 | default=DEFAULTS['mqtt-keyfile'], 217 | help="keyfile (default {})".format(DEFAULTS['mqtt-keyfile']) if MODULE_SSL_AVAIL else configargparse.SUPPRESS) 218 | mqtt_group.add_argument('--keyfile', dest='mqtt_keyfile', help=configargparse.SUPPRESS) 219 | mqtt_group.add_argument( 220 | '--mqtt-insecure', 221 | dest='mqtt_insecure', 222 | action='store_true', 223 | default=DEFAULTS['mqtt-insecure'], 224 | help="suppress TLS verification (default {})".format(DEFAULTS['mqtt-insecure']) if MODULE_SSL_AVAIL else configargparse.SUPPRESS) 225 | mqtt_group.add_argument('--insecure', dest='mqtt_insecure', help=configargparse.SUPPRESS) 226 | mqtt_group.add_argument( 227 | '--mqtt-keepalive', 228 | metavar='', 229 | dest='mqtt_keepalive', 230 | type=int, 231 | default=DEFAULTS['mqtt-keepalive'], 232 | help="keepalive timeout for the client (default {})".format(DEFAULTS['mqtt-keepalive'])) 233 | mqtt_group.add_argument('--keepalive', dest='mqtt_keepalive', type=int, help=configargparse.SUPPRESS) 234 | mqtt_group.add_argument( 235 | '--mqtt-connect-timeout', 236 | metavar='', 237 | dest='mqtt_connect_timeout', 238 | type=int, 239 | default=DEFAULTS['mqtt-connect-timeout'], 240 | help="timeout for mqtt connection (default {})".format(DEFAULTS['mqtt-connect-timeout'])) 241 | 242 | sql_group = parser.add_argument_group('SQL Options') 243 | sql_choices = [] 244 | if MODULE_MYSQLDB_AVAIL: 245 | sql_choices.append('mysql') 246 | if MODULE_SQLITE3_AVAIL: 247 | sql_choices.append('sqlite') 248 | if len(sql_choices) == 0: 249 | SignalHandler.exitus(ExitCode.MISSING_MODULE, 'Either module MySQLdb or sqlite must be installed') 250 | 251 | sql_group.add_argument( 252 | '--sql-type', 253 | metavar='', 254 | dest='sql_type', 255 | choices=sql_choices, 256 | default=DEFAULTS['sql-type'], 257 | help="server type {} (default '{}')".format(sql_choices, DEFAULTS['sql-type'])) 258 | sql_group.add_argument('--sqltype', dest='sql_type', choices=sql_choices, help=configargparse.SUPPRESS) 259 | sql_group.add_argument( 260 | '--sql-host', 261 | metavar='|', 262 | dest='sql_host', 263 | default=DEFAULTS['sql-host'], 264 | help="hostname or unix socket to connect (default '{}')".format(DEFAULTS['sql-host'])) 265 | sql_group.add_argument('--sqlhost', dest='sql_host', help=configargparse.SUPPRESS) 266 | sql_group.add_argument( 267 | '--sql-port', 268 | metavar='', 269 | dest='sql_port', 270 | type=int, 271 | default=DEFAULTS['sql-port'], 272 | help="port to connect (default {}, ignored when unix socket is defined)".format(DEFAULTS['sql-port'])) 273 | sql_group.add_argument('--sqlport', dest='sql_port', type=int, help=configargparse.SUPPRESS) 274 | sql_group.add_argument( 275 | '--sql-username', 276 | metavar='', 277 | dest='sql_username', 278 | default=DEFAULTS['sql-username'], 279 | help="username (default {})".format(DEFAULTS['sql-username'])) 280 | sql_group.add_argument('--sqlusername', dest='sql_username', help=configargparse.SUPPRESS) 281 | sql_group.add_argument( 282 | '--sql-password', 283 | metavar='', 284 | dest='sql_password', 285 | default=DEFAULTS['sql-password'], 286 | help="password (default {})".format(DEFAULTS['sql-password'])) 287 | sql_group.add_argument('--sqlpassword', dest='sql_password', help=configargparse.SUPPRESS) 288 | sql_group.add_argument( 289 | '--sql-db', 290 | metavar='', 291 | dest='sql_db', 292 | default=DEFAULTS['sql-db'], 293 | help="database to use (default '{}')".format(DEFAULTS['sql-db'])) 294 | sql_group.add_argument('--sqldb', dest='sql_db', help=configargparse.SUPPRESS) 295 | sql_group.add_argument( 296 | '--sql-table', 297 | metavar='', 298 | dest='sql_table', 299 | default=DEFAULTS['sql-table'], 300 | help="table to use (default '{}')".format(DEFAULTS['sql-table'])) 301 | sql_group.add_argument('--sqltable', dest='sql_table', help=configargparse.SUPPRESS) 302 | tz_choices = list(zoneinfo.available_timezones()) 303 | sql_group.add_argument( 304 | '--sql-timezone', 305 | metavar='', 306 | dest='sql_timezone', 307 | choices=tz_choices, 308 | default=DEFAULTS['sql-timezone'], 309 | help="server timezone (default '{}')".format(DEFAULTS['sql-timezone'])) 310 | sql_group.add_argument('--sqltimezone', dest='sql_timezone', choices=tz_choices, help=configargparse.SUPPRESS) 311 | 312 | sql_group.add_argument( 313 | '--sql-max-connection', 314 | metavar='', 315 | dest='sql_max_connection', 316 | type=int, 317 | default=DEFAULTS['sql-max-connection'], 318 | help="maximum number of simultaneous connections (default {})".format(DEFAULTS['sql-max-connection'])) 319 | sql_group.add_argument('--sqlmaxconnection', dest='sql_max_connection', type=int, help=configargparse.SUPPRESS) 320 | sql_group.add_argument( 321 | '--sql-connection-retry', 322 | metavar='', 323 | dest='sql_connection_retry', 324 | type=int, 325 | default=DEFAULTS['sql-connection-retry'], 326 | help="maximum number of SQL connection retries on error (default {})".format(DEFAULTS['sql-connection-retry'])) 327 | sql_group.add_argument( 328 | '--sql-connection-retry-start-delay', 329 | metavar='', 330 | dest='sql_connection_retry_start_delay', 331 | type=float, 332 | default=DEFAULTS['sql-connection-retry-start-delay'], 333 | help="start delay between SQL reconnect retry (default {}), is doubled after each occurrence".format(DEFAULTS['sql-connection-retry-start-delay'])) 334 | sql_group.add_argument( 335 | '--sql-transaction-retry', 336 | metavar='', 337 | dest='sql_transaction_retry', 338 | type=int, 339 | default=DEFAULTS['sql-transaction-retry'], 340 | help="maximum number of SQL transaction retry on error (default {})".format(DEFAULTS['sql-transaction-retry'])) 341 | 342 | logging_group = parser.add_argument_group('Informational') 343 | logging_group.add_argument( 344 | '-l', '--logfile', 345 | metavar='', 346 | dest='logfile', 347 | default=DEFAULTS['logfile'], 348 | help="optional logfile (default {}".format(DEFAULTS['logfile'])) 349 | logging_group.add_argument( 350 | '-d', '--debug', 351 | dest='debug', 352 | action='count', 353 | help='debug output') 354 | logging_group.add_argument( 355 | '-v', '--verbose', 356 | dest='verbose', 357 | action='count', 358 | help='verbose output') 359 | logging_group.add_argument( 360 | '-V', '--version', 361 | action='version', 362 | version='%(prog)s v'+VER) 363 | 364 | return parser.parse_args() 365 | 366 | class LogLevel: 367 | """ 368 | Log levels 369 | """ 370 | ALWAYS = 0 371 | INFORMATION = 1 372 | NOTICE = 2 373 | ERROR = 3 374 | 375 | def verbose_level(): 376 | """ 377 | return verbose level 378 | """ 379 | global ARGS # pylint: disable=global-statement 380 | return ARGS.verbose if ARGS.verbose is not None else LogLevel.ALWAYS 381 | 382 | def debug_level(): 383 | """ 384 | return debug level 385 | """ 386 | global ARGS # pylint: disable=global-statement 387 | return ARGS.debug if ARGS.debug is not None else LogLevel.ALWAYS 388 | 389 | def log(loglevel, msg): 390 | """ 391 | Writes a message to stdout and optional logfile 392 | if given loglevel is >= verbose_level() 393 | 394 | @param msg: message to output 395 | """ 396 | if verbose_level() >= loglevel: 397 | global ARGS # pylint: disable=global-statement 398 | strtime = str(time.strftime("%Y-%m-%d %H:%M:%S")) 399 | # print strtime+': '+msg 400 | if ARGS.logfile is not None: 401 | filename = str(time.strftime(ARGS.logfile, time.localtime())) 402 | logfile = open(filename, "a") 403 | logfile.write(strtime+': '+msg+'\n') 404 | logfile.close() 405 | print(strtime+': '+msg) 406 | 407 | def debuglog(dbglevel, msg): 408 | """ 409 | Writes a message to stdout and optional logfile 410 | if given dbglevel is >= debug_level() 411 | 412 | @param dbglevel: 413 | debug level used 414 | e.g. 415 | if -d is given one time and dbglevel is 1, then msg is output 416 | if -d is given one time and dbglevel is 2, then msg will not output 417 | if -d is given two times and dbglevel is 2, then msg will output 418 | @param msg: message to output 419 | """ 420 | if debug_level() > dbglevel: 421 | log(LogLevel.ALWAYS, msg) 422 | 423 | def issocket(name): 424 | """ 425 | Simple check if name is a socket name 426 | 427 | @param name: 428 | name to check 429 | 430 | return True if name is a socket name 431 | """ 432 | nametype = re.search(r'^(\/\S*)*', name) 433 | return nametype is not None and nametype.group(0) == name 434 | 435 | class Mqtt2Sql: 436 | """ 437 | MQTT to SQL handling class 438 | """ 439 | def __init__(self, args): 440 | self.exit_code = ExitCode.OK 441 | self.args_ = args 442 | self.connected = False 443 | self.connect_rc = 0 444 | self.mqtt_url = args.mqtt_url 445 | self.mqtt_host = args.mqtt_host 446 | self.mqtt_port = args.mqtt_port 447 | self.mqtt_username = args.mqtt_username 448 | self.mqtt_password = args.mqtt_password 449 | self.mqtt_keepalive = args.mqtt_keepalive 450 | self.connect_timeout = args.mqtt_connect_timeout 451 | self.mqtt_topic = args.mqtt_topic 452 | self.mqtt_exclude_topic = args.mqtt_exclude_topic 453 | self.cafile = args.mqtt_cafile 454 | self.certfile = args.mqtt_certfile 455 | self.keyfile = args.mqtt_keyfile 456 | self.insecure = args.mqtt_insecure 457 | self.sql_timezone = args.sql_timezone 458 | self.write2sql_thread = None 459 | self.pool_sqlconnections = BoundedSemaphore(value=args.sql_max_connection) 460 | self.userdata = { 461 | 'haveresponse' : False, 462 | 'starttime' : time.time() 463 | } 464 | if self.mqtt_url is not None: 465 | self.get_mqtt_parts() 466 | self.verbose_print() 467 | self.mqttc, ret = self.mqtt_connect() 468 | if ret != ExitCode.OK: 469 | SignalHandler.exitus(ret, '{}:{} failed - [{}] {}'.format(self.mqtt_host, self.mqtt_port, ret, mqtt.error_string(ret))) 470 | 471 | def write2sql(self, message): 472 | """ 473 | Called as thread from mqtt backlog handler when a message has been 474 | received on a topic that the client subscribes to. 475 | 476 | @param message: 477 | an instance of MQTTMessage. 478 | This is a class with members topic, payload, qos, retain. 479 | """ 480 | def sql_execute_exception(retry_condition, error_str): 481 | """ 482 | handling local SQL exceptions 483 | 484 | @param retry_condition: 485 | condition for retry transaction 486 | if True delay process and return 487 | if False rollback transaction and return 488 | @param error_str: 489 | error string to output 490 | """ 491 | global SQLTYPES # pylint: disable=global-statement 492 | nonlocal db_connection, sql, transaction_retry 493 | 494 | typestr = SQLTYPES[self.args_.sql_type] 495 | 496 | transaction_delay = random() 497 | transaction_delay *= 2 498 | debuglog(1, "[{}]: {} transaction ERROR: {}, retry={}, delay={}".format(get_ident(), typestr, error_str, transaction_retry, transaction_delay)) 499 | if retry_condition: 500 | transaction_retry -= 1 501 | log(LogLevel.NOTICE, "SQL transaction WARNING: {} - try retry".format(error_str)) 502 | time.sleep(transaction_delay) 503 | else: 504 | log(LogLevel.NOTICE, "{} transaction ERROR {}".format(typestr, error_str)) 505 | log(LogLevel.ERROR, "{} give up: {}".format(typestr, sql)) 506 | # try rollback in case there is any error 507 | try: 508 | db_connection.rollback() 509 | transaction_retry = 0 510 | except Exception as err: # pylint: disable=broad-except 511 | pass 512 | 513 | # pylint: disable=global-statement 514 | global SQLTYPES 515 | # pylint: enable=global-statement 516 | 517 | if self.exit_code != ExitCode.OK: 518 | sys.exit(0) 519 | 520 | timestamp = datetime.datetime.now(tz=zoneinfo.ZoneInfo(self.args_.sql_timezone)).strftime("%Y-%m-%d %H:%M:%S") 521 | connection_retry = self.args_.sql_connection_retry 522 | connection_delay = self.args_.sql_connection_retry_start_delay 523 | connection_delay_base = self.args_.sql_connection_retry_start_delay 524 | debuglog(3, "SQL type is '{}'".format(SQLTYPES[self.args_.sql_type])) 525 | db_connection = None 526 | while connection_retry > 0: 527 | if self.exit_code != ExitCode.OK: 528 | sys.exit(0) 529 | try: 530 | if self.args_.sql_type == 'mysql': 531 | connection = {'db': self.args_.sql_db} 532 | if issocket(self.args_.sql_host): 533 | connection['unix_socket'] = self.args_.sql_host 534 | else: 535 | connection['host'] = self.args_.sql_host 536 | if self.args_.sql_port is not None: 537 | connection['port'] = self.args_.sql_port 538 | if self.args_.sql_username is not None: 539 | connection['user'] = self.args_.sql_username 540 | if self.args_.sql_password is not None: 541 | connection['passwd'] = self.args_.sql_password 542 | db_connection = MySQLdb.connect(**connection) 543 | 544 | elif self.args_.sql_type == 'sqlite': 545 | db_connection = sqlite3.connect(self.args_.sql_db) 546 | connection_retry = 0 547 | 548 | except Exception as err: # pylint: disable=broad-except 549 | connection_retry -= 1 550 | try: 551 | error_code = err.args[0] 552 | except: # pylint: disable=bare-except 553 | error_code = 0 554 | if error_code == 2005: 555 | connection_retry = 0 556 | debuglog(1, "[{}]: SQL connection ERROR: {}, retry={}, delay={}".format(get_ident(), SQLTYPES[self.args_.sql_type], connection_retry, connection_delay)) 557 | if connection_retry > 0: 558 | log(LogLevel.NOTICE, "SQL connection WARNING: {} - try retry".format(err)) 559 | time.sleep(connection_delay) 560 | connection_delay += connection_delay_base 561 | else: 562 | log(LogLevel.NOTICE, "SQL connection ERROR: {} - give up".format(err)) 563 | os.kill(os.getpid(), signal.SIGTERM) 564 | SignalHandler.exitus(ExitCode.SQL_CONNECTION_ERROR, "SQL connection ERROR: {} - give up".format(err)) 565 | 566 | transaction_retry = self.args_.sql_transaction_retry 567 | while transaction_retry > 0: 568 | if self.exit_code != ExitCode.OK: 569 | sys.exit(0) 570 | cursor = db_connection.cursor() 571 | try: 572 | # INSERT/UPDATE record 573 | if self.args_.sql_type == 'mysql': 574 | sql = "SET SESSION time_zone = '" + self.args_.sql_timezone + "'" 575 | debuglog(4, "SQL exec: '{}'".format(sql)) 576 | cursor.execute(sql) 577 | sql = "INSERT INTO `{0}` \ 578 | SET `ts`='{1}',`topic`='{2}',`value`=x'{3}',`qos`='{4}',`retain`='{5}' \ 579 | ON DUPLICATE KEY UPDATE `ts`='{1}',`value`=x'{3}',`qos`='{4}',`retain`='{5}'"\ 580 | .format( 581 | self.args_.sql_table, 582 | timestamp, 583 | message.topic, 584 | message.payload.hex(), 585 | message.qos, 586 | message.retain 587 | ) 588 | debuglog(4, "SQL exec: '{}'".format(sql)) 589 | cursor.execute(sql) 590 | elif self.args_.sql_type == 'sqlite': 591 | sql = "INSERT OR IGNORE INTO `{0}` \ 592 | (ts,topic,value,qos,retain) \ 593 | VALUES('{1}','{2}',x'{3}','{4}','{5}')"\ 594 | .format( 595 | self.args_.sql_table, 596 | timestamp, 597 | message.topic, 598 | message.payload.hex(), 599 | message.qos, 600 | message.retain 601 | ) 602 | debuglog(4, "SQL exec: '{}'".format(sql)) 603 | try: 604 | cursor.execute(sql) 605 | except sqlite3.OperationalError as err: 606 | self.exit_code = ExitCode.SQL_CONNECTION_ERROR 607 | sys.exit(self.exit_code) 608 | sql = "UPDATE `{0}` \ 609 | SET ts='{1}', \ 610 | value=x'{3}', \ 611 | qos='{4}', \ 612 | retain='{5}' \ 613 | WHERE topic='{2}'"\ 614 | .format( 615 | self.args_.sql_table, 616 | timestamp, 617 | message.topic, 618 | message.payload.hex(), 619 | message.qos, 620 | message.retain 621 | ) 622 | debuglog(4, "SQL exec: '{}'".format(sql)) 623 | try: 624 | cursor.execute(sql) 625 | except sqlite3.OperationalError as err: 626 | self.exit_code = ExitCode.SQL_CONNECTION_ERROR 627 | sys.exit(self.exit_code) 628 | 629 | db_connection.commit() 630 | debuglog(1, "[{}]: SQL success: table='{}', topic='{}', value='{}', qos='{}', retain='{}'".format(get_ident(), self.args_.sql_table, message.topic, message.payload, message.qos, message.retain)) 631 | transaction_retry = 0 632 | 633 | except MySQLdb.Error as err: # pylint: disable=no-member 634 | sql_execute_exception( 635 | err.args[0] in [1040, 1205, 1213], 636 | "[{}]: {}".format(err.args[0], err.args[1]) 637 | ) 638 | 639 | except sqlite3.Error as err: 640 | sql_execute_exception( 641 | "database is locked" in str(err).lower(), 642 | err 643 | ) 644 | 645 | finally: 646 | cursor.close() 647 | db_connection.close() 648 | self.pool_sqlconnections.release() 649 | return 650 | 651 | db_connection.close() 652 | self.pool_sqlconnections.release() 653 | 654 | def verbose_print(self): 655 | """ 656 | Verbose args 657 | """ 658 | log(LogLevel.INFORMATION, ' MQTT server: {}:{} {}{} keepalive {}'.format(self.mqtt_host, self.mqtt_port, 'SSL' if (self.cafile is not None) else '', ' (suppress TLS verification)' if self.insecure else '', self.mqtt_keepalive)) 659 | log(LogLevel.INFORMATION, ' user: {}'.format(self.mqtt_username)) 660 | log(LogLevel.INFORMATION, ' topics: {}'.format(self.mqtt_topic)) 661 | log(LogLevel.INFORMATION, ' exclude: {}'.format(self.mqtt_exclude_topic)) 662 | log(LogLevel.INFORMATION, ' SQL type: {}'.format(SQLTYPES[self.args_.sql_type])) 663 | if issocket(self.args_.sql_host): 664 | log(LogLevel.INFORMATION, ' server: {} [max {} connections]'.format(self.args_.sql_host, self.args_.sql_max_connection)) 665 | else: 666 | log(LogLevel.INFORMATION, ' server: {}:{} [max {} connections]'.format(self.args_.sql_host, self.args_.sql_port, self.args_.sql_max_connection)) 667 | log(LogLevel.INFORMATION, ' db: {}'.format(self.args_.sql_db)) 668 | log(LogLevel.INFORMATION, ' table: {}'.format(self.args_.sql_table)) 669 | log(LogLevel.INFORMATION, ' user: {}'.format(self.args_.sql_username)) 670 | log(LogLevel.INFORMATION, ' timezone: {}'.format(self.args_.sql_timezone)) 671 | if self.args_.logfile is not None: 672 | log(LogLevel.INFORMATION, ' Log file: {}'.format(self.args_.logfile)) 673 | if debug_level() > 0: 674 | log(LogLevel.INFORMATION, ' Debug level: {}'.format(debug_level())) 675 | log(LogLevel.INFORMATION, ' Verbose level: {}'.format(verbose_level())) 676 | 677 | def get_mqtt_parts(self): 678 | """ 679 | Get mqtt connection parameter parts from url/hostnme/ip and optional arguments 680 | """ 681 | try: 682 | URLPARSE = urllib.parse.urlparse(urllib.parse.quote(self.mqtt_url, safe='/:@')) 683 | if URLPARSE.netloc: 684 | if URLPARSE.scheme is not None: 685 | self.scheme = URLPARSE.scheme 686 | if self.mqtt_host is None and URLPARSE.hostname is not None: 687 | self.mqtt_host = urllib.parse.unquote(URLPARSE.hostname) 688 | if self.mqtt_port is None and URLPARSE.port is not None: 689 | self.mqtt_port = URLPARSE.port 690 | if self.mqtt_topic is None and URLPARSE.path is not None: 691 | self.mqtt_topic = urllib.parse.unquote(URLPARSE.path)[1:] 692 | if self.mqtt_username is None and URLPARSE.username is not None: 693 | self.mqtt_username = urllib.parse.unquote(URLPARSE.username) 694 | if self.mqtt_password is None and URLPARSE.password is not None: 695 | self.mqtt_password = urllib.parse.unquote(URLPARSE.password) 696 | except: # pylint: disable=bare-except 697 | pass 698 | # set defaults if not given 699 | if self.scheme is None: 700 | self.scheme = 'mqtt' 701 | if self.cafile is not None or self.certfile is not None or self.keyfile is not None: 702 | self.scheme += 's' 703 | if self.mqtt_host is None: 704 | self.mqtt_host = DEFAULTS['mqtt-host'] 705 | if self.mqtt_port is None: 706 | try: 707 | self.mqtt_port = DEFAULT_PORT_MQTTS if self.scheme[-1] == 's' else DEFAULT_PORT_MQTT 708 | except: # pylint: disable=bare-except 709 | self.mqtt_port = DEFAULT_PORT_MQTT 710 | if self.mqtt_topic is None: 711 | self.mqtt_topic = DEFAULTS['mqtt-topic'] 712 | if self.mqtt_exclude_topic is None: 713 | self.mqtt_exclude_topic = DEFAULTS['mqtt-exclude-topic'] 714 | if self.mqtt_username is None: 715 | self.mqtt_username = DEFAULTS['mqtt-username'] 716 | if self.mqtt_password is None: 717 | self.mqtt_password = DEFAULTS['mqtt-password'] 718 | # disable TLS/SSL if module not available 719 | if not MODULE_SSL_AVAIL and len(self.scheme) and self.scheme[-1] == 's': 720 | log(LogLevel.INFORMATION, "Missing python SSL module - MQTT scheme '{}' not possible, use mqtt instead".format(self.scheme)) 721 | self.scheme = 'mqtt' 722 | self.cafile = None 723 | self.certfile = None 724 | self.keyfile = None 725 | 726 | def wait_for_connect(self, connect_timeout): 727 | timeout = connect_timeout/10 728 | while not self.connected and timeout > 0: 729 | time.sleep(0.01) 730 | timeout = timeout -1 731 | 732 | debuglog(2, "MQTT wait_for_connect({}) returns {}".format(connect_timeout, 0 != timeout)) 733 | return 0 != timeout 734 | 735 | def on_connect(self, client, userdata, message, return_code): 736 | """ 737 | Called when the broker responds to our connection request. 738 | 739 | @param client: 740 | the client instance for this callback 741 | @param userdata: 742 | the private user data as set in Client() or userdata_set() 743 | @param message: 744 | response message sent by the broker 745 | @param return_code: 746 | the connection result 747 | """ 748 | debuglog(1, "MQTT on_connect({},{},{},{}): {}".format(client, userdata, message, return_code, mqtt.error_string(return_code))) 749 | self.connected = mqtt.MQTT_ERR_SUCCESS == return_code 750 | self.connect_rc = return_code 751 | if self.connected: 752 | if isinstance(self.mqtt_topic, (list, tuple)): 753 | for topic in self.mqtt_topic: 754 | debuglog(1, "subscribe to topic {}".format(topic)) 755 | client.subscribe(topic, 0) 756 | else: 757 | debuglog(1, "subscribe to topic {}".format(self.mqtt_topic)) 758 | client.subscribe(self.mqtt_topic, 0) 759 | 760 | def on_message(self, client, userdata, message): 761 | """ 762 | Called when a message has been received on a topic that the client subscribes to. 763 | This callback will be called for every message received. 764 | 765 | @param client: 766 | the client instance for this callback 767 | @param userdata: 768 | the private user data as set in Client() or userdata_set() 769 | @param message: 770 | an instance of MQTTMessage. 771 | This is a class with members topic, payload, qos, retain. 772 | """ 773 | if self.exit_code != ExitCode.OK: 774 | sys.exit(self.exit_code) 775 | log(LogLevel.NOTICE, '{} {} [QOS {} Retain {}]'.format(message.topic, message.payload, message.qos, message.retain)) 776 | 777 | debuglog(2, "on_message({},{},{})".format(client, userdata, message)) 778 | 779 | if self.exit_code == ExitCode.OK: 780 | if self.mqtt_exclude_topic is not None and message.topic in self.mqtt_exclude_topic: 781 | return 782 | self.pool_sqlconnections.acquire() 783 | self.write2sql_thread = Thread(target=self.write2sql, args=(message,)) 784 | self.write2sql_thread.start() 785 | 786 | def on_publish(self, client, userdata, mid): 787 | """ 788 | Called when a message that was to be sent using the publish() call 789 | has completed transmission to the broker. 790 | For messages with QoS levels 1 and 2, this means that the appropriate 791 | handshakes have completed. For QoS 0, this simply means that the 792 | message has left the client. The mid variable matches the mid 793 | variable returned from the corresponding publish() call, to allow 794 | outgoing messages to be tracked. 795 | 796 | @param client: 797 | the client instance for this callback 798 | @param userdata: 799 | the private user data as set in Client() or userdata_set() 800 | @param mid: 801 | matches the mid variable returned from the corresponding 802 | publish() call, to allow outgoing messages to be tracked. 803 | """ 804 | debuglog(2, "on_publish({},{},{})".format(client, userdata, mid)) 805 | 806 | def on_subscribe(self, client, userdata, mid, granted_qos): 807 | """ 808 | Called when the broker responds to a subscribe request. 809 | 810 | @param client: 811 | the client instance for this callback 812 | @param userdata: 813 | the private user data as set in Client() or userdata_set() 814 | @param mid: 815 | Matches the mid variable returned from the corresponding 816 | subscribe() call. 817 | @param granted_qos: 818 | a list of integers that give the QoS level the broker has 819 | granted for each of the different subscription requests. 820 | """ 821 | debuglog(2, "on_subscribe({},{},{},{})".format(client, userdata, mid, granted_qos)) 822 | 823 | def on_log(self, client, userdata, level, string): 824 | """ 825 | Called when the client has log information. 826 | 827 | @param client: 828 | the client instance for this callback 829 | @param userdata: 830 | the private user data as set in Client() or userdata_set() 831 | @param level: 832 | gives the severity of the message and will be one of 833 | MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, 834 | and MQTT_LOG_DEBUG. The message itself is in string. 835 | @param string: 836 | The message itself 837 | """ 838 | debuglog(2, "on_log({},{},{},{})".format(client, userdata, level, string)) 839 | 840 | def mqtt_connect(self): 841 | """ 842 | Create MQTT client and set callback handler 843 | 844 | @returns 845 | mqttc: MQTT client handle (or None on error) 846 | ret: Error code 847 | """ 848 | mqttc = mqtt.Client('{}-{:d}'.format(SCRIPTNAME, os.getpid()), clean_session=True, userdata=self.userdata, protocol=mqtt.MQTTv31) 849 | if debug_level() > 0: 850 | if debug_level() <= 2: 851 | logging.basicConfig(level=logging.WARNING) 852 | elif debug_level() <= 3: 853 | logging.basicConfig(level=logging.INFO) 854 | elif debug_level() >= 4: 855 | logging.basicConfig(level=logging.DEBUG) 856 | logger = logging.getLogger(__name__) 857 | mqttc.enable_logger(logger) 858 | mqttc.on_connect = self.on_connect 859 | mqttc.on_message = self.on_message 860 | mqttc.on_publish = self.on_publish 861 | mqttc.on_subscribe = self.on_subscribe 862 | if debug_level() > 0: 863 | mqttc.on_log = self.on_log 864 | 865 | # cafile controls TLS usage 866 | if self.cafile is not None or self.certfile is not None or self.keyfile is not None: 867 | mqttc.tls_set(ca_certs=self.cafile, 868 | certfile=self.certfile, 869 | keyfile=self.keyfile, 870 | cert_reqs=ssl.CERT_REQUIRED) 871 | mqttc.tls_insecure_set(self.insecure) 872 | 873 | # username & password may be None 874 | if self.mqtt_username is not None: 875 | mqttc.username_pw_set(self.mqtt_username, self.mqtt_password) 876 | 877 | debuglog(1, "mqttc.connect({}, {}, {})".format(self.mqtt_host, self.mqtt_port, self.mqtt_keepalive)) 878 | try: 879 | res = mqttc.connect(self.mqtt_host, self.mqtt_port, self.mqtt_keepalive) 880 | debuglog(1, "mqttc.connect() returns {}".format(res)) 881 | except Exception as err: # pylint: disable=broad-except,unused-variable 882 | return None, ExitCode.MQTT_CONNECTION_ERROR 883 | 884 | mqttc.loop_start() # Start loop to process on_connect() 885 | if not self.wait_for_connect(self.connect_timeout): 886 | return None, self.connect_rc 887 | mqttc.loop_stop() # Stop loop 888 | 889 | return mqttc, ExitCode.OK 890 | 891 | def loop_forever(self): 892 | """ 893 | Main MQTT to SQL loop 894 | does not return until an error occurs 895 | """ 896 | while True: 897 | # Main loop as long as no error occurs 898 | ret = mqtt.MQTT_ERR_SUCCESS 899 | while not self.userdata['haveresponse'] and ret == mqtt.MQTT_ERR_SUCCESS: 900 | try: 901 | ret = self.mqttc.loop() 902 | except Exception as err: # pylint: disable=broad-except 903 | log(LogLevel.ERROR, 'ERROR: loop() - {}'.format(err)) 904 | time.sleep(0.1) 905 | if self.exit_code != ExitCode.OK: 906 | sys.exit(self.exit_code) 907 | if ret == mqtt.MQTT_ERR_CONN_LOST: 908 | # disconnect from server 909 | log(LogLevel.NOTICE, 'Remote disconnected from MQTT - [{}] {})'.format(ret, mqtt.error_string(ret))) 910 | try: 911 | ret = self.mqttc.reconnect() 912 | log(LogLevel.NOTICE, 'MQTT reconnected - [{}] {}'.format(ret, mqtt.error_string(ret))) 913 | except Exception as err: # pylint: disable=broad-except 914 | SignalHandler.exitus(ExitCode.MQTT_CONNECTION_ERROR, '{}:{} failed - [{}] {}'.format(self.mqtt_host, self.mqtt_port, ret, mqtt.error_string(err))) 915 | else: 916 | SignalHandler.exitus(ExitCode.MQTT_CONNECTION_ERROR, '{}:{} failed: - [{}] {}'.format(self.mqtt_host, self.mqtt_port, ret, mqtt.error_string(ret))) 917 | 918 | class SignalHandler: 919 | """ 920 | Signal Handler Class 921 | """ 922 | def __init__(self): 923 | signal.signal(signal.SIGINT, self._exitus) 924 | signal.signal(signal.SIGTERM, self._exitus) 925 | 926 | def _signalname(self, signal_): 927 | signals_ = dict((k, v) for v, k in reversed(sorted(signal.__dict__.items())) if v.startswith('SIG') and not v.startswith('SIG_')) 928 | return signals_.get(signal_, 'UNKNOWN') 929 | 930 | def _exitus(self, signal_, frame_): # pylint: disable=unused-argument 931 | """ 932 | local exit with logging 933 | """ 934 | self.exitus(signal_, 'signal {}#{}'.format(self._signalname(signal_), signal_)) 935 | 936 | def exitus(self, status=0, message="end"): 937 | """ 938 | Called when the program should be exit 939 | 940 | @param status: 941 | the exit status program returns to callert 942 | @param message: 943 | the message logged before exit 944 | """ 945 | # pylint: disable=global-statement 946 | global SCRIPTNAME 947 | global SCRIPTPID 948 | global VER 949 | # pylint: enable=global-statement 950 | if message is not None: 951 | log(LogLevel.INFORMATION, message) 952 | log(LogLevel.INFORMATION, '{}[{}] v{} end'.format(SCRIPTNAME, SCRIPTPID, VER)) 953 | if status in (signal.SIGINT, signal.SIGTERM): 954 | status = 0 955 | sys.exit(status) 956 | 957 | if __name__ == "__main__": 958 | # set signal handler 959 | SIG = SignalHandler() 960 | 961 | # Parse command line arguments 962 | ARGS = parseargs() 963 | 964 | # Log program start 965 | log(LogLevel.INFORMATION, '{}[{}] v{} start'.format(SCRIPTNAME, SCRIPTPID, VER)) 966 | 967 | # Create class 968 | MQTT2SQL = Mqtt2Sql(ARGS) 969 | # run loop 970 | MQTT2SQL.loop_forever() 971 | -------------------------------------------------------------------------------- /mysql.sql: -------------------------------------------------------------------------------- 1 | /* 2 | mysql.sql - mqtt2sql MySQL database objects 3 | 4 | Copyright (C) 2020 Norbert Richter 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | Usage: 20 | See README.md for more details how to install and use 21 | https://github.com/curzon01/mqtt2sql#mqtt2sql 22 | */ 23 | 24 | 25 | /* Comment out or adapt the following lines if you want to use another 26 | * existing database and objects 27 | */ 28 | CREATE schema IF NOT EXISTS mqtt; 29 | USE mqtt; 30 | 31 | DROP TRIGGER IF EXISTS `mqtt_before_insert`; 32 | DROP TRIGGER IF EXISTS `mqtt_after_insert`; 33 | DROP TRIGGER IF EXISTS `mqtt_after_update`; 34 | DROP VIEW IF EXISTS `mqtt_history_view`; 35 | DROP TABLE IF EXISTS `mqtt_history`; 36 | DROP TABLE IF EXISTS `mqtt`; 37 | /* -------------------------------------------------------------------- */ 38 | 39 | 40 | /* Create database objects */ 41 | 42 | CREATE TABLE IF NOT EXISTS `mqtt` ( 43 | `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 44 | `ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 45 | `topic` TEXT NOT NULL, 46 | `value` LONGBLOB NOT NULL, 47 | `qos` TINYINT(3) UNSIGNED NOT NULL, 48 | `retain` TINYINT(3) UNSIGNED NOT NULL, 49 | `history_enable` TINYINT(4) NOT NULL DEFAULT 1, 50 | `history_diffonly` TINYINT(4) NOT NULL DEFAULT 1, 51 | PRIMARY KEY (`topic`(255)), 52 | UNIQUE INDEX `id` (`id`) 53 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 54 | 55 | CREATE TABLE IF NOT EXISTS `mqtt_history` ( 56 | `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 57 | `ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 58 | `topicid` INT(10) UNSIGNED NOT NULL, 59 | `value` LONGBLOB NULL DEFAULT NULL, 60 | PRIMARY KEY (`id`), 61 | INDEX `topicid` (`topicid`), 62 | INDEX `ts` (`ts`), 63 | CONSTRAINT `FK_mqtt_history_mqtt` FOREIGN KEY (`topicid`) REFERENCES `mqtt` (`id`) 64 | ) ENGINE=InnoDB ROW_FORMAT=COMPRESSED DEFAULT CHARSET=utf8; 65 | 66 | DELIMITER // 67 | CREATE TRIGGER IF NOT EXISTS `mqtt_before_insert` BEFORE INSERT ON `mqtt` FOR EACH ROW BEGIN 68 | DECLARE new_id INTEGER; 69 | 70 | SET new_id=(select max(id)+1 from mqtt); 71 | IF NEW.id != new_id THEN 72 | SET NEW.id = new_id; 73 | END IF; 74 | END// 75 | DELIMITER ; 76 | 77 | DELIMITER // 78 | CREATE TRIGGER IF NOT EXISTS `mqtt_after_insert` AFTER INSERT ON `mqtt` FOR EACH ROW BEGIN 79 | IF NEW.history_enable = 1 THEN 80 | INSERT INTO mqtt_history SET ts=NEW.ts, topicid=NEW.id, value=NEW.value; 81 | END IF; 82 | END// 83 | DELIMITER ; 84 | 85 | DELIMITER // 86 | CREATE TRIGGER IF NOT EXISTS `mqtt_after_update` AFTER UPDATE ON `mqtt` FOR EACH ROW BEGIN 87 | IF NEW.history_enable = 1 AND (NEW.history_diffonly = 0 OR (NEW.history_diffonly = 1 AND OLD.value != NEW.value)) THEN 88 | INSERT INTO mqtt_history SET ts=NEW.ts, topicid=NEW.id, value=NEW.value; 89 | END IF; 90 | END// 91 | DELIMITER ; 92 | 93 | 94 | CREATE OR REPLACE VIEW IF NOT EXISTS `mqtt_history_view` AS 95 | SELECT 96 | h.id, 97 | h.ts AS 'ts', 98 | m.ts AS 'ts_last', 99 | m.topic, 100 | h.value 101 | FROM mqtt_history h 102 | INNER JOIN mqtt m 103 | ON m.id = h.topicid; 104 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | configargparse 2 | mysqlclient 3 | paho-mqtt 4 | -------------------------------------------------------------------------------- /sqlite.sql: -------------------------------------------------------------------------------- 1 | /* 2 | sqlite.sql - mqtt2sql SQlite3 database objects 3 | 4 | Copyright (C) 2020 Norbert Richter 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | 19 | Usage: 20 | See README.md for more details how to install and use 21 | https://github.com/curzon01/mqtt2sql#mqtt2sql 22 | */ 23 | 24 | 25 | /* Comment out or adapt the following lines if you want to use another 26 | * existing database and objects 27 | */ 28 | DROP TRIGGER IF EXISTS `mqtt_after_insert`; 29 | DROP TRIGGER IF EXISTS `mqtt_after_update`; 30 | DROP VIEW IF EXISTS `mqtt_history_view`; 31 | DROP TABLE IF EXISTS `mqtt_history`; 32 | DROP TABLE IF EXISTS `mqtt`; 33 | /* -------------------------------------------------------------------- */ 34 | 35 | CREATE TABLE IF NOT EXISTS `mqtt` ( 36 | `id` INTEGER PRIMARY KEY AUTOINCREMENT, 37 | `ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 38 | `topic` TEXT NOT NULL, 39 | `value` LONGBLOB NOT NULL, 40 | `qos` INTEGER NOT NULL, 41 | `retain` INTEGER NOT NULL, 42 | `history_enable` INTEGER NOT NULL DEFAULT 1, 43 | `history_diffonly` INTEGER NOT NULL DEFAULT 1 44 | ); 45 | CREATE INDEX IF NOT EXISTS `mqtt_id` ON `mqtt` ( `id` ); 46 | CREATE UNIQUE INDEX IF NOT EXISTS `mqtt_topic` ON `mqtt` ( `topic` ); 47 | 48 | CREATE TABLE IF NOT EXISTS `mqtt_history` ( 49 | `id` INTEGER PRIMARY KEY AUTOINCREMENT, 50 | `ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 51 | `topicid` INTEGER UNSIGNED NOT NULL, 52 | `value` LONGBLOB NULL DEFAULT NULL 53 | ); 54 | CREATE INDEX IF NOT EXISTS `mqtt_history_topicid` ON `mqtt_history` ( `topicid` ); 55 | CREATE INDEX IF NOT EXISTS `mqtt_history_ts` ON `mqtt` ( `ts` ); 56 | 57 | 58 | CREATE TRIGGER IF NOT EXISTS `mqtt_after_insert` AFTER INSERT ON `mqtt` 59 | FOR EACH ROW 60 | WHEN NEW.history_enable 61 | BEGIN 62 | INSERT INTO mqtt_history (ts, topicid, value) VALUES(NEW.ts, NEW.id, NEW.value); 63 | END; 64 | 65 | CREATE TRIGGER IF NOT EXISTS `mqtt_after_update` AFTER UPDATE ON `mqtt` 66 | FOR EACH ROW 67 | WHEN NEW.history_enable AND (NEW.history_diffonly=0 OR (NEW.history_diffonly=1 AND OLD.value!=NEW.value)) 68 | BEGIN 69 | INSERT INTO mqtt_history (ts, topicid, value) VALUES(NEW.ts, NEW.id, NEW.value); 70 | END; 71 | 72 | 73 | CREATE VIEW IF NOT EXISTS `mqtt_history_view` AS 74 | SELECT 75 | h.id, 76 | h.ts AS 'ts', 77 | m.ts AS 'ts_last', 78 | m.topic, 79 | h.value 80 | FROM mqtt_history h 81 | INNER JOIN mqtt m 82 | ON m.id = h.topicid; 83 | --------------------------------------------------------------------------------