From 42bd3e809b0fa95d3a463462e242caf40d98bf79 Mon Sep 17 00:00:00 2001 From: Roman Bazalevsky Date: Thu, 26 Mar 2015 20:11:26 +0300 Subject: [PATCH] Old version cleaned --- LICENSE | 676 +++++++++++++++++++++++++++++++++ Weather_Station.ino | 197 ++++++++++ Weather_WH2.ino | 435 +++++++++++++++++++++ mysql/meteo_calendar.sql | 43 +++ mysql/meteo_error_log.sql | 40 ++ mysql/meteo_routines.sql | 131 +++++++ mysql/meteo_sensor_types.sql | 53 +++ mysql/meteo_sensor_values.sql | 49 +++ mysql/meteo_sensors.sql | 46 +++ mysql/meteo_sensors_ranges.sql | 48 +++ mysql/meteo_st_parameters.sql | 63 +++ mysql/meteo_unit_conv.sql | 55 +++ mysql/meteo_unit_groups.sql | 51 +++ mysql/meteo_units.sql | 55 +++ weathermon | 414 ++++++++++++++++++++ weathermon-light | 209 ++++++++++ weathermon.lua | 124 ++++++ weathermon.sh | 9 + weathermon.uci | 12 + web/archive.php | 290 ++++++++++++++ web/calendar.php | 87 +++++ web/config_local.php | 14 + web/favicon.png | Bin 0 -> 1536 bytes web/favicon.svg | 15 + web/graphs.php | 53 +++ web/image.php | 241 ++++++++++++ web/image_minmax.php | 241 ++++++++++++ web/index.php | 103 +++++ web/send.php | 42 ++ web/setup.php | 114 ++++++ web/units.php | 61 +++ 31 files changed, 3971 insertions(+) create mode 100644 LICENSE create mode 100644 Weather_Station.ino create mode 100644 Weather_WH2.ino create mode 100644 mysql/meteo_calendar.sql create mode 100644 mysql/meteo_error_log.sql create mode 100644 mysql/meteo_routines.sql create mode 100644 mysql/meteo_sensor_types.sql create mode 100644 mysql/meteo_sensor_values.sql create mode 100644 mysql/meteo_sensors.sql create mode 100644 mysql/meteo_sensors_ranges.sql create mode 100644 mysql/meteo_st_parameters.sql create mode 100644 mysql/meteo_unit_conv.sql create mode 100644 mysql/meteo_unit_groups.sql create mode 100644 mysql/meteo_units.sql create mode 100755 weathermon create mode 100755 weathermon-light create mode 100755 weathermon.lua create mode 100755 weathermon.sh create mode 100644 weathermon.uci create mode 100644 web/archive.php create mode 100644 web/calendar.php create mode 100644 web/config_local.php create mode 100644 web/favicon.png create mode 100644 web/favicon.svg create mode 100644 web/graphs.php create mode 100644 web/image.php create mode 100644 web/image_minmax.php create mode 100644 web/index.php create mode 100644 web/send.php create mode 100644 web/setup.php create mode 100644 web/units.php diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4432540 --- /dev/null +++ b/LICENSE @@ -0,0 +1,676 @@ + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/Weather_Station.ino b/Weather_Station.ino new file mode 100644 index 0000000..8ba7cee --- /dev/null +++ b/Weather_Station.ino @@ -0,0 +1,197 @@ +/* SFE_BMP180 library example sketch + +This sketch shows how to use the SFE_BMP180 library to read the +Bosch BMP180 barometric pressure sensor. +https://www.sparkfun.com/products/11824 + +Like most pressure sensors, the BMP180 measures absolute pressure. +This is the actual ambient pressure seen by the device, which will +vary with both altitude and weather. + +Before taking a pressure reading you must take a temparture reading. +This is done with startTemperature() and getTemperature(). +The result is in degrees C. + +Once you have a temperature reading, you can take a pressure reading. +This is done with startPressure() and getPressure(). +The result is in millibar (mb) aka hectopascals (hPa). + +If you'll be monitoring weather patterns, you will probably want to +remove the effects of altitude. This will produce readings that can +be compared to the published pressure readings from other locations. +To do this, use the sealevel() function. You will need to provide +the known altitude at which the pressure was measured. + +If you want to measure altitude, you will need to know the pressure +at a baseline altitude. This can be average sealevel pressure, or +a previous pressure reading at your altitude, in which case +subsequent altitude readings will be + or - the initial baseline. +This is done with the altitude() function. + +Hardware connections: + +- (GND) to GND ++ (VDD) to 3.3V + +(WARNING: do not connect + to 5V or the sensor will be damaged!) + +You will also need to connect the I2C pins (SCL and SDA) to your +Arduino. The pins are different on different Arduinos: + +Any Arduino pins labeled: SDA SCL +Uno, Redboard, Pro: A4 A5 +Mega2560, Due: 20 21 +Leonardo: 2 3 + +Leave the IO (VDDIO) pin unconnected. This pin is for connecting +the BMP180 to systems with lower logic levels such as 1.8V + +Have fun! -Your friends at SparkFun. + +The SFE_BMP180 library uses floating-point equations developed by the +Weather Station Data Logger project: http://wmrx00.sourceforge.net/ + +Our example code uses the "beerware" license. You can do anything +you like with this code. No really, anything. If you find it useful, +buy me a beer someday. + +V10 Mike Grusin, SparkFun Electronics 10/24/2013 +*/ + +// Your sketch must #include this library, and the Wire library. +// (Wire is a standard library included with Arduino.): + +#include +#include +#include "DHT.h" + +// You will need to create an SFE_BMP180 object, here called "pressure": + +SFE_BMP180 pressure; + +// DHT object for humidity sensor +DHT dht; +#define DHT_PIN 4 +#define GAS_PIN A0 +#define START_DELAY 20000 +#define DELAY 50000 + +byte HasBaro; + +void setup() +{ + delay(START_DELAY); + + Serial1.begin(57600); + Serial1.println("START"); + + // Initialize the sensor (it is important to get calibration values stored on the device). + + if (pressure.begin()) { + Serial1.println("BMP180 init success"); + HasBaro = 1; + } else { + Serial1.println("BMP180 init fail\n\n"); + HasBaro = 0; + } + + dht.setup(DHT_PIN); + +} + +void loop() +{ + char status; + double T,P; + double DHT_T,DHT_H; + int DHTStatus; + int Gas; + + double LastTemp; + byte GotTemperature,GotPressure; + + // Loop here getting pressure readings every 60 seconds. + + GotTemperature = 0; + GotPressure = 0; + + if (HasBaro) { + + status = pressure.startTemperature(); + if (status != 0) { + // Wait for the measurement to complete: + delay(status); + + // Retrieve the completed temperature measurement: + // Note that the measurement is stored in the variable T. + // Function returns 1 if successful, 0 if failure. + + status = pressure.getTemperature(T); + if (status = !0) { + LastTemp=T; + GotTemperature=1; + } else { + Serial1.println("ERROR:TYPE=BMP180,MESSAGE=FAILED MEASURE TEMPERATURE\n"); + } + } else { + Serial1.println("ERROR:TYPE=BMP180,MESSAGE=FAILED START TEMPERATURE MEASUREMENT\n"); + } + + // Start a pressure measurement: + // The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait). + // If request is successful, the number of ms to wait is returned. + // If request is unsuccessful, 0 is returned. + + status = pressure.startPressure(3); + if (status != 0) { + // Wait for the measurement to complete: + delay(status); + + // Retrieve the completed pressure measurement: + // Note that the measurement is stored in the variable P. + // Note also that the function requires the previous temperature measurement (T). + // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.) + // Function returns 1 if successful, 0 if failure. + + status = pressure.getPressure(P,LastTemp); + if (status != 0) { + // Print out the measurement: + GotPressure=1; + + } else { + Serial1.println("ERROR:TYPE=BMP180,MESSAGE=FAILED MEASURE PRESSURE\n"); + } + } else { + Serial1.println("ERROR:TYPE=BMP180,MESSAGE=FAILED START PRESSURE MEASUREMENT\n"); + } + if (GotPressure || GotTemperature) { + Serial1.print("SENSOR:TYPE=BMP180"); + if (GotPressure) { Serial1.print(",PRESSURE="); Serial1.print(P); } + if (GotTemperature) { Serial1.print(",TEMPERATURE="); Serial1.print(T); } + Serial1.println(); + } + } + + delay(dht.getMinimumSamplingPeriod()); + + DHT_H = dht.getHumidity(); + DHT_T = dht.getTemperature(); + + DHTStatus=dht.getStatus(); + + if (DHTStatus == 0) { + Serial1.print("SENSOR:TYPE=DHT22,TEMPERATURE="); + Serial1.print(DHT_T); + Serial1.print(",HUMIDITY="); + Serial1.println(DHT_H); + } else { + Serial1.println("ERROR:TYPE=DHT22,MESSAGE=MEASURING ERROR\n"); + } + + Gas = analogRead(GAS_PIN); + + Serial1.print("SENSOR:TYPE=MQ4,VALUE="); + Serial1.println(Gas); + + delay(DELAY); // Pause for 50 seconds. +} diff --git a/Weather_WH2.ino b/Weather_WH2.ino new file mode 100644 index 0000000..a61dbff --- /dev/null +++ b/Weather_WH2.ino @@ -0,0 +1,435 @@ +/* + Updated code for receiving data from WH2 weather station + This code implements timeouts to make decoding more robust + Decodes received packets and writes a summary of each packet to the Arduino's + serial port + Created by Luc Small on 19 July 2013. + Released into the public domain. +*/ + +#include +#include +#include + +// DHT11 and BMP085 wired sensors +dht DHT; +BMP085 bmp; + +// Humidity sensor at pin 4 +#define DHT11PIN 5 +int sensorPin = 0; +#define DEBUG + +// LED pins +#define REDPIN 11 +#define GREENPIN 12 + +// Read data from 433MHz receiver on digital pin 3 +#define RF_IN 4 +// For better efficiency, the port is read directly +// the following two lines should be changed appropriately +// if the line above is changed. +#define RF_IN_RAW PIND4 +#define RF_IN_PIN PIND + +// Port that is hooked to LED to indicate a packet has been received + +#define COUNTER_RATE 3200-1 // 16,000,000Hz / 3200 = 5000 interrupts per second, ie. 200us between interrupts +// 1 is indicated by 500uS pulse +// wh2_accept from 2 = 400us to 3 = 600us +#define IS_HI_PULSE(interval) (interval >= 2 && interval <= 3) +// 0 is indicated by ~1500us pulse +// wh2_accept from 7 = 1400us to 8 = 1600us +#define IS_LOW_PULSE(interval) (interval >= 7 && interval <= 8) +// worst case packet length +// 6 bytes x 8 bits x (1.5 + 1) = 120ms; 120ms = 200us x 600 +#define HAS_TIMED_OUT(interval) (interval > 600) +// we expect 1ms of idle time between pulses +// so if our pulse hasn't arrived by 1.2ms, reset the wh2_packet_state machine +// 6 x 200us = 1.2ms +#define IDLE_HAS_TIMED_OUT(interval) (interval > 6) +// our expected pulse should arrive after 1ms +// we'll wh2_accept it if it arrives after +// 4 x 200us = 800us +#define IDLE_PERIOD_DONE(interval) (interval >= 4) +// Shorthand for tests +//#define RF_HI (digitalRead(RF_IN) == HIGH) +//#define RF_LOW (digitalRead(RF_IN) == LOW) +#define RF_HI (bit_is_set(RF_IN_PIN, RF_IN_RAW)) +#define RF_LOW (bit_is_clear(RF_IN_PIN, RF_IN_RAW)) + +// wh2_flags +#define GOT_PULSE 0x01 +#define LOGIC_HI 0x02 +volatile byte wh2_flags = 0; +volatile byte wh2_packet_state = 0; +volatile int wh2_timeout = 0; +byte wh2_packet[5]; +byte wh2_calculated_crc; + + +#ifdef DEBUG +byte printed = 0; +#endif + +ISR(TIMER1_COMPA_vect) +{ + static byte sampling_state = 0; + static byte count; + static boolean was_low = false; + + switch(sampling_state) { + case 0: // waiting + wh2_packet_state = 0; + if (RF_HI) { + if (was_low) { + count = 0; + sampling_state = 1; + was_low = false; + } + } else { + was_low = true; + } + break; + case 1: // acquiring first pulse + count++; + // end of first pulse + if (RF_LOW) { + if (IS_HI_PULSE(count)) { + wh2_flags = GOT_PULSE | LOGIC_HI; + sampling_state = 2; + count = 0; + } else if (IS_LOW_PULSE(count)) { + wh2_flags = GOT_PULSE; // logic low + sampling_state = 2; + count = 0; + } else { + sampling_state = 0; + } + } + break; + case 2: // observe 1ms of idle time + count++; + if (RF_HI) { + if (IDLE_HAS_TIMED_OUT(count)) { + sampling_state = 0; + } else if (IDLE_PERIOD_DONE(count)) { + sampling_state = 1; + count = 0; + } + } + break; + } + + if (wh2_timeout > 0) { + wh2_timeout++; + if (HAS_TIMED_OUT(wh2_timeout)) { + wh2_packet_state = 0; + wh2_timeout = 0; +#ifdef DEBUG + if (printed) { + Serial1.println(); + printed=0; + } +#endif + } + } +} + +void setup() { + + Serial1.begin(115200); // Set the baud. + + // Wait for U-boot to finish startup. Consume all bytes until we are done. + do { + while (Serial1.available() > 0) { + Serial1.read(); + } + + delay(1000); + } while (Serial1.available()>0); + + Serial1.begin(57600); + Serial1.println(); + Serial1.println("STATUS:STARTING"); + + bmp.begin(); + + pinMode(REDPIN,OUTPUT); + pinMode(GREENPIN,OUTPUT); + + pinMode(RF_IN, INPUT); + digitalWrite(RF_IN,HIGH); + + TCCR1A = 0x00; + TCCR1B = 0x09; + TCCR1C = 0x00; + OCR1A = COUNTER_RATE; + TIMSK1 = 0x02; + + // enable interrupts + sei(); +} + +unsigned long previousMillis = 0; +unsigned long indoor_interval = 60000; +unsigned long outdoor_interval = 45000; +unsigned long previousIndoor = 0; +unsigned long previousOutdoor = 0; + +float temperature; +float pressure; + +void loop() { + unsigned long now; + int gas = 0; + byte i; + + now = millis(); + + if (wh2_flags) { + if (wh2_accept()) { + // calculate the CRC + wh2_calculate_crc(); + + if (wh2_valid()) { + + Serial1.println(); + Serial1.print("SENSOR:TYPE=OUTDOOR,"); + + Serial1.print("ID="); + Serial1.print(wh2_sensor_id(), HEX); + + Serial1.print(",HUMIDITY="); + Serial1.print(wh2_humidity(), DEC); + + Serial1.print(",TEMPERATURE="); + Serial1.println(format_temp(wh2_temperature())); + + previousOutdoor = now; + digitalWrite(REDPIN,HIGH); + + } else { + + Serial1.println(); + Serial1.println("ERROR:OUTDOOR"); + previousOutdoor = now; + digitalWrite(REDPIN,LOW); + + } + + } + wh2_flags = 0x00; + } + + if ((unsigned long)(now - previousMillis) >= indoor_interval) { + + previousMillis = now; + + int chk = DHT.read11(DHT11PIN); + + if (chk==0) { + + Serial1.println(); + Serial1.print("SENSOR:TYPE=INDOOR,"); + Serial1.print("HUMIDITY="); + Serial1.print(DHT.humidity); + Serial1.print(",TEMPERATURE="); + Serial1.print(DHT.temperature); + + previousIndoor = now; + digitalWrite(GREENPIN,HIGH); + + + } else { + + Serial1.println(); + Serial1.println("ERROR:INDOOR"); + previousIndoor = now; + digitalWrite(GREENPIN,LOW); + + } + + pressure=bmp.readPressure(); + temperature=bmp.readTemperature(); + Serial1.println(); + Serial1.print("SENSOR:TYPE=BARO,"); + Serial1.print("PRESSURE="); + Serial1.print(pressure); + Serial1.print(",TEMPERATURE="); + Serial1.println(temperature); + + gas = analogRead(sensorPin); // Получаем значения из датчика + Serial1.print("SENSOR:TYPE=GAS,VALUE="); + Serial1.println(gas); // Пишем в серийный порт + + } + + if ((unsigned long)(now - previousIndoor) > indoor_interval*10) { + + Serial1.println(); + Serial1.println("ERROR:INDOOR TIMEOUT"); + previousIndoor = now; + digitalWrite(GREENPIN,LOW); + + } + + if ((unsigned long)(now - previousOutdoor) > outdoor_interval*10) { + + Serial1.println(); + Serial1.println("ERROR:OUTDOOR TIMEOUT"); + previousOutdoor = now; + digitalWrite(REDPIN,LOW); + + } + + +} + + +// processes new pulse +boolean wh2_accept() +{ + static byte packet_no, bit_no, history; + + // reset if in initial wh2_packet_state + if(wh2_packet_state == 0) { + // should history be 0, does it matter? + history = 0xFF; + wh2_packet_state = 1; + // enable wh2_timeout + wh2_timeout = 1; + } // fall thru to wh2_packet_state one + + // acquire preamble + if (wh2_packet_state == 1) { + // shift history right and store new value + history <<= 1; + // store a 1 if required (right shift along will store a 0) + if (wh2_flags & LOGIC_HI) { + history |= 0x01; + } + // check if we have a valid start of frame + // xxxxx110 + if ((history & B00000111) == B00000110) { + // need to clear packet, and counters + packet_no = 0; + // start at 1 becuase only need to acquire 7 bits for first packet byte. + bit_no = 1; + wh2_packet[0] = wh2_packet[1] = wh2_packet[2] = wh2_packet[3] = wh2_packet[4] = 0; + // we've acquired the preamble + wh2_packet_state = 2; + } + return false; + } + // acquire packet + if (wh2_packet_state == 2) { + + wh2_packet[packet_no] <<= 1; + if (wh2_flags & LOGIC_HI) { + wh2_packet[packet_no] |= 0x01; +#ifdef DEBUG + Serial1.print('1'); + printed=1; + } else { + Serial1.print('0'); + printed=1; +#endif + } + + bit_no ++; + if(bit_no > 7) { + bit_no = 0; + packet_no ++; + } + + if (packet_no > 4) { + // start the sampling process from scratch + wh2_packet_state = 0; + // clear wh2_timeout + wh2_timeout = 0; + return true; + } + } + return false; +} + + +void wh2_calculate_crc() +{ + wh2_calculated_crc = crc8(wh2_packet, 4); +} + +bool wh2_valid() +{ + return (wh2_calculated_crc == wh2_packet[4]); +} + +int wh2_sensor_id() +{ + return (wh2_packet[0] << 4) + (wh2_packet[1] >> 4); +} + +byte wh2_humidity() +{ + return wh2_packet[3]; +} + +/* Temperature in deci-degrees. e.g. 251 = 25.1 */ +int wh2_temperature() +{ + int temperature; + temperature = ((wh2_packet[1] & B00000111) << 8) + wh2_packet[2]; + // make negative + if (wh2_packet[1] & B00001000) { + temperature = -temperature; + } + return temperature; +} + +String format_temp(int temperature) +{ + byte whole, partial; + String s; + s = String(); + if (temperature<0) { + temperature = -temperature; + s += String('-'); + } + + whole = temperature / 10; + partial = temperature - (whole*10); + + s += String(whole, DEC); + s += '.'; + s += String(partial, DEC); + + return s; + +} + +uint8_t crc8( uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + // Indicated changes are from reference CRC-8 function in OneWire library + while (len--) { + uint8_t inbyte = *addr++; + for (uint8_t i = 8; i; i--) { + uint8_t mix = (crc ^ inbyte) & 0x80; // changed from & 0x01 + crc <<= 1; // changed from right shift + if (mix) crc ^= 0x31;// changed from 0x8C; + inbyte <<= 1; // changed from right shift + } + } + return crc; +} + + + + + + + + + diff --git a/mysql/meteo_calendar.sql b/mysql/meteo_calendar.sql new file mode 100644 index 0000000..2835877 --- /dev/null +++ b/mysql/meteo_calendar.sql @@ -0,0 +1,43 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `calendar` +-- + +DROP TABLE IF EXISTS `calendar`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `calendar` ( + `day` date NOT NULL, + `sensor` int(11) NOT NULL, + PRIMARY KEY (`day`,`sensor`), + KEY `SENSOR` (`sensor`), + CONSTRAINT `fk_calendar_sensor` FOREIGN KEY (`sensor`) REFERENCES `sensors` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:49:31 diff --git a/mysql/meteo_error_log.sql b/mysql/meteo_error_log.sql new file mode 100644 index 0000000..7d3d91c --- /dev/null +++ b/mysql/meteo_error_log.sql @@ -0,0 +1,40 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `error_log` +-- + +DROP TABLE IF EXISTS `error_log`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `error_log` ( + `timestamp` datetime DEFAULT NULL, + `text` varchar(2000) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:49:45 diff --git a/mysql/meteo_routines.sql b/mysql/meteo_routines.sql new file mode 100644 index 0000000..bf72780 --- /dev/null +++ b/mysql/meteo_routines.sql @@ -0,0 +1,131 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping routines for database 'meteo' +-- +/*!50003 DROP FUNCTION IF EXISTS `unitconv` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +CREATE DEFINER=`admin`@`%` FUNCTION `unitconv`(pValue float, pFromUnit integer, pToUnit integer) RETURNS float +BEGIN + declare result float; + declare a,b,c float; + if pFromUnit=pToUnit then + set result = pValue; + else + select u.a,u.b,u.c into a,b,c from unit_conv u where from_unit=pFromUnit and to_unit=pToUnit; + set result=b; + set result = (pValue+a)*b+c; + end if; + return result; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `submit_value` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = '' */ ; +DELIMITER ;; +CREATE DEFINER=`admin`@`%` PROCEDURE `submit_value`(pSType varchar(32),pSID varchar(32),pParam varchar(32),pValue float,pTimestamp datetime) +BEGIN + declare lSTID int; + declare lSID int; + declare lSTPID int; + declare lTime DATETIME; + declare lDay DATE; + declare lCnt integer; + select max(id) into lSTID from sensor_types where st_name=pSType; + if lSTID is not null then + select max(id) into lSID from sensors where st_id=lSTID and s_id=pSID; + if lSID is not null then + select max(id) into lSTPID from st_parameters where st_id=lSTID and st_name=pParam; + if lSTPID is not null then + + if lSTPID>=0 then + + if pTimestamp is null then + set lTime:=current_timestamp(); + else + set lTime:=pTimestamp; + end if; + + insert into sensor_values(sensor_id,parameter_id,timestamp,value) + values(lSID,lSTPID,lTime,pValue); + + set lDay:=DATE(lTime); + select count(*) into lCnt from calendar where sensor=lSID and day=lDay; + if lCnt=0 then + insert into calendar(day,sensor) values(lDay,lSID); + end if; + + select count(*) into lCnt from sensors_ranges where sensor=lSID and day=lDay and parameter=lSTPID; + if lCnt=0 then + insert into sensors_ranges(day,sensor,parameter,min,max) values (lDay,lSID,lSTPID,pValue,pValue); + else + update sensors_ranges + set + min=LEAST(min,pValue), + max=GREATEST(max,pValue) + where + day=lDay and sensor=lSID and parameter=lSTPID; + end if; + end if; + else + insert into error_log(timestamp,text) + values (current_timestamp(),CONCAT("Failed to submit ",pSType,",",pSID,",",pParam,",",pValue)); + end if; + else + insert into error_log(timestamp,text) + values (current_timestamp(),CONCAT("Failed to submit ",pSType,",",pSID,",",pParam,",",pValue)); + end if; + else + insert into error_log(timestamp,text) + values (current_timestamp(),CONCAT("Failed to submit ",pSType,",",pSID,",",pParam,",",pValue)); + end if; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:45:45 diff --git a/mysql/meteo_sensor_types.sql b/mysql/meteo_sensor_types.sql new file mode 100644 index 0000000..c543750 --- /dev/null +++ b/mysql/meteo_sensor_types.sql @@ -0,0 +1,53 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `sensor_types` +-- + +DROP TABLE IF EXISTS `sensor_types`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sensor_types` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `st_name` varchar(32) CHARACTER SET utf8 NOT NULL, + `st_description` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `st_name` (`st_name`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `sensor_types` +-- + +LOCK TABLES `sensor_types` WRITE; +/*!40000 ALTER TABLE `sensor_types` DISABLE KEYS */; +INSERT INTO `sensor_types` VALUES (1,'INDOOR','Внутренний датчик влажности'),(2,'OUTDOOR','Внешний датчик температуры и влажности'),(3,'BARO','Внутренний датчик давления и температуры'); +/*!40000 ALTER TABLE `sensor_types` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:46:53 diff --git a/mysql/meteo_sensor_values.sql b/mysql/meteo_sensor_values.sql new file mode 100644 index 0000000..b954d11 --- /dev/null +++ b/mysql/meteo_sensor_values.sql @@ -0,0 +1,49 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `sensor_values` +-- + +DROP TABLE IF EXISTS `sensor_values`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sensor_values` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `sensor_id` int(11) NOT NULL, + `timestamp` datetime NOT NULL, + `value` float NOT NULL, + `parameter_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `fk_sensor_values_sens_idx` (`sensor_id`), + KEY `sensor_values_idx` (`sensor_id`,`timestamp`), + KEY `fk_sensor_values_param_idx` (`parameter_id`), + CONSTRAINT `fk_sensor_values_param` FOREIGN KEY (`parameter_id`) REFERENCES `st_parameters` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_sensor_values_sens` FOREIGN KEY (`sensor_id`) REFERENCES `sensors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=1163082 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:47:29 diff --git a/mysql/meteo_sensors.sql b/mysql/meteo_sensors.sql new file mode 100644 index 0000000..17441ae --- /dev/null +++ b/mysql/meteo_sensors.sql @@ -0,0 +1,46 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `sensors` +-- + +DROP TABLE IF EXISTS `sensors`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sensors` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `st_id` int(11) NOT NULL, + `s_id` varchar(32) CHARACTER SET utf8 NOT NULL, + `s_description` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UNIQUE` (`st_id`,`s_id`), + KEY `fk_sensors_st_idx` (`st_id`), + CONSTRAINT `fk_sensors_st` FOREIGN KEY (`st_id`) REFERENCES `sensor_types` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:47:17 diff --git a/mysql/meteo_sensors_ranges.sql b/mysql/meteo_sensors_ranges.sql new file mode 100644 index 0000000..6516ad3 --- /dev/null +++ b/mysql/meteo_sensors_ranges.sql @@ -0,0 +1,48 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `sensors_ranges` +-- + +DROP TABLE IF EXISTS `sensors_ranges`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sensors_ranges` ( + `sensor` int(11) NOT NULL, + `day` date NOT NULL, + `min` float NOT NULL, + `max` float NOT NULL, + `parameter` int(11) NOT NULL, + PRIMARY KEY (`day`,`sensor`,`parameter`), + KEY `fk_sensors_ranges_sensors_idx` (`sensor`), + KEY `fk_sensors_ranges_parameters_idx` (`parameter`), + CONSTRAINT `fk_sensors_ranges_parameters` FOREIGN KEY (`parameter`) REFERENCES `st_parameters` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_sensors_ranges_sensors` FOREIGN KEY (`sensor`) REFERENCES `sensors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:47:44 diff --git a/mysql/meteo_st_parameters.sql b/mysql/meteo_st_parameters.sql new file mode 100644 index 0000000..5bcede1 --- /dev/null +++ b/mysql/meteo_st_parameters.sql @@ -0,0 +1,63 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `st_parameters` +-- + +DROP TABLE IF EXISTS `st_parameters`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `st_parameters` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `st_id` int(11) NOT NULL, + `st_name` varchar(32) CHARACTER SET utf8 NOT NULL, + `st_unit` int(11) NOT NULL, + `st_description` varchar(255) CHARACTER SET utf8 DEFAULT NULL, + `st_dot_color` varchar(45) DEFAULT 'red', + `st_fill_color_top` varchar(45) DEFAULT 'red', + `st_fill_color_bottom` varchar(45) DEFAULT 'blue', + `st_line_color` varchar(45) DEFAULT 'navy', + PRIMARY KEY (`id`), + UNIQUE KEY `unique` (`st_id`,`st_name`), + KEY `fk_st_parameters_st_idx` (`st_id`), + KEY `fk_st_parameters_units_idx` (`st_unit`), + CONSTRAINT `fk_st_parameters_st` FOREIGN KEY (`st_id`) REFERENCES `sensor_types` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT `fk_st_parameters_units` FOREIGN KEY (`st_unit`) REFERENCES `units` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `st_parameters` +-- + +LOCK TABLES `st_parameters` WRITE; +/*!40000 ALTER TABLE `st_parameters` DISABLE KEYS */; +INSERT INTO `st_parameters` VALUES (-1,1,'TEMPERATURE',1,'Температура','red','red','navy','red'),(1,3,'TEMPERATURE',1,'Температура','red','red','navy','darkred'),(2,1,'HUMIDITY',2,'Влажность','skyblue','skyblue','blue','royalblue'),(3,2,'TEMPERATURE',1,'Температура','red','red','navy','darkred'),(4,2,'HUMIDITY',2,'Влажность','skyblue','skyblue','blue','royalblue'),(5,3,'PRESSURE',3,'Атмосферное давление','green','green','gold','gold'); +/*!40000 ALTER TABLE `st_parameters` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:48:08 diff --git a/mysql/meteo_unit_conv.sql b/mysql/meteo_unit_conv.sql new file mode 100644 index 0000000..4ac573a --- /dev/null +++ b/mysql/meteo_unit_conv.sql @@ -0,0 +1,55 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `unit_conv` +-- + +DROP TABLE IF EXISTS `unit_conv`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `unit_conv` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `from_unit` int(11) NOT NULL, + `to_unit` int(11) NOT NULL, + `a` float NOT NULL, + `b` float NOT NULL, + `c` float NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `unit_conv` +-- + +LOCK TABLES `unit_conv` WRITE; +/*!40000 ALTER TABLE `unit_conv` DISABLE KEYS */; +INSERT INTO `unit_conv` VALUES (1,1,4,0,1.4,32),(2,4,1,-32,0.5555,0),(3,3,5,0,0.0075,0),(4,5,3,0,133.322,0),(5,3,6,0,0.01,0),(6,6,3,0,100,0),(7,3,7,0,0.0002953,0),(8,7,3,0,3386,0),(9,5,6,0,1.3332,0),(10,6,5,0,0.75,0),(11,5,7,0,0.03937,0),(12,7,5,0,25.4,0),(13,6,7,0,0.02952,0),(14,7,6,0,33.86,0); +/*!40000 ALTER TABLE `unit_conv` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:49:01 diff --git a/mysql/meteo_unit_groups.sql b/mysql/meteo_unit_groups.sql new file mode 100644 index 0000000..2a0d7f6 --- /dev/null +++ b/mysql/meteo_unit_groups.sql @@ -0,0 +1,51 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `unit_groups` +-- + +DROP TABLE IF EXISTS `unit_groups`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `unit_groups` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(45) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `unit_groups` +-- + +LOCK TABLES `unit_groups` WRITE; +/*!40000 ALTER TABLE `unit_groups` DISABLE KEYS */; +INSERT INTO `unit_groups` VALUES (1,'Температура'),(2,'Влажность'),(3,'Давление'); +/*!40000 ALTER TABLE `unit_groups` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:48:40 diff --git a/mysql/meteo_units.sql b/mysql/meteo_units.sql new file mode 100644 index 0000000..110b39d --- /dev/null +++ b/mysql/meteo_units.sql @@ -0,0 +1,55 @@ +-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (x86_64) +-- +-- Host: localhost Database: meteo +-- ------------------------------------------------------ +-- Server version 5.5.38-0ubuntu0.14.04.1 + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `units` +-- + +DROP TABLE IF EXISTS `units`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `units` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(32) CHARACTER SET utf8 NOT NULL, + `name_short` varchar(8) CHARACTER SET utf8 NOT NULL, + `unit_group` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `fk_units_group_idx` (`unit_group`), + CONSTRAINT `fk_units_group` FOREIGN KEY (`unit_group`) REFERENCES `unit_groups` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `units` +-- + +LOCK TABLES `units` WRITE; +/*!40000 ALTER TABLE `units` DISABLE KEYS */; +INSERT INTO `units` VALUES (1,'Градусы Цельсия','C',1),(2,'Проценты','%',2),(3,'Паскали','Па',3),(4,'Градусы Фаренгейта','F',1),(5,'Миллиметры ртутного столба','мм',3),(6,'Миллибары','мбар',3),(7,'Дюймы ртутного столба','inHg',3); +/*!40000 ALTER TABLE `units` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2014-09-25 14:48:27 diff --git a/weathermon b/weathermon new file mode 100755 index 0000000..68798a1 --- /dev/null +++ b/weathermon @@ -0,0 +1,414 @@ +#!/usr/bin/python + +import serial + +from os import listdir,system +from os.path import isfile, join + +from pprint import pprint + +from termios import tcflush, TCIOFLUSH + +from time import sleep,time + +from uuid import getnode + +from hashlib import md5 + +import socket + +import sys,traceback + +import pycurl +from urllib import urlencode +from StringIO import StringIO + +searchpath = '/dev/serial/by-id/' +path = None +baud = None +timeout = None + +proc = None + +external_submit_interval = 320 +owm_submit_interval = 320 +expire_interval = 1200 +submit_time = time() +submit_time_owm = time() + +import MySQLdb +import ConfigParser + +import thread +from threading import Timer + +def find_port(): + + global serial_num + global path + + files = listdir(searchpath) + for f in files: + if serialnum in f: + return join(searchpath,f) + return None + +def open_port(path): + + global proc + + print "Opening path "+path + + if path == "-": + return sys.stdin + + if path[0] == "=": + import subprocess + command=path[1:] + try: + command,args=command.split(' ',1) + proc = subprocess.Popen([command,args],stdout=subprocess.PIPE) + except: + proc = subprocess.Popen([command],stdout=subprocess.PIPE) + import subprocess + return proc.stdout + + ser = serial.Serial(path,baud,timeout=timeout) + if ser.portstr: + tcflush(ser,TCIOFLUSH); + return ser + +def read_port(ser): + + try: + timeout_timer = Timer(timeout, thread.interrupt_main) + timeout_timer.start() + line = ser.readline() + return line.strip() + except KeyboardInterrupt: + return "<>" + finally: + timeout_timer.cancel() + +def read_loop(ser,callback): + + global proc + + while True: + + try: + line=read_port(ser) + if line=="<>": + print "Reopening port..." + ser.close() + if proc: + print "Terminating process..." + proc.terminate() + sleep(5) + ser=open_port(path) + if line: + callback(line) + except KeyboardInterrupt: + break + finally: + None + +def print_log(str): + global logging + print str + if logging == "on": + system("logger -t weathermon \""+str+"\"") + +def submit_narodmon(): + + param = { 'ID':devid } + + c = database.cursor() + c.execute( + ''' + select nm_id,value from + ( + SELECT sensor_id,parameter_id,max(timestamp) timestamp,round(avg(value),1) value FROM meteo.sensor_values + where + timestamp>=date_add(now(), INTERVAL -300 SECOND) + group by sensor_id,parameter_id + ) v,meteo.ext_sensors e + where v.sensor_id=e.sensor_id and v.parameter_id=e.param_id + and nm_id is not null + ''' + ) + + queue=c.fetchall() + + pprint(queue) + + for (sensor,value) in queue: + param[sensor] = value + pprint (param) + + url = "http://narodmon.ru/post.php" + + try: + + response_buffer = StringIO() + curl = pycurl.Curl() + + curl.setopt(curl.URL, url) + curl.setopt(curl.WRITEFUNCTION, response_buffer.write) + curl.setopt(curl.POST, 1) + curl.setopt(curl.POSTFIELDS, urlencode(param)) + + curl.perform() + curl.close() + + response_value = response_buffer.getvalue() + + print_log('Narodmon response: '+response_value) + + return True + + except: + + exc_type, exc_value, exc_traceback = sys.exc_info() + traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) + traceback.print_exception(exc_type, exc_value, exc_traceback, + limit=2, file=sys.stdout) + return False + +def submit_owm(): + + url = "http://openweathermap.org/data/post" + params = {'name':owm_station, 'lat':owm_lat, 'long':owm_lon} + + c = database.cursor() + c.execute( + ''' + select owm_id,value from + ( + SELECT sensor_id,parameter_id,max(timestamp) timestamp,round(avg(value),1) value FROM meteo.sensor_values + where + timestamp>=date_add(now(), INTERVAL -300 SECOND) + group by sensor_id,parameter_id + ) v,meteo.ext_sensors e + where v.sensor_id=e.sensor_id and v.parameter_id=e.param_id + and owm_id is not null + ''' + ) + + queue=c.fetchall() + + pprint(queue) + + for (sensor,value) in queue: + params[sensor]=value + pprint (params) + + try: + + response_buffer = StringIO() + curl = pycurl.Curl() + + curl.setopt(curl.URL, url) + curl.setopt(curl.USERPWD, '%s:%s' % (owmuser, owmpasswd)) + curl.setopt(curl.WRITEFUNCTION, response_buffer.write) + curl.setopt(curl.POST, 1) + curl.setopt(curl.POSTFIELDS, urlencode(params)) + + curl.perform() + curl.close() + + response_value = response_buffer.getvalue() + + print_log('Openweathermap response: '+response_value) + + return True + + except: + + exc_type, exc_value, exc_traceback = sys.exc_info() + traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) + traceback.print_exception(exc_type, exc_value, exc_traceback, + limit=2, file=sys.stdout) + return False + +def submit_data(sensor_type,sensor_id,sensor_param,param_value): + global submit_time + global submit_time_owm + global external_submit_interval + global owm_submit_interval + c = database.cursor() + c.execute('CALL meteo.submit_value(%s,%s,%s,%s,NULL)', (sensor_type,sensor_id,sensor_param,param_value)) + database.commit() + if narmon=='on' and time()>submit_time+external_submit_interval: + submit_narodmon() + submit_time=time() + if owmuser and time()>submit_time_owm+owm_submit_interval: + submit_owm() + submit_time_owm=time() + +def process_str(str): + print_log("Received: "+str) + try: + msg_type, msg_body = str.split(':') + except: + return + try: + if msg_type == 'STATUS': + print_log('Status: '+msg_body) + elif msg_type == 'ERROR': + print_log('Error: '+ msg_body) + elif msg_type == 'SENSOR': + sens = msg_body.split(',') + sensor = {} + sensor_type = None + sensor_id = None + for rec in sens: + key,value = rec.split('=') + value=value.strip() + if len(value)>0: + if key == 'TYPE': + sensor_type = value + elif key == 'ID': + sensor_id = value + else: + sensor[key] = value + if sensor_type: + if not sensor_id: + sensor_id=devid; + for key in sensor: + if sensor[key]: + print_log('Type = '+sensor_type+', ID = '+sensor_id+', Param = '+key+', Value = '+sensor[key]) + submit_data(sensor_type,sensor_id,key,sensor[key]) + else: + print_log('Error: got empty parameter value for '+sensor_type+'.'+sensor_id+'.'+key) + elif msg_type == "ALARM": + alarm = msg_body.split(',') + device_type = None + device_id = None + for rec in alarm: + key,value = rec.split('=') + value=value.strip() + if len(value)>0: + if key == 'TYPE': + device_type = value + if key == 'ID': + device_id = value + if device_type: + if not device_id: + device_id=devid; + print_log("Alarm: Type = "+device_type+", ID = "+device_id) + if alarm_script: + try: + proc = subprocess.Popen([alarm_script,device_type,device_id,msg_body]) + except: + print_log("Failed to execute alarm script") + except: + print_log('Exception processing...') + exc_type, exc_value, exc_traceback = sys.exc_info() + traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) + traceback.print_exception(exc_type, exc_value, exc_traceback, + limit=5, file=sys.stdout) + try: + database.close() + except: + None + reconnect() + +def weather_mon(): + + global path + + if path is None: + path = find_port() + ser = open_port(path) + read_loop(ser,process_str) + +def reconnect(): + + connected = False + + while not connected: + + try: + + global database + database = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpasswd,use_unicode=True,connect_timeout=10) + database.set_character_set('utf8') + c = database.cursor() + c.execute('SET NAMES utf8;') + print_log("Database connected...") + connected = True + + except: + + print_log("Error connecting database") + sleep(30) + +def main(): + weather_mon() + +try: + + cfg = ConfigParser.RawConfigParser(allow_no_value=True) + cfg.readfp(open('/etc/weathermon.conf')) + dbhost = cfg.get("mysql","host") + dbuser = cfg.get("mysql","user") + dbpasswd = cfg.get("mysql","passwd") + try: + path = cfg.get("serial","port"); + except: + path = None + try: + serialnum = cfg.get("serial","id") + except: + serialnum = None + try: + logging = cfg.get("logging","enabled") + except: + logging = None + try: + timeout = int(cfg.get("serial","timeout")) + except: + timeout = 120 + try: + baud = int(cfg.get("serial","baud")) + except: + baud = 57600 + try: + narmon = cfg.get("narodmon","enable") + except: + narmon = 'off' + try: + devid = cfg.get("narodmon","devid") + except: + devid = "{:0>12X}".format(getnode()) + try: + owmuser = cfg.get("openweathermap","user") + owmpasswd = cfg.get("openweathermap",'passwd') + except: + owmuser = None + if owmuser: + owm_temp = cfg.get("openweathermap",'temp') + owm_pres = cfg.get("openweathermap",'pres') + owm_humi = cfg.get("openweathermap",'humi') + owm_lat = cfg.get("openweathermap",'lat') + owm_lon = cfg.get("openweathermap",'lon') + owm_station = cfg.get("openweathermap",'station') + try: + alarm_script = cfg.get("alarm","exec") + import subprocess + except: + alarm_script = None + + reconnect() + +except: + + print_log("Cannot intialize system") + exit() + +if __name__ == "__main__": + import sys + reload(sys) + sys.setdefaultencoding('utf-8') + main() diff --git a/weathermon-light b/weathermon-light new file mode 100755 index 0000000..1827377 --- /dev/null +++ b/weathermon-light @@ -0,0 +1,209 @@ +#!/usr/bin/python + +import serial + +from os import system + +from pprint import pprint + +from termios import tcflush, TCIOFLUSH + +from time import sleep + +from uuid import getnode + +import sys,traceback + +import pycurl +from urllib import urlencode +from StringIO import StringIO + +path = None +baud = None +timeout = None + +import ConfigParser + +import thread +from threading import Timer + +def open_port(path): + + global proc + + print "Opening path "+path + + ser = serial.Serial(path,1200); + ser.open(); + ser.close(); + + ser = serial.Serial(path,baud,timeout=timeout) + if ser.portstr: + tcflush(ser,TCIOFLUSH); + return ser + +def read_port(ser): + + try: + timeout_timer = Timer(timeout, thread.interrupt_main) + timeout_timer.start() + line = ser.readline() + return line.strip() + except KeyboardInterrupt: + return "<>" + finally: + timeout_timer.cancel() + +def read_loop(ser,callback): + + global proc + + while True: + + try: + line=read_port(ser) + if line=="<>": + print "Reopening port..." + ser.close() + ser=open_port(path) + if line: + callback(line) + except KeyboardInterrupt: + break + finally: + None + +def print_log(str): + global logging + print str + if logging == "on": + system("logger -t weathermon \""+str+"\"") + +def submit_data(stype,sid,param,value): + + global url,username,password + + params = {'stype':stype, 'sid':sid, 'param':param, 'value':value} + + pprint (params) + + try: + + response_buffer = StringIO() + curl = pycurl.Curl() + + curl.setopt(curl.URL, url) + if username: + curl.setopt(curl.USERPWD, '%s:%s' % (username, password)) + curl.setopt(curl.WRITEFUNCTION, response_buffer.write) + curl.setopt(curl.POST, 1) + curl.setopt(curl.POSTFIELDS, urlencode(params)) + + curl.perform() + curl.close() + + response_value = response_buffer.getvalue() + + print_log('Server response: '+response_value) + + return True + + except: + + exc_type, exc_value, exc_traceback = sys.exc_info() + traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) + traceback.print_exception(exc_type, exc_value, exc_traceback, + limit=2, file=sys.stdout) + return False + +def process_str(str): + print_log("Received: "+str) + try: + msg_type, msg_body = str.split(':') + except: + return + try: + if msg_type == 'STATUS': + print_log('Status: '+msg_body) + elif msg_type == 'ERROR': + print_log('Error: '+ msg_body) + elif msg_type == 'SENSOR': + sens = msg_body.split(',') + sensor = {} + sensor_type = None + sensor_id = None + for rec in sens: + key,value = rec.split('=') + value=value.strip() + if len(value)>0: + if key == 'TYPE': + sensor_type = value + elif key == 'ID': + sensor_id = value + else: + sensor[key] = value + if sensor_type: + if not sensor_id: + sensor_id=devid; + for key in sensor: + if sensor[key]: + print_log('Type = '+sensor_type+', ID = '+sensor_id+', Param = '+key+', Value = '+sensor[key]) + submit_data(sensor_type,sensor_id,key,sensor[key]) + else: + print_log('Error: got empty parameter value for '+sensor_type+'.'+sensor_id+'.'+key) + except: + print_log('Exception processing...') + exc_type, exc_value, exc_traceback = sys.exc_info() + traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) + traceback.print_exception(exc_type, exc_value, exc_traceback, + limit=5, file=sys.stdout) + +def weather_mon(): + + global path + + ser = open_port(path) + read_loop(ser,process_str) + +def main(): + weather_mon() + +try: + + cfg = ConfigParser.RawConfigParser(allow_no_value=True) + cfg.readfp(open('/etc/weathermon.conf')) + url = cfg.get("web","url") + path = cfg.get("serial","port"); + try: + username = cfg.get("web","user"); + password = cfg.get("web","password"); + except: + username = None + password = None + try: + logging = cfg.get("logging","enabled") + except: + logging = None + try: + timeout = int(cfg.get("serial","timeout")) + except: + timeout = 120 + try: + baud = int(cfg.get("serial","baud")) + except: + baud = 57600 + try: + devid = cfg.get("web","devid") + except: + devid = "{:0>12X}".format(getnode()) + +except: + + print_log("Cannot intialize system") + exit() + +if __name__ == "__main__": + import sys + reload(sys) + sys.setdefaultencoding('utf-8') + main() diff --git a/weathermon.lua b/weathermon.lua new file mode 100755 index 0000000..20f5aca --- /dev/null +++ b/weathermon.lua @@ -0,0 +1,124 @@ +#!/usr/bin/lua + +function getConfig() + + local uci=require("uci") + local cur=uci.cursor() + local config="weathermon" + + web_url = cur.get(config,"web","url") + web_user = cur.get(config,"web","user") + web_pass = cur.get(config,"web","password") + web_devid = cur.get(config,"web","devid") + + io.input("/sys/class/net/eth0/address") + mac = io.read("*line") + mac = mac:gsub(":","") + mac = mac:upper() + + web_devid = web_devid or mac + + logging = cur.get(config,"logging","enabled") + +end + +require "socket" + +function sleep(sec) + socket.select(nil, nil, sec) +end + +function splitStr(str,char) + + local res = {} + local idx = 1 + + + while str:len()>0 do + pos = str:find(char); + if pos == nil then + res[idx]=str + str="" + else + res[idx]=str:sub(1,pos-1) + idx=idx+1 + str=str:sub(pos+1) + end + end + + return res + +end + +function printLog(str) + print(str) + if logging=="on" then + os.execute("logger -t weathermon "..str) + end +end + +function submitValue(type,id,param,val) + + printLog("URL="..web_url) + + url = web_url.."?stype="..type.."&sid="..id.."¶m="..param.."&value="..val + + printLog(url) + + command = "curl" + + if web_user then + command = command.." -u "..web_user..":"..web_pass + end + + command = command.." \""..url.."\"" + + printLog("COMMAND=\""..command.."\"") + os.execute(command) + print("") + +end + +function processLine(str) + + msg=splitStr(line,':') + msg_type=msg[1] or nil + msg_body=msg[2] or nil + if msg_type=="STATUS" then + printLog("Status: "..msg_body) + elseif msg_type=="ERROR" then + printLog("Error: "..msg_body) + elseif msg_type=="SENSOR" then + printLog("SENSOR: "..msg_body) + sens = splitStr(msg_body,",") + sensor = {} + idx = 1 + sensor_type = nil + sensor_id = web_devid + for i,rec in ipairs(sens) do + recrd=splitStr(rec,'=') + key=recrd[1] or nil + value=recrd[2] or nil + if value then + if key=="TYPE" then + sensor_type=value + elseif key=="ID" then + sensor_id=value + else + sensor[key]=value + end + end + end + for k,v in pairs(sensor) do + printLog("Type = "..sensor_type..", ID = "..sensor_id..", Param = "..key..", Value = "..value) + submitValue(sensor_type,sensor_id,key,value) + end + end + +end + +getConfig() + +line=arg[1] +print(line) +processLine(line) diff --git a/weathermon.sh b/weathermon.sh new file mode 100755 index 0000000..3f42275 --- /dev/null +++ b/weathermon.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +ARDUINO_PORT=`uci get weathermon.serial.port` +BAUD=`uci get weathermon.serial.baud` +stty -F $ARDUINO_PORT $BAUD + +while read LINE; do + weathermon.lua $LINE +done < $ARDUINO_PORT diff --git a/weathermon.uci b/weathermon.uci new file mode 100644 index 0000000..490ba91 --- /dev/null +++ b/weathermon.uci @@ -0,0 +1,12 @@ +config internal 'web' + option url http://estia.rvb-home.lan/meteo/send.php + option user meteo + option password somestrictpassword + +config internal 'serial' + option port /dev/ttyUSB0 + option timeout 100 + option baud 9600 + +config internal 'logging' + option enabled on diff --git a/web/archive.php b/web/archive.php new file mode 100644 index 0000000..c403863 --- /dev/null +++ b/web/archive.php @@ -0,0 +1,290 @@ + + + + + + WeatherMon (архив) + + + + + false)))) { + die($err); + } + +$db -> exec('SET CHARACTER SET utf8'); + +if (! $year) { + + $q = $db -> prepare( + 'select + date_format(day,\'%Y\') as year + from + calendar + group by year + order by year'); + $q -> execute(); +?> +

Архив метеоданных

+ fetch(PDO::FETCH_ASSOC)) { +?> + Данные за год
+ prepare( + 'select + date_format(day,\'%m\') as month, + date_format(day,\'%d\') as day + from + calendar + where + day>=str_to_date(\''.$year.'-01-01\',\'%Y-%m-%d\') and + day execute(); +?> +

год

+ fetchAll(PDO::FETCH_ASSOC); + $months = []; + foreach ($data as $row) { + $days [$year.$row['month'].$row['day']] = '&month='.$row['month'].'&day='.$row['day']; + $months[$row['month']]=1; + } + $m = 1; + echo ''; + for ($i=1; $i<=3; $i++) { + echo ''; + for ($j=1; $j<=4; $j++) { + echo ''; + $m++; + } + echo ''; + } + echo '
'; + $month=sprintf('%02d',$m); + $month_name = strftime('%B',mktime(0,0,0,$month,1,$year)); + if (!empty($months[$month])) { + echo '

'.$month_name.'

'; + } else { + echo '

'.$month_name.'

'; + } + calendar($year,$month,$days,'?year='.$year.'%s',0); + echo '
'; + + $next_year = $year+1; + + $q = $db -> prepare ( + 'select + s.id sensor,p.id param,s.s_description sensor_name,p.st_description param_name, + count(distinct day) cnt, + round(min(v.min),1) min_value, + round(max(v.max),1) max_value, + u.name_short unit + from + sensors_ranges v,sensors s,st_parameters p,units u + where + v.sensor=s.id and + v.parameter=p.id and + p.st_unit=u.id and + v.day>=str_to_date(\''.$year.'-01-01\',\'%Y-%m-%d\') and + v.day execute(); + $sensors = $q -> fetchAll(PDO::FETCH_ASSOC); + + foreach ($sensors as $sensor) { + + $units = get_unit($db,$sensor['param']); + $from_unit = $units['from']; + $to_unit = $units['to']; + $param_unit = $units['name']; + + $min_val = convert_unit($db,$sensor['min_value'],$from_unit,$to_unit); + $max_val = convert_unit($db,$sensor['max_value'],$from_unit,$to_unit); + + echo '

'.$sensor['param_name'].'('.$sensor['sensor_name'].')

'; + echo ''; + echo ''; + echo '
'; + echo 'Минимальное значение за год '.$min_val.' '.$param_unit.'
'; + echo 'Максимальное значение за год '.$max_val.' '.$param_unit.'
'; + echo '
'; + + if ($sensor['cnt']>1) { + + echo '
'; + + } + + } + + + } else { + + if (!$day) { + + $next_year = $year; + $next_month = $month+1; + + if ($next_month == 13) { + $next_month = 1; + $next_year = $next_year+1; + } + + $next_month = sprintf('%02d',$next_month); + $next_year = sprintf('%04d',$next_year); + $month = sprintf('%02d',$month); + $year = sprintf('%04d',$year); + + $q = $db -> prepare( + 'select + date_format(day,\'%d\') as day + from + sensors_ranges + where + day>=str_to_date(\''.$year.'-'.$month.'-01\',\'%Y-%m-%d\') and + day execute(); + + $data = $q -> fetchAll(PDO::FETCH_ASSOC); + + $month_name = strftime('%B %Y',mktime(0,0,0,$month,1,$year)); + +?> +

+ prepare ( + 'select + s.id sensor,p.id param,s.s_description sensor_name,p.st_description param_name, + count(distinct day) cnt, + round(min(v.min),1) min_value, + round(max(v.max),1) max_value, + u.name_short unit + from + sensors_ranges v,sensors s,st_parameters p,units u + where + v.sensor=s.id and + v.parameter=p.id and + p.st_unit=u.id and + v.day>=str_to_date(\''.$year.'-'.$month.'-01\',\'%Y-%m-%d\') and + v.day execute(); + $sensors = $q -> fetchAll(PDO::FETCH_ASSOC); + + foreach ($sensors as $sensor) { + + $units = get_unit($db,$sensor['param']); + $from_unit = $units['from']; + $to_unit = $units['to']; + $param_unit = $units['name']; + + $min_val = convert_unit($db,$sensor['min_value'],$from_unit,$to_unit); + $max_val = convert_unit($db,$sensor['max_value'],$from_unit,$to_unit); + + echo '

'.$sensor['param_name'].'('.$sensor['sensor_name'].')

'; + echo ''; + echo ''; + echo '
'; + echo 'Минимальное значение за месяц '.$min_val.' '.$param_unit.'
'; + echo 'Максимальное значение за месяц '.$max_val.' '.$param_unit.'
'; + echo '
'; + + if ($sensor['cnt']>1) { + + echo '
'; + + } + + } + + } else { + + $month = sprintf('%02d',$month); + $year = sprintf('%04d',$year); + $day = sprintf('%02d',$day); + + $q = $db -> prepare( + 'select + distinct v.sensor as sensor_id,s.s_description,p.id as param_id,p.st_description + from + sensors_ranges v,st_parameters p,sensors s + where + v.day=str_to_date(\''.$year.'-'.$month.'-'.$day.'\',\'%Y-%m-%d\') + and v.sensor=s.id + and v.parameter=p.id' + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + + echo '

'.$row['s_description'].'/'.$row['st_description'].'

'; +?> +
+ + + \ No newline at end of file diff --git a/web/calendar.php b/web/calendar.php new file mode 100644 index 0000000..6dbef05 --- /dev/null +++ b/web/calendar.php @@ -0,0 +1,87 @@ + $dayofmonth) break; + + } + + if($day_count > $dayofmonth) break; + + } + + echo ''; + + for($i = 0; $i < count($week); $i++) { + + echo ''; + + for($j = 0; $j < 7; $j++) { + + if(!empty($week[$i][$j])) { + $str = $week[$i][$j]; + $fstr=''.$str.''; + if (!empty($days[$year.$month.sprintf('%02d',$str)])) { + $href=sprintf($ref_template,$days[$year.$month.sprintf('%02d',$str)]); + if($j == 5 || $j == 6) { + echo ''; + } else { + echo ''; + } + } else { + if($j == 5 || $j == 6) { + echo ''; + } else { + echo ''; + } + } + } + + else echo ''; + + } + + echo ''; + + } + + echo '
'.$fstr.''.$fstr.''.$fstr.''.$fstr.' 
'; + +} + +?> \ No newline at end of file diff --git a/web/config_local.php b/web/config_local.php new file mode 100644 index 0000000..00afede --- /dev/null +++ b/web/config_local.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..a8081d8a807fe73d8fc101c9bdd90e0457474c24 GIT binary patch literal 1536 zcmV+b2LJhqP){Y{f7q=HOpgToz zK)6Lz+Ij^kyPWdMjY-h1NsFH)+iqU$>S%@~6*Mt`@~VvNCiPuF!if3a9F zola@nma3|bu3WkDFW{{OBH)KC%a#DnIlT9p#bUA0V6vFCmJosl4k3&#Yb_fa8)R9A z_a1;WO=;T}fcbpB0Db@>Nv)8e&N;Fy!x%%J=frW$Y&N5+Dw?Lj7(KA*E*uW`=NG!1#4lcuSHs_R;Vefjc5jo0_RCQuXw z)9F;_c<(tpJj6LSlIU0#3m9R*i206=j+jg)L{X&riP@^E!Z}BprXvYXpFYiOHbbgM zq?BM?*XeUn6y$l%apEe0?Ya(Q44a#q7-RVK>C=cZ?>$M9P}enG*J*~Ld0p3k(Hh5U z#_X&H<*=DS4jLG|k9h!_rKWL^BT| zP}j8p7%@Oy*NS>Ld9_;My;l>798w`-QpwzVuR)~wNJ3rLk>@$H*=%G&0Nb{$I(B%? zW-~$vG)+TY*IFgQh5!}zWQ|j&PN`ATG}UjMb7I`F1X5ln0m!h{Dvi=mj4>2NK~WTR zUB_y*V!2#uwnKKroC5fy1V-BCw*U-jj^miBs#q)*#Br>>AxRR}>-FE}gb>K{Tr22n z9LI@N^p&n|QMi?ARFzi|qSO8gTwX4N(OrGahYey7+Z6rxT zmSsA3D8rBeBgiG7AeWD?U%$@Nr%#n;S@2s!_5$Y|>-AczN7fuLYepUrI^_eoKYsj} zwr#Q2>V|Yuo~u`{^8ER8q?(2aNN~9y&mDOnk`fvY2~w7&c0MV^;UNTIe}7*k5mTNF ze)Hx{_V)I~1JMwG>HA(MEtg9GK79C~*-DdY+g9IACKK%iP19hl<;)92|^JTM|eVY=zkdDAIr3y=hr50I_NWY{_GMAoH3j5Qs&nVgsey;GwQV~(TMWz4 z9zR&`J!M(4x3@Pk&c%xtxpnK7f&oUx9A+)%9R?R>?%cVfhu32Oqa&H>xLU17bjq1- zcmxx+>bf3v&S%e_je-vWJbLs^tVckjQ4hljrbAIver8Sro5C*UIAcN_xGfZsz1D>E=r m!vFqT$-Xmy2B<;^9l)Qgi%xGS!0BrM0000 + + + + + + image/svg+xml + + + + + + + + diff --git a/web/graphs.php b/web/graphs.php new file mode 100644 index 0000000..dfc7450 --- /dev/null +++ b/web/graphs.php @@ -0,0 +1,53 @@ + + + + + + WeatherMon (Последние 24 часа) + + + + + false)))) { + die($err); + } + +$db -> exec('SET CHARACTER SET utf8'); + +$q = $db -> prepare( + 'select + distinct v.sensor_id,s.s_description,p.id as param_id,p.st_description + from + sensor_values v,st_parameters p,sensors s + where + v.timestamp>adddate(now(), -1) + and v.sensor_id=s.id + and s.st_id=p.st_id + and p.id>=0 + order by s_description,st_description' + ); +$q -> execute(); + +while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + + echo '

'.$row['s_description'].'/'.$row['st_description'].'

'; +?> +
+ +Архивные данные +
+Настройки + + \ No newline at end of file diff --git a/web/image.php b/web/image.php new file mode 100644 index 0000000..16fbafb --- /dev/null +++ b/web/image.php @@ -0,0 +1,241 @@ + false)))) { + + die('Не могу подключиться к БД'); + +} + +$supported = imagetypes(); +if( $supported & IMG_PNG ) $img_format="png"; +elseif( $supported & IMG_GIF ) $img_format="gif"; +elseif( $supported & IMG_JPG ) $img_format="jpeg"; +elseif( $supported & IMG_WBMP ) $img_format="wbmp"; +elseif( $supported & IMG_XPM ) $img_format="xpm"; + +$cachefilename = NULL; + +$db -> exec('SET CHARACTER SET utf8'); + +$type = $_REQUEST['type']; +$sensor=$_REQUEST['sensor']; +$param=$_REQUEST['param']; + +if ($type and $param) { + + $sensor = intval($sensor); + $param = intval($param); + + $q = $db -> prepare( + 'select s_description from sensors where id='.$sensor + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $sensor_name = $row['s_description']; + } + + $q = $db -> prepare( + 'select st.st_dot_color,st.st_line_color,st.st_description,u.id,u.unit_group from st_parameters st,units u where st.id='.$param.' and st.st_unit=u.id' + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $param_name = $row['st_description']; + $from_unit = $row['id']; + $unit_group = $row['unit_group']; + $dot_color = $row['st_dot_color']; + $line_color = $row['st_line_color']; + } + + if (!empty($_COOKIE['unit_'.$unit_group])) { + $to_unit=intval($_COOKIE['unit_'.$unit_group]); + } else { + $to_unit=$from_unit; + } + + $q = $db -> prepare( + 'select u.name_short from units u where u.id='.$to_unit + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $param_unit = $row['name_short']; + } + + $xdata = array(); + $ydata = array(); + + if ($type == 'last24') { + + $q = $db -> prepare( + 'select unix_timestamp(timestamp) as x,unitconv(value,'.$from_unit.','.$to_unit.') as y from sensor_values where timestamp>adddate(now(), -1) and sensor_id='.$sensor.' and parameter_id='.$param.' order by timestamp' + ); + + $bottomheight = 130; + $topheight = 40; + $sizex = 1000; + $sizey = 800; + $scale = True; + + } elseif ($type == 'last24small') { + + $q = $db -> prepare( + 'select unix_timestamp(timestamp) as x,unitconv(value,'.$from_unit.','.$to_unit.') as y from sensor_values where timestamp>adddate(now(), -1) and sensor_id='.$sensor.' and parameter_id='.$param.' order by timestamp' + ); + + $bottomheight = 20; + $topheight = 20; + $sizex = 400; + $sizey = 300; + $scale = False; + + } elseif ($type == 'range') { + + $curr = intval(date('YmdHis')); + + $from = intval($_REQUEST['fromdate']); + $to = intval($_REQUEST['todate']); + + if ($curr>$to) { + + $cachefilename='meteo.'.$sensor.'.'.$param.'.'.$to_unit.'.'.$from.'-'.$to.'.'.$img_format; + + } + + $q = $db -> prepare( + 'select unix_timestamp(timestamp) as x,unitconv(value,'.$from_unit.','.$to_unit.') as y from sensor_values where timestamp>=str_to_date("'.$from.'","%Y%m%d%H%i%s") and timestamp<=str_to_date("'.$to.'","%Y%m%d%H%i%s") and sensor_id='.$sensor.' and parameter_id='.$param.' order by timestamp' + ); + + $bottomheight = 60; + $topheight = 40; + $sizex = 1000; + $sizey = 800; + $scale = True; + + } + + $g = new Graph($sizex,$sizey); + + if ($cachefilename) { + if ($g->cache->IsValid($cachefilename)) { + + $g->cache->StreamImgFile($g->img,$cachefilename); + return; + + } else { + + $timeout = 8640000; + $g->SetupCache($cachefilename,$timeout); + + } + } + + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + + $xdata[] = $row['x']; + $ydata[] = $row['y']; + + } + + + for ($i = 0; $i < count($xdata); ++$i) { + + $total_weight=0; + $sum=0; + $maxdelta = 1800; + + for ($j = $i; $j < count($xdata); ++$j) { + + $delta = abs($xdata[$i]-$xdata[$j]); + if ($delta > $maxdelta) { break; } + + $weight = 1-$delta/$maxdelta; + $total_weight += $weight; + $sum += $weight*$ydata[$j]; + + } + + for ($j = $i-1; $j >=0 ; --$j) { + + $delta = abs($xdata[$i]-$xdata[$j]); + if ($delta > $maxdelta) { break; } + + $weight = 1-$delta/$maxdelta; + $total_weight += $weight; + $sum += $weight*$ydata[$j]; + + } + + $new_val = $sum/$total_weight; + $f_ydata[$i] = $new_val; + + } + + // Create the graph + $g->graph_theme = null; + + $g->img->SetAntiAliasing(); + + // We need a datlin scale since we provide both + // x and y coordinates for the data points, but x is unix timestamp. + $g->SetScale('datlin'); + if ($scale) { + $g->xaxis->SetLabelAngle(90); + } else { + $g->xaxis->HideLabels(True); + } + $g->xaxis->SetPos("min"); +# $g->xaxis->scale->SetTimeAlign( HOURADJ_1 ); + + // We use a scatterplot to illustrate the original + // contro points. + $splot = new ScatterPlot($ydata,$xdata); + $g->Add($splot); + + // + $splot->mark->SetFillColor($dot_color); + $splot->mark->SetColor($dot_color); + $splot->mark->SetType(MARK_FILLEDCIRCLE); + $splot->mark->SetSize(2); + + $fplot = new LinePlot($f_ydata,$xdata); + $g->Add($fplot); + $fplot->SetColor($line_color); + $fplot->SetWeight(2); + + $g->SetMargin(50,30,$topheight,$bottomheight); + if ($scale) { + $g->title->Set($sensor_name.'/'.$param_name.', '.$param_unit); + $g->title->SetFont(FF_DV_SANSSERIF,FS_BOLD,12); + } + $g->SetMarginColor('lightgray'); + + $g->xgrid->Show(); + $g->xgrid->SetLineStyle('dotted'); + $g->ygrid->Show(); + $g->ygrid->SetLineStyle('dotted'); + + // Add the plots to the graph and stroke + $g->Stroke(); + +} else { + + header("Content-Type: text/html; charset=UTF-8"); + die('Сенсор не выбран!'); + +} + +?> \ No newline at end of file diff --git a/web/image_minmax.php b/web/image_minmax.php new file mode 100644 index 0000000..dfa66d2 --- /dev/null +++ b/web/image_minmax.php @@ -0,0 +1,241 @@ + false)))) { + + die('Не могу подключиться к БД'); + +} + +$supported = imagetypes(); +if( $supported & IMG_PNG ) $img_format="png"; +elseif( $supported & IMG_GIF ) $img_format="gif"; +elseif( $supported & IMG_JPG ) $img_format="jpeg"; +elseif( $supported & IMG_WBMP ) $img_format="wbmp"; +elseif( $supported & IMG_XPM ) $img_format="xpm"; + +$cachefilename = NULL; + +$db -> exec('SET CHARACTER SET utf8'); + +$type = $_REQUEST['type']; +$sensor=$_REQUEST['sensor']; +$param=$_REQUEST['param']; +$year=$_REQUEST['year']; +$month=$_REQUEST['month']; + +if ($type and $param) { + + $sensor = intval($sensor); + $param = intval($param); + + $q = $db -> prepare( + 'select s_description from sensors where id='.$sensor + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $sensor_name = $row['s_description']; + } + + $q = $db -> prepare( + 'select st.st_fill_color_top,st.st_fill_color_bottom,st.st_description,u.id,u.unit_group from st_parameters st,units u where st.id='.$param.' and st.st_unit=u.id +' + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $param_name = $row['st_description']; + $from_unit = $row['id']; + $unit_group = $row['unit_group']; + $fill_color_top=$row['st_fill_color_top']; + $fill_color_bottom=$row['st_fill_color_bottom']; + } + + if (!empty($_COOKIE['unit_'.$unit_group])) { + $to_unit=intval($_COOKIE['unit_'.$unit_group]); + } else { + $to_unit=$from_unit; + } + + $q = $db -> prepare( + 'select u.name_short from units u where u.id='.$to_unit + ); + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $param_unit = $row['name_short']; + } + + $xdata = array(); + $ydata = array(); + + if ($type == 'month') { + + $next_year = $year; + $next_month = $month+1; + + if ($month==13) { + + $next_year++; + $next_month=1; + + } + + $curr = date("Ym"); + + if ($curr>$next_year.$next_month) { + + $cachefilename='meteo.month.'.$sensor.'.'.$param.'.'.$to_unit.'.'.$year.'-'.$month.'.'.$img_format; + + } + + $q = $db -> prepare( + ' + select + x, + unitconv(min(min),'.$from_unit.','.$to_unit.') min_value, + unitconv(max(max),'.$from_unit.','.$to_unit.') max_value + from ( + select + unix_timestamp(day) x, + min, + max + from + sensors_ranges + where + day>=str_to_date(\''.$year.$month.'\',\'%Y%m\') + and day$next_year) { + + $cachefilename='meteo.year.'.$sensor.'.'.$param.'.'.$year.'.'.$img_format; + + } + + $q = $db -> prepare( + ' + select + x, + unitconv(min(min),'.$from_unit.','.$to_unit.') min_value, + unitconv(max(max),'.$from_unit.','.$to_unit.') max_value + from ( + select + unix_timestamp( + DATE_SUB(day, INTERVAL DAYOFWEEK(day)-1 DAY) + ) x, + min, + max + from + sensors_ranges + where + day>=str_to_date(\''.$year.'\',\'%Y\') + and daycache->IsValid($cachefilename)) { + + $g->cache->StreamImgFile($g->img,$cachefilename); + return; + + } else { + + $timeout = 8640000; + $g->SetupCache($cachefilename,$timeout); + + } + } + + + $q -> execute(); + + while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + + $xdata[] = $row['x']; + $mindata[] = $row['min_value']; + $maxdata[] = $row['max_value']; + + } + + + // Create the graph + $g->graph_theme = null; + + //$g->img->SetAntiAliasing(); + + // We need a linlin scale since we provide both + // x and y coordinates for the data points. + $g->SetScale('datlin'); + $g->xaxis->SetLabelAngle(90); + $g->xaxis->SetPos("min"); + $g->xaxis->scale->SetTimeAlign( MINADJ_1 ); + + // We use a scatterplot to illustrate the original + // contro points. + + $bplot = new LinePlot($maxdata,$xdata); + $g->Add($bplot); + $bplot->SetColor($fill_color_top); + $bplot->SetFillGradient($fill_color_top.'@0.2',$fill_color_bottom.'@0.9',100,TRUE); + $bplot->SetFillFromYMin(TRUE); + $bplot->SetWeight(4); + + $aplot = new LinePlot($mindata,$xdata); + $g->Add($aplot); + $aplot->SetColor($fill_color_bottom); + $aplot->SetFillGradient($fill_color_bottom.'@0.2','white@0.9',100,TRUE); + $aplot->SetFillFromYMin(TRUE); + $aplot->SetWeight(4); + + $g->SetMargin(60,60,60,130); + $g->title->Set($sensor_name.'/'.$param_name.', '.$param_unit); + $g->title->SetFont(FF_DV_SANSSERIF,FS_BOLD,12); + $g->subtitle->Set('(минимальные и максимальные значения за период)'); + $g->subtitle->SetColor('darkred'); + $g->SetMarginColor('silver'); + + $g->xgrid->Show(); + $g->xgrid->SetLineStyle('dotted'); + $g->ygrid->Show(); + $g->ygrid->SetLineStyle('dotted'); + + // Add the plots to the graph and stroke + $g->Stroke(); + +} else { + + header("Content-Type: text/html; charset=UTF-8"); + die('Сенсор не выбран!'); + +} + +?> \ No newline at end of file diff --git a/web/index.php b/web/index.php new file mode 100644 index 0000000..37251e6 --- /dev/null +++ b/web/index.php @@ -0,0 +1,103 @@ + + + + + + + WeatherMon (Последние 24 часа) + + + + +
+ false)))) { + die($err); + } + +$db -> exec('SET CHARACTER SET utf8'); + +$q = $db -> prepare( + 'select + distinct v.sensor_id,s.s_description,p.id as param_id,p.st_description + from + sensor_values v,st_parameters p,sensors s + where + v.timestamp>adddate(now(), -1) + and v.sensor_id=s.id + and s.st_id=p.st_id + and p.id>=0 + order by s_description,st_description' + ); +$q -> execute(); + +while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + + echo '
'; + echo '
'.$row['s_description'].'/'.$row['st_description'].'
'; + +$ql = $db -> prepare( + ' + SELECT unix_timestamp(timestamp) timestamp,DATE_FORMAT(timestamp,"%H:%i") printable,value + FROM + meteo.sensor_values + WHERE + sensor_id='.$row['sensor_id'].' and parameter_id='.$row['param_id'].' and timestamp>addtime(now(), -3600) + ORDER BY + timestamp desc + ' + ); + +$ql -> execute(); + +$printable_ts = "?"; +$value = "?"; + +if ($rowl = $ql -> fetch(PDO::FETCH_ASSOC)) { + + $timestamp = $rowl['timestamp']; + $printable_ts = $rowl['printable']; + $value = $rowl['value']; + + $units = get_unit($db,$row['param_id']); + $from_unit = $units['from']; + $to_unit = $units['to']; + $param_unit = $units['name']; + + $val = convert_unit($db,$value,$from_unit,$to_unit); + +} + +echo '
'.$printable_ts.'
'; +echo '
'.$val.' '.$param_unit.'
'; +?> +
+"; + +} + +?> +
+ + + \ No newline at end of file diff --git a/web/send.php b/web/send.php new file mode 100644 index 0000000..7a69838 --- /dev/null +++ b/web/send.php @@ -0,0 +1,42 @@ + $valid_ip_end || $valid_ip_start > $client_ip) { + header('HTTP/1.1 403 Forbidden'); + echo "IP not in allowed range"; + exit; + } + + $stype = $_REQUEST['stype']; + $sid = $_REQUEST['sid']; + $param = $_REQUEST['param']; + $value = $_REQUEST['value']; + + $connection = new mysqli($mysql_host, $mysql_user, $mysql_pwd, $mysql_schema, $mysql_port); + if ($connection->connect_errno) { + header('HTTP/1.1 500 Internal Server Error'); + exit; + } + + $str = "CALL meteo.submit_value('".$stype."','".$sid."','".$param."',".$value.",NULL)"; + if (!$connection->query($str)) { + header('HTTP/1.1 500 Internal Server Error'); + exit; + } else { + $connection->commit(); +?> + + + + Meteo logger + + +OK Logged + + + diff --git a/web/setup.php b/web/setup.php new file mode 100644 index 0000000..e591264 --- /dev/null +++ b/web/setup.php @@ -0,0 +1,114 @@ + false)))) { + + die('Не могу подключиться к БД'); + +} + +$db -> exec('SET CHARACTER SET utf8'); + +$selected = []; + +if ($_REQUEST['action']=='submit') { + + foreach($_REQUEST as $key=>$value) { + + if (strpos($key,'unit_')===0) { + + $group_id=intval(substr($key,5)); + $unit_id=$value; + setcookie('unit_'.$group_id,$unit_id,time()+86400*365*10); + $selected[$group_id]=$unit_id; + + } + + } + +?> + + + + + + WeatherMon (Настройки) + + + +

Сохранено...

+ +$value) { + + if (strpos($key,'unit_')===0) { + + $group_id=intval(substr($key,5)); + $unit_id=$value; + setcookie('unit_'.$group_id,$unit_id); + $selected[$group_id]=$unit_id; + + } + + } + +?> + + + + + + WeatherMon (Настройки) + + + + + prepare( + 'select id,name,(select count(*) from units where unit_group=g.id) cnt from unit_groups g' +); +$q -> execute(); + +echo '
'; +while ($row = $q -> fetch(PDO::FETCH_ASSOC)) { + $group_id = $row['id']; + $group_name = $row['name']; + $group_cnt = $row['cnt']; + + echo '

'.$group_name.'

'; + + $q_p = $db -> prepare( + 'select id,name from units where unit_group='.$group_id + ); + + $q_p->execute(); + + echo '
'; +} +echo ''; +echo '

'; +echo '
'; + +} + +?> + + \ No newline at end of file diff --git a/web/units.php b/web/units.php new file mode 100644 index 0000000..16ad227 --- /dev/null +++ b/web/units.php @@ -0,0 +1,61 @@ + prepare( + 'select u.id,u.unit_group from st_parameters st,units u where st.id='.$param.' and st.st_unit=u.id' + ); + $qug -> execute(); + + while ($row = $qug -> fetch(PDO::FETCH_ASSOC)) { + $from_unit = $row['id']; + $unit_group = $row['unit_group']; + } + + if (!empty($_COOKIE['unit_'.$unit_group])) { + $to_unit=intval($_COOKIE['unit_'.$unit_group]); + } else { + $to_unit=$from_unit; + } + + $qu = $db -> prepare( + 'select u.name_short from units u where u.id='.$to_unit + ); + $qu -> execute(); + + while ($row = $qu -> fetch(PDO::FETCH_ASSOC)) { + $param_unit = $row['name_short']; + } + + return Array( + 'from' => $from_unit, + 'to' => $to_unit, + 'name' => $param_unit + ); + +} + +function convert_unit($db,$value,$from,$to) { + + if ($from==$to) { + + $val = $value; + + } else { + + $qv = $db -> prepare( + 'select round(unitconv('.$value.','.$from.','.$to.'),2) res' + ); + $qv -> execute(); + + while ($row = $qv -> fetch(PDO::FETCH_ASSOC)) { + $val = $row['res']; + } + + } + + return $val; + +} + +?> \ No newline at end of file -- 2.34.1