├── .gitignore
├── LICENSE
├── README.md
├── images
├── device.jpg
├── kamstrup_multical21.png
└── wires.jpg
├── include
├── WMbusFrame.h
├── WaterMeter.h
└── hwconfig.h
├── platformio.ini
└── src
├── WMBusFrame.cpp
├── WaterMeter.cpp
├── credentials_template.h
└── main.cpp
/.gitignore:
--------------------------------------------------------------------------------
1 | .pio
2 | .vscode/.browse.c_cpp.db*
3 | .vscode/c_cpp_properties.json
4 | .vscode/launch.json
5 | .vscode/ipch
6 | include/credentials.h
--------------------------------------------------------------------------------
/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 | # Kamstrup Multical 21 water meter in Home Assistant (Wireless MBus)
2 |
3 |
4 |
5 | ### Features
6 | * Configuration ready for Home Assistan with MQTT.
7 | * Support for AES-128 decryption (with vaild key).
8 | * CRC Check of recived data.
9 | * Wireless reading of data.
10 | * Easy to build and configure.
11 |
12 |
13 | ### Parts
14 | Use these arfilliate links to support me!\
15 | [CC1101 Module](https://s.click.aliexpress.com/e/_oDW0qJ2) \
16 | [ESP32 DevKit](https://s.click.aliexpress.com/e/_oFlbQRE) \
17 | Some cables
18 |
19 | ### Wiring
20 |
21 | | CC1101 | ESP32 |
22 | | --- | --- |
23 | | VCC | 3V3 |
24 | | GND | GND |
25 | | CSN | P4 |
26 | | MOSI| P23 |
27 | | MISO| P19 |
28 | | SCK | P18 |
29 | | GD0 | P32 |
30 | | GD2 | Not Connected |
31 |
32 |
33 |
34 |
35 | ### Build and Upload Firmware
36 | * Make sure you have a decryption key for your meter (you need to ask your water service provider for it).
37 | * Read the serial number on the meter (typically S/N: XXXXXXXX/A/20, the serial number is the XXXXXXXXX part).
38 | * Rename credentials_template.h to credentials.h and add your details.
39 | * Compile and upload:
40 | - You need [VS Code](https://code.visualstudio.com/) and the [PIO Plugin](https://platformio.org/)
41 | - Open the project folder with the platformio.ini file (File -> Open Folder...), connect the ESP32 via USB then build and upload with Ctrl+Alt+U.
42 |
43 | ### Home Assistant
44 |
45 | Setup [MQTT](https://www.home-assistant.io/integrations/mqtt/) if you don't already have it.
46 |
47 | Add this to configuration.yaml
48 | ```
49 | mqtt:
50 | sensor:
51 | - name: "Water Meter Usage"
52 | state_topic: "watermeter/0/sensor/mydatajson"
53 | unit_of_measurement: "m³"
54 | value_template: "{{ value_json.CurrentValue }}"
55 | device_class: water
56 | state_class: total_increasing
57 | availability:
58 | - topic: "watermeter/0/online"
59 | payload_available: "True"
60 | payload_not_available: "False"
61 | - name: "Water Meter Month Start Value"
62 | state_topic: "watermeter/0/sensor/mydatajson"
63 | unit_of_measurement: "m³"
64 | value_template: "{{ value_json.MonthStartValue }}"
65 | device_class: water
66 | state_class: total_increasing
67 | - name: "Water Meter Room Temperature"
68 | state_topic: "watermeter/0/sensor/mydatajson"
69 | value_template: "{{ value_json.RoomTemp }}"
70 | unit_of_measurement: "°C"
71 | - name: "Water Meter Water Temperature"
72 | state_topic: "watermeter/0/sensor/mydatajson"
73 | value_template: "{{ value_json.WaterTemp }}"
74 | unit_of_measurement: "°C"
75 | ```
76 |
77 | Donation using [Ko-Fi](https://ko-fi.com/patriksretrotech) or [PayPal](https://www.paypal.com/donate/?business=UCTJFD6L7UYFL&no_recurring=0&item_name=Please+support+me%21¤cy_code=SEK) are highly appreciated!
78 |
79 | This is a based on [chester4444/esp-multical21](https://github.com/chester4444/esp-multical21).
80 | Thanks to chester4444for his effort.
81 |
--------------------------------------------------------------------------------
/images/device.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pthalin/esp32-multical21/635a4ffbe2dd72dea378f6cbbd75e3162a10d223/images/device.jpg
--------------------------------------------------------------------------------
/images/kamstrup_multical21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pthalin/esp32-multical21/635a4ffbe2dd72dea378f6cbbd75e3162a10d223/images/kamstrup_multical21.png
--------------------------------------------------------------------------------
/images/wires.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pthalin/esp32-multical21/635a4ffbe2dd72dea378f6cbbd75e3162a10d223/images/wires.jpg
--------------------------------------------------------------------------------
/include/WMbusFrame.h:
--------------------------------------------------------------------------------
1 | #ifndef __WMBUS_FRAME__
2 | #define __WMBUS_FRAME__
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "credentials.h"
9 |
10 | class WMBusFrame
11 | {
12 | public:
13 | static const uint8_t MAX_LENGTH = 64;
14 | private:
15 | CTR aes128;
16 | uint8_t cipher[MAX_LENGTH];
17 | uint8_t plaintext[MAX_LENGTH];
18 | uint8_t iv[16];
19 | void check(void);
20 | void printMeterInfo(uint8_t *data, size_t len);
21 | uint16_t crc16_EN13757_per_byte(uint16_t crc, uint8_t b);
22 | uint16_t crc16_EN13757(uint8_t *data, size_t len);
23 |
24 | public:
25 | // check frame and decrypt it
26 | void decode(void);
27 |
28 | // true, if meter information is valid for the last received frame
29 | bool isValid = false;
30 |
31 | // payload length
32 | uint8_t length = 0;
33 |
34 | // payload data
35 | uint8_t payload[MAX_LENGTH];
36 |
37 | // constructor
38 | WMBusFrame();
39 | };
40 |
41 | #endif // __WMBUS_FRAME__
42 |
--------------------------------------------------------------------------------
/include/WaterMeter.h:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2020 chester4444@wolke7.net
3 | This program is free software: you can redistribute it and/or modify
4 | it under the terms of the GNU General Public License as published by
5 | the Free Software Foundation, either version 3 of the License, or
6 | (at your option) any later version.
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 | You should have received a copy of the GNU General Public License
12 | along with this program. If not, see .
13 | */
14 |
15 | #ifndef _WATERMETER_H_
16 | #define _WATERMETER_H_
17 |
18 | #include
19 | #include
20 | #include "WMbusFrame.h"
21 |
22 | #define MARCSTATE_SLEEP 0x00
23 | #define MARCSTATE_IDLE 0x01
24 | #define MARCSTATE_XOFF 0x02
25 | #define MARCSTATE_VCOON_MC 0x03
26 | #define MARCSTATE_REGON_MC 0x04
27 | #define MARCSTATE_MANCAL 0x05
28 | #define MARCSTATE_VCOON 0x06
29 | #define MARCSTATE_REGON 0x07
30 | #define MARCSTATE_STARTCAL 0x08
31 | #define MARCSTATE_BWBOOST 0x09
32 | #define MARCSTATE_FS_LOCK 0x0A
33 | #define MARCSTATE_IFADCON 0x0B
34 | #define MARCSTATE_ENDCAL 0x0C
35 | #define MARCSTATE_RX 0x0D
36 | #define MARCSTATE_RX_END 0x0E
37 | #define MARCSTATE_RX_RST 0x0F
38 | #define MARCSTATE_TXRX_SWITCH 0x10
39 | #define MARCSTATE_RXFIFO_OVERFLOW 0x11
40 | #define MARCSTATE_FSTXON 0x12
41 | #define MARCSTATE_TX 0x13
42 | #define MARCSTATE_TX_END 0x14
43 | #define MARCSTATE_RXTX_SWITCH 0x15
44 | #define MARCSTATE_TXFIFO_UNDERFLOW 0x16
45 |
46 | #define WRITE_BURST 0x40
47 | #define READ_SINGLE 0x80
48 | #define READ_BURST 0xC0
49 |
50 | #define CC1101_CONFIG_REGISTER READ_SINGLE
51 | #define CC1101_STATUS_REGISTER READ_BURST
52 |
53 | #define CC1101_PATABLE 0x3E // PATABLE address
54 | #define CC1101_TXFIFO 0x3F // TX FIFO address
55 | #define CC1101_RXFIFO 0x3F // RX FIFO address
56 |
57 | #define CC1101_SRES 0x30 // Reset CC1101 chip
58 | #define CC1101_SFSTXON 0x31 // Enable and calibrate frequency synthesizer (if MCSM0.FS_AUTOCAL=1). If in RX (with CCA):
59 | // Go to a wait state where only the synthesizer is running (for quick RX / TX turnaround).
60 | #define CC1101_SXOFF 0x32 // Turn off crystal oscillator
61 | #define CC1101_SCAL 0x33 // Calibrate frequency synthesizer and turn it off. SCAL can be strobed from IDLE mode without
62 | // setting manual calibration mode (MCSM0.FS_AUTOCAL=0)
63 | #define CC1101_SRX 0x34 // Enable RX. Perform calibration first if coming from IDLE and MCSM0.FS_AUTOCAL=1
64 | #define CC1101_STX 0x35 // In IDLE state: Enable TX. Perform calibration first if MCSM0.FS_AUTOCAL=1.
65 | // If in RX state and CCA is enabled: Only go to TX if channel is clear
66 | #define CC1101_SIDLE 0x36 // Exit RX / TX, turn off frequency synthesizer and exit Wake-On-Radio mode if applicable
67 | #define CC1101_SWOR 0x38 // Start automatic RX polling sequence (Wake-on-Radio) as described in Section 19.5 if
68 | // WORCTRL.RC_PD=0
69 | #define CC1101_SPWD 0x39 // Enter power down mode when CSn goes high
70 | #define CC1101_SFRX 0x3A // Flush the RX FIFO buffer. Only issue SFRX in IDLE or RXFIFO_OVERFLOW states
71 | #define CC1101_SFTX 0x3B // Flush the TX FIFO buffer. Only issue SFTX in IDLE or TXFIFO_UNDERFLOW states
72 | #define CC1101_SWORRST 0x3C // Reset real time clock to Event1 value
73 | #define CC1101_SNOP 0x3D // No operation. May be used to get access to the chip status byte
74 |
75 | #define CC1101_IOCFG2 0x00 // GDO2 Output Pin Configuration
76 | #define CC1101_IOCFG1 0x01 // GDO1 Output Pin Configuration
77 | #define CC1101_IOCFG0 0x02 // GDO0 Output Pin Configuration
78 | #define CC1101_FIFOTHR 0x03 // RX FIFO and TX FIFO Thresholds
79 | #define CC1101_SYNC1 0x04 // Sync Word, High Byte
80 | #define CC1101_SYNC0 0x05 // Sync Word, Low Byte
81 | #define CC1101_PKTLEN 0x06 // Packet Length
82 | #define CC1101_PKTCTRL1 0x07 // Packet Automation Control
83 | #define CC1101_PKTCTRL0 0x08 // Packet Automation Control
84 | #define CC1101_ADDR 0x09 // Device Address
85 | #define CC1101_CHANNR 0x0A // Channel Number
86 | #define CC1101_FSCTRL1 0x0B // Frequency Synthesizer Control
87 | #define CC1101_FSCTRL0 0x0C // Frequency Synthesizer Control
88 | #define CC1101_FREQ2 0x0D // Frequency Control Word, High Byte
89 | #define CC1101_FREQ1 0x0E // Frequency Control Word, Middle Byte
90 | #define CC1101_FREQ0 0x0F // Frequency Control Word, Low Byte
91 | #define CC1101_MDMCFG4 0x10 // Modem Configuration
92 | #define CC1101_MDMCFG3 0x11 // Modem Configuration
93 | #define CC1101_MDMCFG2 0x12 // Modem Configuration
94 | #define CC1101_MDMCFG1 0x13 // Modem Configuration
95 | #define CC1101_MDMCFG0 0x14 // Modem Configuration
96 | #define CC1101_DEVIATN 0x15 // Modem Deviation Setting
97 | #define CC1101_MCSM2 0x16 // Main Radio Control State Machine Configuration
98 | #define CC1101_MCSM1 0x17 // Main Radio Control State Machine Configuration
99 | #define CC1101_MCSM0 0x18 // Main Radio Control State Machine Configuration
100 | #define CC1101_FOCCFG 0x19 // Frequency Offset Compensation Configuration
101 | #define CC1101_BSCFG 0x1A // Bit Synchronization Configuration
102 | #define CC1101_AGCCTRL2 0x1B // AGC Control
103 | #define CC1101_AGCCTRL1 0x1C // AGC Control
104 | #define CC1101_AGCCTRL0 0x1D // AGC Control
105 | #define CC1101_WOREVT1 0x1E // High Byte Event0 Timeout
106 | #define CC1101_WOREVT0 0x1F // Low Byte Event0 Timeout
107 | #define CC1101_WORCTRL 0x20 // Wake On Radio Control
108 | #define CC1101_FREND1 0x21 // Front End RX Configuration
109 | #define CC1101_FREND0 0x22 // Front End TX Configuration
110 | #define CC1101_FSCAL3 0x23 // Frequency Synthesizer Calibration
111 | #define CC1101_FSCAL2 0x24 // Frequency Synthesizer Calibration
112 | #define CC1101_FSCAL1 0x25 // Frequency Synthesizer Calibration
113 | #define CC1101_FSCAL0 0x26 // Frequency Synthesizer Calibration
114 | #define CC1101_RCCTRL1 0x27 // RC Oscillator Configuration
115 | #define CC1101_RCCTRL0 0x28 // RC Oscillator Configuration
116 | #define CC1101_FSTEST 0x29 // Frequency Synthesizer Calibration Control
117 | #define CC1101_PTEST 0x2A // Production Test
118 | #define CC1101_AGCTEST 0x2B // AGC Test
119 | #define CC1101_TEST2 0x2C // Various Test Settings
120 | #define CC1101_TEST1 0x2D // Various Test Settings
121 | #define CC1101_TEST0 0x2E // Various Test Settings
122 |
123 | #define CC1101_PARTNUM 0x30 // Chip ID
124 | #define CC1101_VERSION 0x31 // Chip ID
125 | #define CC1101_FREQEST 0x32 // Frequency Offset Estimate from Demodulator
126 | #define CC1101_LQI 0x33 // Demodulator Estimate for Link Quality
127 | #define CC1101_RSSI 0x34 // Received Signal Strength Indication
128 | #define CC1101_MARCSTATE 0x35 // Main Radio Control State Machine State
129 | #define CC1101_WORTIME1 0x36 // High Byte of WOR Time
130 | #define CC1101_WORTIME0 0x37 // Low Byte of WOR Time
131 | #define CC1101_PKTSTATUS 0x38 // Current GDOx Status and Packet Status
132 | #define CC1101_VCO_VC_DAC 0x39 // Current Setting from PLL Calibration Module
133 | #define CC1101_TXBYTES 0x3A // Underflow and Number of Bytes
134 | #define CC1101_RXBYTES 0x3B // Overflow and Number of Bytes
135 | #define CC1101_RCCTRL1_STATUS 0x3C // Last RC Oscillator Calibration Result
136 | #define CC1101_RCCTRL0_STATUS 0x3D // Last RC Oscillator Calibration Result
137 |
138 | #define CC1101_DEFVAL_SYNC1 0x54 // Synchronization word, high byte
139 | #define CC1101_DEFVAL_SYNC0 0x3D // Synchronization word, low byte
140 | #define CC1101_DEFVAL_MCSM1 0x00 // Main Radio Control State Machine Configuration
141 |
142 | #define CC1101_DEFVAL_IOCFG2 0x2E // GDO2 Output Pin Configuration
143 | #define CC1101_DEFVAL_IOCFG0 0x06 // GDO0 Output Pin Configuration
144 |
145 | #define CC1101_DEFVAL_FSCTRL1 0x08 // Frequency Synthesizer Control
146 | #define CC1101_DEFVAL_FSCTRL0 0x00 // Frequency Synthesizer Control
147 | #define CC1101_DEFVAL_FREQ2 0x21 // Frequency Control Word, High Byte
148 | #define CC1101_DEFVAL_FREQ1 0x6B // Frequency Control Word, Middle Byte
149 | #define CC1101_DEFVAL_FREQ0 0xD0 // Frequency Control Word, Low Byte
150 | #define CC1101_DEFVAL_MDMCFG4 0x5C // Modem configuration. Speed = 103 Kbps
151 | #define CC1101_DEFVAL_MDMCFG3 0x04 // Modem Configuration
152 | #define CC1101_DEFVAL_MDMCFG2 0x06 // Modem Configuration
153 | #define CC1101_DEFVAL_MDMCFG1 0x22 // Modem Configuration
154 | #define CC1101_DEFVAL_MDMCFG0 0xF8 // Modem Configuration
155 | #define CC1101_DEFVAL_CHANNR 0x00 // Channel Number
156 | #define CC1101_DEFVAL_DEVIATN 0x44 // Modem Deviation Setting
157 | #define CC1101_DEFVAL_FREND1 0xB6 // Front End RX Configuration
158 | #define CC1101_DEFVAL_FREND0 0x10 // Front End TX Configuration
159 | #define CC1101_DEFVAL_MCSM0 0x18 // Main Radio Control State Machine Configuration
160 | #define CC1101_DEFVAL_FOCCFG 0x2E // Frequency Offset Compensation Configuration
161 | #define CC1101_DEFVAL_BSCFG 0xBF // Bit Synchronization Configuration
162 | #define CC1101_DEFVAL_AGCCTRL2 0x43 // AGC Control
163 | #define CC1101_DEFVAL_AGCCTRL1 0x09 // AGC Control
164 | #define CC1101_DEFVAL_AGCCTRL0 0xB5 // AGC Control
165 | #define CC1101_DEFVAL_FSCAL3 0xEA // Frequency Synthesizer Calibration
166 | #define CC1101_DEFVAL_FSCAL2 0x2A // Frequency Synthesizer Calibration
167 | #define CC1101_DEFVAL_FSCAL1 0x00 // Frequency Synthesizer Calibration
168 | #define CC1101_DEFVAL_FSCAL0 0x1F // Frequency Synthesizer Calibration
169 | #define CC1101_DEFVAL_FSTEST 0x59 // Frequency Synthesizer Calibration Control
170 | #define CC1101_DEFVAL_TEST2 0x81 // Various Test Settings
171 | #define CC1101_DEFVAL_TEST1 0x35 // Various Test Settings
172 | #define CC1101_DEFVAL_TEST0 0x09 // Various Test Settings
173 | #define CC1101_DEFVAL_PKTCTRL1 0x00 // Packet Automation Control
174 | #define CC1101_DEFVAL_PKTCTRL0 0x02 // 2 - infinite length
175 | #define CC1101_DEFVAL_ADDR 0x00 // Device Address
176 | #define CC1101_DEFVAL_PKTLEN 0x30 // Packet Length
177 | #define CC1101_DEFVAL_FIFOTHR 0x00 // RX 4 bytes and TX 61 bytes Thresholds
178 |
179 | class WaterMeter
180 | {
181 | private:
182 | inline void selectCC1101(void);
183 | inline void deselectCC1101(void);
184 | inline void waitMiso(void);
185 |
186 | // flush fifo and (re)start receiver
187 | void startReceiver(void);
188 |
189 | // burst write registers of cc1101
190 | void writeBurstReg(uint8_t regaddr, uint8_t* buffer, uint8_t len);
191 |
192 | // burst read registers of cc1101
193 | void readBurstReg(uint8_t * buffer, uint8_t regaddr, uint8_t len);
194 |
195 | // strobe command
196 | void cmdStrobe(uint8_t cmd);
197 |
198 | // read a register of cc1101
199 | uint8_t readReg(uint8_t regaddr, uint8_t regtype);
200 |
201 | // read a byte from fifo
202 | uint8_t readByteFromFifo(void);
203 |
204 | // write a register of cc1101
205 | void writeReg(uint8_t regaddr, uint8_t value);
206 |
207 | // initialize cc1101 registers
208 | void initializeRegisters(void);
209 |
210 | // reset cc1101
211 | void reset(void);
212 |
213 | // receive a wmbus frame
214 | void receive(WMBusFrame *payload);
215 |
216 | public:
217 |
218 | // constructor
219 | WaterMeter(void);
220 |
221 | // startup CC1101 for receiving wmbus mode c
222 | void begin();
223 |
224 | // must be called frequently, returns true if a valid frame was received
225 | bool isFrameAvailable(void);
226 | };
227 |
228 | #endif // _WATERMETER_H_
229 |
--------------------------------------------------------------------------------
/include/hwconfig.h:
--------------------------------------------------------------------------------
1 | #ifndef __HWCONFIG_H__
2 | #define __HWCONFIG_H__
3 |
4 | #if defined(ESP8266)
5 | // Attach CC1101 pins to ESP8266 SPI pins
6 | // VCC => 3V3
7 | // GND => GND
8 | // CSN => D8
9 | // MOSI => D7
10 | // MISO => D6
11 | // SCK => D5
12 | // GD0 => D2 A valid interrupt pin for your platform (defined below this)
13 | // GD2 => not connected
14 | #define CC1101_GDO0 D2 // GDO0 input interrupt pin
15 | #define PIN_LED_BUILTIN D4
16 | #elif defined(ESP32)
17 | // Attach CC1101 pins to ESP32 SPI pins
18 | // VCC => 3V3
19 | // GND => GND
20 | // CSN => 4
21 | // MOSI => 23
22 | // MISO => 19
23 | // SCK => 18
24 | // GD0 => 32 any valid interrupt pin for your platform will do
25 | // GD2 => not connected
26 |
27 | // attach CC1101 pins to ESP32 SPI pins
28 |
29 | #define CC1101_GDO0 32
30 | #define PIN_LED_BUILTIN 2
31 | #endif
32 |
33 | #endif //__HWCONFIG_H__
--------------------------------------------------------------------------------
/platformio.ini:
--------------------------------------------------------------------------------
1 | ; PlatformIO Project Configuration File
2 | ;
3 | ; Build options: build flags, source filter
4 | ; Upload options: custom upload port, speed and extra flags
5 | ; Library options: dependencies, extra library storages
6 | ; Advanced options: extra scripting
7 | ;
8 | ; Please visit documentation for the other options and examples
9 | ; https://docs.platformio.org/page/projectconf.html
10 |
11 | [platformio]
12 | ;default_envs = esp8266-test
13 | ;default_envs = esp32, esp8266
14 | default_envs = esp32
15 |
16 | [env:esp32]
17 | framework = arduino
18 | platform = espressif32@3.4.0
19 | board = esp32dev ;az-delivery-devkit-v4
20 | board_build.mcu = esp32
21 | lib_deps = rweather/Crypto @ ^0.2.0, PubSubClient
22 |
23 |
24 | [env:esp8266]
25 | framework = arduino
26 | platform = espressif8266
27 | board = d1_mini_lite
28 | board_build.mcu = esp8266
29 | lib_deps = rweather/Crypto @ ^0.2.0
30 | ; OTA
31 | ;upload_port = 10.0.0.86
32 | ;upload_protocol = espota
33 |
--------------------------------------------------------------------------------
/src/WMBusFrame.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2020 chester4444@wolke7.net
3 | This program is free software: you can redistribute it and/or modify
4 | it under the terms of the GNU General Public License as published by
5 | the Free Software Foundation, either version 3 of the License, or
6 | (at your option) any later version.
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 | You should have received a copy of the GNU General Public License
12 | along with this program. If not, see .
13 | */
14 |
15 | /* Uncoment the line below for exprimental FlowIQ 2200 support. NOTE: It only reports the volume, other values like temperature will be 0. */
16 |
17 | //#define FLOWIQ2200
18 |
19 | #include "WMbusFrame.h"
20 |
21 | void mqttMyData(const char* debug_str);
22 | void mqttMyDataJson(const char* debug_str);
23 |
24 | WMBusFrame::WMBusFrame()
25 | {
26 | aes128.setKey(key, sizeof(key));
27 | }
28 |
29 | void WMBusFrame::check()
30 | {
31 | // check meterId
32 | for (uint8_t i = 0; i< 4; i++)
33 | {
34 | if (meterId[i] != payload[6-i])
35 | {
36 | isValid = false;
37 | return;
38 | }
39 | }
40 |
41 | Serial.printf("Payload: ");
42 | for(int k=0; k < length; k++) {
43 | Serial.printf("%02x", payload[k]);
44 | }
45 | Serial.printf("\n\r");
46 |
47 | isValid = true;
48 | }
49 |
50 | void WMBusFrame::printMeterInfo(uint8_t *data, size_t len)
51 | {
52 | // init positions for compact frame
53 | int pos_tt = 9; // total consumption, 9, 10, 11, 12
54 | int pos_tg = 13; // target consumption 13, 14, 15, 16
55 | //int pos_ic = 7; // info codes
56 | int pos_ft = 17; // flow temp
57 | int pos_at = 18; // ambient temp
58 |
59 | char mqttstring[25];
60 | char mqttjsondstring[100];
61 |
62 | Serial.printf("Data: ");
63 | for(int k=0; k < len; k++) {
64 | Serial.printf("%02x", data[k]);
65 | }
66 | Serial.printf("\n\r");
67 |
68 | #ifdef FLOWIQ2200
69 | if(data[2] == 0x79) //compact frame
70 | {
71 | pos_tt = 29;
72 | }
73 | #else
74 | // Multical 21
75 | if(data[2] == 0x79) //compact frame
76 | {
77 | pos_tt = 9;
78 | pos_tg = 13;
79 | //pos_ic = 7;
80 | pos_ft = 17;
81 | pos_at = 18;
82 | }
83 | else if (data[2] == 0x78) // long frame
84 | {
85 | // overwrite it with long frame positions
86 | pos_tt = 10;
87 | pos_tg = 16;
88 | //pos_ic = 6;
89 | pos_ft = 23;
90 | pos_at = 29;
91 | }
92 | #endif
93 | else
94 | return;
95 |
96 | uint16_t calc_crc = crc16_EN13757(data+2, len-2);
97 | uint16_t read_crc = data[1] << 8 | data[0];
98 | Serial.printf("calc_crc: 0x%04x\n\r", calc_crc);
99 | Serial.printf("read_crc: 0x%04x\n\r", read_crc);
100 |
101 | if (calc_crc == read_crc)
102 | {
103 | Serial.printf("CRC: OK\n\r");
104 | }
105 | else{
106 | Serial.printf("CRC: ERROR\n\r");
107 | return;
108 | }
109 |
110 |
111 | char total[10];
112 | uint32_t tt = data[pos_tt]
113 | + (data[pos_tt+1] << 8)
114 | + (data[pos_tt+2] << 16)
115 | + (data[pos_tt+3] << 24);
116 | snprintf(total, sizeof(total), "%d.%03d", tt/1000, tt%1000 );
117 | Serial.printf("total: %s m%c - ", total, 179);
118 | snprintf(mqttstring, sizeof(mqttstring), "%d.%03d", tt/1000, tt%1000 );
119 | mqttMyData(mqttstring);
120 |
121 | #ifdef FLOWIQ2200
122 | snprintf(mqttjsondstring, sizeof(mqttjsondstring), "{\"CurrentValue\": %d.%03d,\"MonthStartValue\": %d.%03d,\"WaterTemp\": %2d,\"RoomTemp\": %2d}",tt/1000, tt%1000, 0, 0, 0, 0);
123 | #else
124 | char target[10];
125 | uint32_t tg = data[pos_tg]
126 | + (data[pos_tg+1] << 8)
127 | + (data[pos_tg+2] << 16)
128 | + (data[pos_tg+3] << 24);
129 | snprintf(target, sizeof(target), "%d.%03d", tg/1000, tg%1000 );
130 | Serial.printf("target: %s m%c - ", target, 179);
131 |
132 | char flow_temp[3];
133 | snprintf(flow_temp, sizeof(flow_temp), "%2d", data[pos_ft]);
134 | Serial.printf("%s %cC - ", flow_temp, 176);
135 |
136 | char ambient_temp[3];
137 | snprintf(ambient_temp, sizeof(ambient_temp), "%2d", data[pos_at]);
138 | Serial.printf("%s %cC\n\r", ambient_temp, 176);
139 |
140 | snprintf(mqttjsondstring, sizeof(mqttjsondstring), "{\"CurrentValue\": %d.%03d,\"MonthStartValue\": %d.%03d,\"WaterTemp\": %2d,\"RoomTemp\": %2d}",tt/1000, tt%1000, tg/1000, tg%1000, data[pos_ft],data[pos_at]);
141 | #endif
142 | mqttMyDataJson(mqttjsondstring);
143 | }
144 |
145 | void WMBusFrame::decode()
146 | {
147 | // check meterId, CRC
148 | check();
149 | if (!isValid) return;
150 |
151 | uint8_t cipherLength = length - 2 - 16; // cipher starts at index 16, remove 2 crc bytes
152 | memcpy(cipher, &payload[16], cipherLength);
153 |
154 | memset(iv, 0, sizeof(iv)); // padding with 0
155 | memcpy(iv, &payload[1], 8);
156 | iv[8] = payload[10];
157 | memcpy(&iv[9], &payload[12], 4);
158 |
159 | aes128.setIV(iv, sizeof(iv));
160 | aes128.decrypt(plaintext, (const uint8_t *) cipher, cipherLength);
161 |
162 | /*
163 | Serial.printf("C: ");
164 | for (size_t i = 0; i < cipherLength; i++)
165 | {
166 | Serial.printf("%02X", cipher[i]);
167 | }
168 | Serial.println();
169 | Serial.printf("P(%d): ", cipherLength);
170 | for (size_t i = 0; i < cipherLength; i++)
171 | {
172 | Serial.printf("%02X", plaintext[i]);
173 | }
174 | Serial.println();
175 | */
176 |
177 | printMeterInfo(plaintext, cipherLength);
178 | }
179 |
180 |
181 | uint16_t WMBusFrame::crc16_EN13757(uint8_t *data, size_t len)
182 | {
183 | uint16_t crc = 0x0000;
184 |
185 | assert(len == 0 || data != NULL);
186 |
187 | for (size_t i=0; i> 8) ^ (b & 0x80)){
204 | crc = (crc << 1) ^ CRC16_EN_13757;
205 | }else{
206 | crc = (crc << 1);
207 | }
208 |
209 | b <<= 1;
210 | }
211 |
212 | return crc;
213 | }
214 |
--------------------------------------------------------------------------------
/src/WaterMeter.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2020 chester4444@wolke7.net
3 | This program is free software: you can redistribute it and/or modify
4 | it under the terms of the GNU General Public License as published by
5 | the Free Software Foundation, either version 3 of the License, or
6 | (at your option) any later version.
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 | You should have received a copy of the GNU General Public License
12 | along with this program. If not, see .
13 | */
14 |
15 | #include "WaterMeter.h"
16 | #include "hwconfig.h"
17 |
18 | WaterMeter::WaterMeter()
19 | {
20 | }
21 |
22 | // ChipSelect assert
23 | inline void WaterMeter::selectCC1101(void)
24 | {
25 | digitalWrite(SS, LOW);
26 | }
27 |
28 | // ChipSelect deassert
29 | inline void WaterMeter::deselectCC1101(void)
30 | {
31 | digitalWrite(SS, HIGH);
32 | }
33 |
34 | // wait for MISO pulling down
35 | inline void WaterMeter::waitMiso(void)
36 | {
37 | while(digitalRead(MISO) == HIGH);
38 | }
39 |
40 | // write a single register of CC1101
41 | void WaterMeter::writeReg(uint8_t regAddr, uint8_t value)
42 | {
43 | selectCC1101(); // Select CC1101
44 | waitMiso(); // Wait until MISO goes low
45 | SPI.transfer(regAddr); // Send register address
46 | SPI.transfer(value); // Send value
47 | deselectCC1101(); // Deselect CC1101
48 | }
49 |
50 | // send a strobe command to CC1101
51 | void WaterMeter::cmdStrobe(uint8_t cmd)
52 | {
53 | selectCC1101(); // Select CC1101
54 | delayMicroseconds(5);
55 | waitMiso(); // Wait until MISO goes low
56 | SPI.transfer(cmd); // Send strobe command
57 | delayMicroseconds(5);
58 | deselectCC1101(); // Deselect CC1101
59 | }
60 |
61 | // read CC1101 register (status or configuration)
62 | uint8_t WaterMeter::readReg(uint8_t regAddr, uint8_t regType)
63 | {
64 | uint8_t addr, val;
65 |
66 | addr = regAddr | regType;
67 | selectCC1101(); // Select CC1101
68 | waitMiso(); // Wait until MISO goes low
69 | SPI.transfer(addr); // Send register address
70 | val = SPI.transfer(0x00); // Read result
71 | deselectCC1101(); // Deselect CC1101
72 |
73 | return val;
74 | }
75 |
76 | //
77 | void WaterMeter::readBurstReg(uint8_t * buffer, uint8_t regAddr, uint8_t len)
78 | {
79 | uint8_t addr, i;
80 |
81 | addr = regAddr | READ_BURST;
82 | selectCC1101(); // Select CC1101
83 | delayMicroseconds(5);
84 | waitMiso(); // Wait until MISO goes low
85 | SPI.transfer(addr); // Send register address
86 | for(i=0 ; i Output
213 | SPI.begin(); // Initialize SPI interface
214 | pinMode(CC1101_GDO0, INPUT); // Config GDO0 as input
215 |
216 | reset(); // power on CC1101
217 |
218 | //Serial.println("Setting CC1101 registers");
219 | initializeRegisters(); // init CC1101 registers
220 |
221 | cmdStrobe(CC1101_SCAL);
222 | delay(1);
223 |
224 | attachInterrupt(digitalPinToInterrupt(CC1101_GDO0), GD0_ISR, FALLING);
225 | startReceiver();
226 | }
227 |
228 | // reads a single byte from the RX fifo
229 | uint8_t WaterMeter::readByteFromFifo(void)
230 | {
231 | return readReg(CC1101_RXFIFO, CC1101_CONFIG_REGISTER);
232 | }
233 |
234 | // handles a received frame and restart the CC1101 receiver
235 | void WaterMeter::receive(WMBusFrame * frame)
236 | {
237 | // read preamble, should be 0x543D
238 | uint8_t p1 = readByteFromFifo();
239 | uint8_t p2 = readByteFromFifo();
240 | //Serial.printf("Preamble: %02x%02x\n\r", p1, p2);
241 |
242 | uint8_t payloadLength = readByteFromFifo();
243 |
244 | // is it Mode C1, frame B and does it fit in the buffer
245 | if ( (payloadLength < WMBusFrame::MAX_LENGTH )
246 | && (p1 == 0x54) && (p2 == 0x3D) )
247 | {
248 | // 3rd byte is payload length
249 | frame->length = payloadLength;
250 |
251 | //Serial.printf("%02X", lfield);
252 |
253 | // starting with 1! index 0 is lfield
254 | for (int i = 0; i < payloadLength; i++)
255 | {
256 | frame->payload[i] = readByteFromFifo();
257 | }
258 |
259 | // do some checks: my meterId, crc ok
260 | frame->decode();
261 | }
262 |
263 | // flush RX fifo and restart receiver
264 | startReceiver();
265 | //Serial.printf("rxStatus: 0x%02x\n\r", readStatusReg(CC1101_RXBYTES));
266 | }
--------------------------------------------------------------------------------
/src/credentials_template.h:
--------------------------------------------------------------------------------
1 | #ifndef CREDENTIALS_H
2 | #define CREDENTIALS_H
3 | #include
4 |
5 | //Wifi settings: SSID, PW, MQTT broker
6 | #define NUM_SSID_CREDENTIALS 1
7 | static const char *credentials[NUM_SSID_CREDENTIALS][3] =
8 | // SSID, PW, MQTT
9 | { {"wifi name", "wifi pass", "192.168.1.xxx" }
10 | };
11 |
12 |
13 | const char mqtt_user[] = "mosquitto-user";
14 | const char mqtt_pass[] = "mosquitto-pass!";
15 |
16 | const uint8_t meterId[4] = { 0x00, 0x00, 0x00, 0x00 }; // Multical21 serial. Printed as hex on meter.
17 | const uint8_t key[16] = { 0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 }; // AES-128 key. Ask your service provider.
18 |
19 | #endif
--------------------------------------------------------------------------------
/src/main.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2020 chester4444@wolke7.net
3 | This program is free software: you can redistribute it and/or modify
4 | it under the terms of the GNU General Public License as published by
5 | the Free Software Foundation, either version 3 of the License, or
6 | (at your option) any later version.
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 | You should have received a copy of the GNU General Public License
12 | along with this program. If not, see .
13 | */
14 |
15 | #if defined(ESP8266)
16 | #include
17 | #include
18 | #include
19 | #elif defined(ESP32)
20 | #include
21 | #include
22 | #endif
23 | #include
24 | #include
25 | #include "credentials.h"
26 | #include "WaterMeter.h"
27 | #include "hwconfig.h"
28 |
29 | #define ESP_NAME "WaterMeter"
30 |
31 | #define DEBUG 0
32 |
33 | #if defined(ESP32)
34 | #define LED_BUILTIN 2
35 | #endif
36 |
37 |
38 | WaterMeter waterMeter;
39 |
40 | WiFiClient espMqttClient;
41 | PubSubClient mqttClient(espMqttClient);
42 |
43 | char MyIp[16];
44 | int cred = -1;
45 |
46 | int getWifiToConnect(int numSsid)
47 | {
48 | for (int i = 0; i < NUM_SSID_CREDENTIALS; i++)
49 | {
50 | //Serial.println(WiFi.SSID(i));
51 |
52 | for (int j = 0; j < numSsid; ++j)
53 | {
54 | /*Serial.print(j);
55 | Serial.print(": ");
56 | Serial.print(WiFi.SSID(i).c_str());
57 | Serial.print(" = ");
58 | Serial.println(credentials[j][0]);*/
59 | if (strcmp(WiFi.SSID(j).c_str(), credentials[i][0]) == 0)
60 | {
61 | Serial.println("Credentials found for: ");
62 | Serial.println(credentials[i][0]);
63 | return i;
64 | }
65 | }
66 | }
67 | return -1;
68 | }
69 |
70 | // connect to wifi – returns true if successful or false if not
71 | bool ConnectWifi(void)
72 | {
73 | int i = 0;
74 |
75 | Serial.println("starting scan");
76 | // scan for nearby networks:
77 | int numSsid = WiFi.scanNetworks();
78 |
79 | Serial.print("scanning WIFI, found ");
80 | Serial.print(numSsid);
81 | Serial.println(" available access points:");
82 |
83 | if (numSsid == -1)
84 | {
85 | Serial.println("Couldn't get a wifi connection");
86 | return false;
87 | }
88 |
89 | for (int i = 0; i < numSsid; i++)
90 | {
91 | Serial.print(i+1);
92 | Serial.print(") ");
93 | Serial.println(WiFi.SSID(i));
94 | }
95 |
96 | // search for given credentials
97 | cred = getWifiToConnect(numSsid);
98 | if (cred == -1)
99 | {
100 | Serial.println("No Wifi!");
101 | return false;
102 | }
103 |
104 | // try to connect
105 | WiFi.begin(credentials[cred][0], credentials[cred][1]);
106 | Serial.println("");
107 | Serial.print("Connecting to WiFi ");
108 | Serial.println(credentials[cred][0]);
109 |
110 | i = 0;
111 | while (WiFi.status() != WL_CONNECTED)
112 | {
113 | digitalWrite(LED_BUILTIN, LOW);
114 | delay(300);
115 | Serial.print(".");
116 | digitalWrite(LED_BUILTIN, HIGH);
117 | delay(300);
118 | if (i++ > 30)
119 | {
120 | // giving up
121 | return false;
122 | }
123 | }
124 | return true;
125 | }
126 |
127 | void mqttDebug(const char* debug_str)
128 | {
129 | String s="watermeter/0/debug";
130 | mqttClient.publish(s.c_str(), debug_str);
131 | }
132 |
133 | void mqttCallback(char* topic, byte* payload, unsigned int len)
134 | {
135 | // create a local copies of topic and payload
136 | // PubSubClient overwrites it internally
137 | String t(topic);
138 | byte *p = new byte[len];
139 | memcpy(p, payload, len);
140 |
141 | /* Serial.print("MQTT-RECV: ");
142 | Serial.print(topic);
143 | Serial.print(" ");
144 | Serial.println((char)payload[0]); // FIXME LEN
145 | */
146 | if (strstr(topic, "/smarthomeNG/start"))
147 | {
148 | if (len == 4) // True
149 | {
150 | // maybe to something
151 | }
152 | }
153 | else if (strstr(topic, "/espmeter/reset"))
154 | {
155 | if (len == 4) // True
156 | {
157 | // maybe to something
158 | const char *topic = "/espmeter/reset/status";
159 | const char *msg = "False";
160 | mqttClient.publish(topic, msg);
161 | mqttClient.loop();
162 | delay(200);
163 |
164 | // reboot
165 | ESP.restart();
166 | }
167 | }
168 | // and of course, free it
169 | delete[] p;
170 | }
171 |
172 | bool mqttConnect()
173 | {
174 | mqttClient.setServer(credentials[cred][2], 1883);
175 | mqttClient.setCallback(mqttCallback);
176 |
177 | // connect client to retainable last will message
178 | return mqttClient.connect(ESP_NAME, mqtt_user, mqtt_pass, "watermeter/0/online", 0, true, "False");
179 | }
180 |
181 | void mqttMyData(const char* debug_str)
182 | {
183 | String s="watermeter/0/sensor/mydata";
184 | mqttClient.publish(s.c_str(), debug_str, true);
185 | }
186 |
187 | void mqttMyDataJson(const char* debug_str)
188 | {
189 | String s="watermeter/0/sensor/mydatajson";
190 | mqttClient.publish(s.c_str(), debug_str, true);
191 | }
192 |
193 | void mqttSubscribe()
194 | {
195 | String s;
196 | // publish online status
197 | s = "watermeter/0/online";
198 | mqttClient.publish(s.c_str(), "True", true);
199 | Serial.print("MQTT-SEND: ");
200 | Serial.print(s);
201 | Serial.println(" True");
202 |
203 | // publish ip address
204 | s="watermeter/0/ipaddr";
205 | IPAddress MyIP = WiFi.localIP();
206 | snprintf(MyIp, 16, "%d.%d.%d.%d", MyIP[0], MyIP[1], MyIP[2], MyIP[3]);
207 | mqttClient.publish(s.c_str(), MyIp, true);
208 | Serial.print("MQTT-SEND: ");
209 | Serial.print(s);
210 | Serial.print(" ");
211 | Serial.println(MyIp);
212 |
213 | // if smarthome.py restarts -> publish init values
214 | s = "/smarthomeNG/start";
215 | mqttClient.subscribe(s.c_str());
216 |
217 | // if True; meter data are published every 5 seconds
218 | // if False: meter data are published once a minute
219 | s = "watermeter/0/liveData";
220 | mqttClient.subscribe(s.c_str());
221 |
222 | // if True -> perform an reset
223 | s = "espmeter/reset";
224 | mqttClient.subscribe(s.c_str());
225 | }
226 |
227 | void setupOTA()
228 | {
229 | // Port defaults to 8266
230 | // ArduinoOTA.setPort(8266);
231 |
232 | // Hostname defaults to esp8266-[ChipID]
233 | ArduinoOTA.setHostname(ESP_NAME);
234 |
235 | // No authentication by default
236 | // ArduinoOTA.setPassword((const char *)"123");
237 |
238 | ArduinoOTA.onStart([]() {
239 | String type;
240 | if (ArduinoOTA.getCommand() == U_FLASH) {
241 | type = "sketch";
242 | } else { // U_FS
243 | type = "filesystem";
244 | }
245 |
246 | // NOTE: if updating FS this would be the place to unmount FS using FS.end()
247 | Serial.println("Start updating " + type);
248 | });
249 | ArduinoOTA.onEnd([]() {
250 | Serial.println("\nEnd");
251 | });
252 | ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
253 | Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
254 | });
255 | ArduinoOTA.onError([](ota_error_t error) {
256 | Serial.printf("Error[%u]: ", error);
257 | if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
258 | else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
259 | else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
260 | else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
261 | else if (error == OTA_END_ERROR) Serial.println("End Failed");
262 | });
263 | ArduinoOTA.begin();
264 | }
265 |
266 | // receive encrypted packets -> send it via MQTT to decrypter
267 | void waterMeterLoop()
268 | {
269 | if (waterMeter.isFrameAvailable())
270 | {
271 | // publish meter info via MQTT
272 |
273 | }
274 | }
275 |
276 | void setup()
277 | {
278 | pinMode(LED_BUILTIN, OUTPUT);
279 |
280 | Serial.begin(115200);
281 |
282 | waterMeter.begin();
283 | Serial.println("Setup done...");
284 | }
285 |
286 | enum ControlStateType
287 | { StateInit
288 | , StateNotConnected
289 | , StateWifiConnect
290 | , StateMqttConnect
291 | , StateConnected
292 | , StateOperating
293 | };
294 | ControlStateType ControlState = StateInit;
295 |
296 | void loop()
297 | {
298 | switch (ControlState)
299 | {
300 | case StateInit:
301 | //Serial.println("StateInit:");
302 | WiFi.mode(WIFI_STA);
303 |
304 | ControlState = StateNotConnected;
305 | break;
306 |
307 | case StateNotConnected:
308 | //Serial.println("StateNotConnected:");
309 |
310 | ControlState = StateWifiConnect;
311 | break;
312 |
313 | case StateWifiConnect:
314 | //Serial.println("StateWifiConnect:");
315 | // station mode
316 | ConnectWifi();
317 |
318 | delay(500);
319 |
320 | if (WiFi.status() == WL_CONNECTED)
321 | {
322 | Serial.println("");
323 | Serial.print("Connected to ");
324 | Serial.println(credentials[cred][0]); // FIXME
325 | Serial.print("IP address: ");
326 | Serial.println(WiFi.localIP());
327 |
328 | setupOTA();
329 |
330 | ControlState = StateMqttConnect;
331 | }
332 | else
333 | {
334 | Serial.println("");
335 | Serial.println("Connection failed.");
336 |
337 | // try again
338 | ControlState = StateNotConnected;
339 |
340 | // reboot
341 | ESP.restart();
342 | }
343 | break;
344 |
345 | case StateMqttConnect:
346 | Serial.println("StateMqttConnect:");
347 | digitalWrite(LED_BUILTIN, HIGH); // off
348 |
349 | if (WiFi.status() != WL_CONNECTED)
350 | {
351 | ControlState = StateNotConnected;
352 | break; // exit (hopefully) switch statement
353 | }
354 |
355 | Serial.print("try to connect to MQTT server ");
356 | Serial.println(credentials[cred][2]); // FIXME
357 |
358 | if (mqttConnect())
359 | {
360 | ControlState = StateConnected;
361 | }
362 | else
363 | {
364 | Serial.println("MQTT connect failed");
365 |
366 | delay(1000);
367 | // try again
368 | }
369 | ArduinoOTA.handle();
370 |
371 | break;
372 |
373 | case StateConnected:
374 | Serial.println("StateConnected:");
375 |
376 | if (!mqttClient.connected())
377 | {
378 | ControlState = StateMqttConnect;
379 | delay(1000);
380 | }
381 | else
382 | {
383 | // subscribe to given topics
384 | mqttSubscribe();
385 |
386 | ControlState = StateOperating;
387 | digitalWrite(LED_BUILTIN, LOW); // on
388 | Serial.println("StateOperating:");
389 | //mqttDebug("up and running");
390 | }
391 | ArduinoOTA.handle();
392 |
393 | break;
394 |
395 | case StateOperating:
396 | //Serial.println("StateOperating:");
397 |
398 | if (WiFi.status() != WL_CONNECTED)
399 | {
400 | ControlState = StateWifiConnect;
401 | break; // exit (hopefully switch statement)
402 | }
403 |
404 | if (!mqttClient.connected())
405 | {
406 | Serial.println("not connected to MQTT server");
407 | ControlState = StateMqttConnect;
408 | }
409 |
410 | // here we go
411 | waterMeterLoop();
412 |
413 | mqttClient.loop();
414 |
415 | ArduinoOTA.handle();
416 |
417 | break;
418 |
419 | default:
420 | Serial.println("Error: invalid ControlState");
421 | }
422 | }
423 |
--------------------------------------------------------------------------------