├── CHANGELOG.md ├── CONTRIBUTING.md ├── INSTRUCTION.md ├── LICENSE ├── README.md └── code ├── boot.py ├── main.py ├── main2.py ├── secret_cfg.py └── simple2.py /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Features 2 | + controlling and querying of EQ3 devices 3 | - temperature can be set and queried 4 | - modes are not yet available (battery also not) 5 | + readout of Mijia thermometers 6 | + communication as MQTT (partial compatibilty to esp32_mqtt_eq3 from softypit) 7 | + basic webpage interface 8 | + running on async instead of sockets now 9 | + added basic OTA !!! 10 | + files can be uploaded and removed from ESP through the page 11 | + works for any text file, does not work for binary files yet... 12 | + removed necessity of webrepl to save memory 13 | + webrepl can be switched on and off through the webpage 14 | + improved web/sessions - more responsive 15 | + improved links (upload and reset requires confirmation) 16 | + added more clear descriptions 17 | - precompiled the external libraries to save memory and space (simple2.py) 18 | + precompilation was removed, as for every micropython version a new precompiled file might be needed 19 | 20 | # Changes 21 | - planned 22 | - BLE detections with lower signal than -92 are ignored 23 | - 7a5f011 24 | - EQ3 now sends valve open value and battery status (also with home assistant autodiscovery 25 | - web OTA and some other pages, postpone BLE actions to improve responsibility of the webpage 26 | - precompiled MPY files are dropped, due to issues with compatibility with different micropython versions 27 | - all files (also config and simple2) and outputs (page) are now latin-1 encoded (not utf-8) 28 | - this seems to lower and stabilize the memory use, at the cost of using special characters 29 | - presence for BLE beacons (or some smart watches, like Mi Band) detection is added, but works unstable 30 | - temperature range selection is expanded to full EQ3 range (5 to 29.5) 31 | - it does not always work at the start, as new autodiscovery messages need to be sent 32 | - BUG: wrong byte for valve open was extracted 33 | - aefe81f 34 | - significant code rewrite (cleaning pending) 35 | - automatic time NTP querying 36 | - automatic MQTT autodiscovery for Home Assistant 37 | - for thermostats (climate entity) 38 | - for thermometers (sensor entity) 39 | - work list for each device separately 40 | - use of multiple paralel BLE connections, for speed and stability 41 | - whitelist for EQ3, thermometers-sensors 42 | - automatic querying of EQ3 (and thermometers, if available) 43 | - async webpage for more stability 44 | - watchdog for rebooting just in case 45 | - BUG: when the contacted device was not available, then the system stuck in a loop (as it retried the connection all the time) 46 | - now there are 3 retries in a row, and then it moves to the next work 47 | - BUG: there was a 1 second slot, in which the old work was done, and new work could be added, and quickly deleted by the previous deletion request 48 | - this cannot happen now, as there is a work list 49 | - BUG: whitelisted devices could not be removed from GUI 50 | - now possible 51 | - BUG Theoretical: If the connections will be so fast, and amount of the EQ3s larger than 6-7, then all BLE connections will be saturated, and it is not known what will happen 52 | - now, if 4 simultanuous connections are opened, then ESP32 is waiting for done connections to be closed, before opening new 53 | - BUG: Thermometer readout timer was reset so often, that the real readout never happened (as it was always "just done") 54 | - fixed 55 | - BUG: NTP and Autodiscovery were done every few minutes, as the work timer was not set correctly (NTP every 24 hours, Autodiscovery every 6 hours) 56 | - fixed 57 | - ISSUE: worklist could consist of multiple equal commands, which makes no sense 58 | - now if equal command exists in the list, it is dropped, except this, no other commands are dropped 59 | - ISSUE: flooding web connections could comsume all the RAM and lead to reboot 60 | - now it should not happen, as the device will respond "flood" or not respond at all if free RAM amount is critically low, but it will try to stay alive 61 | - ISSUE: it is more an issue, as scanning could be interrupted by any BLE connection request, and scanning did not start when BLE connection was open 62 | - this led to an issue, where the scanning was very short, or did not took place for a few minutes in a row 63 | - now, the scanning reserves 1/2 of the full requested scan time, so in worst case it takes half of time, or in best complete time 64 | - ISSUE: it was hard to controll the ESP32/EQ3 externally, as the MQTT addresses were not known 65 | - now in the Info page there is a list of the devices, current work/status and a list of MQTT addresses to control the system externally (not through Home Assistant) 66 | - previous 67 | - whatever 68 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Basic rules 2 | 3 | + Make the code better. 4 | + If you do it worse, you are out. 5 | + Better is intuitive - i.e. faster, smaller, more efficient, more robust/stable, more functional. 6 | + Keep it simple. 7 | + Functionality should be limited to its core aim. 8 | + If the project should grow in undefined direction, fork it and make a separate one. 9 | 10 | ## Global aim 11 | 12 | The aim is, that by making the code better, you/we make the world better. 13 | Still, in case if doing the code better, we will make the world worse... (unprobable, but not impossible) we need to think about it :D 14 | -------------------------------------------------------------------------------- /INSTRUCTION.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | No compilation is needed, just flash micropython and upload the files as described below. 3 | 4 | - first download micropython binary from here https://micropython.org/download/ 5 | - very probably you need the common esp32 binary (https://micropython.org/download/esp32/) 6 | - IMPORTANT: fill out the secret_cfg.py file 7 | - flash it with your favourite flasher using serial connection, or usb-serial connection (if available) 8 | - for example with esptool - following the instruction on the micropython download page 9 | - now, you need to upload the files (4 files) from the code directory 10 | - It can be done with webrepl or ampy 11 | - webrepl does not require any special installation, but it need to be activated on micropython (through serial connection) 12 | - ampy requires that you have python installed, and can be installed with pip 13 | 14 | ## Usage 15 | - install, as described above 16 | - go to "List of devices" 17 | - add interesting devices to the list of this esp32 18 | - DONE 19 | 20 | Now, the devices will be queried automatically. Furthermore, the MQTT autodiscovery for HomeAssistant will be 21 | published, so that you should see new "climate" entities in the list. 22 | You can control the temperature using the Home Assistant interface. 23 | 24 | Furthermore, in the "Info" part in the ESP32 interface, you will see the MQTT addresses 25 | for each EQ3. Just send the number with requested temperature to the "temp" MQTT address manually, and it is done. 26 | 27 | Whitelisted supported thermometers will be queried automatically and MQTT autodiscovery will be published too (as sensor). 28 | 29 | If MQTT autodiscovery will be not published, you can reboot device, or press "Publish MQTT autodiscovery". 30 | 31 | ## Updates 32 | Updates can be uploaded OTA (over the air), so the device does not have to be physically connected to the PC for the update. 33 | If the main.py fails, then it can be always updated with webrepl. 34 | The only danger is while updating the boot.py or secret_cfg.py, as if there is an error, the webrepl will not start... then the update has to be done with a cable. Still, I try not to upload not working releases ;D 35 | The OTA is available under the http://mydevice/ota link. 36 | 37 | ## Shell 38 | It is possible to connect to shell of MicroPython for some extra functionality. 39 | For this, it is reasonable to setup and use WebREPL, to issue commands and upgrade scripts remotely. 40 | http://micropython.org/webrepl/ 41 | 42 | There are internal functions (not really necessary, as there is a webpage now): 43 | - it is not really important or interesting how the functions work... -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # esp32_python_eq3 2 | Bluetooth bridge between eqiva EQ3 thermostat and WLAN network, using ESP32, micropython and mqtt. 3 | 4 | - INSTRUCTION https://github.com/yunnanpl/esp32_python_eq3/blob/master/INSTRUCTION.md 5 | - CHANGELOG https://github.com/yunnanpl/esp32_python_eq3/blob/master/CHANGELOG.md 6 | 7 | - https://www.eq-3.de/produkte/eqiva/detail/bluetooth-smart-heizkoerperthermostat.html 8 | 9 | # Idea 10 | I used a lot of other solutions, but it seemed to be not stable for me, or hard to extend (for me :)). 11 | In order to use the esp32 for EQ3 and Mijia temperature sensors (or even some BME280-like ones) I needed to get something done on my own. 12 | 13 | So I decided to rewrite it in python (micropython) on esp32. 14 | 15 | This is the result. It can mimic and substitute the esp32_mqtt_eq3 solution from softypit, as it accepts the same mqtt input and returns similar mqtt json output. 16 | 17 | # Status 18 | 19 | It works quite stable. More stable for me than esp32_mqtt_eq3 solution. 20 | I added also work list (so multpiple work can be added, and it will be done one after another). 21 | This solution reads data from Mijia sensors. Plan is to add BME280 and other "local" sensors. 22 | It also does BLE scans, and can report bluetooth devices in the area (for presence testing etc.). 23 | 24 | Communication is done by MQTT, and the syntax is near to identical to esp32_mqtt_eq3 so it can be substituted. 25 | The syntax is still simpler than esp32_mqtt_eq3. 26 | 27 | Serial or WebREPL can be used. THere are some useful functions on the device. 28 | 29 | Script works and is being tested with **EQ3 Thermostats Firmware 1.20** (so the one without 6 digits pairing). 30 | It may work with older and newer version, but probably not the one with pairing. 31 | (Probably does not work with 1.1 or older, but probably does work with 1.4.6, still do not change the firmware if it works fine). 32 | 33 | ## Tests 34 | The aim is stability. 35 | Test system is 4 ESP32 controlling 9 EQ3 (around 2 EQ3 for each ESP32 and reading out 2 thermometers). 36 | Anything can happen: Battery on EQ3 runs out. BLE packets get corrupted, etc... WLAN breaks, MQTT server dies, bad work is sent... DOS happens... 37 | I tried to pick up all imaginable errors. I do up to 700 queries daily (every 2-3 minutes), and send 10-50 commands. 38 | At best, the device should never loose work, even if it is forced sometimes to reboot. 39 | 40 | Tests with newest version... 41 | - 48h, 1400 queries, 30 commands for each of EQ3, configuration as written above -> no issues 42 | - further testing 43 | 44 | It seems that RSSI above -90 leads to issues with connection. It will connect, but after a few tries. 45 | Below -90 it works without any issues. 46 | 47 | ## Features (and anti-features) 48 | - NEW basic webpage added 49 | - NO AP configuration (only config file) 50 | - robust WIFI, survives disconnections, reconnects, etc. 51 | - robust BLE, survives bad addresses, bad messages, disconnections, etc. Has automatic connections cleaning. 52 | - robust MQTT, survives disconnections, automatically resubscribes, etc. 53 | - more robust mqtt, as there were issues that mqtt-robust lib, have not noticed that it was not subscribed 54 | - has "unique" worklist 55 | - if the same message will be sent 5 times, it will be processed once 56 | - if there is a not-yet-processed work in the list for setting temp, then another work for the same device overwrites previous command 57 | - is persistent, if the device is known, but does not respond in 10-20 sec slot, then work is put at the end, and new work is done 58 | 59 | ## Plan 60 | - add basic AP for configuration 61 | - add other temperature sensors like Mijia, BME280, etc. 62 | - add PID regulator for automatic temperature regulation 63 | - in case of real temperature input 64 | - add other basic info, like battery, mode, etc. 65 | - add offset setting, both in eq3 and "external" through esp32 66 | - think about adding support for the new firmware version of eq3 (later :D) 67 | - maybe not so tragic at all, it has to do with the new pairing 68 | - https://github.com/rytilahti/python-eq3bt/issues/41 69 | - and micropython ble seems to support pairing already 70 | - https://github.com/micropython/micropython/pull/6651 71 | - maybe - add temperature history and eq3 setting history graph 72 | 73 | # References 74 | 75 | - mqtt - most robust library chosen 76 | - https://github.com/fizista/micropython-umqtt.simple2 with https://github.com/fizista/micropython-umqtt.robust2 77 | - not clear if necessary 78 | 79 | # Other interesting liks 80 | - https://github.com/softypit/esp32_mqtt_eq3 81 | - https://github.com/rytilahti/python-eq3bt 82 | - https://github.com/bimbar/bluepy_devices 83 | -------------------------------------------------------------------------------- /code/boot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: ascii -*- 2 | # -### boot.py 3 | 4 | #-### 5 | #-### 6 | # -### imports, also CONFIG and settings 7 | # 8 | import gc 9 | gc.enable() 10 | gc.threshold(30000) # ??? was 40000, was 10000 11 | import micropython 12 | micropython.opt_level(3) 13 | micropython.alloc_emergency_exception_buf(2) # was 100 14 | #import uasyncio as asyncio #moved to main 15 | #import _thread #moved to main 16 | import network 17 | import ntptime 18 | import time 19 | import ubluetooth 20 | import simple2 as umqtt 21 | import os 22 | from secret_cfg import * 23 | # speedup/slow down for energy saving :) 24 | import machine 25 | machine.freq(CONFIG['freq']) 26 | # 27 | 28 | #-### 29 | #-### CONFIG compatibility 30 | # moving variable to list of permanent variables, in order to query ntp sometimes 31 | # and not to change CONFIG 32 | try: 33 | CONFIG2['mqtt_thermo_src'] = CONFIG2['mqtt_temp_src'] 34 | except: 35 | pass 36 | 37 | try: 38 | CONFIG2['ntp_host'] = CONFIG['ntp_host'] 39 | except: 40 | pass 41 | 42 | #-### 43 | #-### 44 | # -### activate ble 45 | ble = ubluetooth.BLE() 46 | if ble.active() == False: 47 | ble.active(True) 48 | 49 | #-### 50 | #-### 51 | # -### create timers 52 | #timer_schedule = machine.Timer(0) 53 | timer_work = machine.Timer(0) 54 | timer_check = machine.Timer(1) 55 | 56 | #-### 57 | #-### 58 | # -### conenct to network 59 | try: 60 | station = network.WLAN(network.STA_IF) 61 | station.active(True) 62 | station.connect(CONFIG['wifi_name'], "".join([chr(x) for x in CONFIG['wifi_pass']])) 63 | except: 64 | pass 65 | 66 | #-### 67 | #-### 68 | # -### waiting for connection 69 | while station.isconnected() == False: 70 | # print('LOG waiting for connection') 71 | time.sleep(0.5) # sleep or pass 72 | # if not conencted in 15 sec, then restart 73 | if time.ticks_ms() > 15000: 74 | print('- no WIFI -> reset') 75 | machine.reset() 76 | 77 | #-### 78 | #-### 79 | # -### getting ntp time 80 | try: 81 | ntptime.host = CONFIG2['ntp_host'] 82 | ntptime.settime() 83 | except: 84 | ### v52_04 if no server available, set no time, in case if no internet 85 | pass 86 | # print('LOG NTP time set') 87 | 88 | try: 89 | # if webrepl_cfg file exists then start webrepl 90 | # if not, then pass 91 | os.stat('webrepl_cfg.py') 92 | import webrepl 93 | webrepl.start() 94 | except: 95 | pass 96 | 97 | try: 98 | mqtth = umqtt.MQTTClient(CONFIG2['mqtt_usr'], CONFIG2['mqtt_srv'], user=CONFIG2['mqtt_usr'], password=CONFIG2['mqtt_pass'], port=1883) 99 | #mqtth.keepalive = 180 100 | mqtth.keepalive = 90 101 | while mqtth.connect() == 1: 102 | time.sleep(0.5) 103 | # if not conencted in 20 sec, then restart 104 | if time.ticks_ms() > 20000: 105 | print('- no MQTT -> reset') 106 | machine.reset() 107 | mqtth.ping() 108 | mqtth.set_callback(fmqtt_irq) 109 | # keepalive describes the connection lifetime, 0 means not defined 110 | #mqtth.keepalive = 1 111 | except: 112 | pass 113 | 114 | #-### 115 | #-### some other settings 116 | 117 | # ble.config(rxbuf=256) 118 | # ble.config(mtu=128) 119 | device_name = 'ESP32_' + str(station.ifconfig()[0].split('.')[3]) 120 | ble.config(gap_name=device_name) 121 | 122 | # -### clean up the memory and stuff 123 | CONFIG = '' 124 | del CONFIG 125 | # a lot of garbage expected :D 126 | 127 | print('= ip', str( station.ifconfig()[0] ) ) 128 | print('= time', ntptime.time() ) 129 | print('= mqtt ping', str(time.ticks_ms() - mqtth.last_cpacket) ) 130 | print('+ booted') 131 | 132 | del micropython 133 | gc.collect() 134 | # -### BOOTED 135 | # -### end 136 | -------------------------------------------------------------------------------- /code/main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: ascii -*- 2 | # -### main.py 3 | """ 4 | This is main code part. 5 | 6 | TODO 7 | add presence sensor based on ble trackers 8 | add other temperature sensors 9 | """ 10 | 11 | CONFIG2['__author__'] = "Dr.JJ" 12 | CONFIG2['__version__'] = '54_09' #2023 12 20 13 | CONFIG2['debug'] = 0 14 | 15 | # send print to dev null if not debug, verbose 16 | def print2(*args, **kwargs): 17 | ### substitute print 18 | fullstr = " ".join(map(str,args)) 19 | if CONFIG2['debug'] == 1: 20 | print( "= " + fullstr, **kwargs ) 21 | # else print nothing, to dev null 22 | #else: 23 | # pass 24 | loglenght = 5 25 | # 26 | if CONFIG2['debug'] == 10: 27 | global ERRORLOG 28 | ERRORLOG = ERRORLOG[0:loglenght] 29 | if fullstr.strip() == str(ERRORLOG[0].split(":")[1]).strip(): 30 | ERRORLOG[0] = str(int(time.time())) + ': ' + str(fullstr) 31 | else: 32 | ERRORLOG.insert( 0, str(int(time.time())) + ': ' + str(fullstr) ) 33 | return 34 | 35 | # ### define global variables 36 | VGLOB = {} 37 | # 38 | ### v52_40 works best with micropython 1.19 and 1.20 39 | # version details: ascii, ram clean, shorter delays, stability, fix ble-wifi-mqtt 40 | # 41 | VGLOB['status'] = 8 # 8=disconnected 42 | #VGLOB['timescan'] = time.time() 43 | VGLOB['timeup'] = time.time() 44 | VGLOB['timelast'] = time.time() 45 | VGLOB['timework'] = time.time() 46 | #VGLOB['timecheck'] = time.time() 47 | VGLOB['timentp'] = 0 48 | VGLOB['timedisc'] = 0 49 | VGLOB['flood'] = 0 50 | ERRORLOG = [str(int(time.time())) + ": BOOT"] 51 | ## 52 | 53 | # this does not change much if 2 or 3, but it gives more time to connect 54 | VGLOB['delaywork'] = 2.5 # in seconds, delay for switching to next device 55 | # it is possible to make query more often, but good RSSI is important for fast responses 56 | ## 57 | VGLOB['delayquery'] = 55 # in seconds, delay between automated queries, for thermostates and thermometers 58 | ## 59 | VGLOB['delaycheck'] = 60 # in seconds, check for scan, connections - ble, mqtt and wifi 60 | 61 | # -#### global variables 62 | VSCAN_LIST = {} 63 | VWORK_LIST = {} 64 | VMQTT_SUB_LIST = [] 65 | VMQTT_SUB_LIST.append( CONFIG2['mqtt_eq3_in'] ) 66 | 67 | try: 68 | # load white list 69 | fff = open('wl.txt', 'r') 70 | vwork_temp = str( fff.read() ) 71 | vwork_temp = eval( vwork_temp ) 72 | for jjj, val in vwork_temp.items(): 73 | VWORK_LIST[jjj] = [val[0], time.time() + 30, None, 8, [], None] 74 | #mac = str( jjj[9:17].replace(":", "") ) 75 | mac = str(jjj.replace(":", "")[6:12]) 76 | VMQTT_SUB_LIST.append(f'{CONFIG2['mqtt_eq3']}{mac}/radin/mode') 77 | VMQTT_SUB_LIST.append(f'{CONFIG2['mqtt_eq3']}{mac}/radin/temp') 78 | fff.close() 79 | # load saved work list 80 | fff = open('temp.txt', 'r') 81 | vwork_temp = str( fff.read() ) 82 | if len( vwork_temp ) > 10: 83 | vwork_temp = eval( vwork_temp ) 84 | for jjj, val in vwork_temp.items(): 85 | VWORK_LIST[jjj][4] = val[4] 86 | fff.close() 87 | ## cleanup temp.txt 88 | fff = open('temp.txt', 'w') 89 | fff.close() 90 | # 91 | del vwork_temp, jjj, fff, val, mac 92 | print2("BOOT config loaded") 93 | #gc.collect() 94 | except Exception as e: 95 | print2('BOOT load fff failed, setting default, this is ok ', e) 96 | # if the above fails for whatever reason, start with clean white list 97 | VWORK_LIST['00:00:00:00:00:00'] = [None, time.time() + 30, None, 8, [], None] 98 | print2("BOOT empty config created") 99 | 100 | #-#### 101 | #-#### 102 | #-#### import and extra functions 103 | 104 | # this is not needed in boot 105 | # moved from boot v52_51 106 | import uasyncio as asyncio 107 | import _thread 108 | # separated some functions v53_01 109 | from main2 import fdecode_addr, fcode_addr, ffind_handle, ffind_status, fdisc, fstopscan, fdisconnect, freset 110 | 111 | #-#### 112 | #-#### 113 | # -#### handy functions 114 | 115 | def fnow(nowtime: int = 0, ttt: str = "s", time=time) -> str: 116 | # typing time.time in default value does not work 117 | if nowtime == 0: 118 | nowtime = time.time() 119 | # 120 | localtime = time.gmtime(int(nowtime) + 3600) # +1H 121 | # return(cet) 122 | if ttt == "m": 123 | return "{0:04d}-{1:02d}-{2:02d}".format(*localtime) + " {3:02d}:{4:02d}".format(*localtime) 124 | if ttt == "h": 125 | return "{0:04d}-{1:02d}-{2:02d}".format(*localtime) + " {3:02d}".format(*localtime) 126 | if ttt == "d": 127 | return "{0:04d}-{1:02d}-{2:02d}".format(*localtime) 128 | else: 129 | return "{0:04d}-{1:02d}-{2:02d}".format(*localtime) + " {3:02d}:{4:02d}:{5:02d}".format(*localtime) 130 | 131 | ### start scanning, was 15 sec, is 10, now 20 132 | def fscan(duration: int = 0) -> None: 133 | gc.collect() 134 | #global VGLOB # v53_18 not needed 135 | global VWORK_LIST 136 | print2('scan start') 137 | #VGLOB['timescan'] = time.time() 138 | VWORK_LIST['00:00:00:00:00:00'][1] = time.time() 139 | if len( VWORK_LIST['00:00:00:00:00:00'][4] ) > 0: 140 | # usually started from list, but in case of the first or manual scan catch error 141 | VWORK_LIST['00:00:00:00:00:00'][4].pop(0) 142 | ### 143 | try: 144 | #fpostpone(5) #maybe not necessary 50_11 145 | if int(duration) == 0: 146 | # infinite scan 147 | ble.gap_scan(0, 100000, 30000, 1) 148 | elif int(duration) == -1: 149 | # scan stop 150 | ble.gap_scan(0) 151 | elif int(duration) > 25: 152 | ble.gap_scan(int(duration) * 1000, 100000, 30000, 1) 153 | else: 154 | ble.gap_scan(int(duration) * 1000, 80000, 40000, 1) 155 | except Exception as e: 156 | print2('scan already running ', e) 157 | return 158 | ### v52_07 this part moved after scan test 159 | ### delay other devices, for the a nice scan 160 | ### ERRORs, but solved with time.time 161 | for ffaddr in list(VWORK_LIST): 162 | ### v52_02 update only times which are due, do not set back the timer 163 | if ffaddr != '00:00:00:00:00:00' and VWORK_LIST[ffaddr][1] < time.time(): 164 | ### postpone all work, but not set back time 165 | ### v52_10 was 10, but changed to 5 as scan is startet almost in every idle moment 166 | #pass 167 | VWORK_LIST[ffaddr][1] = time.time() + 5 168 | ### 169 | gc.collect() 170 | return 171 | 172 | ### time=time, ntptime=ntptime 173 | def fntp() -> None: 174 | print2('set time ntp') 175 | VGLOB['timentp'] = time.time() 176 | try: 177 | ntptime.settime() 178 | ### v52_11 add file timestamp 179 | fff = open('temp.txt', 'w') 180 | fff.close() 181 | #del fff 182 | except: 183 | pass 184 | return 185 | 186 | # 187 | def fpostpone(postpone: int = 0) -> None: 188 | VGLOB['timework'] = time.time() + ( postpone ) 189 | #VGLOB['timescan'] = time.time() + ( postpone ) 190 | VGLOB['timedisc'] = time.time() + ( postpone ) 191 | return 192 | 193 | #-#### 194 | #-#### 195 | # -#### load white lists 196 | #### 197 | # definition of VWORK_LIST 198 | # [ last_work, last_check, handle, status, work, work done - for devices sending a lot of ble ] 199 | 200 | #-#### 201 | #-#### 202 | # -#### main ble writer 203 | 204 | def fble_write(addr: str, data1: str, data2: str='') -> None: 205 | #gc.collect() 206 | # ### main loop 207 | # ### try connection 20 times, if succesful stop the loop 208 | print2("fblew work") 209 | mac_type = str(addr.replace(":", "")[0:6]) 210 | # 211 | if (mac_type == '4C65A8' or mac_type == 'A4C138') and data1 == 'gettemp': 212 | data1 = 0x10 213 | data2 = b'\x01\x00' 214 | elif mac_type == '001A22' and data1 == 'settemp' and (str(data2).split('.')[0]).isdigit(): 215 | data1 = 0x0411 216 | ### ver 51_29, set max temp to 30.0 as it may be ON setting 217 | if float(data2) > 30.0: 218 | data2 = 30.0 219 | ### ver 51_29, set min temp to 4.5 as it switches the EQ3 into OFF setting, recommended by wieluk-github 220 | if float(data2) < 4.5: 221 | data2 = 4.5 222 | data2 = '\x41' + chr(int(round(2 * float(data2)))) 223 | elif mac_type == '001A22' and data1 == 'manual': 224 | data1 = 0x0411 225 | data2 = '\x40\x40' 226 | # ### if no issue with above 227 | # ### and variables cleaned, try to write 228 | try: 229 | fhandle = VWORK_LIST[addr][2] 230 | #ble.gattc_write(VGLOB['handle'], data1, data2, 1) 231 | ### BLE WRITE 232 | ble.gattc_write(fhandle, data1, data2, 1) 233 | print2('fblew write') 234 | except Exception as e: 235 | print2('fblew exc write:', e) 236 | # 237 | # ### if loop ended or break then try to disconnect, set status to disconnected 238 | try: 239 | # if run as thread, then stop thread 240 | _thread.exit() 241 | #pass 242 | except Exception as e: 243 | # if this fails, there is no reason to panic, function not in thread 244 | print2('fblew close thread:', e) 245 | gc.collect() 246 | return 247 | 248 | #-#### 249 | #-#### 250 | # -#### main function to handle irqs from mqtt 251 | 252 | 253 | def fble_irq(event, data) -> None: 254 | #gc.collect() 255 | # interrupt triggered by ble 256 | # usually only if connection is processed 257 | global VWORK_LIST 258 | global VSCAN_LIST 259 | global VGLOB 260 | # ### get event variable and publish global so other threads react as needed 261 | VGLOB['status'] = event 262 | #print2( "f ble irq", event) 263 | ### v53_31 not needed here 264 | #try: 265 | # wdt.feed() 266 | #except Exception as e: 267 | # print2('fbleirq wdt error, maybe not yet initialised ', e) 268 | # do not print scans, event 5 269 | #if event not in [5, 6, 18]: # 17 270 | # print2('fbleirq ', event, ', ', list(data)) 271 | ### SET current time for this run 272 | ftimenow = time.time() 273 | # ### 274 | if event == 5: # _IRQ_SCAN_RESULT 275 | # ### scan results, and publish gathered addresses in VSCAN_LIST 276 | addr_type, addr, adv_type, rssi, adv_data = data 277 | # skip nonrequested responses 278 | if adv_type == 0: 279 | return 280 | # ignore randomised addr 281 | if addr_type == 1: 282 | return 283 | # ignore detections with very low signal, -92 is enough, below -94 strong delays with connection 284 | ### v51_30, lowering to 91 from 92, as the new antena improves the signal enough 285 | if int(rssi) < -91: 286 | return 287 | # special case for presence sensors with FF:FF addresses 288 | addrd = str(fdecode_addr(addr)) 289 | mac = str(addrd.replace(":", "")[6:12]) 290 | mac_type = str(addrd.replace(":", "")[0:6]) 291 | #print2('fbleirq ', addrd, addr_type, adv_type, adv_data_dec) 292 | ### 293 | ### this has to before rewriting last seen time 294 | if addrd in VWORK_LIST and addrd in VSCAN_LIST: 295 | if mac_type[0:4] == 'FFFF' and time.time() > VSCAN_LIST[addrd][3] + 5: 296 | #print2('fbleirq ', addrd, bytes(adv_data)) 297 | #msg_out = '{"id":"' + mac + '","name":"tracker' + mac + '","location":"'+ str(CONFIG2['mqtt_usr']) +'","timestamp":' + str(time.time()) + '}' 298 | msg_out = '{"payload":"' + str(CONFIG2['mqtt_usr']) + '", "location":"'+ str(CONFIG2['mqtt_usr']) +'" }' 299 | topic_out = CONFIG2['mqtt_presence'] + mac + '/radout/status' 300 | mqtth.publish(topic_out, bytes(msg_out, 'ascii')) 301 | # #VSCAN_LIST[addrd][3] = time.time() 302 | ### 303 | if mac_type[0:4] == 'FFFF' and adv_type == 0: 304 | adv_type = 4 305 | # this has to be like this, to pass through the cleaner later 306 | adv_data = b'__Tracker' 307 | #adv_data_dec = 'Tracker' 308 | ### only full detections, with names, so adv_type == 4 309 | # v52_33 opt code 310 | adv_data_dec = bytes(x for x in bytes(adv_data)[2:22].split(b'\xff')[0] if x >= 0x20 and x < 127).decode("ascii").strip() 311 | if adv_type == 4: 312 | #print2( str(bytes(adv_data)[2:24].split(b'\xff')[0] ) ) 313 | VSCAN_LIST[addrd] = [bytes(addr), rssi, adv_data_dec, time.time()] 314 | ### here actions for addresses in the list 315 | #if addr_decode[0:8] == '4C:65:A8' or addr_decode == 'A4:C1:38': 316 | # clean after each new result 317 | elif event == 6: # _IRQ_SCAN_DONE 318 | #vwebpage = fwebpage() 319 | # ### scan done and cleanup, reseting variables as needed 320 | # 31 added 321 | VGLOB['status'] = 8 322 | #VGLOB['result'] = 0 323 | # new 324 | gc.collect() 325 | print2('fbleirq scan done') 326 | elif event == 7: # _IRQ_PERIPHERAL_CONNECT 327 | # ### connected 7 328 | handle, addr_type, addr = data 329 | addrd = fdecode_addr(addr) 330 | #del data 331 | #del addr_type 332 | #del addr 333 | #print2( addrd ) 334 | # do not change the time with connect, but time changes only if irq successful 335 | #VWORK_LIST[ addrd ][1] = time.time() 336 | VWORK_LIST[addrd][1] = time.time() 337 | VWORK_LIST[addrd][2] = handle 338 | VWORK_LIST[addrd][3] = event 339 | print2('fbleirq connected') 340 | elif event == 8: # _IRQ_PERIPHERAL_DISCONNECT 341 | # ### disconnected 8, do actions 342 | gc.collect() 343 | handle, addr_type, addr = data 344 | addrd = fdecode_addr(addr) 345 | #del data 346 | #del handle 347 | #del addr_type 348 | #del addr 349 | ### v52_05 do not set time here 350 | #VWORK_LIST[addrd][1] = time.time() 351 | VWORK_LIST[addrd][2] = None # this is handle 352 | VWORK_LIST[addrd][3] = event 353 | ### v52_14 save the temp value, not a good idea 354 | ### v52_28 -check 355 | #print2( str( eval( VWORK_LIST[addrd][5] )['temp'] ) ) 356 | ### v53_11 - added delay for worker and OFF info 357 | try: 358 | #print2( str( eval( VWORK_LIST[addrd][5] )['temp'] ) ) 359 | if str( eval( VWORK_LIST[addrd][5] )['temp'] ) == '4.5': 360 | #print2( 'delaying check while thermostat is OFF' ) 361 | VWORK_LIST[addrd][1] = time.time() + ( 2 * VGLOB['delayquery'] ) 362 | VWORK_LIST[addrd][5] = 'OFF' 363 | else: 364 | VWORK_LIST[addrd][5] = None 365 | except: 366 | VWORK_LIST[addrd][5] = None # 367 | pass 368 | #VWORK_LIST[addrd][1] = time.time() 369 | #VWORK_LIST[addrd][5] = None 370 | # written, so remove from work list 371 | #VGLOB['addr'] = '' 372 | VGLOB['timelast'] = time.time() 373 | #VGLOB['work'] = '' 374 | #gc.collect() 375 | elif event == 17: # 17 _IRQ_GATTC_WRITE_DONE 376 | # ### write to device 377 | handle, value_handle, status = data 378 | addrd = ffind_handle(VWORK_LIST, handle) 379 | #del data 380 | #del handle 381 | #del value_handle 382 | #del status 383 | # update work times, but do not remove work list (until response) 384 | ### v52_05 do not set time here 385 | #VWORK_LIST[addrd][1] = time.time() 386 | VWORK_LIST[addrd][3] = event 387 | ### 388 | #VGLOB['handle'] = handle 389 | #VGLOB['result'] = 4 390 | elif event == 18: # _IRQ_GATTC_NOTIFY 391 | # ### getting ble notification irq 392 | handle, value_handle, notify_data = data 393 | addrd = ffind_handle(VWORK_LIST, handle) 394 | # 395 | #del data 396 | #del handle 397 | #del value_handle 398 | # 399 | VWORK_LIST[addrd][1] = time.time() 400 | VWORK_LIST[addrd][3] = event 401 | # written, so remove from work list 402 | #VWORK_LIST[addrd][4] = None 403 | if len( VWORK_LIST[addrd][4] ) > 0: 404 | VWORK_LIST[addrd][4].pop(0) # pop first value from the list, if written correctly 405 | #VWORK_LIST[ addrd ][5] = notify_data 406 | ### 407 | msg_out = None 408 | ### 409 | ### 410 | #VGLOB['data'] = notify_data 411 | #VGLOB['addr'] = addrd 412 | #mac = str(addrd[9:17].replace(":", "")) 413 | mac = str(addrd.replace(":", "")[6:12]) 414 | mac_type = str(addrd.replace(":", "")[0:6]) 415 | ### 416 | # new 417 | #type( VWORK_LIST[fworkout][5] ) == int: 418 | #if (mac_type == '4C65A8' or mac_type == 'A4C138') and VWORK_LIST[addrd][5] == None: 419 | ### v53_23 added type, as last value can be a number 420 | if (mac_type == '4C65A8' or mac_type == 'A4C138') and type( VWORK_LIST[addrd][5] ) is int: 421 | # ### only if result 3 = if notify succesful, then publish 422 | # ### create mqtt 423 | datas = str(bytes(notify_data), 'ascii').strip('\x00').strip().replace(' ', '=').split('=') 424 | msg_out = '{"trv":"' + addrd + '","temp":"' + str(datas[1]) + '","hum":"' + str(datas[3]) + '"}' 425 | #topic_out = CONFIG2['mqtt_temp_out'] 426 | #topic_out = 'esp/sensor/sensor' + str(addrd[9:17].replace(":", "")) + '/state' 427 | topic_out = CONFIG2['mqtt_thermo'] + mac + '/radout/status' 428 | # CONFIG2['mqtt_thermo'] 429 | # send only once 430 | VWORK_LIST[addrd][5] = 1 431 | ### 432 | elif mac_type == '001A22': 433 | # ### create mqtt 434 | datas = list(bytearray(notify_data)) 435 | # PRINT THIS FOR BLE DEBUG 436 | batt_out = 100 437 | if int(datas[2]) > 70: 438 | batt_out = 0 439 | msg_out = '{"trv":"' + addrd + '","temp":"' + str(float(datas[5]) / 2) + '","valve":"' + str(int(datas[3])) + '","battery":"' + str(batt_out) + '","mode":"manual","mode2":"heat"}' 440 | #topic_out = CONFIG2['mqtt_eq3_out'] 441 | topic_out = CONFIG2['mqtt_eq3'] + mac + '/radout/status' 442 | #mqtth.publish(CONFIG2['mqtt_eq3_out'], bytes(msg_out, 'ascii')) 443 | # ### if connection or writing not succesful, then re-add 444 | ### 445 | ### 446 | if msg_out != None: 447 | #print2('=== msg ===', msg_out) 448 | mqtth.publish(topic_out, bytes(msg_out, 'ascii')) 449 | #=time.sleep(0.1) 450 | #vwork_status[VGLOB['addr']] = msg_out 451 | VWORK_LIST[addrd][5] = msg_out 452 | # recache page only if something changed/sent 453 | # go to status 7 if still work to do # 50_20 454 | if len( VWORK_LIST[addrd][4] ) > 0: 455 | VWORK_LIST[addrd][3] = 7 456 | print2('fbleirq writing-notify success, but more work') 457 | else: 458 | print2('fbleirq writing-notify success, disconnecting') 459 | fdisconnect(ble, value_handle) # was ble.gap_disconnect 460 | ### 461 | gc.collect() 462 | # check if here the value changes to 8 463 | # as connection cleanup is missing 464 | else: 465 | # catch some other ble connection values 466 | print2('fbleirq unknown ble status') 467 | #gc.collect() 468 | ### 469 | ### 470 | # it would be nice to, not collect here, not to overload irq 471 | # still it might make sense 472 | #gc.collect() 473 | return 474 | 475 | #-#### 476 | #-#### 477 | #-#### 478 | 479 | def fmqtt_irq(topic, msg, aaa=False, bbb=False) -> None: 480 | #gc.collect() 481 | # ### if the check msg is started, then this function is triggered 482 | print2("fmqttirq trigger") 483 | # stop scan if any 484 | fstopscan(ble) 485 | # 486 | global VWORK_LIST 487 | if type(msg) is bytes: 488 | msg = msg.decode() 489 | if type(topic) is bytes: 490 | topic = str(topic.decode()) 491 | # ### split address and command 492 | ### 493 | ### 494 | worka = str(msg).strip().split(' ', 1) 495 | #del msg 496 | if len(worka) == 1: 497 | worka.append(worka[0]) 498 | topica = topic.replace(CONFIG2['mqtt_eq3'], "").split("/", 1)[0] 499 | # v52_33 opt code 500 | worka[0] = "00:1A:22:" + ":".join(topica[i:i + 2] for i in range(0, len(topica), 2)) 501 | print2('fmqttirq - ', str(topic), str(worka)) 502 | ### 503 | ### 504 | # 31 add 505 | # -### new approach 506 | if topic in (CONFIG2['mqtt_eq3'] + str(mmm).replace(":", "")[6:12] + "/radin/temp" for mmm in VWORK_LIST): 507 | #VWORK_LIST[worka[0]][4] = "settemp " + worka[1] 508 | workfin = "settemp " + worka[1] 509 | if workfin not in VWORK_LIST[worka[0]][4]: # do not double the work 510 | VWORK_LIST[worka[0]][4].append( "settemp " + worka[1] ) # append instead of setting the value 511 | print2('fmqttirq work added temp') 512 | elif topic in (CONFIG2['mqtt_eq3'] + str(mmm).replace(":", "")[6:12] + "/radin/mode" for mmm in VWORK_LIST): 513 | #VWORK_LIST[worka[0]][4] = worka[1] 514 | print2('fmqttirq work added mode') 515 | elif worka[0] not in list(VWORK_LIST): 516 | # if not the above, and the mac not in the list, then drop 517 | print2('fmqttirq not on list') 518 | elif len(worka[0]) == 17 and len(worka[1]) > 5 and len(worka[1]) < 14: 519 | ### part from previous approach, do not add manual, if some other command exists 520 | workfin = worka[1] 521 | if workfin not in VWORK_LIST[worka[0]][4]: # do not double the work 522 | VWORK_LIST[worka[0]][4].append( worka[1] ) #list 523 | print2('fmqttirq work added global') 524 | else: 525 | print2('fmqttirq irq bad message') 526 | # time.sleep(1) 527 | ### 528 | ### move back the clock so that this work will be done faster 529 | VWORK_LIST[worka[0]][1] -= 60 530 | #except Exception as e: 531 | # print2('-- fmqttirq work prio fail, paralel work') 532 | # ### if len 1, then scan and reset allowed 533 | # ### scan, adds scan to worklist, reset - resets immediately 534 | if len(worka) == 1: 535 | if worka[0] == 'scan': 536 | # start scan 537 | fscan(0) 538 | elif worka[0] == 'reset': 539 | # reset 540 | # machine.reset() 541 | freset(time, machine, VWORK_LIST) 542 | # ### if above not true and address not in the list, then skip 543 | gc.collect() 544 | # _thread.exit() 545 | return 546 | 547 | #-#### 548 | #-#### 549 | #-#### 550 | 551 | def fworker(var=None) -> None: 552 | ### 553 | #print2('worker started') 554 | try: 555 | wdt.feed() 556 | except Exception as e: 557 | print2('fworker wdt error, maybe not initialised ', e) 558 | ### 559 | gc.collect() 560 | global VWORK_LIST 561 | #global VGLOB 562 | # was 20, but now it is the count of the devices to test 563 | #errordelay = int( len(VWORK_LIST) * VGLOB['delaywork'] ) 564 | errordelay = 20 # it has to be slightly longer to allow scanning 565 | VGLOB['flood'] = 0 566 | #global VSCAN_LIST 567 | ### 568 | try: 569 | ### check messages 570 | ### skip check if working v53_31, to avoid overload 571 | # but do not stop worker function, as work needs to be done 572 | # was not in [7, 17, 18, 77] 573 | if VGLOB['status'] in [5, 8]: 574 | mqtth.check_msg() 575 | except Exception as e: 576 | print2('fworker mqtt check error ', e) 577 | #time.sleep(0.5) 578 | #fmqtt_recover() ### do not add this here, it should be fixed automatically 579 | return ### ADDED 580 | ### [int(aaa[2] or 0) for aaa in VWORK_LIST.values()] 581 | #if max(int(aaa[2] or 0) for aaa in VWORK_LIST.values()) > 3: 582 | if len( [aaa[5] for aaa in VWORK_LIST.values() if not 'None'] ) > 1: 583 | ### check how many ble connections open, stop if more than 3 584 | print2('fworker max simultaneous connections') 585 | return 586 | ### SET current time for this run 587 | ftimenow = time.time() 588 | ### 589 | fworkout = '' 590 | ### 591 | ### find if some device is working/connected 592 | # to continue work 593 | if fworkout == '': 594 | fworkout = ffind_status(VWORK_LIST, 7) 595 | ### 596 | ### v53_24 moved this to the end, to allow paralel connections 597 | ### find if some device finished work, and needs to be cleaned 598 | if fworkout == '': 599 | fworkout = ffind_status(VWORK_LIST, 18) 600 | ### 601 | ### get the oldest device with work 602 | # start new work only if no work is being done 603 | if fworkout == '' and VGLOB['status'] in [5, 8]: 604 | try: 605 | # shorter and cleaner 606 | ### v52_02 seleting only due work 607 | ### v52_08 bug fix, bad comparision 608 | #fworkout = min( [ iii for iii in VWORK_LIST.items() if ( len(iii[1][4])>0 and iii[0]!='00:00:00:00:00:00' and iii[1][1]0 and iii[0]!='00:00:00:00:00:00' and iii[1][1] 4: 675 | ### update the check and conn timer 676 | #VWORK_LIST[fworkout][0] = ftimenow 677 | print2('fworker tried a few times, delaying') 678 | # this happens also too often, not logging 679 | ### v51_25 adding 2 minutes 680 | ### v52_17 shortening to 10 sec, as delay time is added elsewhere 681 | ### v52_42 add more, as there were 5 retries 682 | try: 683 | #ble.gap_disconnect(VWORK_LIST[fworkout][2]) 684 | #ble.gap_disconnect(0) 685 | #ble.gap_disconnect(1) 686 | print2('fworker connect cleanup pending ', fworkout) 687 | fdisconnect(ble, 0) 688 | fdisconnect(ble, 1) 689 | VWORK_LIST[fworkout][1] = ftimenow + errordelay 690 | VWORK_LIST[fworkout][3] = 8 691 | VWORK_LIST[fworkout][5] = None 692 | except: 693 | print2('fworker connect cleanup failed ', fworkout) 694 | pass 695 | if len(VWORK_LIST[fworkout][4]) > 4: ### v51_25 was 10 is 4, how many tasks are in the list 696 | ### too much work, removing 697 | VWORK_LIST[fworkout][4].pop(0) 698 | #gc.collect() 699 | return 700 | ### no return in main if, as there might be some work to do 701 | ### 702 | ### if the above is fine, just move forward 703 | ### 704 | if VWORK_LIST[fworkout][3] not in [7, 8, 77]: 705 | # v53_21 added 77 so that waiting connection will not be cleaned up 706 | print2('fworker maybe working') 707 | ### v52_02 clean up in case of stuck device 708 | gc.collect() 709 | # TODO 710 | # if maybe working for more than 10 sec, then disconnect 711 | # it waits until next round 712 | # if ftimenow - VWORK_LIST[fworkout][1] > 10: 713 | if ftimenow - VWORK_LIST[fworkout][1] > ( VGLOB['delaywork'] * len(VWORK_LIST) ) + 5: 714 | try: 715 | #ble.gap_disconnect(VWORK_LIST[fworkout][2]) 716 | fdisconnect(ble, VWORK_LIST[fworkout][2]) 717 | except Exception as e: 718 | print2('fworker disconn warn 3 ', e) 719 | #VWORK_LIST[fworkout][1] = ftimenow + 120 ### v51_24 added 2 minutes wait 720 | VWORK_LIST[fworkout][2] = None 721 | VWORK_LIST[fworkout][3] = 8 # v53_23 722 | ### v52_02 - delaying anyway 723 | ### v51_24 added 2 minutes wait, v52_04 - 3 minutes, v52_10 changed to 1 min, v52_17 delay changed to 20 sec 724 | VWORK_LIST[fworkout][1] = ftimenow + errordelay 725 | print2("fworker connection too long") 726 | # return 727 | ### 728 | # v53_17 added new 729 | elif VWORK_LIST[fworkout][3] == 77: 730 | # 731 | if type( VWORK_LIST[fworkout][5] ) is str: # from == to is 732 | VWORK_LIST[fworkout][5] = None 733 | # longer waiting times 734 | # do not update time here, as the connection may fail 735 | VWORK_LIST[fworkout][5] = int(VWORK_LIST[fworkout][5] or 0) + 1 736 | print2("fworker waiting for connection", VWORK_LIST[fworkout][5] ) 737 | # 738 | # and VGLOB['status'] in [5, 8] 739 | elif VWORK_LIST[fworkout][3] == 8 and ftimenow > VWORK_LIST[fworkout][1]: ### v51_25 added time check 740 | ### finally, all above is fine, and work is to be done, so connect first 741 | print2("fworker connecting") 742 | ### v52_15 cleanup the value, as the detection is postponed already 743 | if type( VWORK_LIST[fworkout][5] ) is str: # from == to is 744 | VWORK_LIST[fworkout][5] = None 745 | # longer waiting times 746 | # do not update time here, as the connection may fail 747 | #VWORK_LIST[fworkout][5] = int(VWORK_LIST[fworkout][5] or 0) + 1 # v53_21 748 | VWORK_LIST[fworkout][3] = 77 # v53_14 added status change !!! to avoid reconnecting 749 | VGLOB['status'] = 77 750 | try: 751 | # increased connection time 752 | #ble.gap_connect( 0, fcode_addr(fworkout), 10000 ) 753 | ### GAP CONNECT 754 | VWORK_LIST[fworkout][5] = 1 # v53_21 755 | #ble.gap_connect( 0, fcode_addr(fworkout), int( 3 * VGLOB['delaywork'] * 1000 ) ) 756 | ble.gap_connect( 0, fcode_addr(fworkout), int( 4 * VGLOB['delaywork'] * 1000 ) ) # v53_16 longer time 4* 757 | ## v52_39 defined error exceptions added 758 | ## v52_40 improved error detection 759 | # other error [Errno 19] ENODEV 760 | except Exception as e: 761 | print2('fworker conn warn ', e, fworkout) 762 | #print2(e.__class__.__name__) 763 | if str(e).split("] ",1)[1] in ('EIO'): 764 | try: 765 | #ble.gap_disconnect(0) # v53_21 changed from 0, to an actual value 766 | #ble.gap_disconnect(VWORK_LIST[fworkout][2]) 767 | #ble.gap_disconnect(1) 768 | fdisconnect(ble, 0) 769 | fdisconnect(ble, 1) 770 | VWORK_LIST[fworkout][1] = ftimenow + errordelay 771 | VWORK_LIST[fworkout][3] = 8 # v53_15 772 | VWORK_LIST[fworkout][5] = None # v53_21 773 | except: 774 | print2('fworker connect cleanup failed ', fworkout) 775 | pass 776 | if str(e).split("] ",1)[1] in ('EALREADY'): 777 | print2('fworker connect already connected ', fworkout) 778 | # this appears every time a single connection fails, not necessary to report 779 | print2("fworker connection timeout") 780 | fpostpone() 781 | # 782 | ### 783 | ### assuming connected, so work 784 | elif VWORK_LIST[fworkout][3] in [7, 18]: 785 | print2("fworker connected, and handle available, send work") 786 | # stop scan if any 787 | fstopscan(ble) 788 | # 789 | if len( VWORK_LIST[fworkout][4] ) == 0: 790 | ### this deletes position 5 if working, is it fine ? 791 | ### clean up [5] only if no work to be done, v53_04 792 | VWORK_LIST[fworkout][5] = None 793 | ### 794 | print2("fworker, connected, but no work, disconnect") 795 | #ble.gap_disconnect(VWORK_LIST[fworkout][2]) 796 | fdisconnect(ble, VWORK_LIST[fworkout][2]) 797 | ### v52_01 - cleaning 798 | gc.collect() 799 | return 800 | # maybe not update, to do whole work in one run 801 | # select first from the work list 802 | worka = str(VWORK_LIST[fworkout][4][0]).strip().split(' ') 803 | for iii in range(max(0, 2 - len(worka))): 804 | worka.append('') 805 | ### 43 no thread 806 | _thread.start_new_thread(fble_write, (fworkout, worka[0], worka[1])) 807 | #fble_write(fworkout, worka[0], worka[1]) 808 | ### 809 | ### some other situation happened 810 | else: 811 | #mqtth.check_msg() 812 | #fscan(0) ### v51_26 added, if nothing happens then scan 813 | print2('fworker unexpected situation - no work, nothing done') 814 | gc.collect() 815 | return 816 | 817 | #-#### 818 | #-#### 819 | # -#### webpage generating function 820 | 821 | def fwebpage() -> str: 822 | html_in = "" 823 | for addr, val in VWORK_LIST.items(): 824 | html_in += str(addr) + " - " + str(val[4]) + "\n" 825 | # generate table 826 | # generate rest of html 827 | #""" + str(VGLOB) + """ 828 | html = """ 829 | 830 | 831 | EQ3 controller 832 | 833 | 834 | 835 | 836 | 837 |

EQ3 controller

838 | By Dr. JJ on ESP32 and micropython.
839 | GitHub page. 840 |

System

841 | Last work done on: """ + str(fnow(VGLOB['timelast'])) + """
842 | Last change: """ + str(fnow()) + """
843 | Boot: """ + str(fnow(VGLOB['timeup'])) + """
844 | Location: """ + str(CONFIG2['mqtt_usr']) + """
845 | IP: """ + str(station.ifconfig()[0]) + """
846 | Version: """ + str(CONFIG2['__version__']) + """ 847 |

Links:

848 | List of devices
849 | Update OTA
850 | System info
851 | Add webrepl - Webrepl console (pass: 1234)
852 |
853 | Publish MQTT autodiscovery
854 | Rescan devices
855 | Reset 856 |

List of contacted devices

857 |
 858 | """ + str(html_in) + """
 859 | 
860 |

---

861 | 862 | """ 863 | del html_in 864 | html = html.encode('ascii') 865 | #html = html.encode('latin-1') 866 | print2('fweb generating page') 867 | # 868 | #gc.collect() 869 | # 870 | return( html ) 871 | 872 | #-#### 873 | #-#### 874 | # -#### webpage loop function 875 | # -#### was based on socket, but now on async is more responsive and less consuming 876 | 877 | async def loop_web(reader, writer) -> None: 878 | flood = 0 879 | # 880 | #if VGLOB['status'] in [17, 18]: # v53_29 if working, skip page to avoid flood 881 | # detect and avoid flood earlier, v53_06, changed from 20000 to 45000 882 | if gc.mem_free() < 25000 or VGLOB['flood'] == 1:# 883 | print2('fweb page flood 1') 884 | flood = 1 885 | #return 886 | #global VGLOB 887 | VGLOB['flood'] = 1 888 | # waiting for input 889 | #recv = await reader.read(64) 890 | ### timeout here ? # v53_10 891 | # reader, writer = yield from asyncio.wait_for(fut, timeout=3) 892 | gc.collect() 893 | #global ERRORLOG 894 | try: 895 | #recvtmp = recv.decode() 896 | if flood == 0: 897 | #=await asyncio.sleep(0.1) 898 | recv = yield from reader.read(64) 899 | requesttype = recv.decode()[0:3] 900 | requestfull = recv.decode().split('\r')[0].split(' ')[1].split('?') 901 | #requestfull = requestfull # [4:-6] 902 | #recv2 = await reader.read() 903 | #print2( recv2.decode() ) 904 | else: 905 | requestfull = ['/flood'] 906 | except Exception as e: 907 | # if request invalid or malformed 908 | print2('fweb page request warn ', e) 909 | requestfull = ['/'] 910 | # continue 911 | # ? 912 | # 913 | print2('fweb serving page ', requestfull) 914 | #global VGLOB 915 | #global VSCAN_LIST 916 | request = requestfull[0] 917 | #print2(request, requestfull) 918 | requestval = '' 919 | vwebpage = b'' 920 | resp = b'' 921 | #timer2 = time.ticks_ms() 922 | #gc.collect() 923 | if len(requestfull) == 2: 924 | requestval = requestfull[1] 925 | # 926 | if request == "/": 927 | vwebpage = fwebpage() 928 | # Server-Timing: text;dur=""" + str(time.ticks_ms() - timer2) + """, req;dur=""" + str(timer2 - timer1) + """ 929 | header = """HTTP/1.1 200 OK 930 | Content-Type: text/html 931 | Content-Length: """ + str(len(vwebpage)) + """ 932 | Connection: close 933 | """ 934 | #conn.sendall(header + "\r\n" + vwebpage) 935 | await writer.awrite(header + "\r\n") 936 | # gc.collect() 937 | # INFO 938 | # continue 939 | ##### 940 | ##### 941 | elif request == "/flood": 942 | header = """HTTP/1.1 429 Too Many Requests 943 | Retry-After: 3 944 | Content-Type: text/plain 945 | Content-Length: 27 946 | Connection: close 947 | 948 | flood, retry in 1-2 seconds 949 | """ 950 | await writer.awrite(header + "\r\n") 951 | # # gc.collect() 952 | elif request == "/list": 953 | # stop scan if any 954 | fstopscan(ble) 955 | # collect 956 | gc.collect() 957 | # 958 | vwebpage = '
\n'
 959 |         vwebpage += '
\n' 960 | if len(VSCAN_LIST) > 0: 961 | vwebpage += '
MAC, last seen, rssi, name\n' 962 | for iii in VSCAN_LIST.items(): 963 | #vwebpage += 'add ' + str(iii[0]) + ' ' + \ 964 | # '{: >{w}}'.format(str(time.time() - iii[1][3]), w=5) + ' ' + str(iii[1][1]) + ' ' + str(iii[1][2]) + '\n' 965 | vwebpage += ''+ str(iii[0]) + ' ' + '{: >{w}}'.format(str(time.time() - iii[1][3]), w=5) + ' ' + str(iii[1][1]) + ' ' + str(iii[1][2]) + '\n' 966 | vwebpage += 'Type:\nnone\nclimate\ntracker\n' 967 | vwebpage += '\n' 968 | vwebpage += '
\n' 969 | else: 970 | vwebpage += '
empty list\n'
 971 |         ###
 972 |         vwebpage += '\n'
 973 |         vwebpage += '
MAC remove white listed\n' 974 | vwebpage += '
\n' 975 | for kkk in list(VWORK_LIST): 976 | if kkk == '00:00:00:00:00:00': 977 | continue 978 | vwebpage += '' + str(kkk) + '\n' 979 | vwebpage += '\n' 980 | vwebpage += '
\n' 981 | vwebpage += '
\n' 982 | ### 983 | header = """HTTP/1.1 200 OK 984 | Content-Type: text/html 985 | Content-Length: """ + str(len(vwebpage)) + """ 986 | Connection: close 987 | """ 988 | #conn.sendall(header + "\r\n" + vwebpage) 989 | await writer.awrite(header + "\r\n") 990 | # INFO 991 | # await writer.awrite(vwebpage) 992 | # conn.close() 993 | ##### 994 | ##### do all the work here 995 | ##### 996 | elif request == "/todo": 997 | #maca=E1:CF:E3:5A:04:28&type=climate&work=add 998 | #if requesttype != "POS": 999 | # #break 1000 | # return 1001 | recv2 = yield from reader.read(2000) 1002 | recv3 = recv2.decode().split('\r')[-1].replace('%3A', ':').strip().split('&') 1003 | print2('fweb', recv3) 1004 | recv3w = recv3[-1].split('=')[1] 1005 | recv3m = recv3[0].split('=')[1] 1006 | #vwork['0'] = 'scan' 1007 | header = """HTTP/1.1 200 OK 1008 | Content-Type: text/html 1009 | Content-Length: 39 1010 | Connection: close 1011 | 1012 | Work -> """ + str( recv3w ) + """, mac -> """ + str( recv3m ) + """. 1013 | """ 1014 | #conn.sendall(header + "\r\n" + vwebpage) 1015 | await writer.awrite(header + "\r\n") 1016 | # addr, time, handle, work, status 1017 | # VSCAN_LIST[str(requestval)][0] 1018 | if recv3w == "del": 1019 | #requestval = str(requestval)[0:17] 1020 | del VWORK_LIST[str(recv3m)] 1021 | elif recv3w == "add": 1022 | VWORK_LIST[str(recv3m)] = [None, time.time(), None, 8, [], None] 1023 | else: 1024 | return 1025 | filewl = open('wl.txt', 'w') 1026 | filewl.write( str(VWORK_LIST) ) 1027 | filewl.close() 1028 | ##### 1029 | ##### 1030 | ##### 1031 | elif request == "/deldo": 1032 | header = """HTTP/1.1 302 Found 1033 | Content-Length: 0 1034 | Location: /info 1035 | Connection: close 1036 | """ 1037 | # Connection: close 1038 | if requestval != '': 1039 | try: 1040 | os.remove(requestval) 1041 | except Exception as e: 1042 | # try to remove file, if fail no panic 1043 | print2('fweb deldo file does not exist ', e) 1044 | #pass 1045 | # conn.sendall(header) 1046 | await writer.awrite(header + "\r\n") 1047 | # await writer.awrite(vwebpage) 1048 | ##### 1049 | ##### 1050 | elif request == "/info": 1051 | # 1052 | if machine.reset_cause() == 0: 1053 | reset_cause = "PWRON_RESET" 1054 | elif machine.reset_cause() == 1: 1055 | reset_cause = "HARD_RESET" 1056 | elif machine.reset_cause() == 2: 1057 | reset_cause = "WDT_RESET" 1058 | elif machine.reset_cause() == 3: 1059 | reset_cause = "DEEPSLEEP_RESET" 1060 | elif machine.reset_cause() == 4: 1061 | reset_cause = "SOFT_RESET" 1062 | elif machine.reset_cause() == 5: 1063 | reset_cause = "BROWN_OUT_RESET" 1064 | else: 1065 | reset_cause = "unknown" 1066 | # 1067 | if VGLOB['status'] == 8: 1068 | status = "idle" 1069 | elif VGLOB['status'] == 5: 1070 | status = "scanning" 1071 | elif VGLOB['status'] == 1: 1072 | status = "recovering" 1073 | else: 1074 | status = "working" 1075 | # 1076 | # MQTT addresses IN:\n""" + "\n".join( [ str(aaa) for aaa in VMQTT_SUB_LIST ] ) + """ 1077 | vwebpage = """Directory listing on ESP. By writing /deldo?filename, files can be removed (dangerous). 1078 | Files with _old are safety copies after OTA, can be safely removed. 1079 | To disable webrepl, delete webrepl_cfg.py and reboot device. 1080 | 1081 | Dir: """ + str(os.listdir()) + """ 1082 | 1083 | Global variables and settings: """ + str(VGLOB) + """ 1084 | 1085 | Current time: """ + str(time.time()) + """ 1086 | 1087 | Status: """ + status + """ 1088 | 1089 | Error log:\n""" + "\n".join( ( str(aaa) for aaa in ERRORLOG ) ) + """ 1090 | 1091 | Details:\n""" + "\n".join( ( str(aaa) for aaa in VWORK_LIST.items() ) ) + """ 1092 | 1093 | Reset cause: """ + str(reset_cause) + """ 1094 | Micropython version: """ + str(os.uname()) + """ 1095 | Free RAM: """ + str(gc.mem_free()) + """.""" 1096 | # v52_33 above, code opt 1097 | #vwebpage = vwebpage.encode('latin-1') 1098 | vwebpage = vwebpage.encode('ascii') 1099 | # 1100 | header = """HTTP/1.1 200 OK 1101 | Content-Type: text/plain 1102 | Content-Length: """ + str(len(vwebpage)) + """ 1103 | Connection: close 1104 | """ 1105 | #conn.sendall(header + "\r\n" + vwebpage) 1106 | await writer.awrite(header + "\r\n") 1107 | # INFO 1108 | # await writer.awrite(vwebpage) 1109 | # conn.close() 1110 | ##### 1111 | ##### 1112 | elif request == "/webrepl": 1113 | #requestval = requestfull.split('\r')[0].split(' ')[1].split('?')[1] 1114 | #vwebpage = str(requestval) + "\n" + str(os.listdir()) 1115 | try: 1116 | fff = open('webrepl_cfg.py', 'w') 1117 | await fff.write("PASS = \'1234\'\n") 1118 | fff.close() 1119 | except Exception as e: 1120 | print2('fweb webrepl init issue ', e) 1121 | # try to open file, if fail no panic 1122 | #pass 1123 | header = """HTTP/1.1 302 Found 1124 | Content-Length: 0 1125 | Location: /reset 1126 | Connection: close 1127 | """ 1128 | #conn.sendall(header + "\r\n" + vwebpage) 1129 | await writer.awrite(header + "\r\n") 1130 | # await writer.awrite(vwebpage) 1131 | # machine.reset() 1132 | ##### 1133 | ##### 1134 | elif request == "/scan": 1135 | #vwork['0'] = 'scan' 1136 | header = """HTTP/1.1 200 OK 1137 | Content-Type: text/html 1138 | Content-Length: 15 1139 | Connection: close 1140 | 1141 | Scan scheduled. 1142 | """ 1143 | #conn.sendall(header + "\r\n" + vwebpage) 1144 | VWORK_LIST['00:00:00:00:00:00'][4].append( 'scan' ) 1145 | await writer.awrite(header + "\r\n") 1146 | # await writer.awrite(vwebpage) 1147 | elif request == "/mqttauto": 1148 | # fpostpone() 1149 | fdisc(mqtth, VWORK_LIST, CONFIG2) 1150 | header = """HTTP/1.1 200 OK 1151 | Content-Type: text/html 1152 | Content-Length: 30 1153 | Connection: close 1154 | 1155 | MQTT Autodiscovery published. 1156 | """ 1157 | #conn.sendall(header + "\r\n" + vwebpage) 1158 | await writer.awrite(header + "\r\n") 1159 | # await writer.awrite(vwebpage) 1160 | ##### 1161 | ##### 1162 | elif request == "/purge": 1163 | fclean(1) 1164 | header = """HTTP/1.1 200 OK 1165 | Content-Type: text/html 1166 | Content-Length: 77 1167 | Connection: close 1168 | 1169 | Old devices removed from the list and if necessary the work status was reset. 1170 | """ 1171 | #conn.sendall(header + "\r\n" + vwebpage) 1172 | await writer.awrite(header + "\r\n") 1173 | # await writer.awrite(vwebpage) 1174 | ##### 1175 | ##### 1176 | elif request == "/ota": 1177 | # postpone job, to speed up ota 1178 | fpostpone() 1179 | # method="post" 1180 | vwebpage = """
Usually upload main.py file. Sometimes boot.py file. Binary files do not work yet.
1181 | 
1182 |
1183 | 1184 | 1185 |
1186 |
""" 1187 | header = """HTTP/1.1 200 OK 1188 | Content-Type: text/html 1189 | Content-Length: """ + str(len(vwebpage)) + """ 1190 | Connection: close 1191 | """ 1192 | #conn.sendall(header + "\r\n" + vwebpage) 1193 | await writer.awrite(header + "\r\n") 1194 | # INFO 1195 | # await writer.awrite(vwebpage) 1196 | ##### 1197 | ##### 1198 | elif request == "/otado": 1199 | # postpone job, to speed up ota 1200 | fpostpone() 1201 | # stop scan if any 1202 | fstopscan(ble) 1203 | # 1204 | vwebpage = '' 1205 | #VGLOB = '' 1206 | #VSCAN_LIST = {} 1207 | #gc.collect() 1208 | # s.setblocking(0) 1209 | ### v52_09 automatic reset after upload 1210 | # Location: /reset 1211 | header = """HTTP/1.1 302 Found 1212 | Content-Length: 0 1213 | Location: / 1214 | Connection: close 1215 | 1216 | """ 1217 | # = 1218 | #ble.active(False) 1219 | #gc.collect() 1220 | #headerin = conn.recv(500).decode() 1221 | headerin = yield from reader.read(500) 1222 | # print2(headerin) 1223 | headerin = headerin.decode() 1224 | boundaryin = headerin.split("boundary=", 2)[1].split('\r\n')[0] 1225 | lenin = int(headerin.split("\r\nContent-Length: ", 2)[1].split('\r\n')[0]) 1226 | # dividing into 2000 bytes pieces 1227 | bufflen = round(lenin / float(str(round(lenin / 2500)) + ".5")) 1228 | #lenin = 0 1229 | #print2( "===" ) 1230 | begin = 0 1231 | try: 1232 | os.remove('upload') 1233 | except Exception as e: 1234 | # try to upload file, if fail no panic 1235 | print2('fweb otado cleaning fail 1, this is fine', e) 1236 | #pass 1237 | fff = open('upload', 'wb') 1238 | while True: 1239 | #dataaa = conn.recv(bufflen).decode().split('\r\n--' + boundaryin, 2) 1240 | dataaa = yield from reader.read(bufflen) 1241 | dataaa = dataaa.decode().split('\r\n--' + boundaryin, 2) 1242 | splita = len(dataaa) 1243 | #print2( splita ) 1244 | #filein += dataaa 1245 | if begin == 0 and splita == 3: 1246 | #print2( "= short" ) 1247 | # short 1248 | # conn.sendall(header) 1249 | # conn.close() 1250 | await writer.awrite(header + "\r\n") 1251 | namein = dataaa[1].split(' filename="', 1)[1].split('"\r\n', 1)[0] 1252 | fff.write(dataaa[1].split('\r\n\r\n', 1)[1]) 1253 | # done with success 1254 | begin = 3 1255 | break 1256 | if begin == 0 and splita == 2: 1257 | #print2( "= first" ) 1258 | # first 1259 | namein = dataaa[1].split(' filename="', 1)[1].split('"\r\n', 1)[0] 1260 | fff.write(dataaa[1].split('\r\n\r\n', 1)[1]) 1261 | begin = 1 1262 | elif begin == 1 and splita == 1: 1263 | #print2( "= middle" ) 1264 | # middle 1265 | fff.write(dataaa[0]) 1266 | elif begin == 1 and splita == 2: 1267 | #print2( "= last" ) 1268 | # last 1269 | # conn.sendall(header) 1270 | await writer.awrite(header + "\r\n") 1271 | # conn.close() 1272 | fff.write(dataaa[0]) 1273 | # done with success 1274 | begin = 3 1275 | break 1276 | fff.close() 1277 | # now replace new file 1278 | if begin == 3: 1279 | try: 1280 | os.remove(namein + "_old") 1281 | except Exception as e: 1282 | print2('fweb otado cleaning fail 2, this is fine', e) 1283 | #pass 1284 | try: 1285 | os.rename(namein, namein + "_old") 1286 | except Exception as e: 1287 | print2('fweb otado cleaning fail 3, this is fine', e) 1288 | os.rename('upload', namein) 1289 | #print2( "===" ) 1290 | #print2( namein ) 1291 | #print2( lenin ) 1292 | dataaa = '' 1293 | ### v52_10 1294 | ### added wait time, so that header is nicely sent 1295 | await asyncio.sleep(0.3) 1296 | freset(time, machine, VWORK_LIST) 1297 | #ble.active(True) 1298 | #gc.collect() 1299 | ##### 1300 | ##### 1301 | elif request == "/reset": 1302 | fpostpone() 1303 | header = """HTTP/1.1 200 OK 1304 | Content-Type: text/html 1305 | Content-Length: 34 1306 | Connection: close 1307 | 1308 | Do reset ? 1309 | """ 1310 | # Connection: close 1311 | # conn.sendall(header) 1312 | await writer.awrite(header + "\r\n") 1313 | # await writer.awrite(vwebpage) 1314 | # conn.close() 1315 | # time.sleep(2) # no sleep here ;) 1316 | ##### 1317 | ##### 1318 | elif request == "/resetdo": 1319 | header = """HTTP/1.1 302 Found 1320 | Content-Length: 0 1321 | Location: / 1322 | Connection: close 1323 | 1324 | """ 1325 | # Connection: close 1326 | # conn.sendall(header) 1327 | await writer.awrite(header + "\r\n") 1328 | # await writer.awrite(vwebpage) 1329 | # conn.close() 1330 | # time.sleep(2) # no sleep here ;) 1331 | await asyncio.sleep(0.3) # was 0.3, 0.1 was not good 1332 | #machine.reset() 1333 | freset(time, machine, VWORK_LIST) 1334 | # time.sleep(1) 1335 | ##### 1336 | ##### 1337 | else: 1338 | # Server-Timing: text;dur=""" + str(time.ticks_ms() - timer2) + """, req;dur=""" + str(timer2 - timer1) + """ 1339 | header = """HTTP/1.0 404 Not Found 1340 | Content-Type: text/plain 1341 | Content-Length: 23 1342 | Connection: close 1343 | 1344 | 404 No page like this. 1345 | """ 1346 | # conn.sendall(header) 1347 | await writer.awrite(header + "\r\n") 1348 | # await writer.awrite(vwebpage) 1349 | # conn.close() 1350 | # END IF 1351 | # conn.close() # close or not ? 1352 | # whatever 1353 | try: 1354 | await writer.awrite(vwebpage) 1355 | #=await asyncio.sleep(0.1) 1356 | await writer.drain() 1357 | except Exception as e: 1358 | print2('fweb page flood 2a', e) 1359 | #vwebpage = b'' 1360 | #resp = b' 1361 | return 1362 | # drain and sleep needed for good transfer 1363 | vwebpage = b'' 1364 | resp = b'' 1365 | # 0.3 is perfect, 0.4 makes delay issues, 0.2 breaks the connections sometimes 1366 | await asyncio.sleep(0.2) 1367 | # waiting until everything is sent, to close 1368 | try: 1369 | await reader.wait_closed() 1370 | except Exception as e: 1371 | print2('fweb page flood 2c', e) 1372 | # await reader.aclose() 1373 | #gc.collect() 1374 | #await asyncio.sleep(0.1) 1375 | #print2("-- f serving page done") 1376 | try: 1377 | # if run as thread, then stop thread 1378 | if not CONFIG2['loop']: 1379 | _thread.exit() 1380 | return 1381 | #pass 1382 | except Exception as e: 1383 | # if this fails, there is no reason to panic, function not in thread 1384 | print2('fweb loop_web close thread:', e) 1385 | # break 1386 | # catch OSError: [Errno 104] ECONNRESET ? 1387 | return 1388 | 1389 | #-#### 1390 | #-#### 1391 | #-#### check function, should be async as it causes locks 1392 | 1393 | def fcheck(var=None) -> None: 1394 | ### 1395 | ### check function run for cleaning, usually every 1-5 minutes 1396 | ### 1397 | ### var is needed, as this function is started in timer, which sends some arguments 1398 | ### 1399 | ### check of station/wifi, mqtt, ble, webpage server, ntptime, and watchdog 1400 | # do not stop scanning, but also do not return if scanning 50_11 1401 | # always collect here 1402 | gc.collect() 1403 | # check log 1404 | print2('fcheck start') 1405 | ### not needed here as already in fworker, v53_07 1406 | #try: 1407 | # wdt.feed() 1408 | #except Exception as e: 1409 | # print2('- fcheck wdt error, maybe not initialised ', e) 1410 | ### 1411 | ### 1412 | try: 1413 | mqtth.ping() 1414 | except Exception as e: 1415 | print2('fcheck mqtt ping error ', e) 1416 | #fmqtt_recover() 1417 | ### 1418 | global VGLOB 1419 | # do not stop if scanning 50_11 1420 | if VGLOB['status'] == 5: 1421 | print2('fcheck stopping scan') 1422 | # stop scan if any 1423 | fstopscan(ble) 1424 | #gc.collect() 1425 | #return 1426 | ### if all is fine, then get some globals first 1427 | global VSCAN_LIST 1428 | global VWORK_LIST 1429 | ftimenow = time.time() 1430 | ### 1431 | ### 1432 | # if still no work done - enforce reset 1433 | # should be slightly longer than router or mqtt server reboot, just in case 1434 | if ftimenow > ( VGLOB['timelast'] + ( VGLOB['delayquery'] * 6 ) ): 1435 | # 3 rounds no response, resetting 1436 | print2('fcheck reset recover') 1437 | ### here add job saving etc 1438 | freset(time, machine, VWORK_LIST) 1439 | # 1440 | # v52_35 readded the check, if no work is done in a few rounds 1441 | if ble.active() == False: #or ftimenow > ( VGLOB['timelast'] + (3 * VGLOB['delayquery'] ) ): 1442 | #or VGLOB['timescan'] > ( VGLOB['timelast'] + (2 * VGLOB['delayquery'] ) ): 1443 | print2('fcheck ble error') 1444 | #fpostpone(5) 1445 | ble.active(False) ### ADDED 1446 | time.sleep(0.1) ### ADDED, was 0.5 1447 | ble.active(True) 1448 | #gc.collect() 1449 | return 1450 | # fble_recover() 1451 | # 1452 | if station.isconnected() == False or station.ifconfig()[0] == '0.0.0.0': 1453 | print2('fcheck wifi error') 1454 | #fpostpone(5) 1455 | station.connect() 1456 | #gc.collect() 1457 | return 1458 | # machine.reset() 1459 | ### 1460 | ### this is in ms, most other calculations for time are in seconds 1461 | # v52_45 changed to 3 minutes, from 5 1462 | if time.ticks_ms() - mqtth.last_cpacket > 3 * 60 * 1000: 1463 | print2('fcheck bad mqtt') 1464 | # postpone is in the function recovery already, 50_7 1465 | #fpostpone(5) 1466 | # has to be in thread 1467 | _thread.start_new_thread(fmqtt_recover, ()) 1468 | #fmqtt_recover() 1469 | #gc.collect() 1470 | return 1471 | ### 1472 | ### remove addresses older than x minutes, clean up old 1473 | ### v51_30, previously it was 20 minutes, now lowering to 10 1474 | ### v51_31, now lowering to 7 minutes 1475 | #last_contact = 9999 1476 | # this concerns VSCAN_LIST and not VWORK_LIST 1477 | for addr, val in VSCAN_LIST.items(): 1478 | if ftimenow - val[3] > 7 * 60: 1479 | VSCAN_LIST.pop(addr) 1480 | ### 1481 | ### check ntp every 12 hours, v52_11 changed from 24h to 12h, with error catching 1482 | if ftimenow - VGLOB['timentp'] > 12 * 60 * 60: 1483 | VGLOB['timentp'] = ftimenow 1484 | fntp() 1485 | ### 1486 | ### check autodiscovery every 1 hours 1487 | if ftimenow - VGLOB['timedisc'] > 1 * 60 * 60: 1488 | VGLOB['timedisc'] = ftimenow 1489 | fdisc(mqtth, VWORK_LIST, CONFIG2) 1490 | ### 1491 | ### if some minutes from the last contact, then scan 1492 | # INFO: optimisations for scan scheduling make no sense, start every 1 minute 1493 | # here I use the global variable timescan 1494 | # still the VWORK_LIST['00:00:00:00:00:00'][0] system variable last work could be used 1495 | ### 1496 | ### v52_04 - TODO increase delay for OFF 1497 | if ftimenow - VGLOB['timework'] > VGLOB['delayquery']: 1498 | VGLOB['timework'] = ftimenow 1499 | for addr, val in VWORK_LIST.items(): 1500 | # check if not connected [2] == None 1501 | # possible to check if no work [4] == None 1502 | #if ftimenow - val[1] > VGLOB['delayquery'] and VGLOB['timework']and val[2] == None and addr.replace(":", "")[0:6] == '001A22': 1503 | if val[2] == None and addr.replace(":", "")[0:6] == '001A22': 1504 | if len( VWORK_LIST[addr][4] ) == 0: 1505 | VWORK_LIST[addr][4].append( 'manual' ) 1506 | #VWORK_LIST['00:00:00:00:00:00'][1] = time.time() 1507 | #if ftimenow - val[1] > VGLOB['delayquery'] and val[2] == None and addr.replace(":", "")[0:6] == '4C65A8': 1508 | if val[2] == None and addr.replace(":", "")[0:6] == '4C65A8': 1509 | if len( VWORK_LIST[addr][4] ) == 0: 1510 | VWORK_LIST[addr][4].append( 'gettemp' ) 1511 | #VWORK_LIST['00:00:00:00:00:00'][1] = time.time() 1512 | ### 1513 | ### 1514 | ### if no work then start long scan 1515 | gc.collect() 1516 | #_thread.exit() 1517 | #VGLOB['status'] = 8 1518 | #print2('-- fcheck done') 1519 | return 1520 | 1521 | #-#### 1522 | #-#### 1523 | #-#### 1524 | 1525 | def fmqtt_recover(var=None) -> None: 1526 | #gc.collect() 1527 | global VGLOB 1528 | print2('fmqtt recover') 1529 | #fpostpone(5) this is skipped here, but added while calling function 1530 | VGLOB['status'] = 1 1531 | # mqtth.keepalive = 130 # that is that ping fits easily 3 times 1532 | mqtth.keepalive = int(3.5 * VGLOB['delaycheck']) 1533 | #time.sleep(0.5) 1534 | mqtth.connect() 1535 | #time.sleep(0.1) # ??? 1536 | mqtth.set_callback(fmqtt_irq) 1537 | #time.sleep(0.5) 1538 | for lll in VMQTT_SUB_LIST: 1539 | mqtth.subscribe(lll) 1540 | #time.sleep(0.1) # ??? 1541 | # mqtth.subscribe(CONFIG2['mqtt_eq3_in']) 1542 | VGLOB['status'] = 8 1543 | #gc.collect() 1544 | try: 1545 | # if run as thread, then stop thread 1546 | _thread.exit() 1547 | #pass 1548 | except Exception as e: 1549 | # if this fails, there is no reason to panic, function not in thread 1550 | print2('fmqtt fblew close thread:', e) 1551 | ### v52_01 - cleaning 1552 | gc.collect() 1553 | return 1554 | 1555 | def fstart_server() -> None: 1556 | async_loop = asyncio.get_event_loop() 1557 | vserver = asyncio.start_server(loop_web, "0.0.0.0", 80, 2) 1558 | # loop=async_loop, limit=4096 # v53_10, none of these settings work 1559 | # backlog set to 2, this works 1560 | # limit streamreader - maybe 4096, as dividing OTA into 2500 bytes pieces 1561 | async_loop.create_task(vserver) 1562 | async_loop.run_forever() 1563 | return 1564 | 1565 | ################ 1566 | ################ BASE 1567 | #gc.collect() 1568 | # -#### mqtt 1569 | # -#### this is moved from boot, to allow recovery 1570 | #_thread.stack_size(1024) 1571 | _thread.start_new_thread(fmqtt_recover, ()) 1572 | # wait for connection at boot 1573 | # wait longer, was 2, but warning at boot 1574 | time.sleep(0.5) # shortened from 4 in 50_8 1575 | 1576 | #-#### 1577 | #-#### 1578 | # -#### connect interrupts 1579 | ble.irq(fble_irq) 1580 | time.sleep(0.5) # 2 in 50_8 1581 | 1582 | #-#### 1583 | # -#### threads 1584 | #loopwebthread = _thread.start_new_thread(loop_web, ()) 1585 | 1586 | #-#### 1587 | #thread_web = _thread.start_new_thread(fstart_server, ()) 1588 | _thread.start_new_thread(fstart_server, ()) 1589 | time.sleep(0.5) 1590 | 1591 | #time.sleep(1) 1592 | #-#### 1593 | fntp() 1594 | time.sleep(0.5) 1595 | 1596 | #-#### WDT 1597 | # do not move this to boot 1598 | # after boot is succesful 1599 | # changed from 3 to 2.5, v53_05 1600 | # changed from delaycheck (around 60 sec) to delaywork (around 2-3 sec), v53_07 1601 | # moved just before workers to avoid too long delays, but scanning does wdt so before scan 1602 | #wdt = machine.WDT( timeout = int( VGLOB['delaycheck'] * 3 ) * 1000 ) 1603 | wdt = machine.WDT( timeout = int( VGLOB['delaywork'] * 4 ) * 1000 ) 1604 | time.sleep(0.5) 1605 | 1606 | ### v52_03 usefull to start anyway in case delays in boot 1607 | fscan(0) 1608 | time.sleep(0.5) 1609 | 1610 | # -#### timers 1611 | # 4-5 seconds is completely fine for work 1612 | # 1613 | ### v51_30, added 0.5, so that it is never 0 1614 | timer_work.init( period = int( ( VGLOB['delaywork'] ) * 1000 ), callback=fworker) 1615 | # ### clean every x minutes, multiplied by 1000, as this is in ms 1616 | #_thread.start_new_thread(fble_write, (fworkout, worka[0], worka[1])) 1617 | time.sleep(0.5) 1618 | # 1619 | timer_check.init( period = int( VGLOB['delaycheck'] * 1000 ), callback=fcheck) 1620 | 1621 | time.sleep(0.5) 1622 | fdisc(mqtth, VWORK_LIST, CONFIG2) 1623 | 1624 | ### cleanup 1625 | gc.collect() 1626 | 1627 | print2("BOOTED") 1628 | 1629 | #-### 1630 | -------------------------------------------------------------------------------- /code/main2.py: -------------------------------------------------------------------------------- 1 | #-#### 2 | #-#### 3 | #-#### 4 | 5 | def ffind_handle(VWORK_LIST, handle: int) -> str: 6 | # get addr of the handle 7 | # cleaner 50_17 8 | try: 9 | return [kkk[0] for kkk in VWORK_LIST.items() if kkk[1][2]==handle][0] 10 | except: 11 | return '' # needed ? 12 | 13 | def ffind_status(VWORK_LIST, status: int = 7) -> str: 14 | # get addr of the connected state 15 | # cleaner 50_17 16 | try: 17 | return [kkk[0] for kkk in VWORK_LIST.items() if kkk[1][3]==status][0] 18 | except: 19 | return '' # needed ? 20 | 21 | def fdecode_addr(addr: bytes) -> str: 22 | # get str addr from hex mac 23 | result = [] 24 | for iii in addr: 25 | result.append('{:0>2}'.format(str(hex(iii).split('x')[1]))) 26 | return str((':').join(result)).upper() 27 | 28 | 29 | def fcode_addr(addr: str) -> bytes: 30 | # encrypt the str addr into connectable hex mac 31 | result = [] 32 | for iii in addr.split(":"): 33 | result.append(int(str(iii), 16)) 34 | return bytes(result) 35 | 36 | #### should be cleanly added here 37 | 38 | def faddwork() -> None: 39 | # function for adding work 40 | # should check where to add the work, and if this or similar work exists 41 | # if the work makes sense 42 | # in the future maybe this should be handled by the TRV object... 43 | pass 44 | return 45 | 46 | # v53_19 moved 47 | def freset(time, machine, VWORK_LIST): 48 | ### v52_08 reset function wrap 49 | ### TODO, add some functions like time save, job save, etc. 50 | #fff1 = open('temp.txt', 'w') 51 | #fff1.close() 52 | fff2 = open('temp.txt', 'w') 53 | fff2.write( str(VWORK_LIST) ) 54 | fff2.close() 55 | #del fff 56 | time.sleep(0.2) 57 | #await fff.write("PASS = \'1234\'\n") 58 | machine.reset() 59 | 60 | # v53_19 moved 61 | def fdisconnect(ble, handle = 0) -> None: 62 | # disconnect and clean up, with all error catching etc 63 | try: 64 | ble.gap_disconnect(handle) 65 | except: 66 | # problem... 67 | return 1 68 | return 69 | 70 | # v53_19 moved 71 | def fstopscan(ble) -> None: 72 | try: 73 | ble.gap_scan(None) 74 | #sleep(0.1) # no sleep as it is used in time critical functions 75 | return 76 | except: 77 | pass 78 | return 79 | 80 | 81 | #-#### 82 | #-#### 83 | #-#### 84 | 85 | def fdisc(mqtth, VWORK_LIST, CONFIG2) -> None: 86 | ### 87 | #print('= send mqtt autodiscovery') 88 | #gc.collect() 89 | #fpostpone() 90 | ### home assistant auto discovery 91 | ### discovery topic should be retained 92 | #print("publishing mqtt autodiscovery") 93 | ### 94 | ### loop through all trusted devices 95 | for hhh in VWORK_LIST: 96 | #time.sleep(0.1) # was 0.5 97 | #mac = str(hhh[9:17].replace(":", "")) 98 | mac = str(hhh.replace(":", "")[6:12]) 99 | mac_type = str(hhh.replace(":", "")[0:6]) 100 | ### 101 | if mac_type == '4C65A8' or mac_type == 'A4C138': 102 | #html_in += str(vvv) + "\n" 103 | ### 104 | #mac = str(hhh[9:17].replace(":", "")) 105 | ### 106 | topict = f'homeassistant/sensor/temp_{mac}_temp/config' 107 | devid = '"device": { "identifiers": [ "temp_' + mac + '_id" ], "name":"temp_' + mac + '_dev", "model":"JJ ESP32 Temp", "sw_version":"' + CONFIG2['__version__'] + '" }' 108 | devicet = '{"device_class": "temperature", "name": "Mijia ' + mac + ' Temperature", \ 109 | "state_topic": "' + CONFIG2["mqtt_thermo"] + mac + '/radout/status", "unit_of_measurement": "°C", "value_template": "{{ value_json.temp }}", \ 110 | "unique_id": "temp_' + mac + '_T", ' + devid + ' }' 111 | mqtth.publish(topict, bytes(devicet, 'ascii'), True) 112 | ### 113 | topich = f'homeassistant/sensor/temp_{mac}_hum/config' 114 | deviceh = '{"device_class": "humidity", "name": "Mijia ' + mac + ' Humidity", \ 115 | "state_topic": "' + CONFIG2["mqtt_thermo"] + mac + '/radout/status", "unit_of_measurement": "%", "value_template": "{{ value_json.hum }}", \ 116 | "unique_id": "temp_' + mac + '_H", '+ devid +' }' 117 | mqtth.publish(topich, bytes(deviceh, 'ascii'), True) 118 | ### 119 | # /hass/climate/climate3/radin/trv 00:1A:22:0E:C9:45 manual 120 | # /hass/climate/climate1/radout/status {"trv":"00:1A:22:0E:F6:F5","temp":"19.0","mode":"manual"} 121 | if mac_type == '001A22': 122 | ### 123 | # "~": "homeassistant/light/kitchen", 124 | # each eq3 has to have its own mqtt 125 | topicc = f'homeassistant/climate/clim_{mac}_eq3/config' 126 | if CONFIG2['mqtt_thermo_src'] != "": 127 | currtemp = '"curr_temp_t": "' + CONFIG2['mqtt_thermo_src'] + '/radout/status", "curr_temp_tpl": "{{value_json.temp}}", ' 128 | else: 129 | currtemp = "" 130 | devid = '"device": { "identifiers": [ "clim_' + mac + '_id" ], "name": "clim_eq3_' + mac + '_dev", "model":"JJ ESP32 Clim EQ3", "sw_version":"' + CONFIG2['__version__'] + '" }' 131 | ### ver 51_29, min 4.5->OFF, 30.0->ON, recommended by wieluk-github 132 | devicec = '{ "name": "clim_eq3_' + mac + '", "unique_id": "clim_' + mac + '_thermostat_id", "modes": [ "heat" ], ' + devid + ', \ 133 | "mode_cmd_t": "' + CONFIG2['mqtt_eq3'] + mac + '/radin/mode2", "mode_stat_t": "' + CONFIG2['mqtt_eq3'] + mac + '/radout/status", \ 134 | "mode_stat_tpl": "{{value_json.mode2}}", "temp_cmd_t": "' + CONFIG2['mqtt_eq3'] + mac + '/radin/temp", \ 135 | "temp_stat_t": "' + CONFIG2['mqtt_eq3'] + mac + '/radout/status", "temp_stat_tpl": "{{value_json.temp}}", \ 136 | ' + currtemp + ' "min_temp": "4.5", "max_temp": "30.0", "temp_step": "0.5", \ 137 | "hold_state_template": "{{value_json.mode}}", "hold_state_topic": "' + CONFIG2['mqtt_eq3'] + mac + '/radout/status", \ 138 | "hold_command_topic": "' + CONFIG2['mqtt_eq3'] + mac + '/radin/mode", "hold_modes": [ "auto", "manual", "boost", "away" ] }' 139 | mqtth.publish(topicc, bytes(devicec, 'ascii'), True) 140 | ### battery and valve open sensors 141 | topicc = f'homeassistant/sensor/clim_{mac}_eq3_valve/config' 142 | devicec = '{ "name": "clim_eq3_' + mac + ' Valve", "unique_id": "clim_' + mac + '_valve_id" , ' + devid + ', \ 143 | "state_topic": "' + CONFIG2['mqtt_eq3'] + mac + '/radout/status", "value_template": "{{ value_json.valve }}" }' 144 | mqtth.publish(topicc, bytes(devicec, 'ascii'), True) 145 | ### 146 | topicc = f'homeassistant/sensor/clim_{mac}_eq3_battery/config' 147 | devicec = '{ "name": "clim_eq3_' + mac + ' Battery", "unique_id": "clim_' + mac + '_battery_id", ' + devid + ', "device_class": "battery", \ 148 | "state_topic": "' + CONFIG2['mqtt_eq3'] + mac + '/radout/status", "value_template": "{{ value_json.battery }}" }' 149 | mqtth.publish(topicc, bytes(devicec, 'ascii'), True) 150 | ### 151 | #del devicec 152 | # add True at the end to retain or retain=True 153 | if mac_type[0:4] == 'FFFF': 154 | #topicp = f'homeassistant/sensor/presence_{mac}_eq3/config' 155 | topicp = f'homeassistant/device_tracker/presence_{mac}_eq3/config' 156 | devid = '"device": { "identifiers": [ "tracker_' + mac + '_id" ], "name": "tracker_' + mac + '_dev", "model":"JJ ESP32 Tracker", "sw_version":"' + CONFIG2['__version__'] + '" }' 157 | devicep = '{"name": "Tracker ' + mac + '", "state_topic": "' + CONFIG2["mqtt_presence"] + mac + '/radout/status", ' + devid + ', \ 158 | "expire_after": "240", "consider_home": "180", "unique_id": "tracker_' + mac + '", "source_type": "bluetooth" }' 159 | mqtth.publish(topicp, bytes(devicep, 'ascii'), True) 160 | # 161 | #del devicep 162 | ### 163 | ### here additional devices for publishing can be added 164 | ### v52_01 - cleaning 165 | #gc.collect() 166 | return 167 | 168 | ##### 169 | 170 | -------------------------------------------------------------------------------- /code/secret_cfg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: latin-1 -*- 2 | #-### secret_cfg.py 3 | 4 | #-### variables / configuration 5 | 6 | #-### 7 | #-### 8 | #-### there variables are used only during boot, then, removed from memory 9 | CONFIG = {} 10 | CONFIG['freq'] = 240000000 11 | #CONFIG['freq'] = 160000000 12 | #-### pass is convoluted with [ ord(x) for x in list(pass) ] 13 | CONFIG['wifi_pass'] = [112, 97, 115, 115] 14 | CONFIG['wifi_name'] = 'wifiname' 15 | CONFIG['ntp_host'] = 'ntp_server' 16 | # 17 | CONFIG2 = {} 18 | CONFIG2['mqtt_eq3_in'] = '/hass/climate/climate/radin/trv' 19 | CONFIG2['mqtt_eq3_out'] = '/hass/climate/climate/radout/status' 20 | CONFIG2['mqtt_mijia_out'] = '/hass/climate/thermo/status' 21 | 22 | CONFIG2['mqtt_eq3'] = 'esp/climate/' 23 | CONFIG2['mqtt_thermo'] = 'esp/thermo/' 24 | # source of real temperature, some other mqtt thermometer or something 25 | CONFIG2['mqtt_thermo_src'] = '' 26 | CONFIG2['mqtt_presence'] = 'esp/presence/' 27 | 28 | CONFIG2['mqtt_srv'] = 'mqtt_srv' 29 | CONFIG2['mqtt_usr'] = 'mqtt_usr' 30 | CONFIG2['mqtt_pass'] = 'mqtt_pass' 31 | 32 | #-### if keep loop is set to 0, then loops die 33 | #-### if you want to kill loops/threads, set this to 0 34 | #-### good for debugging and responsiver webrepl 35 | CONFIG2['loop'] = 1 36 | 37 | #-### done here -------------------------------------------------------------------------------- /code/simple2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: latin-1 -*- 2 | import usocket as socket 3 | import uselect 4 | from utime import ticks_add,ticks_ms,ticks_diff 5 | class MQTTException(Exception):0 6 | def pid_gen(pid=0): 7 | A=pid 8 | while True:A=A+1 if A<65535 else 1;yield A 9 | class MQTTClient: 10 | def __init__(A,client_id,server,port=0,user=None,password=None,keepalive=0,ssl=False,ssl_params=None,socket_timeout=5,message_timeout=10): 11 | C=ssl_params;B=port 12 | if B==0:B=8883 if ssl else 1883 13 | A.client_id=client_id;A.sock=None;A.poller=None;A.server=server;A.port=B;A.ssl=ssl;A.ssl_params=C if C else{};A.newpid=pid_gen() 14 | if not getattr(A,'cb',None):A.cb=None 15 | if not getattr(A,'cbstat',None):A.cbstat=lambda p,s:None 16 | A.user=user;A.pswd=password;A.keepalive=keepalive;A.lw_topic=None;A.lw_msg=None;A.lw_qos=0;A.lw_retain=False;A.rcv_pids={};A.last_ping=ticks_ms();A.last_cpacket=ticks_ms();A.socket_timeout=socket_timeout;A.message_timeout=message_timeout 17 | def _read(A,n): 18 | try: 19 | B=b'' 20 | for C in range(n):A._sock_timeout(A.poller_r,A.socket_timeout);B+=A.sock.read(1) 21 | except AttributeError:raise MQTTException(8) 22 | if B==b'':raise MQTTException(1) 23 | if len(B)!=n:raise MQTTException(2) 24 | return B 25 | def _write(A,bytes_wr,length=-1): 26 | D=bytes_wr;B=length 27 | try:A._sock_timeout(A.poller_w,A.socket_timeout);C=A.sock.write(D,B) 28 | except AttributeError:raise MQTTException(8) 29 | if B<0: 30 | if C!=len(D):raise MQTTException(3) 31 | elif C!=B:raise MQTTException(3) 32 | return C 33 | def _send_str(A,s):assert len(s)<65536;A._write(len(s).to_bytes(2,'big'));A._write(s) 34 | def _recv_len(D): 35 | A=0;B=0 36 | while 1: 37 | C=D._read(1)[0];A|=(C&127)<127:buf[B]=A&127|128;A>>=7;B+=1 43 | buf[B]=A;return B+1 44 | def _sock_timeout(B,poller,socket_timeout): 45 | A=socket_timeout 46 | if B.sock: 47 | C=poller.poll(-1 if A is None else int(A*1000)) 48 | if not C:raise MQTTException(30) 49 | else:raise MQTTException(28) 50 | def set_callback(A,f):A.cb=f 51 | def set_callback_status(A,f):A.cbstat=f 52 | def set_last_will(A,topic,msg,retain=False,qos=0):B=topic;assert 0<=qos<=2;assert B;A.lw_topic=B;A.lw_msg=msg;A.lw_qos=qos;A.lw_retain=retain 53 | def connect(A,clean_session=True): 54 | E=clean_session;A.sock=socket.socket();A.poller_r=uselect.poll();A.poller_r.register(A.sock,uselect.POLLIN);A.poller_w=uselect.poll();A.poller_w.register(A.sock,uselect.POLLOUT);G=socket.getaddrinfo(A.server,A.port)[0][-1];A.sock.connect(G) 55 | if A.ssl:import ussl;A.sock=ussl.wrap_socket(A.sock,**A.ssl_params) 56 | F=bytearray(b'\x10\x00\x00\x00\x00\x00');B=bytearray(b'\x00\x04MQTT\x04\x00\x00\x00');D=10+2+len(A.client_id);B[7]=bool(E)<<1 57 | if bool(E):A.rcv_pids.clear() 58 | if A.user is not None: 59 | D+=2+len(A.user);B[7]|=1<<7 60 | if A.pswd is not None:D+=2+len(A.pswd);B[7]|=1<<6 61 | if A.keepalive:assert A.keepalive<65536;B[8]|=A.keepalive>>8;B[9]|=A.keepalive&255 62 | if A.lw_topic:D+=2+len(A.lw_topic)+2+len(A.lw_msg);B[7]|=4|(A.lw_qos&1)<<3|(A.lw_qos&2)<<3;B[7]|=A.lw_retain<<5 63 | H=A._varlen_encode(D,F,1);A._write(F,H);A._write(B);A._send_str(A.client_id) 64 | if A.lw_topic:A._send_str(A.lw_topic);A._send_str(A.lw_msg) 65 | if A.user is not None: 66 | A._send_str(A.user) 67 | if A.pswd is not None:A._send_str(A.pswd) 68 | C=A._read(4) 69 | if not(C[0]==32 and C[1]==2):raise MQTTException(29) 70 | if C[3]!=0: 71 | if 1<=C[3]<=5:raise MQTTException(20+C[3]) 72 | else:raise MQTTException(20,C[3]) 73 | A.last_cpacket=ticks_ms();return C[2]&1 74 | def disconnect(A):A._write(b'\xe0\x00');A.poller_r.unregister(A.sock);A.poller_w.unregister(A.sock);A.sock.close();A.sock=None;A.poller=None 75 | def ping(A):A._write(b'\xc0\x00');A.last_ping=ticks_ms() 76 | def publish(A,topic,msg,retain=False,qos=0,dup=False): 77 | E=topic;B=qos;assert B in(0,1);C=bytearray(b'0\x00\x00\x00\x00');C[0]|=B<<1|retain|int(dup)<<3;F=2+len(E)+len(msg) 78 | if B>0:F+=2 79 | G=A._varlen_encode(F,C,1);A._write(C,G);A._send_str(E) 80 | if B>0:D=next(A.newpid);A._write(D.to_bytes(2,'big')) 81 | A._write(msg) 82 | if B>0:A.rcv_pids[D]=ticks_add(ticks_ms(),A.message_timeout*1000);return D 83 | def subscribe(A,topic,qos=0):E=topic;assert qos in(0,1);assert A.cb is not None,'Subscribe callback is not set';B=bytearray(b'\x82\x00\x00\x00\x00\x00\x00');C=next(A.newpid);F=2+2+len(E)+1;D=A._varlen_encode(F,B,1);B[D:D+2]=C.to_bytes(2,'big');A._write(B,D+2);A._send_str(E);A._write(qos.to_bytes(1,'little'));A.rcv_pids[C]=ticks_add(ticks_ms(),A.message_timeout*1000);return C 84 | def _message_timeout(A): 85 | C=ticks_ms() 86 | for (B,D) in A.rcv_pids.items(): 87 | if ticks_diff(D,C)<=0:A.rcv_pids.pop(B);A.cbstat(B,0) 88 | def check_msg(A): 89 | if A.sock: 90 | if not A.poller_r.poll(-1 if A.socket_timeout is None else 1):A._message_timeout();return None 91 | try: 92 | G=A._read(1) 93 | if not G:A._message_timeout();return None 94 | except OSError as H: 95 | if H.args[0]==110:A._message_timeout();return None 96 | else:raise H 97 | else:raise MQTTException(28) 98 | if G==b'\xd0': 99 | if A._read(1)[0]!=0:MQTTException(-1) 100 | A.last_cpacket=ticks_ms();return 101 | B=G[0] 102 | if B==64: 103 | D=A._read(1) 104 | if D!=b'\x02':raise MQTTException(-1) 105 | F=int.from_bytes(A._read(2),'big') 106 | if F in A.rcv_pids:A.last_cpacket=ticks_ms();A.rcv_pids.pop(F);A.cbstat(F,1) 107 | else:A.cbstat(F,2) 108 | if B==144: 109 | C=A._read(4) 110 | if C[0]!=3:raise MQTTException(40,C) 111 | if C[3]==128:raise MQTTException(44) 112 | if C[3]not in(0,1,2):raise MQTTException(40,C) 113 | E=C[2]|C[1]<<8 114 | if E in A.rcv_pids:A.last_cpacket=ticks_ms();A.rcv_pids.pop(E);A.cbstat(E,1) 115 | else:raise MQTTException(5) 116 | A._message_timeout() 117 | if B&240!=48:return B 118 | D=A._recv_len();I=int.from_bytes(A._read(2),'big');J=A._read(I);D-=I+2 119 | if B&6:E=int.from_bytes(A._read(2),'big');D-=2 120 | K=A._read(D)if D else b'';L=B&1;M=B&8;A.cb(J,K,bool(L),bool(M));A.last_cpacket=ticks_ms() 121 | if B&6==2:A._write(b'@\x02');A._write(E.to_bytes(2,'big')) 122 | elif B&6==4:raise NotImplementedError() 123 | elif B&6==6:raise MQTTException(-1) 124 | def wait_msg(A):B=A.socket_timeout;A.socket_timeout=None;C=A.check_msg();A.socket_timeout=B;return C --------------------------------------------------------------------------------