Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
241523abfd |
No files matched your search
-28
@@ -1,28 +0,0 @@
|
|||||||
# Node / web build
|
|
||||||
node_modules/
|
|
||||||
dist/
|
|
||||||
.vite/
|
|
||||||
*.tsbuildinfo
|
|
||||||
|
|
||||||
# Python (server/ has its own .gitignore; these are a repo-wide safety net)
|
|
||||||
.venv/
|
|
||||||
venv/
|
|
||||||
__pycache__/
|
|
||||||
*.py[cod]
|
|
||||||
*.egg-info/
|
|
||||||
.pytest_cache/
|
|
||||||
.ruff_cache/
|
|
||||||
|
|
||||||
# Secrets - never commit. Use the .example files instead.
|
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
!.env.example
|
|
||||||
!*.env.example
|
|
||||||
|
|
||||||
# Local runtime state
|
|
||||||
*.log
|
|
||||||
|
|
||||||
# OS / editor
|
|
||||||
Thumbs.db
|
|
||||||
desktop.ini
|
|
||||||
.DS_Store
|
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
“This License” refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||||
|
|
||||||
|
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||||
|
|
||||||
|
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||||
|
|
||||||
|
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||||
|
|
||||||
|
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||||
|
|
||||||
|
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||||
|
|
||||||
|
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||||
|
|
||||||
|
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||||
|
|
||||||
|
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||||
|
|
||||||
|
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
poorBird
|
||||||
|
Copyright (C) 2026 tom
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
poorBird Copyright (C) 2026 tom
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||||
@@ -1,106 +1,3 @@
|
|||||||
# poorBird
|
# poorBird
|
||||||
|
|
||||||
A radar-triggered bird camera. An ESP32-S3 watches a feeder with a 24 GHz
|
Bird feeder with cam + radar sends pics to database with UI for watching pics and editing bird's attributes
|
||||||
radar module, photographs whatever moves, and uploads it to a small server on
|
|
||||||
the same LAN that stores the images and shows them in a gallery you can label.
|
|
||||||
|
|
||||||
Radar rather than a PIR motion sensor: it sees through a plastic housing,
|
|
||||||
does not care about warm air or moving branches, and reports distance and
|
|
||||||
signal energy, which is enough to tell "a bird landed" from "the hedge moved".
|
|
||||||
|
|
||||||
```
|
|
||||||
ESP32-S3 + LD2410 radar FastAPI + PostgreSQL 17 React gallery
|
|
||||||
------------------------ ----------------------- -------------
|
|
||||||
detects, photographs, ----> stores, thumbnails, <---- browse, filter,
|
|
||||||
buffers, uploads authorises label
|
|
||||||
plain HTTP :8080 loopback :8090 over TLS
|
|
||||||
```
|
|
||||||
|
|
||||||
## Where things stand
|
|
||||||
|
|
||||||
Honestly, because a status table that flatters is worse than none:
|
|
||||||
|
|
||||||
| Part | State |
|
|
||||||
|---|---|
|
|
||||||
| **Firmware** | Written, compiles, **never run on hardware.** |
|
|
||||||
| **Device↔server contract** | Specified in full and implemented on the server. **Never yet exercised by real firmware.** |
|
|
||||||
| **Server** | Phases 1–2 and the Phase 3 server half. 308 tests against real PostgreSQL 17. **Not yet on the real host.** |
|
|
||||||
| **WebUI** | Login and a working cursor-paged gallery. Devices and System are honest empty states waiting on Phase 4. |
|
|
||||||
| **Backups** | **None.** Phase 5. Do not let captures you care about accumulate yet. |
|
|
||||||
|
|
||||||
Nothing here has been released, and `main` means "the project", not "a
|
|
||||||
release".
|
|
||||||
|
|
||||||
## Start here
|
|
||||||
|
|
||||||
| If you want to | Read |
|
|
||||||
|---|---|
|
|
||||||
| use it, in plain language | [`docs/README.USER.md`](docs/README.USER.md) · [Deutsch](docs/README.USER.de.md) |
|
|
||||||
| install it on a Linux box | [`server/deploy/INSTALL.md`](server/deploy/INSTALL.md) |
|
|
||||||
| work on the server | [`server/README.md`](server/README.md) |
|
|
||||||
| work on the UI | [`web/README.md`](web/README.md) |
|
|
||||||
| work on the firmware | [`firmware/README.md`](firmware/README.md) |
|
|
||||||
| know what is broken or unfinished | [`docs/OPEN-TOPICS.AI.md`](docs/OPEN-TOPICS.AI.md) |
|
|
||||||
| know *why* it is built this way | [`SPEC.md`](SPEC.md) |
|
|
||||||
| know what is next | [`TODO.md`](TODO.md) |
|
|
||||||
|
|
||||||
Two documents outrank the rest. [`firmware/API.md`](firmware/API.md) is the
|
|
||||||
device contract: the camera cannot be patched from a laptop once it is mounted
|
|
||||||
outdoors, so where the server and that document disagree, the document wins.
|
|
||||||
[`SPEC.md`](SPEC.md) holds the decisions and the reasons, which is what keeps
|
|
||||||
a later change from quietly undoing an earlier one.
|
|
||||||
|
|
||||||
## Layout
|
|
||||||
|
|
||||||
```
|
|
||||||
firmware/ ESP32-S3 sketch (PlatformIO) + API.md, the device contract
|
|
||||||
server/ FastAPI, PostgreSQL, the job queue, the CLI, systemd + Caddy
|
|
||||||
web/ React gallery, built on your machine and shipped as static files
|
|
||||||
docs/ user guides, open topics, and per-branch code reviews
|
|
||||||
SPEC.md the design and the reasoning behind it
|
|
||||||
TODO.md phase-by-phase plan and the open questions
|
|
||||||
```
|
|
||||||
|
|
||||||
## Constraints that are not up for negotiation
|
|
||||||
|
|
||||||
These are decided in `SPEC.md`, and they explain choices that would otherwise
|
|
||||||
look old-fashioned:
|
|
||||||
|
|
||||||
- **No containers.** Native packages and systemd units on an x86 thin client.
|
|
||||||
- **PostgreSQL, not SQLite.** The job queue needs `FOR UPDATE SKIP LOCKED`.
|
|
||||||
- **No Redis.** The queue is a table; one fewer service to run and back up.
|
|
||||||
- **Caddy, not nginx.** It gets a real certificate for a LAN-only hostname
|
|
||||||
over DNS-01, so there is no browser warning and no port forwarding.
|
|
||||||
- **The camera speaks plain HTTP.** TLS on an ESP32 means a CA baked into
|
|
||||||
firmware and a mounted camera that stops uploading when the chain rotates.
|
|
||||||
- **Images are never served straight off disk.** The app authorises the
|
|
||||||
request and Caddy sends the bytes. An unguessable URL is not access control.
|
|
||||||
- **Logs go to stdout.** journald catches them; the app manages no log files.
|
|
||||||
|
|
||||||
## Quick start on a dev machine
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# server
|
|
||||||
cd server && python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
|
||||||
.venv/bin/poorbird check # says what is misconfigured, and why
|
|
||||||
.venv/bin/poorbird migrate
|
|
||||||
.venv/bin/poorbird user add me --role admin
|
|
||||||
.venv/bin/poorbird seed --captures 500 # something to look at
|
|
||||||
.venv/bin/poorbird serve
|
|
||||||
|
|
||||||
# UI, in another terminal
|
|
||||||
cd web && npm install && npm run dev # http://localhost:5173
|
|
||||||
```
|
|
||||||
|
|
||||||
On Windows the venv puts those executables in `.venv\Scripts\` rather than
|
|
||||||
`.venv/bin/`; [`server/README.md`](server/README.md) covers that setup, uv and
|
|
||||||
Podman included.
|
|
||||||
|
|
||||||
There is no sign-up page and no default account, on purpose — a shipped
|
|
||||||
default credential is a backdoor. Accounts are created with the CLI.
|
|
||||||
|
|
||||||
Two settings need flipping for local development, and both say why in
|
|
||||||
[`server/deploy/poorbird.env.example`](server/deploy/poorbird.env.example):
|
|
||||||
`POORBIRD_SESSION_COOKIE_SECURE=false` (a `Secure` cookie is dropped over
|
|
||||||
plain HTTP, so login silently never sticks) and
|
|
||||||
`POORBIRD_SERVE_IMAGES_DIRECTLY=true` (there is no Caddy to hand the files to).
|
|
||||||
@@ -1,597 +0,0 @@
|
|||||||
# SPEC: poorBird — PIR-triggered bird camera with Raspberry Pi backend
|
|
||||||
|
|
||||||
**Status:** Draft for decision · **Date:** 2026-09-08
|
|
||||||
**Purpose:** Three complete, self-consistent full-stack options at increasing effort levels. Pick one, then this document becomes the baseline.
|
|
||||||
|
|
||||||
> Written in English for consistency with the working language of the review; say the word and I'll translate to German to match `TODO.md`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 0. Decisions taken (2026-09-20)
|
|
||||||
|
|
||||||
Hardware and transport are settled. The firmware skeleton in `firmware/` implements these; `firmware/API.md` is the contract for the Pi side.
|
|
||||||
|
|
||||||
| Decision | Consequence |
|
|
||||||
|---|---|
|
|
||||||
| **Board: Seeed XIAO ESP32S3 Sense** | Closes open question 2. 8 MB PSRAM, 8 MB flash, OV2640, built-in charging. Resolves C5 in favour of "low-power board". |
|
|
||||||
| **Sensor: HLK-LD2410 24 GHz radar** instead of PIR | Works through plastic (sealed enclosure, no sensor cutout), reports distance + energy per gate, detects stationary targets. Supersedes most of C4's mitigations — see below. |
|
|
||||||
| **Mains power, not battery + solar** | **Voids C1, C5 and C9 as written.** See below. |
|
|
||||||
| **OTA mandatory** | C6 unchanged and now non-negotiable. Dual slots, SHA-256 verify, trial boot with automatic rollback, implemented. |
|
|
||||||
| **Live stream: build the plumbing now** | Config surface (on/off, resolution, duration, record/watch/both) and a working chunked MJPEG push, device → Pi. Public relay stays out of scope (C3). |
|
|
||||||
| **Time server on the endpoint** | SNTP against the endpoint, with `server_time` in every API response as the fallback. C7 unchanged: `received_at` stays authoritative. |
|
|
||||||
| **Radar: plain LD2410, 5 V, no Bluetooth** | Baud rate is autodetected, not chosen: a factory-default module (256000), a reconfigured one (115200) and one that has been factory-reset all work without intervention. |
|
|
||||||
| **The camera is not physically reachable once mounted** | No USB recovery. Drives the enrollment design below, and raises the stakes on OTA rollback and on verifying the LD2410's logic levels before connecting them. |
|
|
||||||
| **Server host undecided** — Pi, thin client, or something else | Nothing on the ESP side depends on it; the firmware needs an HTTP endpoint at an IP and port. What it *does* change is below. |
|
|
||||||
| **Language: C++ / Arduino-ESP32 3.x under PlatformIO** | Not MicroPython. Reasoning in the reply that accompanied this change; short version: camera + OTA rollback + PSRAM streaming are all first-class in C and third-party or absent in MicroPython. |
|
|
||||||
|
|
||||||
### What mains power changes
|
|
||||||
|
|
||||||
**C1 is void in the default configuration.** The device stays awake, so commands execute within a loop tick rather than at the next heartbeat. The `device_commands` queue is kept unchanged — it is still the right mechanism, and it is what makes the optional sleep mode work — but "Responsive Mode" is no longer a special tier with a documented battery cost. It is simply how the device runs.
|
|
||||||
|
|
||||||
**C5 is void.** Idle sleep current no longer constrains anything. Panel and battery sizing drop out of scope entirely.
|
|
||||||
|
|
||||||
**C9 is void as a constraint, kept as a policy.** Streaming no longer threatens the power budget. Sessions remain time-boxed (default 60 s, firmware-capped at 600 s) because an unbounded stream is still a bad default, not because of the battery.
|
|
||||||
|
|
||||||
**C4 is largely solved, by a mechanism the battery design could not use.** With the camera permanently initialised, the firmware captures continuously into a PSRAM ring buffer and, on a trigger, uploads the frames from *before* it. Effective trigger latency goes negative. This is the single biggest quality gain from the mains decision — see `firmware/README.md`.
|
|
||||||
|
|
||||||
Two schema additions follow from that:
|
|
||||||
- `captures.pre_trigger BOOL` — was this frame captured before the trigger fired
|
|
||||||
- `devices.awake BOOL` — reported in every heartbeat, so the WebUI can show command latency honestly
|
|
||||||
|
|
||||||
### Device conditions and settings
|
|
||||||
|
|
||||||
The device posts a full conditions report (`POST /status`, and the same body on `/heartbeat`) carrying battery voltage, ticks since last wake, and daily captured/delivered counters; it pulls its settings from `GET /config`. Both are specified in `firmware/API.md`. Further schema additions:
|
|
||||||
|
|
||||||
```sql
|
|
||||||
device_status( -- time series, one row per report
|
|
||||||
id, device_id, at, reason, -- heartbeat | periodic | after_event |
|
|
||||||
-- before_sleep | before_night_sleep | on_request
|
|
||||||
battery_mv, battery_pct, battery_valid,
|
|
||||||
awake_ms, boot_count, wake_cause, last_sleep_s, total_sleep_s,
|
|
||||||
captured_today, delivered_today, failed_today, events_today,
|
|
||||||
is_night, nightlight_on, cam_profile,
|
|
||||||
rssi, free_heap, free_psram, ring_depth
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
`devices` also gains the settings surface: the camera tuning profiles (`cam_day`, `cam_night` — full OV2640 parameter sets), the night window and behaviour, nightlight mode and brightness, and battery calibration. Per §3.4 these are pushed via `apply_config` and versioned by `config_version`.
|
|
||||||
|
|
||||||
Two things the WebUI must get right, because both are easy to render as an alarm when they are not one: `battery_valid = false` means *not measured* (no divider is wired by default), not flat; and the daily counters live in RTC memory and reset on power loss, so the `captures` table stays authoritative — the counters' real value is the *gap* between captured and delivered, which is an upload-health signal.
|
|
||||||
|
|
||||||
**Night behaviour supersedes part of C1 in the other direction.** With `night_behaviour = sleep` (the default, since the OV2640's IR cut filter makes IR illumination useless without modification) the device is deliberately unreachable between dusk and dawn, even on mains. That is a decision about what the camera is *for*, not a power constraint.
|
|
||||||
|
|
||||||
**C2, C3, C6, C7, C8 are unchanged.**
|
|
||||||
|
|
||||||
### Deep sleep is implemented anyway, as a switch
|
|
||||||
|
|
||||||
`deep_sleep_enabled` is a per-device config flag, flippable from the WebUI without a reflash. Off by default. Turning it on restores the battery-oriented behaviour described in C1 and §4.3 — and reinstates their costs: no pre-trigger ring, 1–3 s trigger latency, command latency up to `deep_sleep_s`, streaming only from the next wake.
|
|
||||||
|
|
||||||
One caveat worth recording: the LD2410 draws ~80 mA continuously and must stay powered to serve as a wake source, so with radar wake enabled the ESP sleeping saves very little. Real savings need either timer-only wake with the radar power-gated, or a low-quiescent PIR (AM312) as the wake source with the radar confirming once awake. This is a wiring decision; the firmware supports both.
|
|
||||||
|
|
||||||
### Enrollment must be self-healing
|
|
||||||
|
|
||||||
Because there is no USB access to a mounted camera, a rotated token cannot be allowed to strand the device. The firmware therefore keeps a credential in NVS, deliberately:
|
|
||||||
|
|
||||||
1. The device enrolls with a shared bootstrap secret compiled in from `secrets.ini`.
|
|
||||||
2. The endpoint returns a **per-device** `reenroll_secret`, which replaces the shared one in NVS.
|
|
||||||
3. On any `401` the device clears its token, re-enrolls with that per-device secret and retries — mid-burst, without rebooting.
|
|
||||||
|
|
||||||
The credential left on the device is scoped to that device and cannot enroll another identity, which is what makes keeping it acceptable under C2's threat model. The shared bootstrap secret stays in the firmware image as a last-resort path, so **rotating it server-side without shipping new firmware removes the escape hatch.**
|
|
||||||
|
|
||||||
Schema follow-on: `devices.reenroll_secret_hash`, and re-enrollment of a known `device_uid` must return the existing row with a fresh token rather than creating a duplicate.
|
|
||||||
|
|
||||||
### Server host: Pi vs thin client
|
|
||||||
|
|
||||||
Undecided, and it does not block the ESP work. What it changes on the server side:
|
|
||||||
|
|
||||||
| | Raspberry Pi 4/5 | Thin client (x86) |
|
|
||||||
|---|---|---|
|
|
||||||
| Power | 3–8 W | 10–20 W |
|
|
||||||
| Storage | SSD over USB, or NVMe on a Pi 5 hat | Native SATA/NVMe, no SD card to wear out |
|
|
||||||
| Container images | `linux/arm64` — cross-build or build on the device | `linux/amd64` — matches your dev machine |
|
|
||||||
| Detection (Option C) | Marginal; wants a Coral or Hailo accelerator | Comfortable on CPU, and a GPU is an option |
|
|
||||||
| Cost | New | Often €40–80 secondhand, with more RAM and CPU |
|
|
||||||
|
|
||||||
A thin client is the better machine for everything except idle power, and it removes the SD-card-corruption failure mode that eats Pi deployments. If detection is ever likely to matter, it is the stronger choice. Revisit §10 question 5 once decided.
|
|
||||||
|
|
||||||
### Still open from §10
|
|
||||||
|
|
||||||
Question 4 is answered: the stream is watched on the internal server first, and relayed outward from there if and when that is wanted. That is what §5–§7 already assume (C3), so nothing changes.
|
|
||||||
|
|
||||||
Questions 1 (option A/B/C), 5–9 and 11–17 are unanswered. Question 3 (does the trigger work for your birds) is now a radar-tuning question rather than a PIR one, and remains the biggest unknown in the project.
|
|
||||||
|
|
||||||
**On question 1:** A, B and C are *whole server-side stacks*, not just database choices — §5, §6 and §7 each pick a web framework, database, frontend, auth model, backup tool and deployment method together, because those choices constrain each other. The ESP firmware is identical under all three. Given the decisions above, **Option B**: `record` mode means the stream writer and the ingest writer are two concurrent writers, which is C8's actual argument for PostgreSQL. That was the one thing genuinely pushing past Option A, and streaming is now in scope.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Scope
|
|
||||||
|
|
||||||
### 1.1 In scope
|
|
||||||
|
|
||||||
**ESP32-CAM (outdoor, battery + solar)**
|
|
||||||
- Photo capture triggered by PIR motion sensor
|
|
||||||
- Upload to Raspberry Pi over LAN
|
|
||||||
- Battery voltage reporting, low-battery alarm surfaced in the WebUI
|
|
||||||
- Deep sleep with the longest practical duty cycle
|
|
||||||
- Wake-up / command initiation from the WebUI (see constraint **C1** — this needs redefining)
|
|
||||||
- OTA firmware updates, driven from a WebUI admin view
|
|
||||||
|
|
||||||
**Raspberry Pi (headless, SSD)**
|
|
||||||
- Database holding all capture and observation data
|
|
||||||
- WebUI: gallery + edit functions
|
|
||||||
- Backup to a remote NAS
|
|
||||||
- Authentication *and* authorization (roles)
|
|
||||||
- Configurable through the UI, with three themes: light, dark, blue
|
|
||||||
|
|
||||||
**Observation data (editable)**
|
|
||||||
- Species, biologically grounded (scientific name, family, order, stable taxon ID — not free text)
|
|
||||||
- Capture timestamp
|
|
||||||
- Plus: individuals, age, sex, behaviour, certainty, notes, tags, favourite/reject — see §3
|
|
||||||
|
|
||||||
### 1.2 Future (design for, do not build)
|
|
||||||
- Live stream to an external webspace on an own domain (see constraint **C9**)
|
|
||||||
- Automatic species detection (see Option C, and §3 for the schema hooks)
|
|
||||||
|
|
||||||
### 1.3 Out of scope
|
|
||||||
- Audio recording / BirdNET-style song identification (different sensor, different pipeline)
|
|
||||||
- Multi-site deployment, mobile apps
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Design constraints (apply to all three options)
|
|
||||||
|
|
||||||
These are not preferences. They are properties of the hardware and the network, and every option below respects them identically. Read this section before comparing the options — most of the interesting design work is here, not in the framework choice.
|
|
||||||
|
|
||||||
### C1 — A deep-sleeping ESP32 cannot be contacted. At all.
|
|
||||||
|
|
||||||
> **Superseded by §0** for the default (mains-powered, always-awake) configuration. Still applies in full whenever `deep_sleep_enabled` is switched on.
|
|
||||||
|
|
||||||
In deep sleep the radio and the CPU are off. There is no packet, no magic frame, no server push that reaches the device. **"Wake-up triggered by WebUI" as literally stated is not implementable.**
|
|
||||||
|
|
||||||
What is implementable, and what all three options do:
|
|
||||||
|
|
||||||
**Command queue, polled by the device.** The WebUI writes a command row (`wake_and_hold`, `capture_now`, `apply_config`, `ota_update`, `stream_start`). The device drains the queue on every wake — PIR-triggered *or* on a scheduled heartbeat wake. Worst-case latency to a command equals the heartbeat interval.
|
|
||||||
|
|
||||||
Commands ride along on the upload response (§4.4), so a PIR event that happens to occur costs zero extra energy to also deliver a pending command.
|
|
||||||
|
|
||||||
**Optional "Responsive Mode"** for when you genuinely need low latency: light sleep with WiFi association retained (modem sleep, DTIM wake). Reachable within a beacon interval, at roughly **1–3 mA average instead of 15–40 µA** — a factor of ~100. Viable while mains-powered, or in summer with a healthy battery; not viable as the default. Expose it as a per-device toggle with the power cost stated in the UI, defaulting to off.
|
|
||||||
|
|
||||||
So the honest requirement reads: *"Commands issued in the WebUI are executed at the device's next wake; an admin may enable Responsive Mode for near-immediate execution at a documented battery cost."*
|
|
||||||
|
|
||||||
### C2 — No TLS on the ESP32
|
|
||||||
|
|
||||||
The device speaks **plain HTTP with a bearer token** to a fixed LAN address. All TLS terminates on the Pi.
|
|
||||||
|
|
||||||
Rationale: TLS on the ESP32 means a CA certificate baked into firmware. Certificate chains rotate. When that happens, a device mounted outdoors silently stops uploading and needs physical reflashing. The LAN threat model does not justify that failure mode. The bearer token prevents a stray device on your WiFi from filling the disk.
|
|
||||||
|
|
||||||
### C3 — The Pi is the only internet-facing component
|
|
||||||
|
|
||||||
Now and in future. The ESP32 is never reachable from outside the LAN; the future public stream and public gallery are served *by the Pi*, outbound. This keeps the hard problems (TLS, certificate renewal, authn/authz, abuse handling, rate limiting) on the device that has a package manager and logs.
|
|
||||||
|
|
||||||
### C4 — Trigger latency is physical, and birds are fast
|
|
||||||
|
|
||||||
| Stage | Typical |
|
|
||||||
|---|---|
|
|
||||||
| PIR assert after motion | 0.3–2 s (sensor dependent) |
|
|
||||||
| ESP32 boot from deep sleep | ~0.2–0.4 s |
|
|
||||||
| Camera init + auto-exposure settle | 0.3–0.6 s (discard first 2–3 frames) |
|
|
||||||
| **First usable frame** | **~1–3 s after the bird arrives** |
|
|
||||||
|
|
||||||
A bird flying through is gone. Mitigations, all three options:
|
|
||||||
- Capture a **burst of 3–5 frames**, store all, let the UI pick
|
|
||||||
- Aim at a place where birds *linger* — feeder, perch, water bath — not open air
|
|
||||||
- Tune PIR sensitivity and cooldown from the UI
|
|
||||||
|
|
||||||
Also note PIR limitations that specifically hurt here: small warm targets at distance are marginal, direct sunlight and hot surfaces cause false triggers, and it does not work through glass. **Validate the PIR + placement physically before writing backend code.** If the false-trigger rate is unacceptable, the fallback is on-device frame differencing (Option C) or a beam-break / capacitive perch sensor.
|
|
||||||
|
|
||||||
### C5 — Idle sleep current dominates the energy budget, not the photos
|
|
||||||
|
|
||||||
> **Superseded by §0.** Mains powered; the board choice (XIAO ESP32S3 Sense) was made anyway. Kept for the record and for a future battery deployment.
|
|
||||||
|
|
||||||
Rough figures, to be validated by measurement:
|
|
||||||
|
|
||||||
| | AI-Thinker ESP32-CAM (unmodified) | Low-power board (e.g. XIAO ESP32S3 Sense) |
|
|
||||||
|---|---|---|
|
|
||||||
| Deep sleep current | ~1–3 mA (LDO + camera rail leak) | ~15–40 µA |
|
|
||||||
| Idle drain per day | **24–72 mAh** | **0.4–1 mAh** |
|
|
||||||
| 50 PIR events + 48 heartbeats/day | ~12 mAh | ~12 mAh |
|
|
||||||
| **Total per day** | **~36–84 mAh** | **~13 mAh** |
|
|
||||||
| Runtime on 3000 mAh, zero sun | ~5–12 weeks | ~30 weeks |
|
|
||||||
|
|
||||||
The AI-Thinker board is not designed for low power. Its idle leak is 2–6× the entire photographic workload. Either **hardware-mod it** (bypass the LDO, gate the camera rail with a MOSFET) or **pick a board built for battery use**. Both are fine; doing neither means a 2 W panel that is comfortable in June and dead in December.
|
|
||||||
|
|
||||||
Panel sizing follows from that, not the reverse. Very rough Central European figures: a 2 W / 6 V panel yields on the order of ~1200 mAh/day in summer and ~300 mAh/day averaged over December, with multi-day near-zero stretches under snow. Size the *battery* for a ~2-week no-sun reserve.
|
|
||||||
|
|
||||||
Related: a weak WiFi signal at the camera location extends transmit time and therefore drains battery. Measure RSSI at the mounting point before committing.
|
|
||||||
|
|
||||||
### C6 — OTA must be planned from the first flash
|
|
||||||
|
|
||||||
Dual OTA partitions and a rollback slot have to exist in the partition table from the beginning. Retrofitting them means a physical reflash of a device that is by then mounted outdoors.
|
|
||||||
|
|
||||||
Rules in all options:
|
|
||||||
- Device compares its running version against the server's target on wake
|
|
||||||
- **Refuse to flash below a battery threshold** (default 50 %) — a brownout mid-write bricks the device
|
|
||||||
- Verify SHA-256 before activating the new slot
|
|
||||||
- Boot the new image once in a trial state; roll back automatically if it fails to check in
|
|
||||||
|
|
||||||
### C7 — Time: the server clock is authoritative
|
|
||||||
|
|
||||||
The ESP32 RTC survives deep sleep but drifts, and is lost on any power cycle. So:
|
|
||||||
- Device sends best-effort NTP time plus a monotonic boot counter
|
|
||||||
- **Server `received_at` is authoritative** for ordering and for the gallery's date filter
|
|
||||||
- Store both `captured_at_device` and `received_at`
|
|
||||||
- Store UTC everywhere; render in local timezone. Set `TZ` explicitly on every service — a container defaulting to UTC while you think in CEST is a bug that surfaces months later at a DST boundary.
|
|
||||||
|
|
||||||
### C8 — If SQLite, exactly one writer
|
|
||||||
|
|
||||||
SQLite is entirely adequate for this project's volume. Its real constraint is not scale, it is concurrency: two processes writing produces intermittent `database is locked`. Options A and B therefore keep **all writes inside a single process**, with WAL mode and an explicit `busy_timeout`. Option C introduces a genuine second writer and moves to PostgreSQL *for that reason* — not for "scalability".
|
|
||||||
|
|
||||||
### C9 — Live streaming is incompatible with battery operation
|
|
||||||
|
|
||||||
> **Superseded by §0** as a constraint. The time-boxing survives as policy, not as a power measure.
|
|
||||||
|
|
||||||
MJPEG streaming from an ESP32-CAM draws roughly 200 mA continuously and cannot deep sleep while doing it. A 60-second stream costs about 3.3 mAh — several PIR events' worth.
|
|
||||||
|
|
||||||
Therefore the future stream is: **admin-triggered, time-boxed (default 60 s), rate-limited, gated on battery level, and only reachable after the device's next wake.** Not "always available". The ESP32 pushes to the Pi; the Pi relays outward (C3). Reserve the `stream_start` command type in the schema now and build nothing else.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Common data model
|
|
||||||
|
|
||||||
Identical across all three options; only the engine and the migration tooling change.
|
|
||||||
|
|
||||||
The important structural decision: **`captures` 1—n `observations`.** One photo can contain two birds of different species, and a photo can legitimately have zero observations (false PIR trigger, empty frame). A single `species` column on the image would have to be undone later.
|
|
||||||
|
|
||||||
The second important decision: **human labels and model predictions share one table**, distinguished by `source`. This means the edit UI *is* the training-data pipeline for any future detection model, with no migration needed when you get there.
|
|
||||||
|
|
||||||
```sql
|
|
||||||
-- Devices ------------------------------------------------------------------
|
|
||||||
devices(
|
|
||||||
id, name, hw_revision, fw_version,
|
|
||||||
token_hash, -- bearer token for ingest, rotatable from admin UI
|
|
||||||
last_seen_at, battery_mv, battery_pct, rssi, temp_c,
|
|
||||||
responsive_mode BOOL DEFAULT false, -- C1
|
|
||||||
heartbeat_interval_s INT DEFAULT 1800,
|
|
||||||
enabled BOOL, created_at
|
|
||||||
)
|
|
||||||
|
|
||||||
device_commands( -- C1: the wake-up mechanism
|
|
||||||
id, device_id,
|
|
||||||
type, -- wake_and_hold | capture_now | apply_config | ota_update | stream_start | reboot
|
|
||||||
payload, -- JSON
|
|
||||||
created_by, created_at,
|
|
||||||
delivered_at, acked_at, result, expires_at
|
|
||||||
)
|
|
||||||
|
|
||||||
firmware(
|
|
||||||
id, version, semver, file_path, sha256, size_bytes,
|
|
||||||
release_notes, min_battery_pct DEFAULT 50, -- C6
|
|
||||||
uploaded_by, uploaded_at, is_target BOOL
|
|
||||||
)
|
|
||||||
|
|
||||||
-- Captures -----------------------------------------------------------------
|
|
||||||
captures(
|
|
||||||
id, device_id,
|
|
||||||
path, thumb_path, sha256, width, height, bytes,
|
|
||||||
captured_at_device, received_at, -- C7, received_at authoritative
|
|
||||||
trigger, -- pir | timer | manual | stream_grab
|
|
||||||
burst_id, burst_index, -- C4: 3-5 frames per event
|
|
||||||
battery_mv, rssi, temp_c,
|
|
||||||
reviewed BOOL DEFAULT false,
|
|
||||||
kept BOOL DEFAULT true, -- soft reject, drives retention
|
|
||||||
created_at
|
|
||||||
)
|
|
||||||
|
|
||||||
observations(
|
|
||||||
id, capture_id, taxon_id NULL,
|
|
||||||
individuals INT DEFAULT 1,
|
|
||||||
age, -- adult | juvenile | unknown
|
|
||||||
sex, -- male | female | unknown
|
|
||||||
behaviour, -- feeding | bathing | perching | nesting | fighting | other
|
|
||||||
certainty, -- certain | probable | uncertain
|
|
||||||
notes,
|
|
||||||
source, -- human | model
|
|
||||||
model_version NULL, confidence NULL, bbox NULL, -- future detection
|
|
||||||
created_by, created_at, updated_at
|
|
||||||
)
|
|
||||||
|
|
||||||
taxa( -- seeded, not user-entered free text
|
|
||||||
id, gbif_key, scientific_name,
|
|
||||||
name_de, name_en, family, "order",
|
|
||||||
iucn_status, is_local_common BOOL -- drives autocomplete ranking
|
|
||||||
)
|
|
||||||
|
|
||||||
tags(id, label, colour)
|
|
||||||
capture_tags(capture_id, tag_id)
|
|
||||||
|
|
||||||
-- Access -------------------------------------------------------------------
|
|
||||||
users(
|
|
||||||
id, username, email, password_hash, -- Argon2id
|
|
||||||
role, -- admin | editor | viewer
|
|
||||||
totp_secret NULL, is_active,
|
|
||||||
theme, -- light | dark | blue
|
|
||||||
locale, created_at, last_login_at
|
|
||||||
)
|
|
||||||
sessions(id, user_id, created_at, expires_at, ip, user_agent)
|
|
||||||
|
|
||||||
-- Operations ---------------------------------------------------------------
|
|
||||||
settings(key, value, value_type, scope, updated_by, updated_at) -- scope: server | device
|
|
||||||
audit_log(id, at, user_id, action, entity, entity_id, before, after, ip)
|
|
||||||
backup_runs(id, started_at, finished_at, status, bytes, snapshot_id, error)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3.1 Roles
|
|
||||||
|
|
||||||
| | viewer | editor | admin |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Browse gallery, view data | ✅ | ✅ | ✅ |
|
|
||||||
| Create/edit observations, tags | ❌ | ✅ | ✅ |
|
|
||||||
| Delete captures | ❌ | ❌ | ✅ |
|
|
||||||
| Device settings, commands, wake | ❌ | ❌ | ✅ |
|
|
||||||
| Firmware upload / OTA | ❌ | ❌ | ✅ |
|
|
||||||
| Users, backup, server settings | ❌ | ❌ | ✅ |
|
|
||||||
|
|
||||||
**Devices are not users.** The ESP32 authenticates with a per-device bearer token scoped to `POST /ingest`, `POST /heartbeat`, `GET /firmware`. It can never read the gallery.
|
|
||||||
|
|
||||||
### 3.2 Taxonomy
|
|
||||||
|
|
||||||
Seed `taxa` from a curated list of ~60–80 Central European garden species with GBIF taxon keys, German and scientific names, family and order. The edit form autocompletes on either name and ranks `is_local_common` first. Anything beyond the seed list is a one-row admin addition, not free text.
|
|
||||||
|
|
||||||
This is what makes "information about species (biologically)" real rather than a string column that accumulates *Kohlmeise*, *kohlmeise*, *Parus major* and *Kohlmeise?* as four distinct species.
|
|
||||||
|
|
||||||
### 3.3 Storage layout
|
|
||||||
|
|
||||||
Images on the SSD, date-sharded, never in the database:
|
|
||||||
|
|
||||||
```
|
|
||||||
/srv/poorbird/images/2026/09/08/<uuid>.jpg
|
|
||||||
/srv/poorbird/thumbs/2026/09/08/<uuid>_400.webp
|
|
||||||
```
|
|
||||||
|
|
||||||
Auth-checked image serving in all options: the app authorizes the request and hands off the bytes to the reverse proxy (nginx `X-Accel-Redirect` / Caddy equivalent). An unguessable URL is not access control — without this, images are effectively public even though the UI is behind a login.
|
|
||||||
|
|
||||||
### 3.4 Settings exposed in the UI
|
|
||||||
|
|
||||||
"Fully configurable" needs a boundary, or it never finishes. The enumerated list:
|
|
||||||
|
|
||||||
**Device settings** (pushed to NVS via `apply_config` on next wake): resolution, JPEG quality, burst count, PIR cooldown, heartbeat interval, battery alarm threshold, responsive mode, timezone.
|
|
||||||
|
|
||||||
**Server settings:** retention policy, thumbnail size, backup schedule + target, alarm thresholds and channels, default theme, default locale, session lifetime.
|
|
||||||
|
|
||||||
Anything not on this list is a code change, deliberately.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Shared API shape
|
|
||||||
|
|
||||||
Same in all options; the framework differs.
|
|
||||||
|
|
||||||
### 4.1 Device endpoints (bearer token, plain HTTP, LAN only)
|
|
||||||
```
|
|
||||||
POST /api/v1/ingest multipart: image + JSON meta → 201 {capture_id, commands[], config_version, firmware}
|
|
||||||
POST /api/v1/heartbeat JSON: battery, rssi, fw, uptime → 200 {commands[], config_version, firmware}
|
|
||||||
GET /api/v1/firmware/{version}.bin
|
|
||||||
POST /api/v1/commands/{id}/ack JSON: {status, detail}
|
|
||||||
```
|
|
||||||
|
|
||||||
**The upload response carries the pending command queue.** The device is already awake and associated, so this delivers commands and config at zero extra energy cost. A separate poll only happens on heartbeat wakes when no PIR event occurred.
|
|
||||||
|
|
||||||
### 4.2 UI endpoints (session cookie, CSRF-protected)
|
|
||||||
```
|
|
||||||
GET/PATCH/DELETE /api/v1/captures[/{id}] filter: date range, taxon, device, tag, reviewed, kept
|
|
||||||
POST/PATCH/DELETE /api/v1/captures/{id}/observations[/{oid}]
|
|
||||||
GET /api/v1/taxa?q= autocomplete
|
|
||||||
GET/POST /api/v1/devices[/{id}/commands]
|
|
||||||
POST /api/v1/firmware admin upload
|
|
||||||
GET/PATCH /api/v1/settings
|
|
||||||
GET /api/v1/health device online, battery, disk, last backup
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4.3 Firmware state machine (all options)
|
|
||||||
|
|
||||||
```
|
|
||||||
deep sleep
|
|
||||||
│ PIR (ext0/ext1) ──or── timer (heartbeat)
|
|
||||||
▼
|
|
||||||
boot → read NVS config → init camera → discard 2-3 frames
|
|
||||||
│
|
|
||||||
├─ PIR wake: capture burst → connect WiFi → POST /ingest ──┐
|
|
||||||
└─ timer wake: → connect WiFi → POST /heartbeat ──┤
|
|
||||||
▼
|
|
||||||
process commands + config
|
|
||||||
│
|
|
||||||
┌─────────────────────────────────┤
|
|
||||||
▼ ▼
|
|
||||||
ota_update & battery ok? wake_and_hold?
|
|
||||||
download → verify sha256 stay awake N seconds
|
|
||||||
→ flash inactive slot → reboot (bounded, then sleep)
|
|
||||||
│ │
|
|
||||||
└──────────────┬──────────────────┘
|
|
||||||
▼
|
|
||||||
back to deep sleep (bounded retries,
|
|
||||||
exponential backoff, always sleep on failure)
|
|
||||||
```
|
|
||||||
|
|
||||||
**Every failure path ends in sleep.** An unbounded retry loop on a WiFi outage is the fastest way to flatten the battery — bound retries (e.g. 3 attempts with backoff), then sleep and try at the next wake.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Option A — Minimal
|
|
||||||
|
|
||||||
**Goal: bird photos visible in a browser with the least moving parts. No JavaScript build step, no Docker, no broker.**
|
|
||||||
|
|
||||||
| Layer | Choice |
|
|
||||||
|---|---|
|
|
||||||
| Firmware | Arduino-ESP32 core (built on ESP-IDF), `esp32-camera`, `HTTPClient`, `Update.h` for OTA, `Preferences` for NVS |
|
|
||||||
| Transport | HTTP `POST multipart/form-data` — no MQTT, no broker |
|
|
||||||
| Backend | Python 3.13 + Flask, gunicorn (1 process / 4 threads → satisfies C8 structurally) |
|
|
||||||
| Database | SQLite, WAL mode, `busy_timeout=5000` |
|
|
||||||
| Migrations | Plain numbered `.sql` files applied by a small runner |
|
|
||||||
| Frontend | Jinja2 server-rendered + HTMX for inline edit and filtering. **No npm, no bundler, no Node on the Pi.** |
|
|
||||||
| Themes | Hand-written CSS custom properties, `data-theme` on `<html>`, three token sets, persisted per user + `localStorage` for first paint |
|
|
||||||
| Images | Pillow for thumbnails on upload, served via nginx `X-Accel-Redirect` |
|
|
||||||
| Auth | Flask-Login, Argon2id (`argon2-cffi`), server-side sessions, Flask-WTF CSRF, 3 roles via decorator |
|
|
||||||
| Reverse proxy | nginx, self-signed cert or Tailscale-provided cert |
|
|
||||||
| Remote access | Tailscale |
|
|
||||||
| Backup | cron → `VACUUM INTO` snapshot + `rsync -a --delete` over SSH to NAS |
|
|
||||||
| Deploy | systemd units (`poorbird-web.service`), `apt` + `venv`. No containers. |
|
|
||||||
| Alarms | WebUI health banner + a nightly email or `ntfy` push on low battery / device offline / backup failure |
|
|
||||||
|
|
||||||
**Note on the DB backup:** `cp poorbird.db` on a live WAL database can produce a corrupt copy. Use `VACUUM INTO` (or `sqlite3 .backup`) to get a consistent snapshot. This is the single most common way home-lab backups turn out to be worthless.
|
|
||||||
|
|
||||||
**How the tricky requirements are met**
|
|
||||||
- *Wake-up:* `device_commands` table, drained on upload response + 30-minute heartbeat. Responsive Mode not implemented in this tier.
|
|
||||||
- *OTA:* admin uploads a `.bin`, marks it target; device pulls on next wake if version differs and battery ≥ 50 %.
|
|
||||||
- *Low battery:* voltage in every payload; threshold check server-side; banner + push.
|
|
||||||
- *Backup:* rsync to NAS. Non-blocking, alerts on failure.
|
|
||||||
- *3 themes:* CSS variables, no framework.
|
|
||||||
|
|
||||||
**What you give up**
|
|
||||||
- No task queue: thumbnailing happens inline in the request (~100–300 ms, acceptable at this volume)
|
|
||||||
- No 2FA, no audit log, no fine-grained permissions beyond the three roles
|
|
||||||
- Server-rendered UI — snappy, but not a client-side SPA gallery
|
|
||||||
- No detection pipeline, and Postgres would be a migration if you ever need concurrent writers
|
|
||||||
- Restore is manual, from a documented procedure
|
|
||||||
|
|
||||||
**Rough effort:** walking skeleton (PIR → photo → gallery) in a weekend or two; the full spec above in ~4–6 weeks part-time.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Option B — Solid
|
|
||||||
|
|
||||||
**Goal: the version you can still maintain in three years. Proper migrations, typed API, real backups, containerised.**
|
|
||||||
|
|
||||||
| Layer | Choice |
|
|
||||||
|---|---|
|
|
||||||
| Firmware | **ESP-IDF v5.x** — dual OTA partitions + `esp_ota` rollback, calibrated ADC battery read with a MOSFET-gated divider, exponential backoff, structured logging |
|
|
||||||
| Transport | HTTP POST + bearer token (C2) |
|
|
||||||
| Backend | Python 3.13 + FastAPI, Pydantic v2, SQLAlchemy 2.0, **Alembic** migrations |
|
|
||||||
| Database | **PostgreSQL 17** |
|
|
||||||
| Job queue | Postgres-backed, `FOR UPDATE SKIP LOCKED` — thumbnails, backups, retention, exports. **No Redis.** |
|
|
||||||
| Frontend | React + TypeScript + Vite + TanStack Query/Router, virtualised gallery grid. **Built on your dev machine**, shipped as static files. |
|
|
||||||
| Themes | Design tokens → CSS custom properties, `ThemeProvider`, three themes, per-user persisted |
|
|
||||||
| Auth | Session cookies, Argon2id, **optional TOTP 2FA**, per-device tokens, RBAC with an explicit permission matrix, full `audit_log` |
|
|
||||||
| Reverse proxy | **Caddy** — automatic TLS; valid Let's Encrypt certs for a LAN-only hostname via **DNS-01**, so no port forwarding and no browser warnings |
|
|
||||||
| Remote access | Tailscale |
|
|
||||||
| Backup | **restic** → NAS over SFTP; `pg_dump` pre-hook; retention 7 daily / 4 weekly / 12 monthly; healthcheck ping; **monthly automated restore test** into a scratch container |
|
|
||||||
| Deploy | Docker Compose — *now* justified, because there are genuinely several services. Images built with `buildx --platform linux/arm64` on the dev machine. Healthchecks + `condition: service_healthy`, log rotation (`max-size`/`max-file`), `.env` for secrets, `.dockerignore`, explicit `TZ` |
|
|
||||||
| Alarms | `ntfy`/Gotify push + WebUI, for low battery, device offline > N hours, disk > 80 %, backup failure |
|
|
||||||
|
|
||||||
**Why PostgreSQL here and not in Option A:** this tier introduces a background worker, which is a second writer (C8). Multiple writers is a good reason for Postgres. "Scalability" for a one-camera garden project is not — ignore that argument if you meet it.
|
|
||||||
|
|
||||||
**How the tricky requirements are met**
|
|
||||||
- *Wake-up:* command queue + **adaptive heartbeat** (e.g. 5 min in daylight, 60 min at night — better latency when birds are active, less drain when they aren't) + **Responsive Mode** toggle with the mA cost shown in the UI
|
|
||||||
- *OTA:* signed manifest, SHA-256 verify, trial boot with automatic rollback, battery gate, staged rollout per device
|
|
||||||
- *Backup:* restic with a *tested* restore. A backup you have never restored is a hypothesis.
|
|
||||||
- *Config:* `settings` table → `config_version` → device pulls and writes NVS on next wake
|
|
||||||
|
|
||||||
**What you give up**
|
|
||||||
- No automatic species detection (schema is ready; the pipeline is not built)
|
|
||||||
- No public stream
|
|
||||||
- No metrics/dashboards beyond the health endpoint
|
|
||||||
|
|
||||||
**Rough effort:** ~3–4 months part-time. This is the recommendation.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Option C — Full platform
|
|
||||||
|
|
||||||
**Goal: everything in the brief plus automatic species detection, observability, and a real path to the public stream.**
|
|
||||||
|
|
||||||
Everything in Option B, plus:
|
|
||||||
|
|
||||||
| Area | Addition |
|
|
||||||
|---|---|
|
|
||||||
| Hardware | Low-power board (C5) · **DS3231 RTC** for reliable time across power cycles · **BME280** for temperature/humidity enrichment · multi-camera support |
|
|
||||||
| Firmware | **On-device frame differencing** to confirm PIR triggers before spending WiFi energy — cuts false positives and battery drain together · Secure Boot v2 + flash encryption + anti-rollback · device provisioning flow |
|
|
||||||
| Detection | Two-stage: an animal/bird detector (YOLO-class or MegaDetector) then a species classifier fine-tuned on **your own** labelled captures. ONNX Runtime or LiteRT in a dedicated container. Predictions land in `observations` with `source='model'` alongside human labels. |
|
|
||||||
| The loop | The edit UI doubles as a **labelling tool** — keyboard-driven (`j`/`k` to move, `1`–`9` for the top species, `Enter` to confirm) — feeding periodic retraining. This is what makes detection actually work on your garden and your camera angle, rather than a generic model that confuses Blaumeise and Kohlmeise. |
|
|
||||||
| Storage | Content-addressed image store, optional MinIO |
|
|
||||||
| Auth | External OIDC (Pocket ID / Authelia / Keycloak), fine-grained RBAC, ready for the public site's OAuth2 |
|
|
||||||
| Observability | Prometheus + Grafana + Loki; alerting on battery, device offline, disk, backup failure, detection queue depth |
|
|
||||||
| Backup | restic → NAS **and** offsite (B2/S3), monitored with a dead-man switch, documented RPO/RTO, automated restore verification |
|
|
||||||
| Public stream | **MediaMTX** on the Pi: ESP32 pushes on demand → MediaMTX → WebRTC/HLS out via **Cloudflare Tunnel** (public domain + TLS, no port forwarding, ESP32 still never internet-facing per C3). Time-boxed and battery-gated per C9. |
|
|
||||||
| Provisioning | **Ansible** playbook for the whole Pi, so a card failure is a rebuild rather than an archaeology project |
|
|
||||||
| Frontend | PWA, offline-capable, full design-token system across the three themes |
|
|
||||||
|
|
||||||
**Deliberately still not included: Kubernetes.** k3s on a single Pi adds a control plane and gains nothing here. Docker Compose remains correct even at this tier.
|
|
||||||
|
|
||||||
**Honest note on detection accuracy:** a generic pretrained model will disappoint on small, partly obscured, motion-blurred garden birds. Expect to label 500–2000 of your own images before fine-tuning earns its keep. Budget for that, or treat detection as pre-filtering ("bird / no bird", which works well and immediately) rather than species identification.
|
|
||||||
|
|
||||||
**Rough effort:** ~6–12 months part-time. Only worth it if the detection loop is the point.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Comparison
|
|
||||||
|
|
||||||
| | A — Minimal | B — Solid | C — Full platform |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Firmware | Arduino core | ESP-IDF v5 | ESP-IDF v5 + secure boot |
|
|
||||||
| Backend | Flask | FastAPI | FastAPI + workers |
|
|
||||||
| Database | SQLite | PostgreSQL 17 | PostgreSQL 17 + Redis |
|
|
||||||
| Frontend | Jinja2 + HTMX | React + TS | React PWA |
|
|
||||||
| Node.js needed | ❌ | dev machine only | dev machine only |
|
|
||||||
| Containers | ❌ systemd | ✅ Compose | ✅ Compose |
|
|
||||||
| Migrations | numbered SQL | Alembic | Alembic |
|
|
||||||
| 2FA / audit log | ❌ | ✅ | ✅ + OIDC |
|
|
||||||
| Backup | rsync + snapshot | restic + restore test | restic + offsite + verify |
|
|
||||||
| Responsive Mode | ❌ | ✅ | ✅ |
|
|
||||||
| Species detection | ❌ | ❌ (schema ready) | ✅ |
|
|
||||||
| Public stream | ❌ | ❌ | ✅ |
|
|
||||||
| Metrics/alerting | banner + push | push | Prometheus/Grafana |
|
|
||||||
| Effort (part-time) | 4–6 weeks | 3–4 months | 6–12 months |
|
|
||||||
|
|
||||||
### Recommendation
|
|
||||||
|
|
||||||
**Build Option A's walking skeleton first, then grow into Option B.**
|
|
||||||
|
|
||||||
Not because A is the goal, but because the riskiest unknowns in this project are physical, not architectural: does PIR reliably trigger on the birds at your feeder, at your distance, in your light? What is the real sleep current of your board? How many usable frames per day do you actually get? All three options share §2, §3 and §4 — so a week spent proving the hardware with Flask and SQLite is not wasted work if you then move to FastAPI and Postgres. The data model does not change.
|
|
||||||
|
|
||||||
Deciding between B and C can wait until you have a few thousand real captures, at which point you will also know whether you want detection badly enough to label them.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Shared hardware notes
|
|
||||||
|
|
||||||
| Item | Note |
|
|
||||||
|---|---|
|
|
||||||
| Camera board | AI-Thinker ESP32-CAM works, but see C5 — either mod it or use a low-power board with built-in charging |
|
|
||||||
| PIR sensor | **AM312** preferred over HC-SR501: 3.3 V native, far lower quiescent draw. Wake via `ext0` on an RTC-capable GPIO — check pin conflicts carefully, the ESP32-CAM has very few free pins once camera and SD are wired |
|
|
||||||
| Battery | **LiFePO4** worth considering over LiPo: better cold tolerance, far more cycles, and 3.2–3.65 V suits a 3.3 V rail. Either chemistry: **neither can be safely charged below 0 °C** — use a charger with NTC cutoff, or inhibit charging in frost |
|
|
||||||
| Panel | Size after measuring sleep current, not before. ~2 W/6 V is a reasonable starting point *with* a low-power board |
|
|
||||||
| Battery sense | Voltage divider on an ADC pin, **gated by a MOSFET** — an always-connected divider drains the battery continuously. Calibrate; the ESP32 ADC is non-linear |
|
|
||||||
| Enclosure | IP65 minimum, sun shade over the lens, drainage, desiccant. Condensation on the lens ruins more photos than any software bug |
|
|
||||||
| Pi | Model matters (see open questions). Put Docker's `data-root` on the SSD; set up log rotation or the SD card dies |
|
|
||||||
| Network | Measure RSSI at the mounting point. DHCP reservation for the Pi, then hardcode that IP in firmware — simpler and more reliable than mDNS |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Open questions
|
|
||||||
|
|
||||||
Ordered by how much they block. The first four change the build; the rest can be answered as you go.
|
|
||||||
|
|
||||||
### Blocking
|
|
||||||
|
|
||||||
1. **Which option — A, B or C?** Or A-now-then-B, as recommended in §8?
|
|
||||||
2. **Camera board:** unmodified AI-Thinker, hardware-modified AI-Thinker, or a low-power board with built-in charging? Per C5 this decides the solar/battery sizing more than anything else does.
|
|
||||||
3. **Does PIR actually work for your birds, at your placement?** Needs a physical test before software. If not: on-device frame differencing, or a perch/beam sensor?
|
|
||||||
4. **Is Tailscale-only remote access enough**, or do you want a public domain and a public gallery reasonably soon? Answering "public soon" pulls OAuth2, rate limiting, and a hardened ingress back into scope.
|
|
||||||
|
|
||||||
### Shapes the design
|
|
||||||
|
|
||||||
5. **Raspberry Pi model and RAM?** Pi 4 vs Pi 5 vs NVMe-capable — affects boot-from-SSD setup and rules Option C's detection in or out.
|
|
||||||
6. **How many cameras, eventually?** One, or several? The schema supports many; device management UI and OTA staging get more work if it's really more than one.
|
|
||||||
7. **Expected volume:** captures per day, roughly? Drives storage, retention, and whether inline thumbnailing is fine.
|
|
||||||
8. **Retention policy:** keep everything forever, or auto-delete rejected/unlabelled captures after N days? A birdcam will fill any disk you give it. And: does deleting a capture in the UI delete the file, or only hide it?
|
|
||||||
9. **NAS access protocol:** SSH/SFTP available? SMB or NFS only? restic and borg want SFTP or a mounted path — this decides the backup tooling.
|
|
||||||
10. **Battery chemistry**, and do you care about winter operation? Charging below freezing is the crux.
|
|
||||||
|
|
||||||
### Details worth settling early
|
|
||||||
|
|
||||||
11. **UI language:** German, English, or both? i18n is cheap on day one and annoying to retrofit. Species names should carry `name_de` and `name_en` regardless.
|
|
||||||
12. **Taxonomy source:** GBIF backbone keys as proposed, or IOC / Avibase? And which regional species list should seed the autocomplete?
|
|
||||||
13. **The "blue" theme** — any reference you have in mind (a screenshot, a palette, a site you like), or my choice?
|
|
||||||
14. **Is 2FA a requirement**, or is a strong password on a LAN-only service enough for now?
|
|
||||||
15. **Beyond species, timestamp and the fields proposed in §3** — anything else you want to record? Weather, feeder type, ring number, whether you were watching?
|
|
||||||
16. **Your comfort level in C, Python, and TypeScript?** This should genuinely influence the A/B/C choice more than the feature lists do — Option B's React frontend is the largest single chunk of unfamiliar work if TypeScript is new.
|
|
||||||
17. **Can the camera see beyond your own property** — a neighbour's garden, a public path? If so there is a GDPR dimension worth one paragraph in the deployment notes.
|
|
||||||
@@ -1,341 +0,0 @@
|
|||||||
# TODO: poorBird
|
|
||||||
|
|
||||||
**Baseline:** [SPEC.md](SPEC.md) · **Device contract:** [firmware/API.md](firmware/API.md) · **Hardware notes:** [firmware/README.md](firmware/README.md)
|
|
||||||
**Updated:** 2026-09-20
|
|
||||||
|
|
||||||
This file tracks *work*. It does not restate decisions — those live in SPEC §0.
|
|
||||||
Anything here that contradicts SPEC means SPEC needs an edit, not a workaround.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Decisions since SPEC §0
|
|
||||||
|
|
||||||
| Decision | Consequence |
|
|
||||||
|---|---|
|
|
||||||
| **Deploy natively, not with Docker** | SPEC §6's *Deploy* row is void; the stack itself is unchanged (FastAPI + PostgreSQL 17 + React/TS). It runs as systemd units from a venv, with Caddy and Postgres as host packages. `TODO.Dockerization.md` is deleted — the content was obsolete, not the idea. |
|
|
||||||
| **Build container-ready anyway** | Containers stay a plausible future, so the design avoids anything that would make the move expensive. Constraints listed under Phase 1.2. They cost close to nothing and most are better practice natively too. |
|
|
||||||
| **Server = x86 thin client, Linux, same LAN** | Closes SPEC §10 Q5. amd64 matches the dev machine, so no cross-building. Native NVMe/SATA, no SD-card corruption failure mode. Detection (Option C) stays physically possible. |
|
|
||||||
| **The server owns everything non-device** | Database, WebUI, image store, auth, backup, OTA hosting, stream sink. The ESP side only ever needs one IP and port. |
|
|
||||||
|
|
||||||
- [ ] Fold these three rows into SPEC §0 and strike the *Deploy* row of §6 — **do this first**, so SPEC stays the single baseline
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Where things actually stand
|
|
||||||
|
|
||||||
| Area | State |
|
|
||||||
|---|---|
|
|
||||||
| Firmware | Written, compiles, **never run on hardware**. Known gaps below. |
|
|
||||||
| Device↔server contract | Specified in full (`firmware/API.md`). Server half of the **device** endpoints implemented (Phase 2). The operator-facing half (firmware upload, device management) no longer waits on auth — that exists now — only on Phase 4. |
|
|
||||||
| Data model | Designed (SPEC §3) + §0 additions, migration written and applied, guarded by a drift test. |
|
|
||||||
| Server | Phases 1 and 2 plus the Phase 3 server half, in [`server/`](server/) — config, schema, health, job queue, scheduler, systemd units, every device endpoint the firmware calls, and user auth with the captures API behind it. Verified on Python 3.14.7 against PostgreSQL 17: 308 tests, migrations applied, real HTTP ingest through the worker to a WebP thumbnail on disk. Not yet on the real host, and **never yet spoken to by real firmware**. |
|
|
||||||
| WebUI | Shell, themes, i18n, login and a working cursor-paged gallery on `feature/UI_Basic_implementation`. Devices and System are still honest empty states — they need Phase 4 endpoints. **The gallery's appearance has not been checked in a browser yet.** |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 0 — Hardware bring-up (blocks everything)
|
|
||||||
|
|
||||||
The riskiest unknowns in this project are physical, not architectural. None of the
|
|
||||||
server work is wasted if this goes badly, but all of it is pointless until it goes well.
|
|
||||||
|
|
||||||
### 0.1 Before anything is connected
|
|
||||||
|
|
||||||
- [ ] **Measure the LD2410's TX logic level on a 5 V supply.** Unverified on this hardware
|
|
||||||
(`firmware/README.md` → Wiring). A 5 V swing into the ESP32S3 RX damages the pin.
|
|
||||||
Level-shift or divide if it is not 3.3 V.
|
|
||||||
- [ ] Verify `PIN_STATUS_LED` (GPIO21) against the actual XIAO board revision — it has moved between revisions
|
|
||||||
- [ ] Bench-power the board and confirm the mains supply holds up under WiFi TX + camera peaks
|
|
||||||
|
|
||||||
### 0.2 First flash
|
|
||||||
|
|
||||||
- [ ] Fill `secrets.ini` from `secrets.ini.example`, flash with the OTA partition table (`partitions/poorbird_8mb_ota.csv`)
|
|
||||||
- [ ] Confirm PSRAM is detected and the frame ring allocates at the configured depth
|
|
||||||
- [ ] Confirm camera init + the day profile produce a sane JPEG over serial/local dump
|
|
||||||
- [ ] Confirm SNTP sync, and that the device falls back to `server_time` cleanly when SNTP fails
|
|
||||||
|
|
||||||
### 0.3 Radar — the biggest unknown in the project
|
|
||||||
|
|
||||||
SPEC §10 Q3, restated as a radar question. Everything downstream assumes this works.
|
|
||||||
|
|
||||||
- [ ] Verify `ld2410.cpp` frame offsets against real module output — they are from the datasheet, not measured
|
|
||||||
- [ ] Verify baud autodetection across all three cases: factory default (256000), reconfigured (115200), factory-reset
|
|
||||||
- [ ] Make `radarSetGateSensitivity` validate that the ACK *matches*, not merely that bytes came back
|
|
||||||
- [ ] **Tune gates for birds at the real feeder distance.** Log distance + per-gate energy for a full day, then set thresholds from the data rather than from defaults
|
|
||||||
- [ ] Decide the fallback if radar cannot be tuned acceptably: AM312 PIR on `PIN_AUX_ADC` (one function, `radarIsTrigger`), or on-device frame differencing
|
|
||||||
|
|
||||||
### 0.4 Known code defects
|
|
||||||
|
|
||||||
- [ ] `nightlight.cpp` allocates an LEDC channel after the camera has claimed channel 0 for XCLK — routes around it in theory, untested in practice
|
|
||||||
- [ ] Battery percentage curves are generic room-temperature open-circuit approximations. Fine for the low banner and the OTA gate; do not present as a runtime estimate
|
|
||||||
- [ ] Enclosure: IP65, sun shade, drainage, desiccant. Condensation ruins more photos than any software bug
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 1 — Server foundation
|
|
||||||
|
|
||||||
Target host: the x86 Linux thin client. No containers — packages and systemd units.
|
|
||||||
|
|
||||||
Skeleton written — see [`server/README.md`](server/README.md) to run it, and
|
|
||||||
[`server/deploy/INSTALL.md`](server/deploy/INSTALL.md) to deploy it. What is
|
|
||||||
written vs. what still needs doing on the real host:
|
|
||||||
|
|
||||||
- [x] Python venv layout, FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Alembic — `server/`
|
|
||||||
- [x] systemd units `poorbird-api.service` + `poorbird-worker.service`, `After=postgresql.service`, restart policies, sandboxing
|
|
||||||
- [x] Caddyfile with DNS-01 TLS, the `:8080` plain-HTTP camera listener and the auth-checked image handoff
|
|
||||||
- [x] `poorbird check` — validates config, paths and DB before anything starts
|
|
||||||
- [x] **Run it against a real PostgreSQL** — done on the dev machine (uv-managed Python 3.14.7, Podman `postgres:17`): `poorbird check`, `migrate`, `serve`, `worker` and 12/12 tests all green
|
|
||||||
- [ ] Repeat the same four commands on the actual thin client, which is the run that counts
|
|
||||||
- [ ] Base install on the thin client: static IP (or DHCP reservation) and **hardcode that address in firmware** — more reliable than mDNS
|
|
||||||
- [ ] PostgreSQL 17 from the distro or PGDG repo; dedicated role + database; **loopback TCP with `scram-sha-256`, not a Unix socket** (see 1.2)
|
|
||||||
- [ ] Caddy DNS provider plugin build (`caddy add-package …`) and a real hostname
|
|
||||||
- [ ] Tailscale for remote access
|
|
||||||
- [x] Image store at `/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) — writer landed with Phase 2; writes are atomic (`.part` then `os.replace`) so a crash cannot leave a half-JPEG that a thumbnail job would then fail on
|
|
||||||
- [ ] journald log retention capped, disk usage alarmed
|
|
||||||
|
|
||||||
### 1.1 Schema — SPEC §3 plus the §0 additions
|
|
||||||
|
|
||||||
- [x] Initial Alembic migration covering SPEC §3, guarded by a schema-drift test
|
|
||||||
- [x] `captures.pre_trigger BOOL` — was this frame captured *before* the trigger fired
|
|
||||||
- [x] `devices.awake BOOL` — reported every heartbeat, so the UI can show command latency honestly
|
|
||||||
- [x] `devices.reenroll_secret_hash`
|
|
||||||
- [x] `device_status` time-series table (SPEC §0 columns, plus `raw` JSONB so nothing is lost)
|
|
||||||
- [x] `devices` settings surface — **one JSONB `config` column, not forty**: `GET /config` is ~40 optional keys the firmware merges and clamps, so a column per key means a migration per firmware tunable. Validation moves to a Pydantic model. Promote an individual key to a column only if it ever needs querying across devices.
|
|
||||||
- [x] Job queue on Postgres with `FOR UPDATE SKIP LOCKED` — **No Redis.** Handlers for thumbnails / retention / backup arrive with their phases.
|
|
||||||
- [ ] Seed `taxa` (Phase 3) and the `settings` defaults
|
|
||||||
|
|
||||||
### 1.2 Staying container-ready
|
|
||||||
|
|
||||||
Not building containers now. Just not painting into a corner. Each of these is
|
|
||||||
cheap today and most are the better native choice regardless.
|
|
||||||
|
|
||||||
- [x] **All config from environment**, via systemd `EnvironmentFile=/etc/poorbird/poorbird.env`. No paths, hosts or secrets baked into code or committed config. That file becomes a compose `.env` unchanged.
|
|
||||||
- [x] **Postgres over loopback TCP**, not a Unix socket — the one genuinely container-hostile choice, and the only real change from a purely native design
|
|
||||||
- [x] **All mutable state in a few explicit top-level directories** (`/srv/poorbird/images`, `/srv/poorbird/thumbs`, `/var/lib/poorbird`), never scattered under the app dir. These are the future volume mounts.
|
|
||||||
- [x] **Log to stdout/stderr.** journald catches it now, a log driver would catch it later. Simpler than app-managed log files either way.
|
|
||||||
- [x] **Migrations as a standalone idempotent command** (`poorbird migrate`), run from `ExecStartPre` on the API unit only — never at app import time, and never from two units at once
|
|
||||||
- [x] **One env var for the image root**, read by both the app and the Caddy config, since the auth-checked handoff needs them to agree on the path
|
|
||||||
- [x] **Scheduled jobs run in the worker, not as systemd timers** — decided. APScheduler with a SQLAlchemy jobstore on the existing Postgres. Not primarily for portability: SPEC §3.4 makes *backup schedule + target* and *retention policy* UI-editable server settings, and a UI-editable systemd timer means the app writing unit files and calling `daemon-reload` behind a polkit or sudoers rule. In-app, the schedule is just a settings row. Timers stay the better answer for anything that is **not** UI-configurable — if such a job appears, use one.
|
|
||||||
- [x] Keep API and worker as separate processes — maps 1:1 to two services later
|
|
||||||
|
|
||||||
**Deliberately not doing now:** writing Dockerfiles or a compose file speculatively. That means maintaining two deployment paths to prove a point.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 2 — Walking skeleton: radar → photo → gallery
|
|
||||||
|
|
||||||
The first milestone worth celebrating. Nothing below this line matters until a real
|
|
||||||
bird photo appears in a browser.
|
|
||||||
|
|
||||||
- [x] `POST /api/v1/enroll` — bootstrap secret in, per-device `reenroll_secret` + token out.
|
|
||||||
**Re-enrolling a known `device_uid` must return the existing row with a fresh token, never a duplicate.**
|
|
||||||
Accepts the shared secret *or* that device's own `reenroll_secret`; checking only the
|
|
||||||
shared one would lock out every device already enrolled. Hardware facts (`mac`,
|
|
||||||
`hw_revision`, `fw_version`) refresh on every enrollment, the operator's `name` does not.
|
|
||||||
- [x] `POST /api/v1/ingest` — **raw JPEG body with metadata in headers, not multipart.**
|
|
||||||
`firmware/API.md` and `uploader.cpp` send the bytes directly; multipart was a
|
|
||||||
misreading. Honours `X-Pre-Trigger`, dedupes on sha256 per device.
|
|
||||||
- [x] `POST /api/v1/heartbeat` and `POST /status` — full conditions report into `device_status`
|
|
||||||
- [x] `GET /api/v1/config` — enums by name not number, `config_version` bump semantics.
|
|
||||||
Column-backed keys win over stale JSONB copies, so an operator rename actually reaches
|
|
||||||
the device; the device's own `config_version` never overwrites the server's.
|
|
||||||
- [x] Response envelope + `server_time` (SPEC C7: `received_at` stays authoritative).
|
|
||||||
On `/heartbeat` and `/ingest`. **Not** on `/status`, which is 204 with no body per
|
|
||||||
`firmware/API.md` — "every response" was not compatible with the firmware contract.
|
|
||||||
- [x] Thumbnail job on ingest — 400px WebP, decode kept off the request path
|
|
||||||
- [x] Device authentication, rate limiting, `POST /commands/{id}/ack`, `GET /firmware/{v}.bin`
|
|
||||||
— not in the original list, but the firmware calls them (see `docs/reviews/`)
|
|
||||||
- [~] Minimal gallery page purely to prove the path — **superseded.** The scaffold's System page
|
|
||||||
already proves browser → proxy → FastAPI → Postgres, and SPEC §3.3 requires image serving
|
|
||||||
to be auth-checked, so "no auth yet" is not a state the gallery can legitimately pass
|
|
||||||
through. The real grid is Phase 3, behind sessions.
|
|
||||||
- [ ] **End-to-end test on real hardware:** bird walks past → burst uploads → visible in browser.
|
|
||||||
Blocked on Phase 0: the server side is proven only against synthetic uploads.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 3 — WebUI
|
|
||||||
|
|
||||||
Scaffolding done — see [`web/README.md`](web/README.md). Typechecks, builds,
|
|
||||||
and the System page reads live data through the Vite proxy.
|
|
||||||
|
|
||||||
- [x] React 19 + TS + Vite + TanStack Query/Router, built on the dev machine, served as static files by Caddy
|
|
||||||
- [x] Three themes as design tokens, `data-theme` on `<html>`, no flash of the wrong theme
|
|
||||||
- [x] `npm run check:contrast` — asserts WCAG AA across all three themes; caught three failing `--border-strong` values on its first run
|
|
||||||
- [x] i18n de/en with a build-time-complete catalogue
|
|
||||||
- [x] Auth shell: provider, login form with TOTP field, `RequireAuth` (no dev bypass, on purpose)
|
|
||||||
- [x] System page on live `/health` — the end-to-end proof browser → proxy → FastAPI → Postgres
|
|
||||||
- [x] Wire `RequireAuth` into `router.tsx` and delete the "not enforced" banner — gallery needs
|
|
||||||
any signed-in user, Devices and System need `admin`. Sign-out is in the header.
|
|
||||||
- [ ] ESLint (skipped during scaffolding; `tsc --noEmit` covers the important cases for now)
|
|
||||||
- [x] Virtualised gallery grid, cursor-paged, thumbnails through the auth-checked route.
|
|
||||||
Filters for date range, device, kept, reviewed and pre-trigger — the columns that have
|
|
||||||
data. **Taxon and tag filters are deliberately still missing:** both need a join, and
|
|
||||||
neither has anything to join to until `taxa` is seeded and the observation editor exists.
|
|
||||||
A filter that can only return nothing is worse than an absent one, because the UI offers it.
|
|
||||||
- [x] `poorbird seed --captures 500` — synthetic captures with real JPEGs on disk, realistic
|
|
||||||
burst structure and pre-trigger flags. `--clear` is scoped to its own device so it can
|
|
||||||
never remove a real camera's frames.
|
|
||||||
- [ ] Full-size viewer: keyboard navigation is in, but it only steps through what is already
|
|
||||||
loaded. Stepping past the last loaded page needs the viewer to be able to trigger a fetch.
|
|
||||||
- [ ] Observation editor — `captures` 1—n `observations`, so a photo can hold two species or none
|
|
||||||
- [ ] Taxon autocomplete; seed `taxa` with 60–80 Central European garden species incl. GBIF keys, `name_de` + `name_en`, `is_local_common` ranking first
|
|
||||||
- [ ] Tags, favourite/reject (`kept`), review flag
|
|
||||||
- [ ] Persist the theme choice **per user** (`users.theme`) rather than in localStorage — the
|
|
||||||
tokens and the switcher are done (above); this is the half that needs accounts to exist
|
|
||||||
- [x] Auth: session cookies, Argon2id, CSRF, RBAC per SPEC §3.1 (viewer / editor / admin),
|
|
||||||
`audit_log` on login, failed login and logout. Sessions are rows, so logout is immediate;
|
|
||||||
only the SHA-256 of the cookie is stored; CSRF is bound to the session, not just
|
|
||||||
double-submitted. Accounts come from `poorbird user add` — there is no sign-up endpoint.
|
|
||||||
- [ ] Extend `audit_log` to the *content* mutations (observations, tags, device config) as each
|
|
||||||
endpoint lands. Auth events are covered; nothing else writes to it yet.
|
|
||||||
- [x] **Auth-checked image serving** — the app authorizes, Caddy serves the bytes via `X-Accel-Redirect`.
|
|
||||||
An unguessable URL is not access control. One authorization path, two ways of finishing the
|
|
||||||
response: `serve_images_directly=true` makes the app send the file for development, where there
|
|
||||||
is no Caddy. Not a separate unauthenticated dev route — that is the kind of thing that survives
|
|
||||||
into production because it works. `poorbird check` validates the sibling `images`/`thumbs`
|
|
||||||
layout the handoff depends on, since getting it wrong yields 404s from Caddy with nothing in
|
|
||||||
the app's log.
|
|
||||||
- [x] TOTP 2FA — enforced at account creation for `admin` rather than at login, because a
|
|
||||||
login-time check can lock the only admin out of their own account. Codes required whenever
|
|
||||||
the account has a secret. Replay inside the ~90s window is documented, not closed.
|
|
||||||
- [ ] **Revisit CORS.** Deliberately not configured in Phase 2: Caddy serves the built UI and the
|
|
||||||
API from one origin, so there is no cross-origin request to permit, and adding permissive
|
|
||||||
headers "for the UI" would only weaken that. The Vite dev server proxies `/api` for the
|
|
||||||
same reason, so development matches production. Decide it properly only if the UI is ever
|
|
||||||
served from somewhere else — *then* it matters.
|
|
||||||
|
|
||||||
### 3.0 UI decisions (2026-09-21)
|
|
||||||
|
|
||||||
**Language: German and English, both, from the first component (Q11).** i18n is
|
|
||||||
nearly free on day one and miserable to retrofit. `taxa` already carries
|
|
||||||
`name_de` and `name_en`; `users.locale` already exists and defaults to `de`.
|
|
||||||
Rule: no user-facing string literal in a component, ever — every one goes
|
|
||||||
through the translation catalogue, including the first one.
|
|
||||||
|
|
||||||
**Theme "blue" is a dark navy (Q13).** Tokens below. Light and dark stay
|
|
||||||
conventional; blue is the distinctive one. Contrast targets WCAG AA (≥4.5:1 for
|
|
||||||
body text) — check it when the tokens land, do not assume it.
|
|
||||||
|
|
||||||
| Token | Blue |
|
|
||||||
|---|---|
|
|
||||||
| `--bg` | `#0B1220` |
|
|
||||||
| `--surface` | `#111C2E` |
|
|
||||||
| `--surface-raised` | `#17253B` |
|
|
||||||
| `--border` | `#22344F` |
|
|
||||||
| `--text` | `#E6EDF7` |
|
|
||||||
| `--text-muted` | `#9FB3CE` |
|
|
||||||
| `--accent` | `#4C8DFF` |
|
|
||||||
| `--accent-hover` | `#6BA1FF` |
|
|
||||||
| `--success` / `--warning` / `--danger` | `#3DD68C` / `#F0B429` / `#F2545B` |
|
|
||||||
|
|
||||||
**2FA: build TOTP now, optional per user, enforced for `admin` (Q14).** The
|
|
||||||
reasoning matters more than the setting, because "the UI does not need it" and
|
|
||||||
"I need access from outside" describe the *same* surface — whatever is reachable
|
|
||||||
from outside is the UI. What differs is the path:
|
|
||||||
|
|
||||||
- Over **Tailscale** (the SPEC §0 decision): the network layer already demands an
|
|
||||||
enrolled device, and Tailscale enforces 2FA at your identity provider. UI 2FA
|
|
||||||
is then belt-and-braces.
|
|
||||||
- Over a **public domain** (SPEC §1.2, "design for, do not build"): UI 2FA stops
|
|
||||||
being optional.
|
|
||||||
|
|
||||||
Build it now regardless, because retrofitting 2FA means reopening the login
|
|
||||||
flow, the session model, the user model and the audit log at once — the four
|
|
||||||
places you least want to revisit. `users.totp_secret` already exists. Enforce
|
|
||||||
for `admin`; leave it opt-in for `viewer`/`editor` on the LAN. A
|
|
||||||
`require_2fa` server setting flips the whole thing on the day you go public.
|
|
||||||
|
|
||||||
**Stack stays React + TypeScript (Q16), with the learning curve taken seriously.**
|
|
||||||
No TS experience, but willing to learn. The gallery is genuinely a client-side
|
|
||||||
app — a virtualised grid and the keyboard-driven labelling loop — and that is
|
|
||||||
the thing HTMX would fight later. So: plain function components, no exotic
|
|
||||||
generics, no state-management library beyond TanStack Query, and comments that
|
|
||||||
explain the TypeScript rather than assuming it. **Fallback if it stops being
|
|
||||||
fun:** SPEC §5's Jinja2 + HTMX frontend is still a valid target and the API does
|
|
||||||
not change. Deciding to switch is not a failure; discovering it three months in
|
|
||||||
would be.
|
|
||||||
|
|
||||||
**Placeholder data: generated, not downloaded.** A seed command
|
|
||||||
(`poorbird seed --captures 500`) synthesises captures with realistic burst
|
|
||||||
structure, pre-trigger flags, timestamps and species spread. Reasons: no image
|
|
||||||
licensing question at all, no binary blobs in git, and it can produce the
|
|
||||||
*volume* the virtualised grid actually needs to be tested against. Real photos
|
|
||||||
prove nothing about a gallery that a generated one does not — until Phase 2
|
|
||||||
brings real captures, which is the only test that counts.
|
|
||||||
|
|
||||||
### 3.1 Two things the UI must not get wrong
|
|
||||||
|
|
||||||
- [ ] `battery_valid = false` means **not measured** (no divider is wired by default) — render as "n/a", never as a flat-battery alarm
|
|
||||||
- [ ] Daily counters live in RTC memory and reset on power loss. The `captures` table is authoritative; the counters' value is the **gap** between captured and delivered, which is an upload-health signal
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 4 — Device management & OTA
|
|
||||||
|
|
||||||
- [ ] Device list with live/awake state, last seen, RSSI, heap/PSRAM, ring depth
|
|
||||||
- [ ] Settings editor writing the `devices` settings surface → `apply_config` → `config_version`
|
|
||||||
- [ ] Command queue UI: `wake_and_hold`, `capture_now`, `apply_config`, `ota_update`, `stream_start`, `reboot`; commands ride along on the ingest response
|
|
||||||
- [ ] Firmware upload, SHA-256, target marking, per-device staged rollout.
|
|
||||||
`GET /firmware/{version}.bin` already serves the bytes; the upload half was left out of
|
|
||||||
Phase 2 because it needs operator auth. **Constrain `firmware.is_target` to a single row
|
|
||||||
while doing this** — nothing enforces it today, and the lookup takes the first match, so
|
|
||||||
two target rows would pick non-deterministically between them.
|
|
||||||
- [ ] Verify the full OTA path on hardware: **trial boot and automatic rollback**. The camera is unreachable once mounted — this is the one feature with no recovery if it is broken
|
|
||||||
- [ ] Document that rotating the shared bootstrap secret server-side without shipping new firmware **removes the last-resort escape hatch**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 5 — Operations
|
|
||||||
|
|
||||||
- [ ] restic → NAS. **Decide the NAS protocol first (open Q9)** — SFTP or a mounted path; SMB-only changes the tooling
|
|
||||||
- [ ] `pg_dump` pre-hook; retention 7 daily / 4 weekly / 12 monthly
|
|
||||||
- [ ] **Monthly automated restore test** into a scratch Postgres database on the same host (the Docker-based scratch container from SPEC §6 is replaced by a throwaway cluster/DB). A backup you have never restored is a hypothesis.
|
|
||||||
- [ ] Alarms via ntfy or Gotify + WebUI banner: low battery, device offline > N hours, disk > 80 %, backup failure, ingest stalled
|
|
||||||
- [ ] Retention policy job (open Q8 — and decide whether deleting in the UI deletes the file or only hides it)
|
|
||||||
- [ ] `GET /api/v1/health` covering device liveness, battery, disk, last backup
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phase 6 — Streaming (plumbing only)
|
|
||||||
|
|
||||||
Scope is device → server, watched internally. Public relay stays out (SPEC C3).
|
|
||||||
|
|
||||||
- [ ] Chunked MJPEG sink per `firmware/API.md` → Streaming
|
|
||||||
- [ ] `record` / `watch` / `both` modes; the record writer plus the ingest writer are the two concurrent writers that justified Postgres
|
|
||||||
- [ ] Session time-box: 60 s default, firmware-capped at 600 s. Kept as policy, not as a power constraint
|
|
||||||
- [ ] Live view in the WebUI, admin-only
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Explicitly not now
|
|
||||||
|
|
||||||
- **Species detection** — schema is ready (`observations.source`, `model_version`, `confidence`, `bbox`), pipeline is not built. Revisit after a few thousand real captures, when you also know whether you want to label them.
|
|
||||||
- **Public stream / public gallery** — SPEC Option C.
|
|
||||||
- **Local SD buffering** of failed uploads — pins are free; add only if the WiFi link proves marginal.
|
|
||||||
- **On-device frame differencing** — the PSRAM ring makes this easy to add later.
|
|
||||||
- **TLS on the device** — deliberate, SPEC C2.
|
|
||||||
- **Containers** — not now, but the door stays open; see Phase 1.2. **Kubernetes** stays shut regardless: a control plane on a single host gains nothing here.
|
|
||||||
- **Audio / BirdNET** — different sensor, different pipeline.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Still open (from SPEC §10)
|
|
||||||
|
|
||||||
Answered and closed: Q1 (Option B), Q2 (XIAO ESP32S3 Sense), Q4 (internal first),
|
|
||||||
Q5 (x86 thin client), **Q11, Q13, Q14 and Q16 — see Phase 3.0**.
|
|
||||||
Void under mains power: Q10 (battery chemistry).
|
|
||||||
|
|
||||||
| # | Question | Blocks |
|
|
||||||
|---|---|---|
|
|
||||||
| 3 | Does the radar trigger reliably on *your* birds, at *your* distance? | Phase 0.3 — the project's biggest unknown |
|
|
||||||
| 9 | NAS access protocol — SFTP, SMB, NFS? | Phase 5, backup tooling choice |
|
|
||||||
| 6 | How many cameras eventually? | Phase 4 scope (device management, OTA staging) |
|
|
||||||
| 7 | Expected captures per day? | Storage sizing, retention, inline-vs-queued thumbnailing |
|
|
||||||
| 8 | Retention policy, and does UI delete remove the file? | Phase 5 |
|
|
||||||
| 11 | UI language — German, English, or both? | Cheap on day one, annoying to retrofit. `name_de`/`name_en` exist either way |
|
|
||||||
| 12 | Taxonomy source — GBIF backbone, IOC, Avibase? Which regional seed list? | Phase 3 taxa seed |
|
|
||||||
| 13 | The "blue" theme — a reference palette, or my choice? | Phase 3 theming |
|
|
||||||
| 14 | Is 2FA required, or is a strong password on a LAN-only service enough? | Phase 3 auth |
|
|
||||||
| 15 | Anything to record beyond SPEC §3 — weather, feeder type, ring number? | Schema, cheapest to settle before the first migration |
|
|
||||||
| 16 | Comfort level in C / Python / TypeScript? | The React frontend is the largest chunk of potentially unfamiliar work |
|
|
||||||
| 17 | Can the camera see a neighbour's garden or a public path? | One GDPR paragraph in the deployment notes |
|
|
||||||
@@ -1,386 +0,0 @@
|
|||||||
# Open topics and unfixed security issues
|
|
||||||
|
|
||||||
**Scope:** the whole repository, `develop`.
|
|
||||||
**Written against:** `f9d0b09` plus the deploy changes committed alongside this file.
|
|
||||||
**Date:** 2026-09-21.
|
|
||||||
**Audience:** an AI or a maintainer picking this up cold.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## How to read this
|
|
||||||
|
|
||||||
This is a list of what is **not** done, deliberately or otherwise. It is not a
|
|
||||||
review of the code that exists — for that, see
|
|
||||||
[`reviews/`](reviews/), which holds branch-scoped snapshots.
|
|
||||||
|
|
||||||
Three labels are used, and the difference between them is the point of the
|
|
||||||
document:
|
|
||||||
|
|
||||||
| Label | Means |
|
|
||||||
|---|---|
|
|
||||||
| **ACCEPTED** | A known trade-off, decided on purpose, with the reasoning recorded. Do not "fix" one of these without reopening the decision — several exist specifically to prevent a well-meant change that breaks something worse. |
|
|
||||||
| **OPEN** | A real gap. Not yet paid for. Fixing it is straightforward and wanted. |
|
|
||||||
| **TRAP** | Works as written, but will mislead someone. Usually a default, a missing step, or a silent failure mode. |
|
|
||||||
|
|
||||||
Every claim below was verified against the code at the commit named above.
|
|
||||||
Where a line number is given, it was read, not remembered. If you are reading
|
|
||||||
this later and a reference does not match, trust the code.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Security — accepted trade-offs
|
|
||||||
|
|
||||||
### 1.1 ACCEPTED — the device link is plain HTTP, and the token rides on it
|
|
||||||
|
|
||||||
`SPEC` C2. The camera speaks unencrypted HTTP on `:8080`
|
|
||||||
(`server/deploy/Caddyfile`, the `:8080` block). TLS on an ESP32-S3 means a CA
|
|
||||||
baked into the firmware image and a camera that silently stops uploading when
|
|
||||||
that chain rotates — while mounted outdoors, where it cannot be reflashed.
|
|
||||||
|
|
||||||
**What this actually exposes:** the device bearer token crosses the LAN in
|
|
||||||
cleartext on every request. Anyone already on the network can capture it and
|
|
||||||
then impersonate that camera indefinitely — post fabricated captures, drain
|
|
||||||
its command queue, read its config. Passive capture of the images themselves
|
|
||||||
is the lesser problem.
|
|
||||||
|
|
||||||
**What would fix it without TLS:** HMAC request signing with a per-device key,
|
|
||||||
which is cheap on an ESP32 and needs no certificate chain. It requires a
|
|
||||||
coordinated firmware change, so it is a `firmware/API.md` contract revision,
|
|
||||||
not a server-side patch.
|
|
||||||
|
|
||||||
**Why it stays:** the threat model is a home LAN behind Tailscale. Worth
|
|
||||||
revisiting the moment this is reachable from anywhere else.
|
|
||||||
|
|
||||||
### 1.2 ACCEPTED — one enrollment secret, shared, compiled into firmware
|
|
||||||
|
|
||||||
`POORBIRD_ENROLL_SECRET` is one value for all cameras
|
|
||||||
(`server/src/poorbird/config.py:84`) and is compiled into the firmware image as
|
|
||||||
the last-resort recovery path for a camera that cannot be reached over USB
|
|
||||||
(`firmware/API.md`).
|
|
||||||
|
|
||||||
Consequences, both real: extracting the flash of one camera yields the
|
|
||||||
enrollment credential for the whole fleet; and rotating it on the server
|
|
||||||
without shipping new firmware removes the only way back into a mounted camera.
|
|
||||||
Both are documented at the point of use, including in `config.py` and
|
|
||||||
`deploy/poorbird.env.example`.
|
|
||||||
|
|
||||||
Per-device pre-shared keys would fix the first and worsen the second.
|
|
||||||
|
|
||||||
### 1.3 ACCEPTED — failed logins are limited by address, never by username
|
|
||||||
|
|
||||||
`api/ratelimit.py:201` — `LOGIN = Limit.per_hour(30, burst=8)`, keyed
|
|
||||||
`by_address`.
|
|
||||||
|
|
||||||
Keying on username would let anyone lock a known account out of its own
|
|
||||||
service by guessing at it, which converts a nuisance into a denial of service
|
|
||||||
against a specific person. The cost of the choice is the mirror image: an
|
|
||||||
attacker spread across many source addresses gets proportionally more
|
|
||||||
attempts, and a legitimate user sharing a NAT with an attacker gets throttled.
|
|
||||||
|
|
||||||
There is deliberately **no account lockout** for the same reason.
|
|
||||||
|
|
||||||
### 1.4 ACCEPTED — `SameSite=Lax`, not `Strict`
|
|
||||||
|
|
||||||
`api/sessions.py`. `Strict` means following a link from anywhere outside the
|
|
||||||
app presents as signed out, which trains people to distrust the login. `Lax`
|
|
||||||
permits the cookie on top-level cross-site **GET** only; every mutation is
|
|
||||||
POST/PUT/PATCH/DELETE and goes through the CSRF middleware, so the residual
|
|
||||||
exposure is limited to read-only navigations.
|
|
||||||
|
|
||||||
### 1.5 ACCEPTED — device endpoints have no CSRF check
|
|
||||||
|
|
||||||
`api/userauth.py`, `csrf_middleware`. It returns early unless the method is
|
|
||||||
unsafe **and** the request carries the session cookie. Device requests are
|
|
||||||
bearer-authenticated and carry no cookies, so they are never in scope — which
|
|
||||||
is correct, because CSRF is an attack on ambient browser credentials and a
|
|
||||||
camera has no browser.
|
|
||||||
|
|
||||||
**Do not "fix" this by applying CSRF to all unsafe methods.** It would break
|
|
||||||
every device endpoint and protect nothing.
|
|
||||||
|
|
||||||
### 1.6 ACCEPTED — images are authorised by the app, served by Caddy
|
|
||||||
|
|
||||||
`api/delivery.py` + the `protected_files` snippet in `deploy/Caddyfile`. The
|
|
||||||
app checks the session, then returns an empty 200 carrying
|
|
||||||
`X-Accel-Redirect`; Caddy reads the file. `serve_images_directly=true` makes
|
|
||||||
the app send the bytes itself, for development where there is no Caddy.
|
|
||||||
|
|
||||||
The flag does **not** relax authorisation — the same check runs in both paths,
|
|
||||||
and the only difference is how an already-authorised response is finished.
|
|
||||||
This was built as one code path with two endings, specifically to avoid a
|
|
||||||
separate unauthenticated dev route, which is the kind of thing that survives
|
|
||||||
into production because it works.
|
|
||||||
|
|
||||||
`_safe_absolute()` resolves the stored relative path and answers 404 — not
|
|
||||||
403 — on any escape from the configured root. The traversal test escapes to a
|
|
||||||
canary file that genuinely exists outside the root; it was originally written
|
|
||||||
against `/etc/passwd`, which does not exist on the Windows dev machine, so it
|
|
||||||
would have passed with the guard removed. Keep the canary.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Security — open, not yet paid for
|
|
||||||
|
|
||||||
### 2.1 OPEN — a TOTP code can be replayed for ~90 seconds
|
|
||||||
|
|
||||||
`totp.py:25` sets `VALID_WINDOW = 1`, so the previous, current and next
|
|
||||||
30-second steps are all accepted. Nothing records which codes have been used,
|
|
||||||
because there is no column for it. An observer who sees a code once can use it
|
|
||||||
until its window closes.
|
|
||||||
|
|
||||||
**Fix:** add `users.totp_last_counter`, reject any counter `<=` the stored
|
|
||||||
value, and persist on success. One migration, a few lines in
|
|
||||||
`api/routes/auth.py` around the check at `auth.py:135-140`.
|
|
||||||
|
|
||||||
The limitation is documented in the `verify()` docstring rather than left
|
|
||||||
implicit. On a Tailscale-only LAN the observer has already had to get onto the
|
|
||||||
network; that stops being reassuring the day this is public.
|
|
||||||
|
|
||||||
### 2.2 OPEN — TOTP cannot be added, removed or repaired after account creation
|
|
||||||
|
|
||||||
`cli.py` exposes only `user add`, `user list` and `user passwd`. There is **no
|
|
||||||
`user delete`** and no way to change the second factor later.
|
|
||||||
|
|
||||||
Three consequences, all reachable today:
|
|
||||||
|
|
||||||
- An account created with `--no-totp` (`cli.py:133-134`, which warns) stays
|
|
||||||
without a second factor permanently.
|
|
||||||
- Losing the `otpauth://` URI — printed exactly once — bricks that account.
|
|
||||||
There is no recovery path short of editing the database.
|
|
||||||
- A wrong `--role` or a typo'd username cannot be undone.
|
|
||||||
|
|
||||||
The dev admin `me` on this machine was created with `--no-totp`, so it is an
|
|
||||||
instance of the first case.
|
|
||||||
|
|
||||||
**Fix:** `poorbird user totp --enable|--disable NAME`, `poorbird user delete
|
|
||||||
NAME`, `poorbird user role NAME --role X`. All small; none exist.
|
|
||||||
|
|
||||||
### 2.3 OPEN — `audit_log` only records authentication
|
|
||||||
|
|
||||||
`api/routes/auth.py` writes `login`, `login_failed` (with a reason) and
|
|
||||||
`logout`. Nothing else writes to the table. Content mutations — observations,
|
|
||||||
tags, device config, keep/reject decisions — leave no trace, so "who changed
|
|
||||||
this label, and when" is currently unanswerable.
|
|
||||||
|
|
||||||
The table and its `ON DELETE SET NULL` on `user_id` are already in the schema,
|
|
||||||
so this is purely a matter of adding writes as each endpoint lands. Recorded in
|
|
||||||
`TODO.md` Phase 3.
|
|
||||||
|
|
||||||
### 2.4 OPEN — no password reset, and no second admin by default
|
|
||||||
|
|
||||||
If the only admin's password is lost, recovery is manual SQL. `user passwd`
|
|
||||||
requires shell access on the server, which is the intended trust model, but it
|
|
||||||
means there is no in-band recovery at all. Worth at least documenting a
|
|
||||||
"create a second admin" step; worth more if this is ever used by someone other
|
|
||||||
than its author.
|
|
||||||
|
|
||||||
### 2.5 OPEN — rate limits are per-process, and nothing enforces one process
|
|
||||||
|
|
||||||
`api/ratelimit.py` uses in-process token buckets, sized for a single uvicorn
|
|
||||||
process. Running with `--workers N` silently multiplies every effective limit
|
|
||||||
by N, including the login limit.
|
|
||||||
|
|
||||||
Nothing in `deploy/poorbird-api.service` prevents that being added later by
|
|
||||||
someone reasoning that more workers is faster. SPEC C8 rules out Redis, so the
|
|
||||||
fix is either a Postgres-backed limiter or an assertion at startup that there
|
|
||||||
is exactly one worker. Currently it is a comment in the module docstring.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Traps
|
|
||||||
|
|
||||||
### 3.1 TRAP — `api_port` defaults to 8080, which is the camera's Caddy port
|
|
||||||
|
|
||||||
`config.py:52` — `api_port: int = 8080`. Meanwhile
|
|
||||||
`deploy/poorbird.env.example:30` sets `POORBIRD_API_PORT=8090`, and
|
|
||||||
`deploy/Caddyfile` proxies to `127.0.0.1:8090` and itself binds `:8080` for
|
|
||||||
the camera.
|
|
||||||
|
|
||||||
So the code default and the deployment disagree, and the default collides with
|
|
||||||
Caddy's own listener. Any host where `POORBIRD_API_PORT` is unset gets uvicorn
|
|
||||||
on `127.0.0.1:8080` — contending with Caddy's `:8080` site and unreachable
|
|
||||||
from the proxy, which is looking at 8090.
|
|
||||||
|
|
||||||
**Fix:** change the default in `config.py` to `8090` so code and deployment
|
|
||||||
agree. Trivial, and nothing depends on 8080.
|
|
||||||
|
|
||||||
### 3.2 TRAP — `POORBIRD_SESSION_COOKIE_SECURE` fails silently and invisibly
|
|
||||||
|
|
||||||
A `Secure` cookie is discarded by the browser over plain HTTP. The login
|
|
||||||
returns **200**, the session row is created, and the browser is not signed in.
|
|
||||||
Nothing appears in any log, because from the server's point of view nothing
|
|
||||||
went wrong.
|
|
||||||
|
|
||||||
This is documented in three places now (`config.py:92-97`,
|
|
||||||
`poorbird.env.example`, `web/README.md`) and, as of this commit, in
|
|
||||||
`deploy/INSTALL.md` next to the "for a first test, drop the `tls` block"
|
|
||||||
suggestion that triggers it. It stays on this list because the failure mode is
|
|
||||||
undetectable from the server side and costs an hour every time it is met fresh.
|
|
||||||
|
|
||||||
### 3.3 TRAP — a `git pull` on the host never updates the UI
|
|
||||||
|
|
||||||
`web/` is built on the dev machine and shipped as static files (SPEC §6).
|
|
||||||
There is no Node on the server and no build step in
|
|
||||||
`deploy/poorbird-api.service`. Pulling and restarting gives a new API with the
|
|
||||||
old bundle, and the mismatch shows up as UI features that appear not to work.
|
|
||||||
|
|
||||||
Covered in `INSTALL.md` step 7 and the Upgrading section as of this commit.
|
|
||||||
Vite emits content-hashed filenames, so the copy must use `--delete` or stale
|
|
||||||
bundles accumulate indefinitely.
|
|
||||||
|
|
||||||
### 3.4 TRAP — running the test suite deletes seeded captures
|
|
||||||
|
|
||||||
`tests/test_seed.py:36-49`, the `no_seed_left_behind` autouse fixture, sweeps
|
|
||||||
`Device.device_uid.startswith(SEED_UID_PREFIX)` and deletes every match plus
|
|
||||||
its captures. A developer's own `poorbird seed --captures 500` uses that same
|
|
||||||
`5eed` prefix, so **`pytest` destroys it.** Observed twice on 2026-09-21.
|
|
||||||
|
|
||||||
The fixture cannot delegate to `clear()`, because `clear()` is the function
|
|
||||||
under test — a broken `clear()` would then leave the database dirty *and* hide
|
|
||||||
that it was broken. So it re-derives the scope, and the derived scope cannot
|
|
||||||
distinguish a test's seed device from a person's.
|
|
||||||
|
|
||||||
**Fix:** have the fixture record the device ids it creates and delete exactly
|
|
||||||
those.
|
|
||||||
|
|
||||||
**Not at risk:** user accounts and real camera devices. Every other teardown
|
|
||||||
in the suite deletes by explicit id — verified across
|
|
||||||
`test_auth.py:110`, `test_captures.py:73,127-128`. The `garden-feeder` device
|
|
||||||
on the dev machine has survived every run.
|
|
||||||
|
|
||||||
### 3.5 TRAP — the test suite shares the development database
|
|
||||||
|
|
||||||
`tests/conftest.py` connects to whatever `POORBIRD_DATABASE_URL` points at,
|
|
||||||
and `test_schema_matches_models.py` additionally creates and drops a
|
|
||||||
`poorbird_schema_check` database on the same server, needing a role that may
|
|
||||||
`CREATE DATABASE`. Combined with 3.4, running tests against a database that
|
|
||||||
holds anything you care about is a mistake waiting to happen.
|
|
||||||
|
|
||||||
Mutation-testing `clear()` was done against an isolated scratch database for
|
|
||||||
exactly this reason.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Deployment — changed in this commit, and unverified
|
|
||||||
|
|
||||||
`deploy/Caddyfile` previously had no `file_server` for the built UI, and
|
|
||||||
FastAPI mounts no static files, so **nothing served the WebUI in production**.
|
|
||||||
`INSTALL.md` also never created an account, so a by-the-book install ended at
|
|
||||||
a login form with no usable credentials.
|
|
||||||
|
|
||||||
Both are addressed in this commit. What that is worth:
|
|
||||||
|
|
||||||
- The Caddyfile **syntax is validated** — `caddy validate` via the official
|
|
||||||
`caddy:2` image, with the cloudflare-DNS `tls` block stripped because that
|
|
||||||
plugin is not in the stock image and that block is unchanged. Result: *Valid
|
|
||||||
configuration*.
|
|
||||||
- `npm run build` was run: typecheck clean, 192 modules, 400 kB → 127 kB gzip.
|
|
||||||
- **Nothing has been run on a real host.** The `try_files` fallback, the
|
|
||||||
`X-Accel-Redirect` handoff against a real Caddy, the systemd units and the
|
|
||||||
account-creation step under `sudo -u poorbird` are all unexercised. Treat
|
|
||||||
section 6-8 of `INSTALL.md` as untested instructions.
|
|
||||||
|
|
||||||
The whole install has never been performed end to end. Until it has, the
|
|
||||||
deploy directory is a plausible plan, not a proven procedure.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Test and process debt
|
|
||||||
|
|
||||||
| | |
|
|
||||||
|---|---|
|
|
||||||
**OPEN** | No ESLint. `tsc --noEmit` catches the important class of mistakes; the flat-config setup was skipped during scaffolding and never revisited.
|
|
||||||
**OPEN** | No test runs the UI. There is no component or end-to-end test in `web/` at all — the gallery's behaviour is covered only by the server tests behind it and by looking at it.
|
|
||||||
**OPEN** | Virtualisation is unmeasured. The grid is built to recycle rows and the data path is verified over 506 captures, but nothing asserts that DOM node count stays bounded as you scroll. That is the property the whole design exists for.
|
|
||||||
**ACCEPTED** | Two tests once passed for the wrong reason, both now fixed: a pool-size assertion whose expected value equalled SQLAlchemy's own default, and the traversal test described in 1.6. The lesson is recorded here because it generalises — assert against values that differ from the library's defaults, or the test cannot fail.
|
|
||||||
**ACCEPTED** | Reviews under `reviews/` are point-in-time snapshots and are deliberately **not** updated. Their "12/12 tests" and "what's missing" sections describe the commit in their header. Several reference implementations in them are wrong; where that mattered, the code that replaced them says so.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Functional gaps, by phase
|
|
||||||
|
|
||||||
**Phase 3, still open:**
|
|
||||||
|
|
||||||
- `taxa` is not seeded, so there is no species list. Taxon and tag filters are
|
|
||||||
therefore absent from both `GET /api/v1/captures` and the UI — deliberately,
|
|
||||||
rather than shipped as controls with nothing behind them.
|
|
||||||
- No observation editor. The gallery reads and displays observations; nothing
|
|
||||||
writes them. Labelling, the actual point of the project, does not exist yet.
|
|
||||||
- `users.theme` and `users.locale` are in the schema and returned by
|
|
||||||
`/auth/session`, but the UI keeps both in `localStorage`. A second browser
|
|
||||||
starts from the default.
|
|
||||||
- The viewer steps only through loaded captures. At the end of a page the
|
|
||||||
arrow disables rather than fetching the next one.
|
|
||||||
|
|
||||||
**Phase 4:**
|
|
||||||
|
|
||||||
- No device listing endpoint, so the Devices page is an honest empty state and
|
|
||||||
the gallery's device filter is built from whatever devices appear in loaded
|
|
||||||
captures.
|
|
||||||
- No admin `POST /api/v1/firmware`, so OTA images cannot be uploaded through
|
|
||||||
the UI.
|
|
||||||
- `firmware.is_target` has no single-row constraint. Two rows marked as the
|
|
||||||
target is a state the schema currently permits and the OTA logic does not
|
|
||||||
expect.
|
|
||||||
- CORS is unconfigured. Correct today — Caddy serves UI and API from one
|
|
||||||
origin — but it needs a deliberate answer before anything is ever served
|
|
||||||
from a second origin, rather than a permissive header added under pressure.
|
|
||||||
|
|
||||||
**Phase 5:**
|
|
||||||
|
|
||||||
- **No backups of any kind.** Blocked on open question 9 (whether the NAS
|
|
||||||
offers SFTP or only SMB/NFS), which decides between restic and a mounted
|
|
||||||
path. The image store and the database are both unprotected. This is the
|
|
||||||
single largest operational gap in the project.
|
|
||||||
- No retention or pruning. Captures accumulate without bound; `kept` exists in
|
|
||||||
the schema but nothing acts on it.
|
|
||||||
|
|
||||||
**Phase 6:**
|
|
||||||
|
|
||||||
- `/stream` is unimplemented. It is the one part of `firmware/API.md` with no
|
|
||||||
server side at all.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Not problems — do not re-open these
|
|
||||||
|
|
||||||
Listed because each one looks like an oversight and is not.
|
|
||||||
|
|
||||||
- **Sync SQLAlchemy, not async.** Deliberate. The workload is a handful of
|
|
||||||
concurrent requests and a background worker; async buys nothing here and
|
|
||||||
costs a second idiom for every contributor.
|
|
||||||
- **The job queue is a Postgres table** using `FOR UPDATE SKIP LOCKED`, not
|
|
||||||
Redis or Celery (SPEC C8). One fewer service to run, monitor and back up.
|
|
||||||
- **Device tokens are SHA-256, user passwords are Argon2id.** Not an
|
|
||||||
inconsistency. Device tokens are 256-bit CSPRNG output, so there is nothing
|
|
||||||
to brute-force and a slow hash would only add latency to every ingest;
|
|
||||||
passwords are human-chosen, so slowness is the entire point. Both are
|
|
||||||
explained at `api/deps.py.hash_credential` and `passwords.py`.
|
|
||||||
- **`verify_password` returns `False` instead of raising** for `None`, `""` or
|
|
||||||
a corrupt hash. Every Phase 1 row has a NULL `password_hash`, so raising
|
|
||||||
would turn a normal state into a 500.
|
|
||||||
- **Password rehash on login is already wired** (`auth.py:147`,
|
|
||||||
`needs_rehash`). If Argon2 parameters change, hashes migrate as people sign
|
|
||||||
in.
|
|
||||||
- **The login endpoint hashes a password even when the username does not
|
|
||||||
exist**, discarding the result. Without it, a missing username returns
|
|
||||||
measurably faster than a wrong password, which is a username oracle.
|
|
||||||
- **CSRF is compared against the token on the session row**, not merely
|
|
||||||
cookie-against-header. Plain double-submit accepts any self-consistent pair,
|
|
||||||
so anyone able to set a cookie on the domain satisfies it while the victim's
|
|
||||||
session cookie rides along.
|
|
||||||
- **`0001_initial.py` is frozen explicit DDL.** It used to call
|
|
||||||
`Base.metadata.create_all()`, which meant a clean database got the current
|
|
||||||
models and then later migrations tried to add columns that already existed.
|
|
||||||
Do not edit it to reflect a model change; add a revision.
|
|
||||||
- **`pool_timeout` is finite (30s), on purpose.** An infinite timeout turns a
|
|
||||||
pool leak into a permanent hang with no error.
|
|
||||||
- **`received_at` is authoritative, not `captured_at_device`** (SPEC C7). The
|
|
||||||
camera has no battery-backed clock; `captured_at_device` is NULL when it was
|
|
||||||
unsynced and must never be rendered as 1970.
|
|
||||||
- **Model-sourced observations are badged as predictions.** The observations
|
|
||||||
table is also the training data for any future model, so a guess displayed
|
|
||||||
as a human label would poison it.
|
|
||||||
- **The purge of expired sessions lives in `worker/handlers.py`**, not
|
|
||||||
imported from `api/`. The worker must not import from the API layer; that
|
|
||||||
layering rule is why `images.py` sits at the package root.
|
|
||||||
@@ -1,355 +0,0 @@
|
|||||||
# poorBird — Anleitung für den Gebrauch
|
|
||||||
|
|
||||||
*English version: [`README.USER.md`](README.USER.md)*
|
|
||||||
|
|
||||||
Diese Anleitung erklärt, wie man poorBird **benutzt**, nicht wie man es
|
|
||||||
entwickelt. Sie setzt voraus, dass du einen vorgegebenen Befehl in ein
|
|
||||||
Terminal kopieren kannst — mehr nicht. Jeder Fachbegriff wird dort erklärt, wo
|
|
||||||
er zum ersten Mal auftaucht.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Was es eigentlich macht
|
|
||||||
|
|
||||||
Du hängst eine kleine Kamera an ein Vogelhaus. Sie beobachtet die Futterstelle
|
|
||||||
mit einem **Radarsensor** — kein kamerabasierter Bewegungsmelder, sondern ein
|
|
||||||
Bauteil, das ein harmloses Funksignal aussendet und merkt, wenn sich davor
|
|
||||||
etwas bewegt. Kommt ein Vogel, macht die Kamera eine Bildserie und schickt sie
|
|
||||||
über dein Heimnetz an einen kleinen Rechner im Haus. Dieser Rechner speichert
|
|
||||||
die Bilder und zeigt sie in einer Webseite, in der du sie durchsehen und
|
|
||||||
festhalten kannst, welchen Vogel du gesehen hast.
|
|
||||||
|
|
||||||
**Warum Radar und kein normaler Bewegungsmelder?** Ein klassischer
|
|
||||||
Bewegungsmelder — die Sorte in einer Außenlampe — reagiert auf Wärme. Er löst
|
|
||||||
aus, wenn die Sonne herauskommt, wenn warme Luft zieht, wenn ein Zweig
|
|
||||||
schwankt. Radar erkennt echte Bewegung und meldet zusätzlich, *wie weit weg*
|
|
||||||
sie war und *wie stark* sie war. Das genügt, um „ein Vogel ist auf der Stange
|
|
||||||
gelandet" von „die Hecke hat sich im Wind bewegt" zu unterscheiden. Außerdem
|
|
||||||
funktioniert Radar durch ein Kunststoffgehäuse hindurch, der Sensor bleibt
|
|
||||||
also trocken.
|
|
||||||
|
|
||||||
**Drei Teile, und jedes kann für sich ausfallen:**
|
|
||||||
|
|
||||||
| Teil | Was es ist | Wo es sitzt |
|
|
||||||
|---|---|---|
|
|
||||||
| Die Kamera | Eine kleine Platine mit Objektiv und Radarsensor | Draußen, am Futterhaus |
|
|
||||||
| Der Server | Ein Programm, das Bilder speichert und die Webseite beantwortet | Ein kleiner Rechner im Haus, dauerhaft an |
|
|
||||||
| Die Webseite | Die Galerie, die du ansiehst | In deinem Browser |
|
|
||||||
|
|
||||||
Die Kamera behält selbst nichts auf Dauer. Die Bilder liegen auf dem Server.
|
|
||||||
Geht die Kamera kaputt oder wird sie gestohlen, ist alles bereits Hochgeladene
|
|
||||||
sicher.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Was du vorher brauchst
|
|
||||||
|
|
||||||
- Den **Server**, eingerichtet und laufend. Das ist eine eigene, technischere
|
|
||||||
Aufgabe: [`../server/deploy/INSTALL.md`](../server/deploy/INSTALL.md).
|
|
||||||
- Ein **Konto**. Es gibt bewusst nirgends einen „Registrieren"-Knopf — warum,
|
|
||||||
steht gleich unten.
|
|
||||||
- Einen Browser im selben Netz.
|
|
||||||
|
|
||||||
### Es gibt keine Registrierung und kein Standardpasswort
|
|
||||||
|
|
||||||
Viele Geräte kommen mit einem eingebauten Zugang wie `admin` / `admin`. Das
|
|
||||||
ist eine Hintertür: alle kennen sie, und die meisten ändern sie nie. poorBird
|
|
||||||
hat kein solches Konto. Wer Zugang zum Server hat, muss dein Konto bewusst
|
|
||||||
anlegen:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
poorbird user add deinname --role admin
|
|
||||||
```
|
|
||||||
|
|
||||||
Das Programm fragt nach einem Passwort und gibt danach eine lange Zeile aus,
|
|
||||||
die mit `otpauth://` beginnt.
|
|
||||||
|
|
||||||
**Scanne diese Zeile in eine Authenticator-App, bevor du weitermachst.** Eine
|
|
||||||
Authenticator-App (Google Authenticator, Aegis, 1Password und andere) zeigt
|
|
||||||
einen sechsstelligen Code, der sich alle 30 Sekunden ändert. Diesen Code
|
|
||||||
brauchst du bei jeder Anmeldung. **Die Zeile wird genau einmal angezeigt und
|
|
||||||
nie wieder.** Geht sie verloren, kann sie niemand wiederherstellen, und das
|
|
||||||
Konto ist nicht mehr zu reparieren — es gibt derzeit keinen Befehl, den
|
|
||||||
zweiten Faktor zu entfernen oder neu einzurichten.
|
|
||||||
|
|
||||||
Wenn du den sechsstelligen Code wirklich nicht willst, hängst du `--no-totp`
|
|
||||||
an. Das Programm warnt dich dann. In einem Heimnetz, das von außen niemand
|
|
||||||
erreicht, ist das eine vertretbare Entscheidung — sonst nicht.
|
|
||||||
|
|
||||||
**Drei Arten von Konto**, damit nicht jeder alles ändern kann:
|
|
||||||
|
|
||||||
| Rolle | Darf |
|
|
||||||
|---|---|
|
|
||||||
| `viewer` | Bilder ansehen |
|
|
||||||
| `editor` | Ansehen und beschriften |
|
|
||||||
| `admin` | Alles davon, dazu die Seiten „Geräte" und „System" |
|
|
||||||
|
|
||||||
Die Kameras selbst sind *keine* Konten und tauchen in dieser Liste nie auf.
|
|
||||||
Sie weisen sich anders aus und können sich nicht an der Webseite anmelden.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Anmelden
|
|
||||||
|
|
||||||
Öffne die Adresse deines Servers im Browser. Du bekommst ein Anmeldeformular:
|
|
||||||
Benutzername, Passwort und — falls dein Konto einen hat — der sechsstellige
|
|
||||||
Code aus der Authenticator-App.
|
|
||||||
|
|
||||||
Wird der Code abgelehnt, prüfe die Uhr deines Handys. Diese Codes werden aus
|
|
||||||
der aktuellen Zeit berechnet; ein Handy, das eine Minute falsch liegt,
|
|
||||||
erzeugt Codes, die der Server für falsch hält. Ein paar Sekunden sind kein
|
|
||||||
Problem — der Server akzeptiert auch den Code davor und danach.
|
|
||||||
|
|
||||||
**Ein falsches Passwort und ein nicht existierender Benutzername ergeben genau
|
|
||||||
dieselbe Meldung.** Das ist Absicht: ein „diesen Benutzer gibt es nicht"
|
|
||||||
würde einem Fremden verraten, welche Benutzernamen existieren.
|
|
||||||
|
|
||||||
Wiederholte Fehlversuche werden gebremst. Diese Bremse gilt **pro
|
|
||||||
Netzwerkadresse, nicht pro Benutzername** — und zwar bewusst, denn eine Bremse
|
|
||||||
pro Benutzername würde es jedem erlauben, dich aus deinem eigenen Konto
|
|
||||||
auszusperren, indem er einfach darauf herumrät.
|
|
||||||
|
|
||||||
Angemeldet bleibst du standardmäßig **zwei Wochen**, danach musst du dich neu
|
|
||||||
anmelden.
|
|
||||||
|
|
||||||
„Abmelden" wirkt sofort, weil die Sitzung auf dem Server gelöscht wird und
|
|
||||||
nicht bloß vom Browser vergessen — es gibt kein Zeitfenster, in dem eine alte
|
|
||||||
Anmeldung noch funktioniert. Es beendet allerdings **nur die Sitzung in diesem
|
|
||||||
Browser**. Wenn du zusätzlich am Handy angemeldet bist, bleibt das angemeldet.
|
|
||||||
Erst ein Passwortwechsel (`poorbird user passwd`) beendet alle Sitzungen dieses
|
|
||||||
Kontos gleichzeitig.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Die Galerie benutzen
|
|
||||||
|
|
||||||
Die Hauptseite ist ein Raster aus Vorschaubildern, die neuesten zuerst. Beim
|
|
||||||
Scrollen werden ältere automatisch nachgeladen; es gibt keine Seitenzahlen.
|
|
||||||
|
|
||||||
> Im Browser existieren nur die Kacheln, die du gerade sehen kannst. Das
|
|
||||||
> klingt nach einer Nebensache, ist aber der Grund, warum die Seite bedienbar
|
|
||||||
> bleibt: eine gut besuchte Futterstelle bringt tausende Bilder pro Tag, und
|
|
||||||
> ein Browser, der ein ganzes Jahr davon gleichzeitig halten soll, reagiert
|
|
||||||
> irgendwann einfach nicht mehr.
|
|
||||||
|
|
||||||
**Klick auf ein Bild** zeigt es in voller Größe, die Details daneben. In
|
|
||||||
dieser Ansicht:
|
|
||||||
|
|
||||||
| Taste | Tut |
|
|
||||||
|---|---|
|
|
||||||
| `→` | Nächstes Bild |
|
|
||||||
| `←` | Voriges Bild |
|
|
||||||
| `Esc` | Zurück zum Raster |
|
|
||||||
|
|
||||||
Nimm die Tastatur. Einen Tag Bilder zu beschriften heißt ansehen – entscheiden
|
|
||||||
– weiter, ein paar hundert Mal, und das ist mit der Maus ermüdend.
|
|
||||||
|
|
||||||
Die Pfeile halten beim letzten bereits geladenen Bild an, statt dir ein leeres
|
|
||||||
Fenster zu zeigen, während weitere eintreffen. Scrolle das Raster ein Stück
|
|
||||||
weiter, dann geht es weiter.
|
|
||||||
|
|
||||||
### Filter
|
|
||||||
|
|
||||||
Über dem Raster kannst du nach Zeitraum, nach Kamera und nach drei
|
|
||||||
Ja/Nein-Fragen einschränken: **behalten**, **durchgesehen** und
|
|
||||||
**Vorauslöser**.
|
|
||||||
|
|
||||||
Jede davon ist eine Auswahl mit drei Zuständen — *beliebig*, *ja*, *nein* —
|
|
||||||
und keine Checkbox. Eine Checkbox kann nur „behalten" oder „egal" sagen, und
|
|
||||||
„zeig mir nur die, die ich verworfen habe" ist eine Frage, die du stellen
|
|
||||||
wirst.
|
|
||||||
|
|
||||||
Einen Filter zu ändern beginnt die Liste von vorne. Es hängt nichts an das an,
|
|
||||||
was schon auf dem Schirm war.
|
|
||||||
|
|
||||||
**„Vorauslöser" braucht eine Erklärung.** Die Kamera nimmt ständig leise
|
|
||||||
Bilder in einen kleinen Speicher auf, den sie immer wieder überschreibt. Löst
|
|
||||||
das Radar aus, schickt sie auch die zwei Bilder von *unmittelbar davor* mit.
|
|
||||||
Oft sind das die besten — ein landender Vogel statt eines schon sitzenden. Sie
|
|
||||||
sind markiert, damit du weißt: als sie entstanden, hatte das Radar noch nicht
|
|
||||||
ausgelöst.
|
|
||||||
|
|
||||||
### Was die Angaben bedeuten
|
|
||||||
|
|
||||||
- **Empfangen** — wann der Server das Bild bekommen hat. Dieser Zeitstempel
|
|
||||||
ist der, dem das System traut.
|
|
||||||
- **Aufgenommen** — wann die Kamera meint, das Bild gemacht zu haben. Hier
|
|
||||||
kann **„nicht synchronisiert"** stehen: die Kamera hat keine batteriegepufferte
|
|
||||||
Uhr, nach einem Stromausfall kennt sie die Zeit also nicht, bis sie
|
|
||||||
nachfragen kann. Sie sagt das ehrlich, anstatt den 1. Januar 1970 zu
|
|
||||||
behaupten — was ein naives System anzeigen würde.
|
|
||||||
- **Entfernung / Energie** — was das Radar gemessen hat: wie weit weg, und wie
|
|
||||||
stark die Bewegung.
|
|
||||||
- **Serie 2 von 5** — Bilder kommen in Serien. Dies ist das zweite von fünf.
|
|
||||||
- **Ein Hinweis „Vorhersage"** an einer Art bedeutet: *der Rechner hat
|
|
||||||
geraten*, nicht dass ein Mensch sie bestimmt hat. Automatische
|
|
||||||
Artbestimmung gibt es noch nicht; wenn es sie gibt, bleiben ihre Vermutungen
|
|
||||||
markiert. Deine eigenen Beschriftungen sind das Lernmaterial dafür, und eine
|
|
||||||
stillschweigend untergemischte Vermutung würde dieses Material verderben.
|
|
||||||
|
|
||||||
### Fehlende Vorschaubilder
|
|
||||||
|
|
||||||
Ein Bild, dessen kleine Vorschau noch nicht erzeugt wurde, zeigt einen
|
|
||||||
Platzhalter statt eines kaputten Bildes. Die Vorschauen macht ein
|
|
||||||
Hintergrundprogramm („Worker"). Verschwinden die Platzhalter nicht, läuft
|
|
||||||
dieses Programm wahrscheinlich nicht.
|
|
||||||
|
|
||||||
### Farben und Sprache
|
|
||||||
|
|
||||||
Oben rechts: drei Farbschemata (hell, dunkel und ein dunkles Blau) und zwei
|
|
||||||
Sprachen (Deutsch, Englisch). Beides merkt sich dein Browser. Es hängt noch
|
|
||||||
nicht am Konto, ein anderer Browser fängt also bei der Voreinstellung an.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Befehle, die du brauchen könntest
|
|
||||||
|
|
||||||
Diese laufen dort, wo der Server installiert ist. `poorbird` ist das Programm.
|
|
||||||
|
|
||||||
| Befehl | Tut |
|
|
||||||
|---|---|
|
|
||||||
| `poorbird check` | **Das zuerst, wenn etwas nicht stimmt.** Prüft Einstellungen, Datenbank und Ordner und erklärt, was es findet, ohne etwas zu starten. |
|
|
||||||
| `poorbird user add NAME --role admin` | Konto anlegen |
|
|
||||||
| `poorbird user list` | Konten anzeigen, und ob jedes einen sechsstelligen Code verwendet |
|
|
||||||
| `poorbird user passwd NAME` | Neues Passwort setzen. Meldet diese Person überall ab. |
|
|
||||||
| `poorbird serve` | Den Server-Teil der Webseite laufen lassen |
|
|
||||||
| `poorbird worker` | Das Hintergrundprogramm für die Vorschaubilder laufen lassen |
|
|
||||||
| `poorbird migrate` | Die Datenbankstruktur nach einem Update aktualisieren |
|
|
||||||
| `poorbird seed --captures 500` | 500 erfundene Bilder anlegen, um die Galerie auszuprobieren, ohne auf Vögel zu warten |
|
|
||||||
| `poorbird seed --clear` | Diese erfundenen Bilder wieder löschen |
|
|
||||||
|
|
||||||
`seed --clear` entfernt ausschließlich erfundene Daten. Es ist auf die
|
|
||||||
erfundene Kamera beschränkt, die es selbst angelegt hat — die Bilder einer
|
|
||||||
echten Kamera sind also nie in Gefahr. Es gibt einen Test, der eine echte
|
|
||||||
Kamera neben die erfundene stellt und prüft, dass sie überlebt.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Einstellungen
|
|
||||||
|
|
||||||
Die Einstellungen stehen in einer Datei, `/etc/poorbird/poorbird.env`, eine
|
|
||||||
`NAME=wert`-Zeile je Einstellung. Damit eine Änderung wirkt, wird das Programm
|
|
||||||
neu gestartet:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo systemctl restart poorbird-api poorbird-worker
|
|
||||||
```
|
|
||||||
|
|
||||||
Die vollständige Datei samt Begründungen ist
|
|
||||||
[`../server/deploy/poorbird.env.example`](../server/deploy/poorbird.env.example).
|
|
||||||
In Klartext:
|
|
||||||
|
|
||||||
### Die, die du setzen musst
|
|
||||||
|
|
||||||
| Einstellung | Bedeutung |
|
|
||||||
|---|---|
|
|
||||||
| `POORBIRD_DATABASE_URL` | Wo die Datenbank liegt und das Passwort dafür. **Keine Voreinstellung** — das Programm startet lieber nicht, als zu raten, und es weigert sich auch, wenn du die Beispieldatei kopiert und `CHANGE_ME` darin stehen gelassen hast. |
|
|
||||||
| `POORBIRD_ENROLL_SECRET` | Ein gemeinsames Geheimnis, mit dem sich Kameras beim allerersten Mal vorstellen. Erzeugen mit `openssl rand -hex 32`. |
|
|
||||||
|
|
||||||
> **Ändere `POORBIRD_ENROLL_SECRET` nicht leichtfertig.** Es steckt in der
|
|
||||||
> Software der Kamera als letzter Rückweg, falls die Kamera anders nicht mehr
|
|
||||||
> erreichbar ist. Es hier zu ändern, ohne auch die Kamera zu aktualisieren,
|
|
||||||
> nimmt dir diesen Notausgang — und eine Kamera, die draußen montiert ist,
|
|
||||||
> erreicht man nur mühsam.
|
|
||||||
|
|
||||||
### Wo Dateien landen
|
|
||||||
|
|
||||||
| Einstellung | Bedeutung |
|
|
||||||
|---|---|
|
|
||||||
| `POORBIRD_IMAGE_ROOT` | Die Bilder in voller Größe. Standard `/srv/poorbird/images`. |
|
|
||||||
| `POORBIRD_THUMB_ROOT` | Die kleinen Vorschauen. Standard `/srv/poorbird/thumbs`. |
|
|
||||||
| `POORBIRD_STATE_DIR` | Interne Verwaltungsdaten. Standard `/var/lib/poorbird`. |
|
|
||||||
|
|
||||||
Die ersten beiden müssen nebeneinander liegen, `images` und `thumbs` heißen
|
|
||||||
und denselben übergeordneten Ordner haben. Der Webserver liest sie von dort.
|
|
||||||
`poorbird check` sagt dir, wenn sie auseinandergelaufen sind — denn sonst ist
|
|
||||||
das Symptom, dass Bilder auf unerklärliche Weise nicht laden und in keinem
|
|
||||||
Protokoll etwas steht.
|
|
||||||
|
|
||||||
**Bilder werden nie direkt aus dem Ordner herausgegeben.** Jede Anfrage wird
|
|
||||||
zuerst gegen deine Anmeldung geprüft, und erst danach werden die Daten
|
|
||||||
gesendet. Dass die Adresse eines Bildes schwer zu erraten ist, ist kein
|
|
||||||
Schutz.
|
|
||||||
|
|
||||||
### Die zwei, über die alle stolpern
|
|
||||||
|
|
||||||
| Einstellung | Bedeutung |
|
|
||||||
|---|---|
|
|
||||||
| `POORBIRD_SESSION_COOKIE_SECURE` | Auf `true` lassen. Nur dann `false`, wenn du die Seite über einfaches `http://` statt `https://` erreichst. |
|
|
||||||
| `POORBIRD_SERVE_IMAGES_DIRECTLY` | Auf `false` lassen. `true` ist ausschließlich für einen Entwicklerrechner. |
|
|
||||||
|
|
||||||
Die erste ist wichtig wegen einer Browser-Regel: ein Cookie, das als „secure"
|
|
||||||
markiert ist, wird über eine unverschlüsselte Verbindung verworfen. Der
|
|
||||||
Browser warnt nicht, die Anmeldung meldet Erfolg, und du bist einfach nicht
|
|
||||||
angemeldet — und in keinem Protokoll steht, warum. Wenn du je „Anmeldung hat
|
|
||||||
geklappt, aber ich bin nicht drin" siehst: das ist der Grund.
|
|
||||||
|
|
||||||
Die zweite entscheidet, *wer das Bild von der Platte liest* — das
|
|
||||||
Hauptprogramm oder der Webserver davor. Der Webserver kann das deutlich
|
|
||||||
besser. **An der Rechteprüfung ändert sie nichts**: die läuft in beiden
|
|
||||||
Fällen gleich.
|
|
||||||
|
|
||||||
### Selten angefasst
|
|
||||||
|
|
||||||
| Einstellung | Bedeutung | Standard |
|
|
||||||
|---|---|---|
|
|
||||||
| `POORBIRD_SESSION_LIFETIME_H` | Wie lange du angemeldet bleibst, in Stunden | `336` (zwei Wochen) |
|
|
||||||
| `POORBIRD_RATE_LIMIT_ENABLED` | Wiederholte Fehlanmeldungen und flutende Kameras bremsen | `true` |
|
|
||||||
| `POORBIRD_API_HOST` / `_PORT` | Wo das Programm lauscht. Es sollte nur vom Rechner selbst erreichbar bleiben; nach außen kümmert sich der Webserver davor. | `127.0.0.1`, in der Beispieldatei Port `8090` |
|
|
||||||
| `POORBIRD_DB_POOL_SIZE` / `_MAX_OVERFLOW` | Wie viele Datenbankverbindungen gleichzeitig offen sein dürfen | `15` / `10` |
|
|
||||||
| `POORBIRD_WORKER_POLL_INTERVAL_S` | Wie lange das Hintergrundprogramm wartet, bevor es erneut nach Arbeit schaut, wenn es keine gibt. Es bremst *nicht* Arbeit, die schon wartet. | `5` |
|
|
||||||
| `POORBIRD_JOB_MAX_ATTEMPTS` | Wie oft ein fehlgeschlagener Hintergrundauftrag wiederholt wird | `3` |
|
|
||||||
| `POORBIRD_LOG_LEVEL` | Wie gesprächig das Protokoll ist | `INFO` |
|
|
||||||
| `POORBIRD_LOG_FORMAT` | `text` zum Selberlesen, `json` für Protokoll-Sammelwerkzeuge | `text` |
|
|
||||||
| `POORBIRD_DB_ECHO` | Jede Datenbankabfrage mitschreiben. Nur zur Fehlersuche, sehr geschwätzig. | `false` |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Wenn etwas nicht stimmt
|
|
||||||
|
|
||||||
**Fang mit `poorbird check` an.** Es ist genau dafür gebaut, „ist dieser
|
|
||||||
Rechner richtig eingerichtet" zu beantworten — und zu erklären, nicht nur zu
|
|
||||||
scheitern.
|
|
||||||
|
|
||||||
| Symptom | Wahrscheinlich |
|
|
||||||
|---|---|
|
|
||||||
| Anmeldung meldet Erfolg, aber du bist nicht angemeldet | `POORBIRD_SESSION_COOKIE_SECURE=true` bei einfachem `http://`. Siehe oben. |
|
|
||||||
| Die Webseite sagt, sie erreicht den Server nicht | Das Programm `poorbird serve` läuft nicht. |
|
|
||||||
| Die Seite lädt, aber das Raster ist leer | Noch keine Bilder. Mit `poorbird seed --captures 500` prüfen, ob die Galerie selbst funktioniert. |
|
|
||||||
| Vorschaubilder bleiben Platzhalter | Das Programm `poorbird worker` läuft nicht. |
|
|
||||||
| Bilder laden nicht, im Protokoll steht nichts | `images` und `thumbs` liegen nicht dort nebeneinander, wo der Webserver sie erwartet. `poorbird check`. |
|
|
||||||
| Der sechsstellige Code wird abgelehnt | Die Uhr deines Handys ist verstellt. |
|
|
||||||
| Das Anmeldeformular lehnt wiederholt ab und reagiert dann nicht mehr | Die Bremse gegen Fehlversuche. Warten, dann einmal sorgfältig versuchen. |
|
|
||||||
| Neu laden auf einer Seite wie `/devices` ergibt „nicht gefunden" | In der Konfiguration des Webservers fehlt die Regel, unbekannte Pfade zurück an die Galerie zu geben. Das ist die `try_files`-Zeile in der Caddyfile, eingerichtet in `INSTALL.md`, Schritt 6. |
|
|
||||||
|
|
||||||
### Zwei Dinge, die du wissen solltest, bevor du dich darauf verlässt
|
|
||||||
|
|
||||||
**Es gibt noch keine Sicherungen.** Nichts in poorBird kopiert deine Bilder
|
|
||||||
irgendwohin. Fällt diese Platte aus, sind die Bilder weg. Das ist geplante
|
|
||||||
Arbeit und kein Versehen — aber bis es sie gibt: lass hier keine Bilder als
|
|
||||||
einzige Kopie auflaufen, die dir fehlen würden.
|
|
||||||
|
|
||||||
**Die Kamera hat noch nie auf echter Hardware gelaufen**, und der Server noch
|
|
||||||
nie außerhalb eines Entwicklerrechners. Alles hier Beschriebene funktioniert —
|
|
||||||
es gibt 308 automatische Tests, und die Galerie wurde mit 500 Bildern benutzt
|
|
||||||
— aber „funktioniert auf dem Schreibtisch" und „funktioniert ein Jahr lang an
|
|
||||||
einem Pfahl im Regen" sind zwei verschiedene Behauptungen.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Datenschutz, kurz
|
|
||||||
|
|
||||||
Die Kamera spricht mit deinem Server über dein eigenes Netz, und zwar
|
|
||||||
unverschlüsselt. Das ist ein bewusster Handel: Verschlüsselung auf einem so
|
|
||||||
kleinen Gerät bedeutet ein Zertifikat, das in seiner Software festgeschrieben
|
|
||||||
ist — und eine Kamera, die stillschweigend aufhört hochzuladen, wenn dieses
|
|
||||||
Zertifikat getauscht wird, während sie an einem Pfahl hängt. Wer schon in
|
|
||||||
deinem Heimnetz ist, könnte die Uploads also mitlesen.
|
|
||||||
|
|
||||||
Dein eigener Blick in die Galerie *ist* verschlüsselt und braucht eine
|
|
||||||
Anmeldung.
|
|
||||||
|
|
||||||
Es geht nichts woandershin. Es gibt keinen Cloud-Dienst, kein Konto
|
|
||||||
irgendwo sonst und keine automatische Weitergabe. Die Bilder liegen auf deiner
|
|
||||||
Platte und nirgends sonst — was ebenfalls ein Grund ist, die fehlende
|
|
||||||
Sicherung ernst zu nehmen.
|
|
||||||
@@ -1,330 +0,0 @@
|
|||||||
# poorBird — a guide for using it
|
|
||||||
|
|
||||||
*Deutsche Fassung: [`README.USER.de.md`](README.USER.de.md)*
|
|
||||||
|
|
||||||
This guide is for **using** poorBird, not for building it. It assumes you can
|
|
||||||
follow a copy-and-paste command in a terminal, and nothing else. Every term
|
|
||||||
that matters is explained where it first appears.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. What it actually does
|
|
||||||
|
|
||||||
You hang a small camera near a bird feeder. It watches the feeder with a
|
|
||||||
**radar sensor** — not a camera-based motion detector, but a module that sends
|
|
||||||
out a harmless radio signal and notices when something moves in front of it.
|
|
||||||
When a bird arrives, the camera takes a burst of photos and sends them over
|
|
||||||
your home network to a small computer indoors. That computer stores the
|
|
||||||
photos and shows them to you in a web page where you can look through them and
|
|
||||||
write down which bird you saw.
|
|
||||||
|
|
||||||
**Why radar and not a normal motion sensor?** A classic motion sensor (the
|
|
||||||
kind in an outdoor lamp) reacts to warmth. It fires when the sun comes out,
|
|
||||||
when warm air moves, when a branch sways. Radar sees actual movement and also
|
|
||||||
reports *how far away* it was and *how strong* the movement was — which is
|
|
||||||
enough to tell "a bird landed on the perch" from "the hedge moved in the wind".
|
|
||||||
It also works through a plastic housing, so the sensor stays dry.
|
|
||||||
|
|
||||||
**Three pieces, and each can fail independently:**
|
|
||||||
|
|
||||||
| Piece | What it is | Where it lives |
|
|
||||||
|---|---|---|
|
|
||||||
| The camera | A small circuit board with a lens and the radar sensor | Outdoors, at the feeder |
|
|
||||||
| The server | A program storing photos and answering the website | A small computer indoors, always on |
|
|
||||||
| The website | The gallery you look at | Your browser |
|
|
||||||
|
|
||||||
The camera keeps nothing for long. Photos live on the server, so if the camera
|
|
||||||
breaks or is stolen, everything already uploaded is safe.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. What you need before you start
|
|
||||||
|
|
||||||
- The **server** set up and running. That is a separate, more technical job:
|
|
||||||
[`../server/deploy/INSTALL.md`](../server/deploy/INSTALL.md).
|
|
||||||
- An **account**. There is no "sign up" button anywhere, on purpose — see
|
|
||||||
below.
|
|
||||||
- A browser on the same network.
|
|
||||||
|
|
||||||
### There is no sign-up, and no default password
|
|
||||||
|
|
||||||
Many devices ship with a built-in login like `admin` / `admin`. That is a
|
|
||||||
back door: everyone knows it, and most people never change it. poorBird has no
|
|
||||||
such account. A person with access to the server has to create yours
|
|
||||||
deliberately:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
poorbird user add yourname --role admin
|
|
||||||
```
|
|
||||||
|
|
||||||
It asks for a password, then prints a long line starting with `otpauth://`.
|
|
||||||
|
|
||||||
**Scan that line into an authenticator app before you continue.** An
|
|
||||||
authenticator app (Google Authenticator, Aegis, 1Password, and others) shows a
|
|
||||||
six-digit code that changes every 30 seconds. You will need one of those codes
|
|
||||||
every time you sign in. **The line is shown once and never again.** If you
|
|
||||||
lose it, nobody can recover it and the account cannot be repaired — there is
|
|
||||||
currently no command to remove or re-arm the second factor.
|
|
||||||
|
|
||||||
If you genuinely do not want the six-digit code, add `--no-totp`. It will warn
|
|
||||||
you. It is a reasonable choice on a home network that nobody else can reach,
|
|
||||||
and a bad one otherwise.
|
|
||||||
|
|
||||||
**Three kinds of account**, so that not everyone can change everything:
|
|
||||||
|
|
||||||
| Role | Can |
|
|
||||||
|---|---|
|
|
||||||
| `viewer` | Look at photos |
|
|
||||||
| `editor` | Look, and label what it sees |
|
|
||||||
| `admin` | All of that, plus the Devices and System pages |
|
|
||||||
|
|
||||||
The cameras themselves are *not* accounts and never appear in this list. They
|
|
||||||
identify themselves a different way and cannot log into the website.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Signing in
|
|
||||||
|
|
||||||
Open the address of your server in a browser. You get a login form asking for
|
|
||||||
your username, your password, and — if your account has one — the six-digit
|
|
||||||
code from your authenticator app.
|
|
||||||
|
|
||||||
If the code is refused, check your phone's clock. These codes are generated
|
|
||||||
from the current time, so a phone that is a minute off produces codes the
|
|
||||||
server considers wrong. A few seconds out is fine; the server accepts the code
|
|
||||||
before and after the current one.
|
|
||||||
|
|
||||||
**A wrong password and a username that does not exist give exactly the same
|
|
||||||
message.** That is deliberate: telling you "no such user" would let a stranger
|
|
||||||
work out which usernames exist.
|
|
||||||
|
|
||||||
Repeated failed attempts are slowed down. This is limited **per network
|
|
||||||
address, not per username** — on purpose, because limiting by username would
|
|
||||||
let anyone lock you out of your own account just by guessing at it.
|
|
||||||
|
|
||||||
You stay signed in for **two weeks** by default, then have to sign in again.
|
|
||||||
|
|
||||||
"Sign out" takes effect immediately, because the session is deleted on the
|
|
||||||
server rather than merely forgotten by the browser — there is no window in
|
|
||||||
which an old login still works. It ends the session **in that browser only**,
|
|
||||||
though. If you are also signed in on your phone, that stays signed in.
|
|
||||||
Changing the password (`poorbird user passwd`) is what ends every session for
|
|
||||||
that account at once.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Using the gallery
|
|
||||||
|
|
||||||
The main page is a grid of thumbnails, newest first. Scroll and older photos
|
|
||||||
load automatically; there are no page numbers.
|
|
||||||
|
|
||||||
> Only the tiles you can actually see exist in the browser. This sounds like a
|
|
||||||
> detail but it is the reason the page stays usable: a busy feeder can produce
|
|
||||||
> thousands of photos a day, and a browser asked to hold a year of them at
|
|
||||||
> once simply stops responding.
|
|
||||||
|
|
||||||
**Click a photo** to see it full size with its details beside it. In that view:
|
|
||||||
|
|
||||||
| Key | Does |
|
|
||||||
|---|---|
|
|
||||||
| `→` | Next photo |
|
|
||||||
| `←` | Previous photo |
|
|
||||||
| `Esc` | Back to the grid |
|
|
||||||
|
|
||||||
Use the keyboard. Labelling a day of photos is look-decide-next a few hundred
|
|
||||||
times, and that is tiring with a mouse.
|
|
||||||
|
|
||||||
The arrows stop at the last photo loaded so far rather than showing you an
|
|
||||||
empty frame while more arrive. Scroll the grid a little further and they
|
|
||||||
continue.
|
|
||||||
|
|
||||||
### Filters
|
|
||||||
|
|
||||||
Above the grid you can narrow things down by date range, by camera, and by
|
|
||||||
three yes/no questions: **kept**, **reviewed**, and **pre-trigger**.
|
|
||||||
|
|
||||||
Each of those is a three-way choice — *any*, *yes*, *no* — not a checkbox. A
|
|
||||||
checkbox can only say "kept" or "don't care", and "show me only the ones I
|
|
||||||
rejected" is a question you will want to ask.
|
|
||||||
|
|
||||||
Changing a filter starts the list again from the top. It does not add to what
|
|
||||||
was already on screen.
|
|
||||||
|
|
||||||
**"Pre-trigger" needs explaining.** The camera is always quietly taking
|
|
||||||
pictures into a small buffer it keeps overwriting. When the radar fires, it
|
|
||||||
sends the couple of frames from *just before* the trigger as well. Those are
|
|
||||||
often the best ones — a bird landing rather than a bird already sitting. They
|
|
||||||
are marked so you know the radar had not fired yet when they were taken.
|
|
||||||
|
|
||||||
### What the details mean
|
|
||||||
|
|
||||||
- **Received** — when the server got the photo. This is the timestamp the
|
|
||||||
system trusts.
|
|
||||||
- **Taken** — when the camera thinks it took the photo. It may say **"not
|
|
||||||
synced"**: the camera has no battery-backed clock, so after a power cut it
|
|
||||||
does not know the time until it can ask. It reports that honestly instead of
|
|
||||||
claiming 1 January 1970, which is what a naive system shows.
|
|
||||||
- **Distance / energy** — what the radar measured: how far away, and how
|
|
||||||
strong the movement.
|
|
||||||
- **Burst 2 of 5** — photos arrive in bursts. This is the second of five.
|
|
||||||
- **A "prediction" badge** on a species means *the computer guessed*, not that
|
|
||||||
a person identified it. Automatic identification does not exist yet; when it
|
|
||||||
does, its guesses stay marked. The labels you write are training material
|
|
||||||
for it, and a guess quietly mixed in with confirmed labels would poison
|
|
||||||
that.
|
|
||||||
|
|
||||||
### Missing thumbnails
|
|
||||||
|
|
||||||
A photo whose small preview has not been generated yet shows a placeholder
|
|
||||||
instead of a broken image. The previews are made by a background program (the
|
|
||||||
"worker"). If placeholders do not disappear, that program is probably not
|
|
||||||
running.
|
|
||||||
|
|
||||||
### Themes and language
|
|
||||||
|
|
||||||
Top right: three colour schemes (light, dark, and a dark blue) and two
|
|
||||||
languages (German, English). Both are remembered in your browser. They are not
|
|
||||||
yet tied to your account, so a different browser starts from the default.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Commands you may need
|
|
||||||
|
|
||||||
Run these where the server is installed. `poorbird` is the program.
|
|
||||||
|
|
||||||
| Command | Does |
|
|
||||||
|---|---|
|
|
||||||
| `poorbird check` | **Run this first when something is wrong.** Checks the settings, the database and the folders, and explains what it finds without starting anything. |
|
|
||||||
| `poorbird user add NAME --role admin` | Create an account |
|
|
||||||
| `poorbird user list` | Show accounts and whether each uses a six-digit code |
|
|
||||||
| `poorbird user passwd NAME` | Set a new password. Also signs that person out everywhere. |
|
|
||||||
| `poorbird serve` | Run the website's server part |
|
|
||||||
| `poorbird worker` | Run the background program that makes thumbnails |
|
|
||||||
| `poorbird migrate` | Bring the database structure up to date after an update |
|
|
||||||
| `poorbird seed --captures 500` | Invent 500 fake photos, to try the gallery without waiting for birds |
|
|
||||||
| `poorbird seed --clear` | Delete those fake photos again |
|
|
||||||
|
|
||||||
`seed --clear` only ever removes invented data. It is restricted to the fake
|
|
||||||
camera it created, so a real camera's photos are never at risk. There is a
|
|
||||||
test that puts a real camera alongside the fake one and checks it survives.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Settings
|
|
||||||
|
|
||||||
Settings live in one file, `/etc/poorbird/poorbird.env`, one `NAME=value` per
|
|
||||||
line. The program is restarted to pick up a change:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo systemctl restart poorbird-api poorbird-worker
|
|
||||||
```
|
|
||||||
|
|
||||||
The full file with the reasoning is
|
|
||||||
[`../server/deploy/poorbird.env.example`](../server/deploy/poorbird.env.example).
|
|
||||||
In plain language:
|
|
||||||
|
|
||||||
### The ones you must set
|
|
||||||
|
|
||||||
| Setting | Meaning |
|
|
||||||
|---|---|
|
|
||||||
| `POORBIRD_DATABASE_URL` | Where the database is and the password to reach it. **No default** — the program refuses to start rather than guess, and it also refuses if you copied the example and left `CHANGE_ME` in place. |
|
|
||||||
| `POORBIRD_ENROLL_SECRET` | A shared password the cameras use to introduce themselves the very first time. Make one with `openssl rand -hex 32`. |
|
|
||||||
|
|
||||||
> **Do not change `POORBIRD_ENROLL_SECRET` casually.** It is built into the
|
|
||||||
> camera's own software as a last-resort way back in if the camera can no
|
|
||||||
> longer be reached. Changing it here without also updating the camera removes
|
|
||||||
> that escape hatch — and a camera mounted outside is hard to reach.
|
|
||||||
|
|
||||||
### Where files go
|
|
||||||
|
|
||||||
| Setting | Meaning |
|
|
||||||
|---|---|
|
|
||||||
| `POORBIRD_IMAGE_ROOT` | The full-size photos. Default `/srv/poorbird/images`. |
|
|
||||||
| `POORBIRD_THUMB_ROOT` | The small previews. Default `/srv/poorbird/thumbs`. |
|
|
||||||
| `POORBIRD_STATE_DIR` | Internal bookkeeping. Default `/var/lib/poorbird`. |
|
|
||||||
|
|
||||||
These two must stay next to each other, named `images` and `thumbs`, in the
|
|
||||||
same parent folder. The web server reads them from there. `poorbird check`
|
|
||||||
tells you if they have drifted apart, because the symptom otherwise is photos
|
|
||||||
that mysteriously fail to load with nothing written in any log.
|
|
||||||
|
|
||||||
**Photos are never handed out straight from the folder.** Every request is
|
|
||||||
checked against your login first, and only then are the bytes sent. A photo's
|
|
||||||
address being hard to guess is not protection.
|
|
||||||
|
|
||||||
### The two that trip everyone up
|
|
||||||
|
|
||||||
| Setting | Meaning |
|
|
||||||
|---|---|
|
|
||||||
| `POORBIRD_SESSION_COOKIE_SECURE` | Leave `true`. Set `false` **only** if you are reaching the site over plain `http://` instead of `https://`. |
|
|
||||||
| `POORBIRD_SERVE_IMAGES_DIRECTLY` | Leave `false`. `true` is for a developer's machine only. |
|
|
||||||
|
|
||||||
The first one matters because of a browser rule: a cookie marked "secure" is
|
|
||||||
thrown away over an unencrypted connection. The browser does not warn, the
|
|
||||||
login reports success, and you simply are not signed in — with nothing in any
|
|
||||||
log to explain it. If you ever see "login worked but I'm not signed in", this
|
|
||||||
is why.
|
|
||||||
|
|
||||||
The second changes *who reads the photo off the disk* — the main program, or
|
|
||||||
the web server in front of it. The web server is far better at it. **It does
|
|
||||||
not change the permission check**: the same check runs either way.
|
|
||||||
|
|
||||||
### Rarely touched
|
|
||||||
|
|
||||||
| Setting | Meaning | Default |
|
|
||||||
|---|---|---|
|
|
||||||
| `POORBIRD_SESSION_LIFETIME_H` | How long you stay signed in, in hours | `336` (two weeks) |
|
|
||||||
| `POORBIRD_RATE_LIMIT_ENABLED` | Slow down repeated failed logins and flooding cameras | `true` |
|
|
||||||
| `POORBIRD_API_HOST` / `_PORT` | Where the program listens. It should stay reachable only from the machine itself; the web server in front handles the outside world. | `127.0.0.1`, and set `8090` in the example file |
|
|
||||||
| `POORBIRD_DB_POOL_SIZE` / `_MAX_OVERFLOW` | How many database connections it may open at once | `15` / `10` |
|
|
||||||
| `POORBIRD_WORKER_POLL_INTERVAL_S` | How long the background program waits before checking for new work when there is none. It does *not* slow down work already waiting. | `5` |
|
|
||||||
| `POORBIRD_JOB_MAX_ATTEMPTS` | How many times to retry a failed background job | `3` |
|
|
||||||
| `POORBIRD_LOG_LEVEL` | How chatty the log is | `INFO` |
|
|
||||||
| `POORBIRD_LOG_FORMAT` | `text` to read by eye, `json` for log-collecting tools | `text` |
|
|
||||||
| `POORBIRD_DB_ECHO` | Print every database query. Debugging only; very noisy. | `false` |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. When something is wrong
|
|
||||||
|
|
||||||
**Start with `poorbird check`.** It is built to answer "is this machine set up
|
|
||||||
correctly" and to explain, not just to fail.
|
|
||||||
|
|
||||||
| Symptom | Most likely |
|
|
||||||
|---|---|
|
|
||||||
| Login says success, but you are not signed in | `POORBIRD_SESSION_COOKIE_SECURE=true` while using plain `http://`. See above. |
|
|
||||||
| The website says it cannot reach the server | The `poorbird serve` program is not running. |
|
|
||||||
| The page loads but the grid is empty | No photos yet. Try `poorbird seed --captures 500` to confirm the gallery itself works. |
|
|
||||||
| Thumbnails stay as placeholders | The `poorbird worker` program is not running. |
|
|
||||||
| Photos fail to load, nothing in the log | `images` and `thumbs` are not siblings where the web server expects. `poorbird check`. |
|
|
||||||
| The six-digit code is refused | Your phone's clock is off. |
|
|
||||||
| The login form rejects you repeatedly, then stops responding | Rate limiting. Wait, then try once, carefully. |
|
|
||||||
| Refreshing on a page like `/devices` gives "not found" | The web server's configuration is missing the rule that sends unknown paths back to the gallery. It is the `try_files` line in the Caddyfile, installed in `INSTALL.md` step 6. |
|
|
||||||
|
|
||||||
### Two things to know before you trust it
|
|
||||||
|
|
||||||
**There are no backups yet.** Nothing in poorBird copies your photos
|
|
||||||
anywhere. If that disk fails, the photos are gone. This is planned work, not
|
|
||||||
an oversight, but until it exists: do not let photos you would miss pile up
|
|
||||||
here as their only copy.
|
|
||||||
|
|
||||||
**The camera has never run on real hardware**, and the server has never run
|
|
||||||
outside a developer's machine. Everything described here works — there are 308
|
|
||||||
automated tests and the gallery has been used against 500 photos — but "works
|
|
||||||
on a desk" and "works on a pole in the rain for a year" are different claims.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Privacy, briefly
|
|
||||||
|
|
||||||
The camera talks to your server over your own network in plain, unencrypted
|
|
||||||
form. This is a deliberate trade: encryption on a device this small means a
|
|
||||||
certificate baked into its software, and a camera that silently stops
|
|
||||||
uploading when that certificate is replaced — while it is mounted on a pole.
|
|
||||||
Anyone already on your home network could therefore see the uploads.
|
|
||||||
|
|
||||||
Your own browsing of the gallery *is* encrypted, and needs a login.
|
|
||||||
|
|
||||||
Nothing is sent anywhere else. There is no cloud service, no account
|
|
||||||
elsewhere, and no automatic sharing. The photos are on your disk and nowhere
|
|
||||||
else — which is also why the missing backup is worth taking seriously.
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
# Code reviews
|
|
||||||
|
|
||||||
One directory per reviewed scope:
|
|
||||||
|
|
||||||
```
|
|
||||||
docs/reviews/<scope>/REVIEW.md human-readable review
|
|
||||||
docs/reviews/<scope>/REVIEW.AI.md long-form context, written for an AI to
|
|
||||||
read before working on that scope
|
|
||||||
```
|
|
||||||
|
|
||||||
`<scope>` is the branch the review was made against, with slashes flattened —
|
|
||||||
`feature/Server_Basic_implementation` becomes `server-basic-implementation`.
|
|
||||||
|
|
||||||
## Why the directory, and not `server/REVIEW.md`
|
|
||||||
|
|
||||||
These documents are **branch-scoped snapshots**, pinned to a commit that is
|
|
||||||
named in their header. They are not living documentation of the directory they
|
|
||||||
sit in.
|
|
||||||
|
|
||||||
Kept at a fixed path like `server/REVIEW.md`, every reviewed branch writes the
|
|
||||||
same two filenames with different content, and every merge is an unresolvable
|
|
||||||
`add/add` conflict. That happened: the review of the UI branch lived at
|
|
||||||
`server/REVIEW.md` — a path that describes neither its subject nor its scope —
|
|
||||||
and merging the two feature branches conflicted on both files.
|
|
||||||
|
|
||||||
A directory per scope means two reviews never collide, both survive into
|
|
||||||
`develop`, and the path says what was reviewed without opening the file.
|
|
||||||
|
|
||||||
## Reading one
|
|
||||||
|
|
||||||
Check the header first. Every review states its branch and commit:
|
|
||||||
|
|
||||||
```
|
|
||||||
**Branch:** feature/Server_Basic_implementation (Commit: 142b476)
|
|
||||||
```
|
|
||||||
|
|
||||||
If that commit is behind the branch tip, the review is a snapshot of an older
|
|
||||||
state — treat its "what's missing" sections as of that date, not as current.
|
|
||||||
Verify a claim against the code before acting on it. Several findings in the
|
|
||||||
existing reviews are accurate; several reference implementations in them are
|
|
||||||
not, and the ones that were wrong are noted in the code that replaced them.
|
|
||||||
|
|
||||||
## Adding one
|
|
||||||
|
|
||||||
Create `docs/reviews/<scope>/` and write both files. Do not copy a review from
|
|
||||||
one branch to another: a review describes the branch it was made against, and
|
|
||||||
a branch without one simply has not been reviewed yet.
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,596 +0,0 @@
|
|||||||
# Code Review: poorBird Server (feature/Server_Basic_implementation)
|
|
||||||
|
|
||||||
**Reviewer:** Mistral Vibe
|
|
||||||
**Date:** 2026-09-21
|
|
||||||
**Branch:** feature/Server_Basic_implementation
|
|
||||||
**Commit:** 142b476 (Server: Phase 2 (REVIEW not respected yet))
|
|
||||||
**Version:** 0.1.0
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Executive Summary
|
|
||||||
|
|
||||||
**Status: Phase 1 COMPLETE, Phase 2 STARTED**
|
|
||||||
|
|
||||||
Der Server-Branch enthalt die **vollstandige Phase 1 Implementation** (Server Foundation) und erste Ansatze fur Phase 2. Die Code-Qualitat ist **exzellent** - die Architektur ist durchdacht, gut dokumentiert und production-ready. Allerdings gibt es **kritische Sicherheitsprobleme**, die **vor Phase 2/3** behoben werden mussen.
|
|
||||||
|
|
||||||
| Kategorie | Rating | Priority | Notes |
|
|
||||||
|----------|--------|----------|-------|
|
|
||||||
| **Architektur** | 5/5 | Niedrig | Sehr gut durchdacht, UI-ready |
|
|
||||||
| **Sicherheit** | 2/5 | **Hoch** | **Muss vor Phase 2/3 fixen** |
|
|
||||||
| **Performance** | 4/5 | Mittel | Gut fur aktuelle Skala |
|
|
||||||
| **Code Qualitat** | 5/5 | Niedrig | Exzellent |
|
|
||||||
| **Test Coverage** | 5/5 | Niedrig | 12/12 Tests passen |
|
|
||||||
| **Dokumentation** | 5/5 | Niedrig | Ausgezeichnet |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Branch Status
|
|
||||||
|
|
||||||
### Current State
|
|
||||||
- **Branch Name:** feature/Server_Basic_implementation
|
|
||||||
- **Commit:** 142b476 ("Server: Phase 2 (REVIEW not respected yet)")
|
|
||||||
- **Phase:** 1 (Server Foundation) - **COMPLETE**
|
|
||||||
- **Phase 2:** STARTED (Web-Build-Dateien vorhanden, aber keine Device-Endpoints)
|
|
||||||
- **Relation:** Basis fur feature/UI_Basic_implementation
|
|
||||||
|
|
||||||
### Wichtige Beobachtung
|
|
||||||
Dieser Branch ist der **kanonische Server-Branch**. Er enthalt:
|
|
||||||
- ✅ Vollstandige Server-Infrastruktur (Phase 1)
|
|
||||||
- ✅ Alle Datenbank-Modelle
|
|
||||||
- ✅ Job-Queue mit PostgreSQL (FOR UPDATE SKIP LOCKED)
|
|
||||||
- ✅ Health-Endpoints
|
|
||||||
- ✅ Systemd-Units und Caddy-Konfiguration
|
|
||||||
- ✅ migrations und Schema-Validierung
|
|
||||||
- ❌ **Keine Device-Endpoints** (Phase 2 noch nicht implementiert)
|
|
||||||
- ❌ **Keine Authentifizierung** (wird fur Phase 2/3 benotigt)
|
|
||||||
|
|
||||||
### Phasen-Information
|
|
||||||
```
|
|
||||||
Phase 1 (DONE): Server foundation, config, schema, health, job queue, scheduler
|
|
||||||
Phase 2 (STARTED): Device endpoints (/enroll, /ingest, /heartbeat, /status, /config)
|
|
||||||
Phase 3 (TARGET): WebUI (React+TS+Vite) - in feature/UI_Basic_implementation
|
|
||||||
Phase 4: Device management, OTA
|
|
||||||
Phase 5: Operations (backup, retention, alarms)
|
|
||||||
Phase 6: Streaming
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Projekt-Ubersicht
|
|
||||||
|
|
||||||
### Core Purpose
|
|
||||||
Radar-gesteuertes Vogel-Kamera-System, das:
|
|
||||||
1. Vogel mit LD2410 Radar-Sensor erkennt
|
|
||||||
2. Bilder mit ESP32 Kamera aufnimmt
|
|
||||||
3. Bilder uber MQTT an Server sendet
|
|
||||||
4. Bilder und Metadaten in PostgreSQL speichert
|
|
||||||
5. Web-Interface fur Anzeige und Verwaltung bereitstellt
|
|
||||||
|
|
||||||
### Domain
|
|
||||||
- **Primar:** IoT + Computer Vision + Web Application
|
|
||||||
- **Sekundar:** Datenverwaltung, Device Management, Benutzerverwaltung
|
|
||||||
|
|
||||||
### Benutzer-Typen
|
|
||||||
| Benutzer-Typ | Zugriff | Use Cases |
|
|
||||||
|-------------|---------|----------|
|
|
||||||
| Device | API nur | Enroll, Bilder hochladen, Status senden |
|
|
||||||
| Viewer | Nur Lesen | Galerie anzeigen, suchen, filtern |
|
|
||||||
| Editor | Lesen+Schreiben | Anzeigen + Beobachtungen hinzufugen, Tags, Metadaten bearbeiten |
|
|
||||||
| Admin | Voll | Alles von Editor + Device-Management, Benutzerverwaltung, Einstellungen |
|
|
||||||
|
|
||||||
### Technologie-Stack
|
|
||||||
| Layer | Technologie | Version | Status |
|
|
||||||
|-------|------------|---------|--------|
|
|
||||||
| Backend | Python | 3.14.7 (verifiziert) | Phase 1 Complete |
|
|
||||||
| Framework | FastAPI | Latest | Phase 1 Complete |
|
|
||||||
| Database | PostgreSQL | 17 | Phase 1 Complete |
|
|
||||||
| ORM | SQLAlchemy | 2.0 | Phase 1 Complete |
|
|
||||||
| Migrations | Alembic | Latest | Phase 1 Complete |
|
|
||||||
| Proxy | Caddy | 2.x | Phase 1 Complete |
|
|
||||||
| Logging | structlog/stdout | - | Phase 1 Complete |
|
|
||||||
|
|
||||||
### Skalierungs-Erwartungen
|
|
||||||
| Metrik | Wert | Notes |
|
|
||||||
|--------|------|-------|
|
|
||||||
| Kameras | 1-10 (Phase 3), 100+ (zukunftig) | Aktuell: 1 |
|
|
||||||
| Captures/Tag | 5000 | 1 Kamera, ~10/Stunde |
|
|
||||||
| Bild-Grose | 200-500KB | JPEG |
|
|
||||||
| Thumb-Grose | 20-50KB | WebP, 400px |
|
|
||||||
| Gleichzeitige Nutzer | 1-5 typisch, 10 peak | LAN-only |
|
|
||||||
| Storage/Monat | ~1GB | 5000 Bilder * 200KB |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Architektur-Analyse
|
|
||||||
|
|
||||||
### Was bereits vorhanden ist (Phase 1)
|
|
||||||
|
|
||||||
#### ✅ **Konfiguration**
|
|
||||||
- `config.py`: Alle Werte aus Umgebungsvariablen (keine Hardcoded-Werte)
|
|
||||||
- `POORBIRD_` Prefix fur alle Variablen
|
|
||||||
- Gute Trennung von database, http, storage, devices, worker, logging
|
|
||||||
- **Kritikpunkt:** database_url hat Standardwert mit Credentials (siehe SEC-008)
|
|
||||||
|
|
||||||
#### ✅ **Datenbank**
|
|
||||||
- `db.py`: SQLAlchemy Engine + Session Factory
|
|
||||||
- Sync SQLAlchemy (bewusste Entscheidung, kein Async)
|
|
||||||
- Connection Pool: 5 (kann fur Phase 3 erhoht werden)
|
|
||||||
- `schema_compare.py`: Normalisierung von Server-Defaults (geniale Losung!)
|
|
||||||
- Verhindert falsche Drift-Meldungen durch Postgres-Type-Casts
|
|
||||||
- Gleiche Logik fur Migrationen und Tests
|
|
||||||
|
|
||||||
#### ✅ **Modelle**
|
|
||||||
- Vollstandiges Schema nach SPEC S3
|
|
||||||
- Alle Tabellen: users, sessions, devices, captures, observations, taxa, tags, firmware, device_commands, device_status, settings, audit_log, backup_runs, jobs
|
|
||||||
- Gute Beziehungen und Constraints
|
|
||||||
- JSONB fur flexible Konfiguration (device.config)
|
|
||||||
|
|
||||||
#### ✅ **API**
|
|
||||||
- `app.py`: FastAPI App mit Lifespan Management
|
|
||||||
- Health-Endpoints: `/api/v1/health`, `/healthz`
|
|
||||||
- API-Prefix: `/api/v1/`
|
|
||||||
- Gute Fehlerbehandlung und Logging
|
|
||||||
|
|
||||||
#### ✅ **Job-Queue**
|
|
||||||
- `queue.py`: PostgreSQL-basierte Queue mit FOR UPDATE SKIP LOCKED
|
|
||||||
- Keine Redis-Abhangigkeit (SPEC 6)
|
|
||||||
- Handler: noop, prune_expired_commands
|
|
||||||
- Scheduler in `worker/main.py`
|
|
||||||
- Worker claimt Jobs und verarbeitet sie sequentiell
|
|
||||||
|
|
||||||
#### ✅ **CLI**
|
|
||||||
- `cli.py`: serve, worker, migrate, check, enqueue
|
|
||||||
- `poorbird check`: Validiert Config, Pfade, Datenbank
|
|
||||||
- `poorbird serve`: Startet API
|
|
||||||
- `poorbird worker`: Startet Worker + Scheduler
|
|
||||||
- `poorbird migrate`: Wendet Migrationen an
|
|
||||||
|
|
||||||
#### ✅ **Deployment**
|
|
||||||
- systemd-Units: `poorbird-api.service`, `poorbird-worker.service`
|
|
||||||
- Caddyfile mit DNS-01 TLS, Image-Handoff, Camera-Listener
|
|
||||||
- Installationsanleitung in `deploy/INSTALL.md`
|
|
||||||
- Windows-Entwicklung mit uv + Podman dokumentiert
|
|
||||||
|
|
||||||
### Was fehlt fur Phase 2/3
|
|
||||||
|
|
||||||
#### ❌ **Device-Endpoints** (Phase 2)
|
|
||||||
- `/api/v1/enroll` - Device-Registrierung
|
|
||||||
- `/api/v1/ingest` - Bild-Hochladen
|
|
||||||
- `/api/v1/heartbeat` - Device-Status
|
|
||||||
- `/api/v1/status` - Device-Statistik
|
|
||||||
- `/api/v1/config` - Device-Konfiguration
|
|
||||||
- `/api/v1/firmware` - Firmware-Upload
|
|
||||||
|
|
||||||
#### ❌ **Authentifizierung**
|
|
||||||
- Keine Device-Authentifizierung
|
|
||||||
- Keine User-Authentifizierung (fur WebUI)
|
|
||||||
- Keine Session-Verwaltung
|
|
||||||
- Kein Passwort-Hashing
|
|
||||||
- Keine CSRF-Schutz
|
|
||||||
- Keine Rate-Limiting
|
|
||||||
|
|
||||||
#### ❌ **CORS**
|
|
||||||
- Keine CORS-Konfiguration (wird fur WebUI benotigt)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Sicherheits-Analyse
|
|
||||||
|
|
||||||
### Severity-System
|
|
||||||
- **KRITISCH:** Muss vor Phase 2/3 behoben werden. Blockiert Produktion.
|
|
||||||
- **HOCH:** Muss vor Phase 3 behoben werden. Ernstes Risiko.
|
|
||||||
- **MITTEL:** Sollte vor Phase 3 behoben werden. Moderates Risiko.
|
|
||||||
- **NIEDRIG:** Nice to have. Geringes Risiko.
|
|
||||||
|
|
||||||
### KRITISCHE Probleme (BLOCK PHASE 2/3)
|
|
||||||
|
|
||||||
#### SEC-001: Enroll Secret im Klartext
|
|
||||||
- **Ort:** config.py:53, .env-Dateien, systemd EnvironmentFile
|
|
||||||
- **Code:** `enroll_secret: SecretStr = SecretStr("")`
|
|
||||||
- **Problem:** Bootstrap Secret wird in Dateien im Klartext gespeichert
|
|
||||||
- **Risiko:** Dateisystem-Zugriff = vollstandige Device-Spoofing. Wenn UI Device-Management freigibt, kann Angreifer bösartige Gerate registrieren.
|
|
||||||
- **Auswirkung:** Katastrophal. Gefahrdet gesamten Device-Netzwerk.
|
|
||||||
- **Lösung:**
|
|
||||||
```python
|
|
||||||
# Option 1: Nur uber CLI setzen
|
|
||||||
enroll_secret: SecretStr # Kein Standardwert
|
|
||||||
# Nur setzen uber: poorbird config set enroll_secret <wert>
|
|
||||||
|
|
||||||
# Option 2: Environment-Variable ohne Standard
|
|
||||||
enroll_secret: SecretStr
|
|
||||||
```
|
|
||||||
- **Dateien zu andern:** config.py, deploy/poorbird.env.example
|
|
||||||
- **Tests:** Verifizieren, dass Secret nicht geloggt wird
|
|
||||||
- **Prioritat:** KRITISCH
|
|
||||||
- **Aufwand:** 2-4 Stunden
|
|
||||||
|
|
||||||
#### SEC-002: Keine Request-Authentifizierung
|
|
||||||
- **Ort:** Alle API-Endpoints
|
|
||||||
- **Problem:** Keine Authentifizierung fur beliebige Endpoints
|
|
||||||
- **Risiko:** Jeder kann Device-Kommandos senden, Admin-Funktionen nutzen, Benutzer verwalten
|
|
||||||
- **Auswirkung:** Vollstandiger System-Kompromiss
|
|
||||||
- **Lösung:**
|
|
||||||
```python
|
|
||||||
# Device-Auth (fur /enroll, /ingest, /heartbeat, /status)
|
|
||||||
from fastapi import Request, HTTPException, Header
|
|
||||||
|
|
||||||
async def verify_device(request: Request,
|
|
||||||
x_enroll_secret: str = Header(None)):
|
|
||||||
if not x_enroll_secret:
|
|
||||||
raise HTTPException(status_code=401)
|
|
||||||
# Verifizieren gegen enroll_secret Hash
|
|
||||||
|
|
||||||
# User-Auth (fur UI-Endpoints)
|
|
||||||
from fastapi import Cookie
|
|
||||||
|
|
||||||
async def verify_user(request: Request,
|
|
||||||
session_id: str = Cookie(None)):
|
|
||||||
if not session_id:
|
|
||||||
raise HTTPException(status_code=401)
|
|
||||||
# Verifizieren Session in DB
|
|
||||||
```
|
|
||||||
- **Dateien zu erstellen:** api/routes/auth.py, api/deps.py
|
|
||||||
- **Dateien zu andern:** app.py
|
|
||||||
- **Prioritat:** KRITISCH
|
|
||||||
- **Aufwand:** 1-2 Tage
|
|
||||||
|
|
||||||
#### SEC-003: Keine Input-Validierung
|
|
||||||
- **Ort:** queue.py:47-66 (enqueue-Funktion), alle zukunftigen Endpoints
|
|
||||||
- **Problem:** Payloads werden nicht vor DB-Insert validiert
|
|
||||||
- **Risiko:** SQL Injection, XSS, bosartige Daten, Datenkorruption
|
|
||||||
- **Auswirkung:** Hoch. UI akzeptiert User-Input
|
|
||||||
- **Lösung:**
|
|
||||||
```python
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from typing import Literal, Optional, Union
|
|
||||||
|
|
||||||
class NoopJobPayload(BaseModel):
|
|
||||||
message: Optional[str] = None
|
|
||||||
|
|
||||||
class ThumbnailJobPayload(BaseModel):
|
|
||||||
capture_id: str # UUID
|
|
||||||
quality: int = Field(ge=1, le=100)
|
|
||||||
width: int = Field(ge=100, le=2000)
|
|
||||||
|
|
||||||
JobPayload = Union[NoopJobPayload, ThumbnailJobPayload]
|
|
||||||
|
|
||||||
def enqueue(session: Session,
|
|
||||||
kind: Literal["noop", "thumbnail"],
|
|
||||||
payload: JobPayload,
|
|
||||||
...):
|
|
||||||
# Payload ist jetzt validiert!
|
|
||||||
```
|
|
||||||
- **Dateien zu erstellen:** api/schemas.py
|
|
||||||
- **Dateien zu andern:** queue.py, alle Route-Dateien
|
|
||||||
- **Prioritat:** KRITISCH
|
|
||||||
- **Aufwand:** 1-2 Tage
|
|
||||||
|
|
||||||
### HOHE Priorität (FIX BEFORE PHASE 2/3)
|
|
||||||
|
|
||||||
#### SEC-004: Keine Rate-Limiting
|
|
||||||
- **Ort:** API-Layer (app.py)
|
|
||||||
- **Problem:** Kein Schutz vor DoS oder Brute Force
|
|
||||||
- **Risiko:** API-Endpoints konnen uberflutet werden
|
|
||||||
- **Lösung:** slowapi oder FastAPI-Limiter
|
|
||||||
- **Prioritat:** HOCH
|
|
||||||
- **Aufwand:** 1 Tag
|
|
||||||
|
|
||||||
#### SEC-005: Keine CORS-Konfiguration
|
|
||||||
- **Ort:** API-Layer
|
|
||||||
- **Problem:** Keine CORS-Header konfiguriert
|
|
||||||
- **Risiko:** WebUI kann keine Requests machen (auch localhost:3000)
|
|
||||||
- **Lösung:**
|
|
||||||
```python
|
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
|
||||||
|
|
||||||
app.add_middleware(
|
|
||||||
CORSMiddleware,
|
|
||||||
allow_origins=["http://localhost:3000", "http://localhost:5173", "https://poorbird.local"],
|
|
||||||
allow_credentials=True,
|
|
||||||
allow_methods=["*"],
|
|
||||||
allow_headers=["*"],
|
|
||||||
)
|
|
||||||
```
|
|
||||||
- **Prioritat:** HOCH
|
|
||||||
- **Aufwand:** 1 Stunde
|
|
||||||
|
|
||||||
#### SEC-006: DB-URL mit Credentials in Defaults
|
|
||||||
- **Ort:** config.py:30
|
|
||||||
- **Problem:** Standardwert enthalt Credentials im Klartext
|
|
||||||
- **Risiko:** Accidentelles Committen von Credentials
|
|
||||||
- **Lösung:**
|
|
||||||
```python
|
|
||||||
# Andern von:
|
|
||||||
database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird"
|
|
||||||
|
|
||||||
# Zu:
|
|
||||||
database_url: str = "" # Muss uber POORBIRD_DATABASE_URL gesetzt werden
|
|
||||||
```
|
|
||||||
- **Prioritat:** HOCH
|
|
||||||
- **Aufwand:** 1 Stunde
|
|
||||||
|
|
||||||
#### SEC-007: Keine Session-Verwaltung
|
|
||||||
- **Ort:** models/users.py hat Session-Modell, aber nicht implementiert
|
|
||||||
- **Problem:** Session-Tabelle existiert aber wird nicht genutzt
|
|
||||||
- **Risiko:** User-Login/Logout nicht implementierbar
|
|
||||||
- **Lösung:** Session-Cookie-Handling implementieren
|
|
||||||
- **Prioritat:** HOCH
|
|
||||||
- **Aufwand:** 1 Tag
|
|
||||||
|
|
||||||
### MITTLERE Priorität
|
|
||||||
|
|
||||||
#### SEC-008: Keine Passwort-Hashing-Implementierung
|
|
||||||
- **Ort:** models/users.py (password_hash-Spalte existiert)
|
|
||||||
- **Problem:** Keine Hashing-Implementierung vorhanden
|
|
||||||
- **Lösung:** Argon2id implementieren
|
|
||||||
- **Prioritat:** MITTEL
|
|
||||||
- **Aufwand:** 2-4 Stunden
|
|
||||||
|
|
||||||
#### SEC-009: Keine Bild-Upload-Validierung
|
|
||||||
- **Ort:** Zukunftige UI-Endpoints
|
|
||||||
- **Problem:** Bilder werden nicht vor Speicherung validiert
|
|
||||||
- **Lösung:** MIME-Type, Grose, Dimensionen prufen
|
|
||||||
- **Prioritat:** MITTEL
|
|
||||||
- **Aufwand:** 2-4 Stunden
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Datenmodell-Analyse
|
|
||||||
|
|
||||||
### Vollständiges Schema
|
|
||||||
|
|
||||||
Das Datenmodell ist **exzellent entworfen** und perfekt fur die Anforderungen. Alle Tabellen sind vorhanden:
|
|
||||||
|
|
||||||
**Benutzer & Authentifizierung:**
|
|
||||||
- `users` - Benutzer mit Rollen (admin, editor, viewer)
|
|
||||||
- `sessions` - Session-Verwaltung
|
|
||||||
|
|
||||||
**Gerate & Kommandos:**
|
|
||||||
- `devices` - Gerate-Informationen
|
|
||||||
- `device_commands` - Kommando-Queue
|
|
||||||
- `device_status` - Zeitreihen-Daten
|
|
||||||
- `firmware` - Firmware-Versionen
|
|
||||||
|
|
||||||
**Captures & Beobachtungen:**
|
|
||||||
- `captures` - Haupttabelle fur Bilder
|
|
||||||
- `observations` - Beobachtungen zu Captures
|
|
||||||
- `taxa` - Taxonomie (Arten)
|
|
||||||
- `tags` - Tags fur Kategorisierung
|
|
||||||
- `capture_tags` - n:m Beziehung
|
|
||||||
|
|
||||||
**Operationen:**
|
|
||||||
- `settings` - System-Einstellungen
|
|
||||||
- `audit_log` - Audit-Log
|
|
||||||
- `backup_runs` - Backup-Informationen
|
|
||||||
|
|
||||||
**Job-Queue:**
|
|
||||||
- `jobs` - PostgreSQL-basierte Queue
|
|
||||||
|
|
||||||
### Wichtige Beziehungen
|
|
||||||
```
|
|
||||||
users (1) ----(n) sessions
|
|
||||||
\-- (n) audit_log
|
|
||||||
\-- (n) device_commands (created_by)
|
|
||||||
\-- (n) firmware (uploaded_by)
|
|
||||||
\-- (n) observations (created_by)
|
|
||||||
|
|
||||||
devices (1) ----(n) captures
|
|
||||||
|--- (n) device_status
|
|
||||||
|--- (n) device_commands
|
|
||||||
\-- (1) current firmware (via is_target)
|
|
||||||
|
|
||||||
captures (1) ----(n) observations
|
|
||||||
|--- (n) tags (via capture_tags)
|
|
||||||
\-- (1) device
|
|
||||||
|
|
||||||
observations (n) ----(1) taxa
|
|
||||||
observations (n) ----(1) capture
|
|
||||||
observations (n) ----(1) user (created_by)
|
|
||||||
|
|
||||||
tags (n) ----(n) captures (via capture_tags)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Wichtige Felder
|
|
||||||
|
|
||||||
**Captures:**
|
|
||||||
- `id` (UUID) - Primar-Schlussel, fur URLs geeignet
|
|
||||||
- `path`, `thumb_path` - Datei-Pfade
|
|
||||||
- `received_at` - **AUTHORITATIV** (SPEC C7)
|
|
||||||
- `trigger` - Ausloser (radar, manual, timer, stream_grab)
|
|
||||||
- `pre_trigger` - Wurde das Bild VOR dem Trigger aufgenommen?
|
|
||||||
- `kept` - Soft-Reject-Flag
|
|
||||||
- `reviewed` - Wurde-reviewed?
|
|
||||||
- `radar_*` - Radar-Daten
|
|
||||||
- `battery_*`, `rssi`, `temp_c` - Device-Zustand
|
|
||||||
|
|
||||||
**Devices:**
|
|
||||||
- `device_uid` - MAC-basierte Identitat
|
|
||||||
- `config` - JSONB mit allen Einstellungen
|
|
||||||
- `config_version` - Inkrementiert bei jeder Anderung
|
|
||||||
- `battery_valid` - **KRITISCH:** false = **NICHT GEMESSEN** (nicht leer!)
|
|
||||||
- `awake` - Device ist aktiv
|
|
||||||
|
|
||||||
**Device Status:**
|
|
||||||
- Alle Felder sind Zeitreihen-Daten
|
|
||||||
- Zähler (captured_today, etc.) kommen aus RTC-Speicher
|
|
||||||
- **KRITISCH:** Zähler werden bei Stromausfall zuruckgesetzt
|
|
||||||
- **UI-Anzeige:** Zähler zeigen GAP zwischen captured und delivered
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Performance-Analyse
|
|
||||||
|
|
||||||
### Aktuelle Konfiguration
|
|
||||||
|
|
||||||
| Komponente | Einstellung | Aktueller Wert | Bewertung | Empfehlung |
|
|
||||||
|-----------|-------------|----------------|-----------|-------------|
|
|
||||||
| DB Connection Pool | db_pool_size | 5 | 3/5 | 15-20 fur Phase 3 |
|
|
||||||
| Worker Poll Intervall | worker_poll_interval_s | 2.0 | 3/5 | 5.0 (weniger Polling) |
|
|
||||||
| Batch Grose | worker_batch_size | 1 | 3/5 | 5-10 |
|
|
||||||
| Sync SQLAlchemy | - | Aktiviert | 4/5 | OK fur aktuelle Skala |
|
|
||||||
| Log Level | log_level | INFO | 4/5 | OK |
|
|
||||||
| Image Root | image_root | /srv/poorbird/images | 5/5 | OK |
|
|
||||||
| Thumb Root | thumb_root | /srv/poorbird/thumbs | 5/5 | OK |
|
|
||||||
|
|
||||||
### Empfehlungen
|
|
||||||
|
|
||||||
#### Datenbank
|
|
||||||
```python
|
|
||||||
# db.py - Empfohlene Anderungen
|
|
||||||
engine = create_engine(
|
|
||||||
_settings.database_url,
|
|
||||||
pool_size=15, # War 5
|
|
||||||
pool_pre_ping=True,
|
|
||||||
pool_recycle=3600,
|
|
||||||
pool_timeout=30,
|
|
||||||
connect_timeout=10,
|
|
||||||
echo=_settings.db_echo,
|
|
||||||
future=True,
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Worker
|
|
||||||
- **Poll Intervall:** Erhohen auf 5 Sekunden (weniger Overhead)
|
|
||||||
- **Batch Grose:** Erhohen auf 5-10 (bessere Auslastung)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Test-Status
|
|
||||||
|
|
||||||
### Aktueller Stand
|
|
||||||
|
|
||||||
| Test-Datei | Typ | Status | Benotigt | Coverage |
|
|
||||||
|-----------|-----|--------|----------|----------|
|
|
||||||
| test_health.py | Integration | ✅ PASS | PostgreSQL | API Health |
|
|
||||||
| test_queue.py | Integration | ✅ PASS | PostgreSQL | Job Queue |
|
|
||||||
| test_schema_matches_models.py | Integration | ✅ PASS | PostgreSQL + CREATE DB | Schema Drift |
|
|
||||||
| test_config.py | Unit | ✅ PASS | Keine | Config Validierung |
|
|
||||||
| conftest.py | Fixtures | ✅ | PostgreSQL | Test Setup |
|
|
||||||
|
|
||||||
**Gesamt:** 12/12 Tests passieren (100%)
|
|
||||||
|
|
||||||
### Fehlende Tests
|
|
||||||
|
|
||||||
#### Unit Tests (Backend - Phase 2)
|
|
||||||
- Device-Endpoint-Tests
|
|
||||||
- Authentifizierungs-Tests
|
|
||||||
- Validierungs-Tests
|
|
||||||
|
|
||||||
#### Integration Tests (Backend - Phase 2)
|
|
||||||
- Device-Integrationstests
|
|
||||||
- Authentifizierungs-Integrationstests
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Deployment-Analyse
|
|
||||||
|
|
||||||
### Aktueller Stand
|
|
||||||
|
|
||||||
✅ **Alles fur Phase 1 vorhanden:**
|
|
||||||
- systemd-Units: `poorbird-api.service`, `poorbird-worker.service`
|
|
||||||
- Caddyfile mit TLS (DNS-01), Image-Handoff, Camera-Listener
|
|
||||||
- Installationsanleitung in `deploy/INSTALL.md`
|
|
||||||
- Windows-Entwicklung dokumentiert
|
|
||||||
|
|
||||||
### Caddy-Konfiguration
|
|
||||||
|
|
||||||
Die Caddy-Konfiguration ist **exzellent**:
|
|
||||||
- TLS uber DNS-01 (Let's Encrypt)
|
|
||||||
- Auth-checked Image-Handoff (X-Accel-Redirect)
|
|
||||||
- Camera-Listener auf Port 8080 (Plain HTTP, SPEC C2)
|
|
||||||
- Menschliche UI auf Port 443 mit TLS
|
|
||||||
|
|
||||||
### Verifizierter Setup
|
|
||||||
- Python 3.14.7
|
|
||||||
- PostgreSQL 17 (Podman Container)
|
|
||||||
- Alle 12 Tests passieren
|
|
||||||
- Migrationen funktionieren
|
|
||||||
- API lauffahig
|
|
||||||
- Worker verarbeitet Queue
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Zusammenfassung & Empfehlungen
|
|
||||||
|
|
||||||
### Sofort zu tun (vor Phase 2)
|
|
||||||
|
|
||||||
1. **KRITISCHE Sicherheitsprobleme fixen:**
|
|
||||||
- [ ] SEC-001: Enroll Secret aus Defaults entfernen
|
|
||||||
- [ ] SEC-002: Request-Authentifizierung implementieren
|
|
||||||
- [ ] SEC-003: Input-Validierung implementieren
|
|
||||||
- [ ] SEC-006: DB-URL Default entfernen
|
|
||||||
|
|
||||||
2. **HOCH Priorität:**
|
|
||||||
- [ ] SEC-004: Rate-Limiting konfigurieren
|
|
||||||
- [ ] SEC-005: CORS konfigurieren
|
|
||||||
- [ ] SEC-007: Session-Verwaltung implementieren
|
|
||||||
|
|
||||||
### Fur Phase 2
|
|
||||||
|
|
||||||
1. **Device-Endpoints implementieren:**
|
|
||||||
- [ ] `/api/v1/enroll`
|
|
||||||
- [ ] `/api/v1/ingest`
|
|
||||||
- [ ] `/api/v1/heartbeat`
|
|
||||||
- [ ] `/api/v1/status`
|
|
||||||
- [ ] `/api/v1/config`
|
|
||||||
- [ ] `/api/v1/firmware`
|
|
||||||
|
|
||||||
2. **Authentifizierung implementieren:**
|
|
||||||
- [ ] Device-Authentifizierung (X-Enroll-Secret)
|
|
||||||
- [ ] Token-Generierung und -Verwaltung
|
|
||||||
- [ ] Command-Queue
|
|
||||||
|
|
||||||
### Fur Phase 3
|
|
||||||
|
|
||||||
1. **WebUI-Vorbereitung:**
|
|
||||||
- [ ] Passwort-Hashing (Argon2id)
|
|
||||||
- [ ] User-Authentifizierung (Session Cookies)
|
|
||||||
- [ ] CSRF-Schutz
|
|
||||||
- [ ] UI-Endpoints
|
|
||||||
|
|
||||||
### Architektur-Entscheidungen (Respektieren!)
|
|
||||||
|
|
||||||
| Entscheidung | Begründung |
|
|
||||||
|--------------|------------|
|
|
||||||
| **Native Deployment** | SPEC-Anforderung, kein Container-Overhead |
|
|
||||||
| **Sync SQLAlchemy** | Kein Async-Overhead bei 1 Kamera |
|
|
||||||
| **PostgreSQL uber TCP** | Container-ready, bessere Performance |
|
|
||||||
| **FOR UPDATE SKIP LOCKED** | Keine Redis-Abhangigkeit |
|
|
||||||
| **JSONB fur Config** | Flexibel, zukunftssicher |
|
|
||||||
| **UUID fur Captures** | URL-sicher, verteilt |
|
|
||||||
| **Caddy als Proxy** | Einfache TLS-Verwaltung |
|
|
||||||
|
|
||||||
### Nicht in Frage stellen
|
|
||||||
- Kein Docker (SPEC-Anforderung)
|
|
||||||
- Kein Kubernetes
|
|
||||||
- Kein SQLite (PostgreSQL erforderlich)
|
|
||||||
- Kein public Streaming (Phase 6 ist nur intern)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Offene Fragen
|
|
||||||
|
|
||||||
| ID | Frage | Optionen | Impact | Entscheidung durch |
|
|
||||||
|----|-------|---------|--------|-------------------|
|
|
||||||
| Q6 | Anzahl Kameras | 1, 5, 10, 100 | Architektur-Skalierung | Phase 4 |
|
|
||||||
| Q7 | Captures/Tag | 100, 1000, 10000 | Storage, Retention | Phase 5 |
|
|
||||||
| Q8 | Retention: Lschen oder verstecken? | Datei loschen oder Soft-Delete | Datenmodell | Phase 5 |
|
|
||||||
| Q9 | NAS-Protokoll | SFTP, SMB, NFS | Backup-Tooling | Phase 5 |
|
|
||||||
| Q14 | 2FA | Erforderlich oder optional | Sicherheit | Phase 3 |
|
|
||||||
|
|
||||||
### Bereits entschieden (NICHT HINTERFRAGEN)
|
|
||||||
|
|
||||||
| Entscheidung | Begründung | Quelle |
|
|
||||||
|--------------|------------|--------|
|
|
||||||
| Native Deployment | SPEC-Anforderung | TODO.md |
|
|
||||||
| PostgreSQL uber Loopback TCP | Container-ready | TODO.md |
|
|
||||||
| Alle mutable State in expliziten Verzeichnissen | Zukunftige Volume Mounts | TODO.md |
|
|
||||||
| Sync SQLAlchemy | Kein Async-Overhead | README.md |
|
|
||||||
| Job-Queue ohne Redis | Einfachheit | SPEC C8 |
|
|
||||||
| FastAPI | Modern, schnell, gute Typisierung | SPEC 6 |
|
|
||||||
| Caddy | Einfache automatische TLS | SPEC 6 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*Dieses Review wurde erstellt von Mistral Vibe am 2026-09-21 fur den poorBird Server-Branch.*
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,732 +0,0 @@
|
|||||||
# Code Review: poorBird Server (feature/UI_Basic_implementation)
|
|
||||||
|
|
||||||
**Reviewer:** Mistral Vibe
|
|
||||||
**Date:** 2026-09-21
|
|
||||||
**Branch:** feature/UI_Basic_implementation
|
|
||||||
**Commit:** 5d16ded (Server: verify Phase 1 end to end against PostgreSQL 17)
|
|
||||||
**Version:** 0.1.0
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Executive Summary
|
|
||||||
|
|
||||||
**Important Note:** This branch (`feature/UI_Basic_implementation`) currently contains **ONLY server code** (Phase 1) - **no UI implementation exists yet**. The branch name indicates it's **prepared for UI development** (Phase 3), but the UI itself is not implemented.
|
|
||||||
|
|
||||||
The server infrastructure is **architecturally excellent** and **UI-ready**. All foundational work for Phase 3 (WebUI) is in place. The code quality is very high, documentation is outstanding, but **critical security issues must be fixed before UI development begins**.
|
|
||||||
|
|
||||||
| Category | Rating | Priority | Notes |
|
|
||||||
|----------|--------|----------|-------|
|
|
||||||
| **Architecture** | 5/5 | Low | UI-ready foundation |
|
|
||||||
| **Security** | 2/5 | **High** | **Must fix before Phase 3** |
|
|
||||||
| **Performance** | 4/5 | Medium | Good for current scale |
|
|
||||||
| **Code Quality** | 5/5 | Low | Excellent |
|
|
||||||
| **UI Readiness** | 4/5 | Medium | Infrastructure ready, UI missing |
|
|
||||||
| **Test Coverage** | 5/5 | Low | 12/12 tests passing |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Branch Status
|
|
||||||
|
|
||||||
### Current State
|
|
||||||
- **Branch Name:** feature/UI_Basic_implementation
|
|
||||||
- **Actual Content:** Server code only (identical to feature/Server_Basic_implementation)
|
|
||||||
- **Commit:** 5d16ded
|
|
||||||
- **Phase:** 1 (Server Foundation) - **UI Phase (3) not started**
|
|
||||||
|
|
||||||
### Interpretation
|
|
||||||
This branch appears to be a **preparation branch** for UI development. It contains:
|
|
||||||
- ✅ Complete server foundation (Phase 1)
|
|
||||||
- ✅ All infrastructure needed for UI (Phase 3)
|
|
||||||
- ❌ No actual UI code (React/TS/Vite)
|
|
||||||
- ⏳ UI endpoints not implemented (Phase 3 task)
|
|
||||||
|
|
||||||
**Recommendation:** Either rename the branch to reflect its actual content, or start UI implementation.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Architecture Analysis - UI Perspective
|
|
||||||
|
|
||||||
### What's Already UI-Ready
|
|
||||||
|
|
||||||
#### ✅ **API Infrastructure for UI**
|
|
||||||
- FastAPI app with proper lifespan management
|
|
||||||
- API versioning (`/api/v1/` prefix)
|
|
||||||
- Health endpoints for UI monitoring
|
|
||||||
- CORS-ready (needs configuration)
|
|
||||||
|
|
||||||
#### ✅ **Data Models for UI**
|
|
||||||
- `captures` table with all UI-needed fields
|
|
||||||
- `observations` table for species data
|
|
||||||
- `taxa` table for taxonomy autocomplete
|
|
||||||
- `tags` table for categorization
|
|
||||||
- `devices` table with status for device list
|
|
||||||
- `device_status` for time-series data
|
|
||||||
|
|
||||||
#### ✅ **Storage for UI**
|
|
||||||
- `image_root` and `thumb_root` configured
|
|
||||||
- Image path structure: `/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg`
|
|
||||||
- Thumbnails: `_400.webp` suffix
|
|
||||||
- Auth-checked image serving planned (app authorizes, Caddy serves)
|
|
||||||
|
|
||||||
#### ✅ **Authentication Infrastructure**
|
|
||||||
- `users` table with roles (admin, editor, viewer)
|
|
||||||
- `sessions` table for session management
|
|
||||||
- Argon2id password hashing planned
|
|
||||||
- RBAC ready (SPEC 3.1)
|
|
||||||
|
|
||||||
#### ✅ **Deployment for UI**
|
|
||||||
- Caddy reverse proxy with TLS (DNS-01)
|
|
||||||
- Static file serving via Caddy
|
|
||||||
- systemd units for API and worker
|
|
||||||
|
|
||||||
### What's Missing for UI
|
|
||||||
|
|
||||||
#### ❌ **No UI Code**
|
|
||||||
- No React/TypeScript code
|
|
||||||
- No Vite configuration
|
|
||||||
- No frontend build process
|
|
||||||
- No UI dependency management
|
|
||||||
|
|
||||||
#### ❌ **No UI Endpoints**
|
|
||||||
- No gallery API endpoints
|
|
||||||
- No observation management endpoints
|
|
||||||
- No settings endpoints
|
|
||||||
- No user management endpoints
|
|
||||||
|
|
||||||
#### ❌ **No Authentication Implementation**
|
|
||||||
- No session cookie handling
|
|
||||||
- No login/logout endpoints
|
|
||||||
- No password hashing implementation
|
|
||||||
- No CSRF protection
|
|
||||||
|
|
||||||
#### ❌ **No UI-Specific Configuration**
|
|
||||||
- No frontend build directory
|
|
||||||
- No static asset configuration
|
|
||||||
- No theme settings implementation
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Security Analysis - Critical for UI
|
|
||||||
|
|
||||||
### 🔴 CRITICAL Issues (Must Fix Before Phase 3 / UI Development)
|
|
||||||
|
|
||||||
#### 1. **Enroll Secret in Plaintext (CRITICAL)**
|
|
||||||
- **Location:** config.py:53, .env files, systemd EnvironmentFile
|
|
||||||
- **Issue:** Shared bootstrap secret stored in plaintext
|
|
||||||
- **Risk:** Filesystem access = complete device spoofing
|
|
||||||
- **UI Impact:** If UI exposes device management, this is catastrophic
|
|
||||||
- **Solution:**
|
|
||||||
- Use HashiCorp Vault or AWS Secrets Manager
|
|
||||||
- Or: Only accept via CLI, never store in files
|
|
||||||
- Set file permissions to 600
|
|
||||||
- **Priority:** **CRITICAL - Block Phase 3**
|
|
||||||
|
|
||||||
#### 2. **No Request Authentication (CRITICAL)**
|
|
||||||
- **Location:** All API endpoints
|
|
||||||
- **Issue:** No authentication for any endpoint
|
|
||||||
- **Risk:** Anyone can send device commands, access admin functions
|
|
||||||
- **UI Impact:** UI would be completely insecure
|
|
||||||
- **Solution:**
|
|
||||||
- Device auth: X-Enroll-Secret header validation
|
|
||||||
- User auth: Session cookies with CSRF protection
|
|
||||||
- Admin auth: API keys or JWT
|
|
||||||
- **Priority:** **CRITICAL - Block Phase 3**
|
|
||||||
|
|
||||||
#### 3. **No Input Validation (CRITICAL for UI)**
|
|
||||||
- **Location:** queue.py, future UI endpoints
|
|
||||||
- **Issue:** No validation of user input
|
|
||||||
- **Risk:** SQL injection, XSS, malicious data
|
|
||||||
- **UI Impact:** High - UI accepts user input
|
|
||||||
- **Solution:** Pydantic models for ALL requests
|
|
||||||
- **Priority:** **CRITICAL - Block Phase 3**
|
|
||||||
|
|
||||||
#### 4. **No Rate Limiting (HIGH for UI)**
|
|
||||||
- **Location:** API layer
|
|
||||||
- **Issue:** No protection against DoS/brute force
|
|
||||||
- **Risk:** UI endpoints can be flooded
|
|
||||||
- **Solution:** slowapi middleware, 100 req/min/IP
|
|
||||||
- **Priority:** **HIGH - Fix Before Phase 3**
|
|
||||||
|
|
||||||
### 🟡 HIGH Priority Issues (Fix Before Phase 3)
|
|
||||||
|
|
||||||
#### 5. **No CORS Configuration**
|
|
||||||
- **Issue:** No CORS headers
|
|
||||||
- **Risk:** UI cannot make requests if on different origin
|
|
||||||
- **Solution:** Add CORS middleware with specific origins
|
|
||||||
- **Priority:** HIGH
|
|
||||||
|
|
||||||
#### 6. **No CSRF Protection**
|
|
||||||
- **Issue:** Required for WebUI forms
|
|
||||||
- **Risk:** Cross-site request forgery attacks
|
|
||||||
- **Solution:** CSRF tokens for all mutating requests
|
|
||||||
- **Priority:** HIGH
|
|
||||||
|
|
||||||
#### 7. **No Session Management**
|
|
||||||
- **Issue:** sessions table exists but not used
|
|
||||||
- **Risk:** Cannot implement user authentication
|
|
||||||
- **Solution:** Implement session cookie handling
|
|
||||||
- **Priority:** HIGH
|
|
||||||
|
|
||||||
#### 8. **Database URL with Credentials in Defaults**
|
|
||||||
- **Location:** config.py:30
|
|
||||||
- **Issue:** Plaintext credentials in default value
|
|
||||||
- **Risk:** Accidental commit of credentials
|
|
||||||
- **Solution:** Set default to empty string
|
|
||||||
- **Priority:** HIGH
|
|
||||||
|
|
||||||
### 🟡 MEDIUM Priority Issues
|
|
||||||
|
|
||||||
#### 9. **No Password Hashing Implementation**
|
|
||||||
- **Issue:** password_hash column exists but no hashing code
|
|
||||||
- **Solution:** Implement Argon2id hashing (planned per SPEC)
|
|
||||||
- **Priority:** MEDIUM
|
|
||||||
|
|
||||||
#### 10. **No Image Upload Validation**
|
|
||||||
- **Issue:** Images not validated before saving
|
|
||||||
- **Risk:** Malicious file uploads
|
|
||||||
- **Solution:** Validate file type, size, dimensions
|
|
||||||
- **Priority:** MEDIUM
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. UI-Specific Analysis
|
|
||||||
|
|
||||||
### 3.1 What's Prepared for UI
|
|
||||||
|
|
||||||
#### ✅ **Data Model**
|
|
||||||
```
|
|
||||||
Captures (1:n) Observations
|
|
||||||
- UUID primary key (good for URLs)
|
|
||||||
- path, thumb_path
|
|
||||||
- sha256 (for deduplication)
|
|
||||||
- trigger, burst_id, burst_index
|
|
||||||
- pre_trigger flag
|
|
||||||
- radar data (distance, energy)
|
|
||||||
- battery, rssi, temp
|
|
||||||
- kept, reviewed flags
|
|
||||||
- received_at (authoritative timestamp)
|
|
||||||
|
|
||||||
Observations
|
|
||||||
- capture_id (FK)
|
|
||||||
- taxon_id (FK to Taxa)
|
|
||||||
- source (human/model)
|
|
||||||
- model_version, confidence, bbox (for ML)
|
|
||||||
- age, sex, behaviour, certainty
|
|
||||||
- notes
|
|
||||||
|
|
||||||
Taxa
|
|
||||||
- scientific_name, name_de, name_en
|
|
||||||
- gbif_key, family, order
|
|
||||||
- is_local_common (for autocomplete ranking)
|
|
||||||
|
|
||||||
Tags
|
|
||||||
- label, colour
|
|
||||||
- Many-to-many with captures
|
|
||||||
|
|
||||||
Devices
|
|
||||||
- device_uid (MAC-based identity)
|
|
||||||
- config (JSONB - all device settings)
|
|
||||||
- status fields (battery, rssi, etc.)
|
|
||||||
- commands queue
|
|
||||||
- reenroll_secret_hash
|
|
||||||
```
|
|
||||||
|
|
||||||
**Rating:** 5/5 - Excellent data model for UI
|
|
||||||
|
|
||||||
#### ✅ **Storage Structure**
|
|
||||||
- `/srv/poorbird/images/YYYY/MM/DD/<uuid>.jpg`
|
|
||||||
- `/srv/poorbird/thumbs/<uuid>_400.webp`
|
|
||||||
- Single source of truth: `image_root` in config
|
|
||||||
|
|
||||||
**Rating:** 5/5 - Well-designed for UI consumption
|
|
||||||
|
|
||||||
#### ✅ **Authentication Model**
|
|
||||||
- Users: admin, editor, viewer roles
|
|
||||||
- Sessions: for persistent login
|
|
||||||
- TOTP 2FA: optional (SPEC Q14)
|
|
||||||
- Argon2id: for password hashing
|
|
||||||
|
|
||||||
**Rating:** 4/5 - Good foundation, needs implementation
|
|
||||||
|
|
||||||
### 3.2 What Needs to Be Built for UI
|
|
||||||
|
|
||||||
#### 📋 **Phase 3 Tasks (from TODO.md)**
|
|
||||||
|
|
||||||
**Frontend:**
|
|
||||||
- [ ] React + TS + Vite + TanStack Query/Router
|
|
||||||
- [ ] Virtualised gallery grid with filters
|
|
||||||
- [ ] Observation editor
|
|
||||||
- [ ] Taxon autocomplete
|
|
||||||
- [ ] Tags, favourite/reject, review flag
|
|
||||||
- [ ] Three themes (light, dark, blue)
|
|
||||||
- [ ] Auth: session cookies, CSRF, RBAC
|
|
||||||
|
|
||||||
**Backend (UI Endpoints):**
|
|
||||||
- [ ] Gallery API (list, filter, paginate)
|
|
||||||
- [ ] Observation CRUD
|
|
||||||
- [ ] Taxa search/autocomplete
|
|
||||||
- [ ] Tag management
|
|
||||||
- [ ] User management
|
|
||||||
- [ ] Settings management
|
|
||||||
- [ ] Auth endpoints (login, logout, register)
|
|
||||||
|
|
||||||
**Security:**
|
|
||||||
- [ ] Session cookie implementation
|
|
||||||
- [ ] CSRF protection
|
|
||||||
- [ ] Password hashing (Argon2id)
|
|
||||||
- [ ] Audit logging
|
|
||||||
- [ ] Image upload validation
|
|
||||||
|
|
||||||
### 3.3 UI Technology Stack (Planned)
|
|
||||||
|
|
||||||
| Component | Technology | Status |
|
|
||||||
|-----------|------------|--------|
|
|
||||||
| Frontend Framework | React + TypeScript | Not started |
|
|
||||||
| Build Tool | Vite | Not started |
|
|
||||||
| State Management | TanStack Query | Not started |
|
|
||||||
| Routing | TanStack Router | Not started |
|
|
||||||
| Styling | CSS Custom Properties | Not started |
|
|
||||||
| Theming | Design tokens → CSS vars | Not started |
|
|
||||||
| Backend | FastAPI | Phase 1 complete |
|
|
||||||
| Auth | Session cookies + CSRF | Not started |
|
|
||||||
| 2FA | TOTP (optional) | Not started |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Performance Analysis - UI Considerations
|
|
||||||
|
|
||||||
### Current Configuration
|
|
||||||
| Component | Setting | UI Impact | Rating |
|
|
||||||
|-----------|---------|-----------|--------|
|
|
||||||
| DB Connection Pool | 5 | May limit concurrent UI requests | 3/5 |
|
|
||||||
| Worker Poll Interval | 2s | Affected by background jobs only | 4/5 |
|
|
||||||
| Sync SQLAlchemy | Enabled | Blocks event loop under load | 4/5 |
|
|
||||||
| Image Storage | Date-based directories | Good for organization | 5/5 |
|
|
||||||
|
|
||||||
### Expected UI Load
|
|
||||||
- **Gallery View:** 20-50 images per page, paginated
|
|
||||||
- **Search/Filter:** 100-500ms per query (with indexes)
|
|
||||||
- **Image Upload:** ~200-500KB per image
|
|
||||||
- **Thumbnail Generation:** 100-300ms per image (Phase 2)
|
|
||||||
- **Concurrent Users:** 1-5 typical, 10 peak
|
|
||||||
|
|
||||||
### Performance Recommendations for UI
|
|
||||||
|
|
||||||
#### 1. **Database Optimization**
|
|
||||||
```python
|
|
||||||
# Current: 5 connections
|
|
||||||
# Recommended for UI: 15-20 connections
|
|
||||||
db_pool_size: int = 15
|
|
||||||
|
|
||||||
# Add timeouts
|
|
||||||
pool_recycle=3600 # Recycle after 1 hour
|
|
||||||
pool_timeout=30 # Timeout after 30 seconds
|
|
||||||
connect_timeout=10
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 2. **API Performance**
|
|
||||||
- **Pagination:** All list endpoints should be paginated
|
|
||||||
- **Caching:** Cache gallery queries, taxon lists
|
|
||||||
- **Lazy Loading:** Images should load as user scrolls
|
|
||||||
- **Compression:** Enable gzip for API responses
|
|
||||||
|
|
||||||
#### 3. **Image Handling**
|
|
||||||
- **Thumbnails:** Pre-generate on ingest (Phase 2)
|
|
||||||
- **Lazy Load:** Only load visible images
|
|
||||||
- **Progressive Loading:** Show low-res first, then high-res
|
|
||||||
- **CDN:** Consider for production (not needed for LAN-only)
|
|
||||||
|
|
||||||
#### 4. **Frontend Performance**
|
|
||||||
- **Code Splitting:** Split React bundles
|
|
||||||
- **Tree Shaking:** Remove unused code
|
|
||||||
- **Image Optimization:** WebP format for thumbnails
|
|
||||||
- **Bundle Analysis:** Track bundle size
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Data Model Analysis - UI Perspective
|
|
||||||
|
|
||||||
### ✅ Excellent Decisions
|
|
||||||
|
|
||||||
#### 1. **Captures with UUID Primary Key**
|
|
||||||
- **Benefit:** Safe for URLs, distributed systems
|
|
||||||
- **UI Usage:** `/gallery/{capture_id}` URLs
|
|
||||||
- **Rating:** 5/5
|
|
||||||
|
|
||||||
#### 2. **Observations 1:n to Captures**
|
|
||||||
- **Benefit:** One photo can have multiple species
|
|
||||||
- **UI Usage:** Multiple birds in one photo
|
|
||||||
- **Rating:** 5/5
|
|
||||||
|
|
||||||
#### 3. **Human vs Model Observations**
|
|
||||||
- **Benefit:** Same table, different source
|
|
||||||
- **UI Usage:** Human labels + future ML predictions
|
|
||||||
- **Rating:** 5/5
|
|
||||||
|
|
||||||
#### 4. **JSONB for Device Config**
|
|
||||||
- **Benefit:** Flexible, future-proof
|
|
||||||
- **UI Usage:** Device settings form
|
|
||||||
- **Rating:** 5/5
|
|
||||||
|
|
||||||
#### 5. **battery_valid Flag**
|
|
||||||
- **Important:** false = **not measured**, not empty
|
|
||||||
- **UI Requirement:** Display as "N/A", never as low battery alarm
|
|
||||||
- **Rating:** 5/5
|
|
||||||
|
|
||||||
### ⚠️ Potential Issues
|
|
||||||
|
|
||||||
#### 1. **No Index on sha256**
|
|
||||||
- **Issue:** Deduplication queries may be slow
|
|
||||||
- **Solution:** Add unique index on sha256
|
|
||||||
- **Priority:** MEDIUM
|
|
||||||
|
|
||||||
#### 2. **No Index on burst_id**
|
|
||||||
- **Issue:** Burst grouping queries may be slow
|
|
||||||
- **Check:** Already has index (ix_captures_burst)
|
|
||||||
- **Status:** ✅ Already indexed
|
|
||||||
|
|
||||||
#### 3. **Daily Counters in RTC Memory**
|
|
||||||
- **Important:** Counters reset on power loss
|
|
||||||
- **UI Display:** Show as "gap" between captured and delivered
|
|
||||||
- **Rating:** 4/5 - Good design, UI must understand
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. UI Implementation Recommendations
|
|
||||||
|
|
||||||
### 6.1 Frontend Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
webui/
|
|
||||||
├── src/
|
|
||||||
│ ├── components/
|
|
||||||
│ │ ├── Gallery/
|
|
||||||
│ │ │ ├── GalleryGrid.tsx
|
|
||||||
│ │ │ ├── ImageCard.tsx
|
|
||||||
│ │ │ └── Filters.tsx
|
|
||||||
│ │ ├── Observation/
|
|
||||||
│ │ │ ├── ObservationEditor.tsx
|
|
||||||
│ │ │ └── TaxonAutocomplete.tsx
|
|
||||||
│ │ ├── Settings/
|
|
||||||
│ │ │ └── DeviceSettings.tsx
|
|
||||||
│ │ └── Common/
|
|
||||||
│ │ ├── ThemeToggle.tsx
|
|
||||||
│ │ ├── LanguageToggle.tsx
|
|
||||||
│ │ └── Layout.tsx
|
|
||||||
│ ├── hooks/
|
|
||||||
│ │ ├── useGallery.ts
|
|
||||||
│ │ ├── useObservations.ts
|
|
||||||
│ │ └── useAuth.ts
|
|
||||||
│ ├── store/
|
|
||||||
│ │ ├── gallerySlice.ts
|
|
||||||
│ │ └── authSlice.ts
|
|
||||||
│ ├── utils/
|
|
||||||
│ │ └── api.ts (axios/fetch wrapper)
|
|
||||||
│ ├── styles/
|
|
||||||
│ │ ├── theme.css
|
|
||||||
│ │ └── global.css
|
|
||||||
│ ├── App.tsx
|
|
||||||
│ └── main.tsx
|
|
||||||
├── public/
|
|
||||||
│ └── index.html
|
|
||||||
├── vite.config.ts
|
|
||||||
├── package.json
|
|
||||||
└── tsconfig.json
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6.2 Backend Endpoints Needed for UI
|
|
||||||
|
|
||||||
#### Gallery
|
|
||||||
- `GET /api/v1/captures` - Paginated list with filters
|
|
||||||
- `GET /api/v1/captures/{id}` - Single capture with observations
|
|
||||||
- `GET /api/v1/captures/{id}/image` - Full image (auth-checked)
|
|
||||||
- `GET /api/v1/captures/{id}/thumb` - Thumbnail (auth-checked)
|
|
||||||
|
|
||||||
#### Observations
|
|
||||||
- `POST /api/v1/captures/{id}/observations` - Add observation
|
|
||||||
- `PUT /api/v1/observations/{id}` - Update observation
|
|
||||||
- `DELETE /api/v1/observations/{id}` - Delete observation
|
|
||||||
|
|
||||||
#### Taxonomy
|
|
||||||
- `GET /api/v1/taxa` - Search with pagination
|
|
||||||
- `GET /api/v1/taxa/autocomplete` - Autocomplete endpoint
|
|
||||||
|
|
||||||
#### Tags
|
|
||||||
- `GET /api/v1/tags` - List all tags
|
|
||||||
- `POST /api/v1/tags` - Create tag (admin only)
|
|
||||||
|
|
||||||
#### Devices
|
|
||||||
- `GET /api/v1/devices` - List devices with status
|
|
||||||
- `GET /api/v1/devices/{id}` - Device details
|
|
||||||
- `PUT /api/v1/devices/{id}/settings` - Update settings
|
|
||||||
|
|
||||||
#### Users
|
|
||||||
- `POST /api/v1/auth/login` - Login
|
|
||||||
- `POST /api/v1/auth/logout` - Logout
|
|
||||||
- `GET /api/v1/users/me` - Current user
|
|
||||||
|
|
||||||
### 6.3 UI-Specific Security
|
|
||||||
|
|
||||||
#### Authentication Flow
|
|
||||||
```
|
|
||||||
1. POST /api/v1/auth/login (username, password)
|
|
||||||
→ Returns session cookie
|
|
||||||
|
|
||||||
2. All authenticated requests include session cookie
|
|
||||||
|
|
||||||
3. CSRF token in forms (for POST/PUT/DELETE)
|
|
||||||
|
|
||||||
4. Role-based access control (RBAC):
|
|
||||||
- viewer: Read-only
|
|
||||||
- editor: Read + Write (observations, tags)
|
|
||||||
- admin: Full access (devices, users, settings)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Image Security
|
|
||||||
- **Never** serve images directly from filesystem
|
|
||||||
- **Always** check authorization in app first
|
|
||||||
- **Then** have Caddy serve the bytes
|
|
||||||
- **URLs** should be unguessable (UUID-based)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Deployment Analysis - UI Impact
|
|
||||||
|
|
||||||
### ✅ Current Deployment (UI-Ready)
|
|
||||||
- **Reverse Proxy:** Caddy with TLS (DNS-01)
|
|
||||||
- **Static Files:** Caddy can serve built React app
|
|
||||||
- **API:** FastAPI behind Caddy
|
|
||||||
- **Images:** Auth-checked handoff to Caddy
|
|
||||||
|
|
||||||
### 📋 UI Deployment Tasks
|
|
||||||
|
|
||||||
#### Caddy Configuration
|
|
||||||
```caddyfile
|
|
||||||
# Current (API only)
|
|
||||||
:8080 {
|
|
||||||
reverse_proxy /api/* 127.0.0.1:8090
|
|
||||||
}
|
|
||||||
|
|
||||||
# Needed for UI
|
|
||||||
:80 {
|
|
||||||
# Serve static UI files
|
|
||||||
root * /srv/poorbird/webui
|
|
||||||
try_files {path} /index.html
|
|
||||||
|
|
||||||
# API reverse proxy
|
|
||||||
handle_path /api/* {
|
|
||||||
reverse_proxy 127.0.0.1:8090
|
|
||||||
}
|
|
||||||
|
|
||||||
# Image serving (auth-checked)
|
|
||||||
handle_path /images/* {
|
|
||||||
reverse_proxy 127.0.0.1:8090
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### systemd Unit for UI
|
|
||||||
- **Not needed:** Static files served by Caddy
|
|
||||||
- **Build process:** Should be part of deployment
|
|
||||||
- **Location:** `/srv/poorbird/webui`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Test Analysis - UI Considerations
|
|
||||||
|
|
||||||
### Current Tests
|
|
||||||
- **12/12 tests passing** (server only)
|
|
||||||
- All tests require PostgreSQL 17
|
|
||||||
- Integration tests for queue, schema, config, health
|
|
||||||
|
|
||||||
### Missing UI Tests
|
|
||||||
|
|
||||||
#### Unit Tests (Frontend)
|
|
||||||
- Component rendering tests
|
|
||||||
- Hook tests
|
|
||||||
- Utility function tests
|
|
||||||
- **Tool:** Jest + React Testing Library
|
|
||||||
|
|
||||||
#### Integration Tests (API)
|
|
||||||
- UI endpoint tests
|
|
||||||
- Authentication tests
|
|
||||||
- Authorization tests
|
|
||||||
- **Tool:** pytest + httpx
|
|
||||||
|
|
||||||
#### E2E Tests
|
|
||||||
- User flows: login → gallery → edit → logout
|
|
||||||
- **Tool:** Playwright or Cypress
|
|
||||||
|
|
||||||
### Test Environment for UI
|
|
||||||
- **Frontend:** Node.js 18+
|
|
||||||
- **Testing:** Jest, React Testing Library, Playwright
|
|
||||||
- **CI/CD:** GitHub Actions or similar
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Recommended Implementation Order
|
|
||||||
|
|
||||||
### Phase 3: WebUI (Estimated: 3-4 weeks)
|
|
||||||
|
|
||||||
#### Week 1: Authentication & Foundation
|
|
||||||
1. [ ] Implement session management
|
|
||||||
2. [ ] Add CORS configuration
|
|
||||||
3. [ ] Add CSRF protection
|
|
||||||
4. [ ] Implement password hashing (Argon2id)
|
|
||||||
5. [ ] Create auth endpoints (login, logout, me)
|
|
||||||
6. [ ] Setup React + Vite project
|
|
||||||
7. [ ] Create basic layout and routing
|
|
||||||
|
|
||||||
#### Week 2: Gallery & Viewing
|
|
||||||
1. [ ] Implement gallery API endpoints
|
|
||||||
2. [ ] Create Gallery component
|
|
||||||
3. [ ] Add pagination
|
|
||||||
4. [ ] Implement ImageCard component
|
|
||||||
5. [ ] Add date/taxon/device filters
|
|
||||||
6. [ ] Setup image lazy loading
|
|
||||||
|
|
||||||
#### Week 3: Editing & Management
|
|
||||||
1. [ ] Implement observation CRUD endpoints
|
|
||||||
2. [ ] Create ObservationEditor
|
|
||||||
3. [ ] Add TaxonAutocomplete
|
|
||||||
4. [ ] Implement tag management
|
|
||||||
5. [ ] Add device list and status view
|
|
||||||
6. [ ] Create settings pages
|
|
||||||
|
|
||||||
#### Week 4: Polish & Testing
|
|
||||||
1. [ ] Implement theme switching
|
|
||||||
2. [ ] Add language support
|
|
||||||
3. [ ] Write frontend tests
|
|
||||||
4. [ ] Write E2E tests
|
|
||||||
5. [ ] Performance optimization
|
|
||||||
6. [ ] Security audit
|
|
||||||
|
|
||||||
### Dependencies
|
|
||||||
- **Phase 2 must be complete** (device endpoints)
|
|
||||||
- **Security issues must be fixed** (CRITICAL items)
|
|
||||||
- **Authentication must work** before UI can be used
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Architecture Rating
|
|
||||||
|
|
||||||
| Criterion | Rating | Notes |
|
|
||||||
|-----------|--------|-------|
|
|
||||||
| **Scalability** | 4/5 | Good for 10 cameras, may need optimization for 100+ |
|
|
||||||
| **Maintainability** | 5/5 | Very clean code, excellent docs |
|
|
||||||
| **Security** | 2/5 | **Critical issues block Phase 3** |
|
|
||||||
| **Performance** | 4/5 | Good for current scale |
|
|
||||||
| **UI Readiness** | 4/5 | Infrastructure ready, UI missing |
|
|
||||||
| **Code Quality** | 5/5 | Excellent |
|
|
||||||
| **Test Coverage** | 5/5 | Server: 12/12 passing |
|
|
||||||
| **Documentation** | 5/5 | Outstanding |
|
|
||||||
|
|
||||||
### SPEC Compliance
|
|
||||||
| Requirement | Status | Rating |
|
|
||||||
|-------------|--------|--------|
|
|
||||||
| Native Deployment | ✅ | 5/5 |
|
|
||||||
| Container-Ready | ✅ | 5/5 |
|
|
||||||
| PostgreSQL | ✅ | 5/5 |
|
|
||||||
| Job Queue without Redis | ✅ | 5/5 |
|
|
||||||
| FastAPI | ✅ | 5/5 |
|
|
||||||
| PostgreSQL 17 Support | ✅ | 5/5 |
|
|
||||||
| **UI Infrastructure** | ⚠️ | **4/5 (Ready, not implemented)** |
|
|
||||||
| Device Contract | ❌ | Not implemented (Phase 2) |
|
|
||||||
| Auth System | ❌ | Not implemented (Phase 2) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Conclusion & Recommendations
|
|
||||||
|
|
||||||
### What's Excellent
|
|
||||||
1. ✅ **Architecture** - UI-ready foundation
|
|
||||||
2. ✅ **Data Model** - Perfect for gallery and observations
|
|
||||||
3. ✅ **Storage** - Well-designed for images and thumbnails
|
|
||||||
4. ✅ **Deployment** - Caddy + systemd ready for UI
|
|
||||||
5. ✅ **Tests** - Complete server test coverage
|
|
||||||
|
|
||||||
### What's Missing (But Prepared For)
|
|
||||||
1. ❌ **UI Code** - React/TS/Vite project not started
|
|
||||||
2. ❌ **UI Endpoints** - Gallery, observation, auth endpoints missing
|
|
||||||
3. ❌ **Authentication** - Session management not implemented
|
|
||||||
4. ❌ **Authorization** - RBAC not enforced
|
|
||||||
|
|
||||||
### Critical Blockers for Phase 3
|
|
||||||
1. 🔴 **Enroll Secret in Plaintext** - Must fix
|
|
||||||
2. 🔴 **No Request Authentication** - Must fix
|
|
||||||
3. 🔴 **No Input Validation** - Must fix
|
|
||||||
4. 🔴 **No Rate Limiting** - Must fix
|
|
||||||
5. 🟡 **No CORS Configuration** - Must fix
|
|
||||||
6. 🟡 **No CSRF Protection** - Must fix
|
|
||||||
|
|
||||||
### Summary
|
|
||||||
|
|
||||||
The `feature/UI_Basic_implementation` branch is **misnamed** - it contains only server code (Phase 1), not UI code. However, the server is **perfectly prepared** for UI development (Phase 3).
|
|
||||||
|
|
||||||
**The server infrastructure is production-ready for UI development, but critical security issues must be fixed first.**
|
|
||||||
|
|
||||||
### Overall Rating
|
|
||||||
- **Code Quality:** 5/5 - Excellent
|
|
||||||
- **Architecture:** 5/5 - Excellent (UI-ready)
|
|
||||||
- **Security:** 2/5 - **Critical (blocking)**
|
|
||||||
- **Performance:** 4/5 - Good
|
|
||||||
- **UI Readiness:** 4/5 - Infrastructure ready
|
|
||||||
- **Test Coverage:** 5/5 - Excellent (server)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 12. Quick Start: UI Implementation
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
1. Fix CRITICAL security issues (enroll secret, authentication)
|
|
||||||
2. Complete Phase 2 (device endpoints)
|
|
||||||
3. Setup Node.js 18+ and npm
|
|
||||||
|
|
||||||
### Setup
|
|
||||||
```bash
|
|
||||||
# Create webui directory
|
|
||||||
mkdir -p webui
|
|
||||||
cd webui
|
|
||||||
|
|
||||||
# Initialize Vite + React + TypeScript
|
|
||||||
npm create vite@latest . -- --template react-ts
|
|
||||||
|
|
||||||
# Install dependencies
|
|
||||||
npm install @tanstack/react-query @tanstack/react-router axios
|
|
||||||
npm install --save-dev @types/react @types/node
|
|
||||||
|
|
||||||
# Install Vite plugins
|
|
||||||
npm install vite-plugin-svgr @svgr/core
|
|
||||||
|
|
||||||
# Setup project structure (see Section 6.1)
|
|
||||||
```
|
|
||||||
|
|
||||||
### First Endpoints to Implement
|
|
||||||
```python
|
|
||||||
# server/src/poorbird/api/routes/gallery.py
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
|
||||||
from sqlalchemy.orm import Session
|
|
||||||
from typing import Optional
|
|
||||||
from datetime import date
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/v1/captures", tags=["gallery"])
|
|
||||||
|
|
||||||
@router.get("/")
|
|
||||||
async def list_captures(
|
|
||||||
page: int = 1,
|
|
||||||
limit: int = 20,
|
|
||||||
device_id: Optional[int] = None,
|
|
||||||
taxon_id: Optional[int] = None,
|
|
||||||
date_from: Optional[date] = None,
|
|
||||||
date_to: Optional[date] = None,
|
|
||||||
kept: Optional[bool] = None,
|
|
||||||
reviewed: Optional[bool] = None,
|
|
||||||
):
|
|
||||||
"""List captures with pagination and filters."""
|
|
||||||
# Implementation here
|
|
||||||
pass
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
*Review created by Mistral Vibe on 2026-09-21. Based on commit 5d16ded.*
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
.pio/
|
|
||||||
.vscode/
|
|
||||||
secrets.ini
|
|
||||||
*.bin
|
|
||||||
-588
@@ -1,588 +0,0 @@
|
|||||||
# Device ↔ Endpoint contract
|
|
||||||
|
|
||||||
Written for: whoever implements the server side — framework-neutral, and
|
|
||||||
host-neutral. The firmware only needs *an HTTP endpoint at an IP and port*, so
|
|
||||||
a Raspberry Pi, a thin client, a NUC or a VM are all the same to it. This
|
|
||||||
document says "the endpoint" throughout for that reason.
|
|
||||||
|
|
||||||
This is what the firmware in `firmware/` actually sends and expects. It refines
|
|
||||||
`SPEC.md` §4.1 in two places, both noted below. Base URL is
|
|
||||||
`http://<endpoint>:<port>/api/v1`, plain HTTP on the LAN, TLS terminating on
|
|
||||||
the endpoint (SPEC C2/C3).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Authentication
|
|
||||||
|
|
||||||
Two steps. The long-lived token never exists in firmware source or in a build
|
|
||||||
flag.
|
|
||||||
|
|
||||||
### 1. Enrollment (once per device)
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /api/v1/enroll
|
|
||||||
X-Enroll-Secret: <shared provisioning secret>
|
|
||||||
Content-Type: application/json
|
|
||||||
|
|
||||||
{ "device_uid": "a0b7651f2c3d", "device_name": "poorbird-cam-1",
|
|
||||||
"hw_revision": "xiao-esp32s3-sense-ld2410", "fw_version": "0.1.0",
|
|
||||||
"mac": "A0:B7:65:1F:2C:3D" }
|
|
||||||
```
|
|
||||||
|
|
||||||
`device_uid` is the eFuse MAC in hex. It survives reflashing, which is what
|
|
||||||
makes it usable as an identity.
|
|
||||||
|
|
||||||
```
|
|
||||||
201 { "token": "<64 hex chars>", "device_id": 1,
|
|
||||||
"reenroll_secret": "<64 hex chars, per device>",
|
|
||||||
"server_time": 1758376267000, "config_version": 7 }
|
|
||||||
```
|
|
||||||
|
|
||||||
The endpoint stores only `token_hash` (SPEC §3 `devices.token_hash`; the token
|
|
||||||
is high-entropy, so a fast hash is defensible here).
|
|
||||||
|
|
||||||
### `reenroll_secret` — why the device keeps a credential
|
|
||||||
|
|
||||||
**The camera cannot be reached over USB once it is mounted.** That single fact
|
|
||||||
decides this design. If enrollment wiped the device's secret, rotating a token
|
|
||||||
in the admin UI would permanently lock the device out, and recovering it would
|
|
||||||
mean taking it down and reflashing. So:
|
|
||||||
|
|
||||||
1. The device enrolls with the **shared bootstrap secret** from `secrets.ini`.
|
|
||||||
2. The endpoint returns a **per-device** `reenroll_secret`, which the device
|
|
||||||
stores in NVS *in place of* the shared one.
|
|
||||||
3. On any `401`, the device clears its token, re-enrolls with that per-device
|
|
||||||
secret, and retries — mid-burst, without rebooting.
|
|
||||||
|
|
||||||
Rotating a token is therefore a normal operation with no physical access. The
|
|
||||||
credential left on the device is scoped to that device and cannot enroll any
|
|
||||||
other identity, which is the part that makes keeping it acceptable.
|
|
||||||
|
|
||||||
`reenroll_secret` is optional. Omit it and the device keeps using the shared
|
|
||||||
bootstrap secret instead — still self-healing, just a coarser credential.
|
|
||||||
|
|
||||||
There is one last-resort path: the shared bootstrap secret is compiled into
|
|
||||||
the firmware image, and the device falls back to it if the stored per-device
|
|
||||||
secret is ever rejected. The consequence worth knowing: **do not rotate the
|
|
||||||
shared bootstrap secret server-side without also shipping new firmware**, or
|
|
||||||
you remove the escape hatch.
|
|
||||||
|
|
||||||
Re-enrollment of a known `device_uid` must return the existing device row with
|
|
||||||
a fresh token, not create a duplicate. Expect to see this on every token
|
|
||||||
rotation and after any endpoint database restore.
|
|
||||||
|
|
||||||
### 2. Everything else
|
|
||||||
|
|
||||||
```
|
|
||||||
Authorization: Bearer <token>
|
|
||||||
```
|
|
||||||
|
|
||||||
Scoped to `/ingest`, `/heartbeat`, `/status`, `/config`, `/commands/*/ack`,
|
|
||||||
`/firmware/*`, `/stream/*`. **Never** the gallery (SPEC §3.1: devices are not
|
|
||||||
users).
|
|
||||||
|
|
||||||
Rotating a token in the admin UI needs no device-side action: the next request
|
|
||||||
gets a `401` and the device re-enrolls itself, as described above.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Common request headers
|
|
||||||
|
|
||||||
Present on every authenticated request:
|
|
||||||
|
|
||||||
| Header | Meaning |
|
|
||||||
|---|---|
|
|
||||||
| `X-Device-Uid` | eFuse MAC hex |
|
|
||||||
| `X-Fw-Version` | running firmware version |
|
|
||||||
| `X-Hw-Revision` | build-time hardware tag |
|
|
||||||
| `X-Config-Version` | config version the device is running |
|
|
||||||
| `X-Rssi` | current WiFi RSSI in dBm |
|
|
||||||
|
|
||||||
`X-Config-Version` is what lets the Pi push settings without the device
|
|
||||||
polling: if it differs from the server's, put the new version in the response
|
|
||||||
envelope and the device pulls `/config`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Response envelope
|
|
||||||
|
|
||||||
`/ingest` and `/heartbeat` return the **same** JSON shape. This is deliberate —
|
|
||||||
SPEC §4.1 — so a capture that was going to happen anyway also delivers the
|
|
||||||
command queue at no extra cost.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"capture_id": 4711,
|
|
||||||
"server_time": 1758376267000,
|
|
||||||
"config_version": 7,
|
|
||||||
"firmware": {
|
|
||||||
"version": "0.2.0",
|
|
||||||
"url": "/firmware/0.2.0.bin",
|
|
||||||
"sha256": "3f786850e387550fdab836ed7e6dc881de23001b…",
|
|
||||||
"size": 1148320
|
|
||||||
},
|
|
||||||
"commands": [
|
|
||||||
{ "id": 12, "type": "stream_start",
|
|
||||||
"payload": { "session_id": "s-88f1", "duration_s": 45, "mode": 0 },
|
|
||||||
"expires_at": 1758376400000 }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- `server_time` — epoch ms, UTC. **Authoritative** (SPEC C7). The device adopts
|
|
||||||
it whenever it is unsynced or more than 2 s out, so the Pi works as the clock
|
|
||||||
even if SNTP is unavailable.
|
|
||||||
- `firmware` — omit the key entirely when the device is on target. Present and
|
|
||||||
different ⇒ the device flashes it on its own; no command needed. Use an
|
|
||||||
explicit `ota_update` command only for staged rollouts.
|
|
||||||
- `commands` — omit or send `[]` when empty.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## `POST /api/v1/ingest`
|
|
||||||
|
|
||||||
**Deviation from SPEC §4.1.** The spec says `multipart/form-data` with image +
|
|
||||||
JSON meta. The firmware sends the **raw JPEG as the body** with metadata in
|
|
||||||
headers.
|
|
||||||
|
|
||||||
Why: multipart makes the device assemble a second buffer purely to add a
|
|
||||||
wrapper the server strips immediately. Raw body hands the framebuffer pointer
|
|
||||||
straight to the HTTP client — no copy, less heap, fewer failure modes. The
|
|
||||||
metadata is a dozen flat scalars, which is exactly what headers are good at.
|
|
||||||
It is still plainly REST:
|
|
||||||
|
|
||||||
```
|
|
||||||
curl -X POST http://pi:8080/api/v1/ingest \
|
|
||||||
-H 'Authorization: Bearer …' -H 'Content-Type: image/jpeg' \
|
|
||||||
-H 'X-Trigger: radar' -H 'X-Burst-Id: a0b765-3-91204' \
|
|
||||||
--data-binary @frame.jpg
|
|
||||||
```
|
|
||||||
|
|
||||||
| Header | Type | Notes |
|
|
||||||
|---|---|---|
|
|
||||||
| `Content-Type` | `image/jpeg` | body is the JPEG, nothing else |
|
|
||||||
| `X-Trigger` | enum | `radar` · `manual` · `timer` · `stream_grab` |
|
|
||||||
| `X-Burst-Id` | string | groups the frames of one event → `captures.burst_id` |
|
|
||||||
| `X-Burst-Index` | int | 0-based → `captures.burst_index` |
|
|
||||||
| `X-Burst-Count` | int | frames in this burst |
|
|
||||||
| `X-Pre-Trigger` | 0/1 | **1 = this frame predates the trigger** (see below) |
|
|
||||||
| `X-Captured-At` | int64 | epoch ms UTC, **0 when the device clock is unsynced** |
|
|
||||||
| `X-Frame-Seq` | int | monotonic per boot |
|
|
||||||
| `X-Radar-State` | 0–3 | none / moving / stationary / both |
|
|
||||||
| `X-Radar-Distance-Cm` | int | |
|
|
||||||
| `X-Radar-Energy` | 0–100 | |
|
|
||||||
|
|
||||||
Response: `201` + the envelope above.
|
|
||||||
|
|
||||||
### `X-Pre-Trigger` — worth a column in the database
|
|
||||||
|
|
||||||
With mains power the camera runs continuously into a PSRAM ring, so a burst
|
|
||||||
contains frames from **before** the radar fired. Those are usually the good
|
|
||||||
ones: the bird is still arriving rather than already leaving.
|
|
||||||
|
|
||||||
Add a `pre_trigger BOOL` column to `captures` and surface it in the gallery as
|
|
||||||
a sort key within a burst. `X-Captured-At` already orders them correctly, but
|
|
||||||
the flag tells you *why* a frame predates its own trigger, which is otherwise a
|
|
||||||
confusing thing to see in the data.
|
|
||||||
|
|
||||||
**`X-Captured-At: 0` means unsynced, not 1970.** Store `NULL`, not an epoch
|
|
||||||
date. `received_at` stays authoritative either way (SPEC C7).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Device conditions — `POST /heartbeat` and `POST /status`
|
|
||||||
|
|
||||||
**One body, two endpoints.** Both send exactly the same JSON; they differ only
|
|
||||||
in what comes back:
|
|
||||||
|
|
||||||
| | `POST /api/v1/heartbeat` | `POST /api/v1/status` |
|
|
||||||
|---|---|---|
|
|
||||||
| Response | `200` + the envelope (commands, config, firmware) | `204`, no body |
|
|
||||||
| Cadence | `heartbeat_interval_s` (default 300 s) | `status_interval_s` (default 900 s), plus on events |
|
|
||||||
| Also sent | — | after an upload burst, before sleep, before night sleep, on `report_status` |
|
|
||||||
|
|
||||||
The split exists for one reason: **the device posts status immediately before
|
|
||||||
deep sleep**, and pulling down a command queue at that moment would mark
|
|
||||||
commands delivered that the device is about to become unable to execute. So
|
|
||||||
`/status` deliberately returns nothing actionable. If you only want to
|
|
||||||
implement one endpoint, implement `/heartbeat` and return `204` from
|
|
||||||
`/status` — everything still works, you just get coarser telemetry.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"reason": "periodic",
|
|
||||||
"fw_version": "0.1.0", "hw_revision": "xiao-esp32s3-sense-ld2410",
|
|
||||||
"config_version": 8,
|
|
||||||
|
|
||||||
"power": {
|
|
||||||
"uptime_ms": 91204,
|
|
||||||
"awake_ms": 91204, // ticks since the last wake
|
|
||||||
"boot_count": 37,
|
|
||||||
"wake_cause": "radar", // power-on | radar | timer | other
|
|
||||||
"last_sleep_s": 300,
|
|
||||||
"total_sleep_s": 10800,
|
|
||||||
"sleep_enabled": false,
|
|
||||||
"sleep_allowed": false,
|
|
||||||
"inhibits": "stream,upload"
|
|
||||||
},
|
|
||||||
|
|
||||||
"battery": {
|
|
||||||
"valid": true, // false = no divider wired
|
|
||||||
"mv": 3912, "pct": 74, "raw_mv": 1956,
|
|
||||||
"chemistry": 1, "low": false
|
|
||||||
},
|
|
||||||
|
|
||||||
"counters": {
|
|
||||||
"captured_today": 412, "delivered_today": 407,
|
|
||||||
"failed_today": 5, "events_today": 41,
|
|
||||||
"day_index": 20716,
|
|
||||||
"captured_boot": 88, "delivered_boot": 88
|
|
||||||
},
|
|
||||||
|
|
||||||
"camera": { "frame_size": 8, "jpeg_quality": 12, "profile": "day", "ready": true },
|
|
||||||
"night": { "is_night": false, "nightlight_on": false,
|
|
||||||
"behaviour": 2, "capture_allowed": true },
|
|
||||||
"stream": { "enabled": false, "active": false, "frames_sent": 0, "seconds_left": 0 },
|
|
||||||
"radar": { "baud": 256000, "uart_ok": true, "out_pin": false, "state": 0,
|
|
||||||
"moving_cm": 0, "moving_energy": 0,
|
|
||||||
"stationary_cm": 0, "stationary_energy": 0 },
|
|
||||||
"system": { "rssi": -61, "ip": "192.168.1.88",
|
|
||||||
"free_heap": 184320, "free_psram": 6815744,
|
|
||||||
"ring_depth": 24, "ring_bytes": 1179648 },
|
|
||||||
|
|
||||||
"time_synced": true,
|
|
||||||
"device_time": "2026-09-20T14:31:07Z"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`reason` is one of `heartbeat` · `periodic` · `after_event` · `before_sleep` ·
|
|
||||||
`before_night_sleep` · `on_request`. Useful for spotting *why* a device went
|
|
||||||
quiet: the last row before a gap tells you whether it slept deliberately.
|
|
||||||
|
|
||||||
### Reading the fields that are easy to misread
|
|
||||||
|
|
||||||
**`battery.valid: false` means not measured, not empty.** No divider is wired
|
|
||||||
by default — the XIAO does not bring its battery rail out to a readable pin.
|
|
||||||
Render this as "—", never as 0 V, and do not raise a low-battery alarm on it.
|
|
||||||
`chemistry: 0` likewise means `pct` is meaningless; show the voltage only.
|
|
||||||
|
|
||||||
**The counters are the device's opinion, not the truth.** They live in RTC
|
|
||||||
memory: they survive deep sleep and reset on power loss, and they are
|
|
||||||
approximate by design. Your `captures` table is authoritative. What the
|
|
||||||
counters are genuinely good for is the *gap*: `captured_today` well above
|
|
||||||
`delivered_today` means frames are being taken and not arriving, which is a
|
|
||||||
WiFi or disk problem you would otherwise only notice as "quiet camera".
|
|
||||||
|
|
||||||
**`day_index` is days since epoch in local time**, and it is the rollover key.
|
|
||||||
It stays `0` until the clock syncs, so counters accumulated before the first
|
|
||||||
sync land in a phantom day and then roll over once. Do not chart that bucket.
|
|
||||||
|
|
||||||
**`power.awake_ms` is the "ticks since last sleep"** — it resets on every wake,
|
|
||||||
unlike `uptime_ms`, which also resets but only on reboot. In awake mode they
|
|
||||||
are identical; in sleep mode `awake_ms` is the useful one.
|
|
||||||
|
|
||||||
A heartbeat the endpoint **accepts** is also what confirms an OTA trial boot.
|
|
||||||
Returning `5xx` to a device on a trial image will roll it back — correct
|
|
||||||
behaviour, but worth knowing before you restart the Pi mid-rollout.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## `GET /api/v1/config`
|
|
||||||
|
|
||||||
Returns the full device config. Every key optional; the device merges and
|
|
||||||
clamps. See `AppConfig` in `include/app_config.h` for the authoritative list.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"config_version": 8,
|
|
||||||
|
|
||||||
"frame_size": "SVGA", "jpeg_quality": 12, "vflip": false, "hmirror": false,
|
|
||||||
"cam_day": { "...": "see below" },
|
|
||||||
"cam_night": { "...": "see below" },
|
|
||||||
|
|
||||||
"ring_frames": 24, "pre_roll": 4, "post_roll": 6,
|
|
||||||
"post_roll_gap_ms": 250, "cooldown_s": 5, "idle_period_ms": 400,
|
|
||||||
|
|
||||||
"radar_mode": 2, "accept_stationary": true,
|
|
||||||
"min_distance_cm": 20, "max_distance_cm": 300, "min_energy": 20,
|
|
||||||
"radar_baud": 0,
|
|
||||||
|
|
||||||
"stream_enabled": false, "stream_frame_size": "VGA", "stream_jpeg_quality": 15,
|
|
||||||
"stream_duration_s": 60, "stream_fps": 10, "stream_mode": 0,
|
|
||||||
"stream_blocks_sleep": true,
|
|
||||||
|
|
||||||
"night_start_min": 1260, "night_end_min": 360,
|
|
||||||
"night_behaviour": 2, "nightlight_mode": 0, "nightlight_brightness": 128,
|
|
||||||
|
|
||||||
"battery_chemistry": 0, "battery_divider_x100": 200,
|
|
||||||
"battery_offset_mv": 0, "battery_min_pct_ota": 50, "battery_warn_pct": 20,
|
|
||||||
|
|
||||||
"heartbeat_interval_s": 300, "status_interval_s": 900, "ota_enabled": true,
|
|
||||||
|
|
||||||
"deep_sleep_enabled": false, "deep_sleep_s": 300,
|
|
||||||
"sleep_wake_on_radar": true, "sleep_idle_timeout_s": 20,
|
|
||||||
"sleep_max_awake_s": 300,
|
|
||||||
|
|
||||||
"tz": "CET-1CEST,M3.5.0,M10.5.0/3"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Bump `config_version` on every change — that is the only thing the device
|
|
||||||
compares. Every key is optional and the device clamps out-of-range values, so
|
|
||||||
partial pushes are fine.
|
|
||||||
|
|
||||||
### Enums
|
|
||||||
|
|
||||||
| Key | Values |
|
|
||||||
|---|---|
|
|
||||||
| `frame_size`, `stream_frame_size` | **a name**: `QVGA` `CIF` `VGA` `SVGA` `XGA` `HD` `SXGA` `UXGA` `QXGA` `QSXGA` `5MP` — see below |
|
|
||||||
| `stream_mode` | 0=watch 1=record 2=both |
|
|
||||||
| `radar_mode` | 0=OUT pin only 1=UART only 2=both |
|
|
||||||
| `night_behaviour` | 0=capture 1=idle 2=sleep |
|
|
||||||
| `nightlight_mode` | 0=off 1=on during burst 2=always on at night |
|
|
||||||
| `battery_chemistry` | 0=none 1=Li-ion/LiPo 2=LiFePO4 |
|
|
||||||
| `radar_baud` | 0=autodetect (recommended), or an explicit rate to pin |
|
|
||||||
|
|
||||||
`radar.baud` in the status payload reports what the device actually settled
|
|
||||||
on, and `0` there means no valid frame was decoded at any rate — wiring or a
|
|
||||||
dead module, worth an alert.
|
|
||||||
|
|
||||||
### Send frame sizes by name, not by number
|
|
||||||
|
|
||||||
`framesize_t` is an enum in the camera driver, and **entries have been
|
|
||||||
inserted into the middle of it between driver releases** — `FRAMESIZE_128X128`
|
|
||||||
and `FRAMESIZE_320X320` both landed after the original ordering. A stored
|
|
||||||
numeric index therefore means a *different resolution* after a firmware
|
|
||||||
update built against a newer driver.
|
|
||||||
|
|
||||||
This bit this very firmware: an early draft defaulted to `frame_size: 8`
|
|
||||||
believing it was SVGA 800×600. In the driver actually installed, index 8 is
|
|
||||||
CIF 400×296.
|
|
||||||
|
|
||||||
So the device accepts a name and resolves it against the enum symbols:
|
|
||||||
|
|
||||||
| Name | Pixels | Note |
|
|
||||||
|---|---|---|
|
|
||||||
| `QVGA` | 320×240 | |
|
|
||||||
| `CIF` | 400×296 | |
|
|
||||||
| `VGA` | 640×480 | stream default |
|
|
||||||
| `SVGA` | 800×600 | stills default |
|
|
||||||
| `XGA` | 1024×768 | |
|
|
||||||
| `HD` | 1280×720 | |
|
|
||||||
| `SXGA` | 1280×1024 | |
|
|
||||||
| `UXGA` | 1600×1200 | OV2640 maximum |
|
|
||||||
| `QXGA` | 2048×1536 | OV3660 / OV5640 only |
|
|
||||||
| `QSXGA` / `5MP` | 2560×1920 / 2592×1944 | OV5640 only |
|
|
||||||
|
|
||||||
A raw index is still accepted for compatibility, but store names.
|
|
||||||
|
|
||||||
The status payload reports both, plus the dimensions and the sensor's PID, so
|
|
||||||
the UI never has to guess:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"camera": { "frame_size": "SVGA", "frame_size_id": 11,
|
|
||||||
"width": 800, "height": 600,
|
|
||||||
"sensor_pid": 9646, "profile": "day", "ready": true }
|
|
||||||
```
|
|
||||||
|
|
||||||
`sensor_pid` is `0x2640` OV2640, `0x3660` OV3660, `0x5640` OV5640. Worth
|
|
||||||
surfacing: **newer XIAO Sense units have shipped with OV3660 rather than
|
|
||||||
OV2640**, so do not assume from the product listing. A frame size the fitted
|
|
||||||
sensor cannot reach is refused by the driver and logged, and the previous size
|
|
||||||
stays in effect.
|
|
||||||
|
|
||||||
### Camera tuning — `cam_day` and `cam_night`
|
|
||||||
|
|
||||||
Two complete OV2640 profiles. The device switches between them at the night
|
|
||||||
boundary on its own, so dusk costs no round trip.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"cam_day": {
|
|
||||||
"brightness": 0, "contrast": 1, "saturation": 0, "sharpness": 0,
|
|
||||||
"ae_level": 1, "special_effect": 0, "wb_mode": 0,
|
|
||||||
"gainceiling": 1, "agc_gain": 0, "aec_value": 300,
|
|
||||||
"whitebal": true, "awb_gain": true,
|
|
||||||
"exposure_ctrl": true, "aec2": true, "gain_ctrl": true,
|
|
||||||
"bpc": true, "wpc": true, "raw_gma": true, "lenc": true,
|
|
||||||
"dcw": true, "colorbar": false
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
| Key | Range | What it does here |
|
|
||||||
|---|---|---|
|
|
||||||
| `brightness`, `contrast`, `saturation`, `sharpness` | −2…2 | Cosmetic. `sharpness` support on the OV2640 is patchy. |
|
|
||||||
| `ae_level` | −2…2 | Exposure bias. **Raise it.** Birds are usually backlit against bright sky, which fools metering into underexposing the bird. |
|
|
||||||
| `gainceiling` | 0…6 (2×…128×) | **The setting that matters most.** High gain lets the sensor pick a shorter shutter (freezes the bird, noisier); low gain forces a longer one (clean, smeared). Day default 4×, night 32×. |
|
|
||||||
| `exposure_ctrl` | bool | `false` = manual, use `aec_value`. Set this if motion blur turns out to be your limiting factor — it is the direct lever. |
|
|
||||||
| `aec_value` | 0…1200 | Manual shutter. Only read when `exposure_ctrl` is false. |
|
|
||||||
| `gain_ctrl` / `agc_gain` | bool / 0…30 | Same pattern for gain. |
|
|
||||||
| `aec2` | bool | DSP-assisted metering. On. |
|
|
||||||
| `wb_mode` | 0…4 | auto / sunny / cloudy / office / home. Auto is fine outdoors. |
|
|
||||||
| `whitebal`, `awb_gain` | bool | Leave on. |
|
|
||||||
| `bpc`, `wpc`, `raw_gma`, `lenc` | bool | Dead-pixel, gamma and lens-shading correction. Leave on. |
|
|
||||||
| `dcw` | bool | Downsize/crop. On. |
|
|
||||||
| `special_effect` | 0…6 | none/negative/grayscale/red/green/blue/sepia. Grayscale (2) is arguably right for a night profile with IR illumination. |
|
|
||||||
| `colorbar` | bool | Test pattern. **Set true to prove the whole pipeline works before you have optics or light** — very useful during bring-up. |
|
|
||||||
|
|
||||||
### Night window and nightlight
|
|
||||||
|
|
||||||
`night_start_min` / `night_end_min` are **minutes from local midnight**
|
|
||||||
(1260 = 21:00, 360 = 06:00). The fixed defaults are a fallback: the Pi knows
|
|
||||||
the site's latitude, so the intended design is for it to compute real
|
|
||||||
sunset/sunrise and push them daily via `apply_config`. That is a much better
|
|
||||||
boundary than a fixed clock time, which is two hours wrong by December.
|
|
||||||
|
|
||||||
`night_behaviour` decides what happens inside that window:
|
|
||||||
|
|
||||||
| | Behaviour | Reachable at night? |
|
|
||||||
|---|---|---|
|
|
||||||
| 0 `capture` | Keep working, using `cam_night` and the illuminator | yes |
|
|
||||||
| 1 `idle` | Stay awake and reachable, capture nothing | yes |
|
|
||||||
| 2 `sleep` | **Deep sleep until morning, even when `deep_sleep_enabled` is false** | **no** |
|
|
||||||
|
|
||||||
Mode 2 is the one that answers "nightlight off could make the ESP sleep by
|
|
||||||
night". It is deliberately independent of the deep-sleep switch: a camera with
|
|
||||||
no illuminator has nothing to do at 03:00 whether it is mains-powered or not.
|
|
||||||
The cost is that the device is unreachable until `night_end_min`, so a config
|
|
||||||
change made at 23:00 lands at dawn. It wakes a minute early to let
|
|
||||||
auto-exposure settle.
|
|
||||||
|
|
||||||
Night sleep never wakes on the radar — the point is to ignore the night, not
|
|
||||||
to photograph every cat that walks past.
|
|
||||||
|
|
||||||
**Before you buy an illuminator, read the warning at the top of
|
|
||||||
`include/nightlight.h`.** Short version: the obvious choice is 850 nm IR,
|
|
||||||
because birds barely perceive it — but the OV2640 on the XIAO Sense has an IR
|
|
||||||
cut filter bonded over the sensor, so an IR LED produces a black frame.
|
|
||||||
Your options are to accept no night capture (mode 2, and most garden birds are
|
|
||||||
diurnal anyway), use dim continuous white light, or remove the IR filter.
|
|
||||||
|
|
||||||
### Streaming vs sleeping
|
|
||||||
|
|
||||||
`stream_blocks_sleep` (default `true`) is the coupling between the two. A
|
|
||||||
sleeping device cannot be told to start a stream (SPEC C1), so with this set,
|
|
||||||
merely **enabling** streaming keeps the device awake and reachable — not just
|
|
||||||
while a session runs. Clear it to let the device sleep anyway and accept that
|
|
||||||
`stream_start` waits for the next wake.
|
|
||||||
|
|
||||||
The status payload reports this: `power.sleep_allowed: false` with
|
|
||||||
`inhibits` naming the reason, so the WebUI can explain why a device that is
|
|
||||||
configured to sleep is not sleeping.
|
|
||||||
|
|
||||||
### Battery sensing
|
|
||||||
|
|
||||||
Nothing is wired by default and readings report `valid: false`. To enable it,
|
|
||||||
add an external divider from BAT+ to `PIN_BATTERY_ADC` (default D3/GPIO4) —
|
|
||||||
the wiring diagram is at the top of `include/battery.h` — then set
|
|
||||||
`battery_divider_x100` to your measured ratio and trim `battery_offset_mv`
|
|
||||||
against a multimeter.
|
|
||||||
|
|
||||||
`battery_min_pct_ota` is SPEC C6's flash gate. Note the deliberate choice in
|
|
||||||
`batteryAboveOtaThreshold()`: with no sensing hardware the gate **allows** the
|
|
||||||
flash rather than blocking it, because refusing every OTA on a mains-powered
|
|
||||||
device because an optional sensor is absent would be worse than the risk.
|
|
||||||
Wire the divider if you want the gate to bite.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
`POST /api/v1/commands/{id}/ack` → `{ "status": "done|failed|rejected", "detail": "…" }`
|
|
||||||
|
|
||||||
| `type` | payload | when it runs |
|
|
||||||
|---|---|---|
|
|
||||||
| `apply_config` | inline config object, or omit to make the device `GET /config` | immediately |
|
|
||||||
| `capture_now` | — | next capture-task tick |
|
|
||||||
| `report_status` | — | main loop; posts `/status` with `reason: on_request` |
|
|
||||||
| `wake_and_hold` | `{"seconds": 60}` (capped at 900) | immediately |
|
|
||||||
| `sleep_now` | `{"seconds": 0}` (0 = `deep_sleep_s`) | after the ack is sent |
|
|
||||||
| `stream_start` | `{"session_id","duration_s","mode","frame_size"}` | main loop |
|
|
||||||
| `stream_stop` | — | immediately |
|
|
||||||
| `ota_update` | `{"url","sha256","size"}`, or empty to use the envelope target | main loop |
|
|
||||||
| `reboot` | — | immediately, acked first |
|
|
||||||
|
|
||||||
`sleep_now` on a device with sleep switched off acks `rejected`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Firmware / OTA
|
|
||||||
|
|
||||||
`GET /api/v1/firmware/{version}.bin` — bearer auth, **must send
|
|
||||||
`Content-Length`** (the device refuses chunked: it wants to size-check against
|
|
||||||
the manifest before erasing a partition).
|
|
||||||
|
|
||||||
The device verifies SHA-256 over the whole image before activating the slot,
|
|
||||||
then boots it in `PENDING_VERIFY`. It calls `esp_ota_mark_app_valid` **only
|
|
||||||
after a heartbeat the endpoint accepted** — that proves WiFi, HTTP, auth and
|
|
||||||
JSON parsing all work on the new image. Anything weaker would confirm a
|
|
||||||
firmware that boots but cannot talk. If the trial image never checks in, the
|
|
||||||
next reset rolls back automatically.
|
|
||||||
|
|
||||||
So: a bad firmware costs a reboot cycle, not a ladder.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Streaming
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /api/v1/stream/{session_id}
|
|
||||||
Authorization: Bearer …
|
|
||||||
Content-Type: multipart/x-mixed-replace; boundary=poorbirdframe
|
|
||||||
X-Stream-Mode: watch | record | both
|
|
||||||
X-Duration-S: 60
|
|
||||||
Transfer-Encoding: chunked
|
|
||||||
```
|
|
||||||
|
|
||||||
The device pushes; the endpoint relays and/or records (SPEC C3 — the ESP32
|
|
||||||
never serves a stream and is never reachable from outside the LAN).
|
|
||||||
|
|
||||||
**Getting it outside is then entirely the endpoint's problem**, which is the
|
|
||||||
point of the design: the hard parts (TLS, certificate renewal, auth, rate
|
|
||||||
limiting, abuse handling) live on the machine with a package manager and logs,
|
|
||||||
not on the camera. In rough order of effort:
|
|
||||||
|
|
||||||
- **LAN only** — the endpoint re-serves the same `multipart/x-mixed-replace`
|
|
||||||
stream to a browser. An `<img src="/stream/live">` tag renders it with no
|
|
||||||
JavaScript. Maybe thirty lines of server code.
|
|
||||||
- **Public, low effort** — the same MJPEG endpoint behind a Cloudflare Tunnel:
|
|
||||||
public hostname and TLS, no port forwarding, nothing exposed inbound.
|
|
||||||
MJPEG is bandwidth-hungry but perfectly watchable for one or two viewers.
|
|
||||||
- **Public, done properly** — feed the frames into MediaMTX and serve WebRTC
|
|
||||||
or HLS. Lower latency, many viewers, and the transcode happens on the
|
|
||||||
endpoint where there is CPU to spare.
|
|
||||||
|
|
||||||
None of these change anything on the device. It pushes JPEGs to one URL in
|
|
||||||
every case.
|
|
||||||
|
|
||||||
Each part:
|
|
||||||
|
|
||||||
```
|
|
||||||
--poorbirdframe
|
|
||||||
Content-Type: image/jpeg
|
|
||||||
Content-Length: 18422
|
|
||||||
X-Timestamp: 1758376267123
|
|
||||||
|
|
||||||
<jpeg bytes>
|
|
||||||
```
|
|
||||||
|
|
||||||
Terminated by `--poorbirdframe--`. The device stops itself at `X-Duration-S`
|
|
||||||
(hard-capped at 600 s in firmware, SPEC C9). **Closing the connection
|
|
||||||
server-side is a supported way to stop a stream** — the device treats five
|
|
||||||
consecutive failed writes as a normal end, so a viewer navigating away does not
|
|
||||||
need a `stream_stop` command.
|
|
||||||
|
|
||||||
`mode` is advisory to the Pi; the device sends identical bytes in all three.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Behaviour the Pi should expect
|
|
||||||
|
|
||||||
- **Bounded retries, always.** Three WiFi attempts with exponential backoff,
|
|
||||||
then give up until the next cycle (SPEC §4.3). The device never hammers.
|
|
||||||
- **Heartbeat backoff.** After four consecutive failures the interval doubles
|
|
||||||
per failure up to one hour. A Pi that is down for maintenance does not
|
|
||||||
generate a wall of failed requests.
|
|
||||||
- **Burst uploads are sequential, not concurrent.** One connection at a time.
|
|
||||||
- **401 anywhere** clears the stored token and triggers re-enrollment.
|
|
||||||
- **Events are dropped while a stream is running.** You will see a gap in
|
|
||||||
captures for the duration of a session.
|
|
||||||
@@ -1,314 +0,0 @@
|
|||||||
# poorBird firmware — XIAO ESP32S3 Sense + HLK-LD2410
|
|
||||||
|
|
||||||
ESP-side skeleton.
|
|
||||||
|
|
||||||
**Verified:** builds clean from scratch against pioarduino 53.03.13
|
|
||||||
(Arduino-ESP32 3.1.x / IDF 5.3), no warnings in project sources.
|
|
||||||
1132 KB flash (34 % of a 3.2 MB OTA slot), 60 KB static RAM.
|
|
||||||
|
|
||||||
**Not verified:** none of it has run on hardware. The LD2410 frame offsets are
|
|
||||||
transcribed from the datasheet, the XIAO status-LED pin has moved between board
|
|
||||||
revisions, and no radio, camera or radar code path has executed. Treat the
|
|
||||||
first bring-up as a debugging session, not a smoke test.
|
|
||||||
|
|
||||||
## Layout
|
|
||||||
|
|
||||||
```
|
|
||||||
platformio.ini build config; the knobs live in [common]
|
|
||||||
secrets.ini.example copy to secrets.ini (gitignored) before flashing
|
|
||||||
partitions/ 8 MB, dual OTA slots + rollback (SPEC C6)
|
|
||||||
scripts/load_secrets.py turns secrets.ini into -D flags
|
|
||||||
|
|
||||||
include/board_pins.h ALL wiring in one place, every free pin overridable
|
|
||||||
include/app_config.h the full runtime config struct
|
|
||||||
|
|
||||||
src/app_config.cpp NVS load/save, JSON merge from the endpoint, clamps
|
|
||||||
src/power_mgr.cpp the deep-sleep on/off switch and its inhibit locks
|
|
||||||
src/camera_mgr.cpp OV2640 lifecycle + day/night tuning profiles
|
|
||||||
src/frame_ring.cpp PSRAM pre-trigger ring ← the interesting one
|
|
||||||
src/ld2410.cpp radar UART protocol + presence pin
|
|
||||||
src/net_mgr.cpp WiFi with bounded retries, clock from the endpoint
|
|
||||||
src/api_client.cpp REST client: enroll, ingest, heartbeat, status, config, stream
|
|
||||||
src/battery.cpp supply voltage, percentage curves, the OTA gate
|
|
||||||
src/device_stats.cpp daily counters in RTC memory, local-midnight rollover
|
|
||||||
src/nightlight.cpp night window, illuminator, what to do after dark
|
|
||||||
src/ota_mgr.cpp SHA-256 verify, trial boot, automatic rollback
|
|
||||||
src/stream_session.cpp time-boxed MJPEG push
|
|
||||||
src/commands.cpp the WebUI → device command queue
|
|
||||||
src/main.cpp both operating modes
|
|
||||||
```
|
|
||||||
|
|
||||||
`API.md` is the contract for the Pi side.
|
|
||||||
|
|
||||||
## Wiring
|
|
||||||
|
|
||||||
| LD2410 | XIAO | GPIO | Note |
|
|
||||||
|---|---|---|---|
|
|
||||||
| VCC | 5V | — | plain LD2410, no Bluetooth |
|
|
||||||
| GND | GND | — | |
|
|
||||||
| TX | D1 | 2 | ESP receives — **measure this, see below** |
|
|
||||||
| RX | D0 | 1 | ESP transmits; 3.3 V clears the module's input threshold |
|
|
||||||
| OUT | D2 | 3 | active high; RTC-capable, so it doubles as the deep-sleep wake pin — **measure this too** |
|
|
||||||
|
|
||||||
**Measure OUT and TX with a multimeter before connecting them.** The LD2410's
|
|
||||||
logic is supposed to be 3.3 V even on a 5 V supply, but this varies between
|
|
||||||
batches and clones, and the ESP32-S3 is not 5 V tolerant. Wave a hand at the
|
|
||||||
module so OUT asserts, then measure. If either reads ~5 V, drop it with a
|
|
||||||
divider: 10k from the module into the GPIO, 20k from the GPIO to ground. Two
|
|
||||||
minutes now beats discovering a dead pin on a camera you cannot reach.
|
|
||||||
|
|
||||||
**Baud rate needs no decision.** `radarBegin()` probes 256000, 115200, 57600,
|
|
||||||
38400 and 9600 and keeps whichever produces valid frames, so a factory-default
|
|
||||||
module and a reconfigured one both just work — and a factory reset (which
|
|
||||||
returns the module to 256000) does not silently take the trigger offline. Pin
|
|
||||||
it with the `radar_baud` setting if you would rather it not probe.
|
|
||||||
|
|
||||||
Optional, nothing wired by default:
|
|
||||||
|
|
||||||
| Function | Default pin | Note |
|
|
||||||
|---|---|---|
|
|
||||||
| Battery sense | `D3` / GPIO4 | needs an external divider — see the diagram in `include/battery.h` |
|
|
||||||
| Divider enable | — (`-1`) | MOSFET on the divider's low side, so it only draws during a read |
|
|
||||||
| Nightlight | — (`-1`) | PWM; drive a MOSFET, never the LED directly |
|
|
||||||
| Radar power gate | — (`-1`) | only useful for timer-only deep sleep |
|
|
||||||
|
|
||||||
Still free: `D4`/GPIO5 + `D5`/GPIO6 (I²C for a future BME280 or DS3231),
|
|
||||||
`D6`/GPIO43 + `D7`/GPIO44 (UART0 — deliberately left for hardware debug).
|
|
||||||
`D8`–`D10` are the Sense board's microSD; leave them if you want local
|
|
||||||
buffering later.
|
|
||||||
|
|
||||||
Change any of it with a `-D` flag, no source edit:
|
|
||||||
|
|
||||||
```ini
|
|
||||||
build_flags = ${common.build_flags} -DPIN_RADAR_OUT=4 -DRADAR_BAUD=115200
|
|
||||||
```
|
|
||||||
|
|
||||||
## First flash
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp secrets.ini.example secrets.ini # then edit it
|
|
||||||
pio run -e xiao_s3_sense -t upload
|
|
||||||
pio device monitor
|
|
||||||
```
|
|
||||||
|
|
||||||
The first build downloads ~1 GB of toolchain and takes about 12 minutes;
|
|
||||||
afterwards a clean rebuild is under a minute.
|
|
||||||
|
|
||||||
`platformio.ini` pins pioarduino `53.03.13` because PlatformIO Core 6.1.x
|
|
||||||
cannot load the current `stable` release (it needs Core >= 6.2.0). If you run
|
|
||||||
`pio upgrade` to 6.2.0, you can switch the `platform =` line to the `stable`
|
|
||||||
alias and get Arduino 3.3 / IDF 5.5.
|
|
||||||
|
|
||||||
On the Pi, generate the enrollment secret with `openssl rand -hex 32` and put
|
|
||||||
the same value in both places. On first boot the device trades it for a
|
|
||||||
per-device token, stores that in NVS, and wipes the secret.
|
|
||||||
|
|
||||||
Expected first-boot log:
|
|
||||||
|
|
||||||
```
|
|
||||||
poorBird 0.1.0 (xiao-esp32s3-sense-ld2410)
|
|
||||||
power: boot #1, wake cause power-on, 0s slept so far
|
|
||||||
--- poorBird config ---
|
|
||||||
radar: UART1 @256000 baud (detected) rx=2 tx=1 out=3
|
|
||||||
radar self-test: 1284 bytes, 7 decoded frames, OUT=0
|
|
||||||
wifi: 192.168.1.88 rssi -58 dBm
|
|
||||||
enrolled via stored secret: token + per-device re-enrollment secret stored
|
|
||||||
time: synced, 2026-09-20T14:31:07Z
|
|
||||||
camera ready: sensor PID 0x2640, SVGA (800x600) quality=12 psram_free=6784KB
|
|
||||||
ring: 24 slots x 48KB = 1152KB PSRAM (free 6784KB)
|
|
||||||
awake mode: pre-trigger ring active (24 frames, ~9.6 s of history)
|
|
||||||
```
|
|
||||||
|
|
||||||
`radar: no UART frames at any baud` ⇒ TX and RX are not crossed, the module
|
|
||||||
is not powered, or it is dead. The baud rate is no longer a candidate
|
|
||||||
explanation, since all the plausible rates were tried. The OUT pin path still
|
|
||||||
works in the meantime: set `radar_mode: 0` to trigger on it alone.
|
|
||||||
|
|
||||||
## The two power modes
|
|
||||||
|
|
||||||
One flag, `deep_sleep_enabled`, switchable from the WebUI at runtime.
|
|
||||||
|
|
||||||
| | **awake** (default) | **sleep** |
|
|
||||||
|---|---|---|
|
|
||||||
| Camera | always initialised | off between events |
|
|
||||||
| Pre-trigger frames | **yes**, ~10 s of history | no |
|
|
||||||
| Trigger→first frame | effectively negative | 1–3 s (SPEC C4) |
|
|
||||||
| Command latency | one loop tick | up to `deep_sleep_s` |
|
|
||||||
| Streaming | on demand | only from the next wake |
|
|
||||||
| ESP current | ~80–120 mA | tens of µA asleep |
|
|
||||||
|
|
||||||
Switching it on does not slam the door: the device finishes the current wake
|
|
||||||
(so the ack reaches the Pi) and only then sleeps, giving you
|
|
||||||
`sleep_idle_timeout_s` to change your mind. Switching it off takes effect at
|
|
||||||
the next wake — unavoidable, that is SPEC C1.
|
|
||||||
|
|
||||||
Sleep is blocked outright by refcounted inhibits: an upload in flight, a live
|
|
||||||
stream, an OTA flash, a `wake_and_hold`. `sleep_max_awake_s` is a deadlock
|
|
||||||
escape that overrides all of them **except OTA** — sleeping mid-flash bricks
|
|
||||||
the device.
|
|
||||||
|
|
||||||
### The honest caveat
|
|
||||||
|
|
||||||
The LD2410 draws roughly 80 mA continuously and must stay powered to act as a
|
|
||||||
wake source. So with `sleep_wake_on_radar = true`, the ESP sleeping at 20 µA
|
|
||||||
saves you almost nothing — the radar dominates. Deep sleep is a real power win
|
|
||||||
only if you either:
|
|
||||||
|
|
||||||
- set `sleep_wake_on_radar = false`, wake on the timer alone, and power-gate
|
|
||||||
the radar through a MOSFET on `PIN_RADAR_EN`; or
|
|
||||||
- fit an AM312 PIR on `PIN_AUX_ADC` as the wake source and use the radar only
|
|
||||||
to confirm once awake.
|
|
||||||
|
|
||||||
That is a wiring decision. The switch works either way.
|
|
||||||
|
|
||||||
## Why the ring buffer is the point
|
|
||||||
|
|
||||||
SPEC C4 says the first usable frame lands 1–3 s after the bird arrives, by
|
|
||||||
which time a small bird is gone. That is only true if capture *starts* at the
|
|
||||||
trigger.
|
|
||||||
|
|
||||||
Running on mains, the camera captures continuously into a PSRAM ring. On a
|
|
||||||
trigger the device ships `pre_roll` frames from **before** it plus `post_roll`
|
|
||||||
frames from after. Effective latency goes negative and C4 stops being a
|
|
||||||
problem. Cost: `ring_frames × ~48 KB` of the 8 MB PSRAM — about 1.1 MB at the
|
|
||||||
defaults, for roughly 10 s of history.
|
|
||||||
|
|
||||||
This is the single largest quality difference between the battery design in
|
|
||||||
`SPEC.md` and this one, and it is why the mains decision is worth more than it
|
|
||||||
first looks.
|
|
||||||
|
|
||||||
## Cameras
|
|
||||||
|
|
||||||
The XIAO ESP32S3 **Sense** ships with an OV2640 on its expansion board, and
|
|
||||||
that is what this firmware drives. The ESP32-S3 handles it better than the
|
|
||||||
original ESP32-CAM does, because the S3 has a dedicated LCD_CAM peripheral
|
|
||||||
rather than repurposing I²S.
|
|
||||||
|
|
||||||
Three things worth knowing before you buy or swap anything:
|
|
||||||
|
|
||||||
**The bare XIAO ESP32S3 cannot take a camera.** The DVP pins (GPIO 10–18, 38,
|
|
||||||
39, 40, 47, 48) are not on the 14 castellated pads — they only come out
|
|
||||||
through the board-to-board connector that the Sense expansion board mates
|
|
||||||
with. "XIAO ESP32S3 + a camera module" is not a working combination; you need
|
|
||||||
the Sense.
|
|
||||||
|
|
||||||
**You may receive an OV3660 rather than an OV2640.** Seeed's wiki still says
|
|
||||||
OV2640, but newer units have reportedly shipped with OV3660. The driver
|
|
||||||
detects the sensor over SCCB at init, so the firmware does not care — it logs
|
|
||||||
the PID (`0x2640` / `0x3660` / `0x5640`) and reports it in the status payload.
|
|
||||||
An OV3660 gives you QXGA 2048×1536 instead of the OV2640's UXGA ceiling.
|
|
||||||
|
|
||||||
**The OV5640 is an official drop-in upgrade** (Seeed sells it for this board,
|
|
||||||
with a heat sink). 2592×1944 versus the OV2640's 1600×1200, better low light,
|
|
||||||
and autofocus. Whether it is worth it here:
|
|
||||||
|
|
||||||
- *For* — pixels on target is the real limit when the bird is small in frame.
|
|
||||||
- *Against* — bigger JPEGs mean fewer ring slots and longer uploads, it is
|
|
||||||
slower at full resolution (so a lower ring frame rate and less pre-trigger
|
|
||||||
history), and it runs hot enough to ship with a heat sink. Autofocus is
|
|
||||||
arguably a downside on a fixed-distance feeder, where fixed focus is more
|
|
||||||
predictable and never hunts at the wrong moment.
|
|
||||||
- If you switch, **drop `ring_frames`**. Twenty-four slots at ~400 KB is
|
|
||||||
9.6 MB, more than the 8 MB of PSRAM; the ring degrades gracefully and logs,
|
|
||||||
but you want about 12.
|
|
||||||
|
|
||||||
The frame size is set by name (`"SVGA"`, `"UXGA"`), never by number — see
|
|
||||||
`API.md` for why that matters.
|
|
||||||
|
|
||||||
## Night, and why the default is to sleep through it
|
|
||||||
|
|
||||||
`night_behaviour` decides what happens between `night_start_min` and
|
|
||||||
`night_end_min` (minutes from local midnight; the Pi should push real
|
|
||||||
sunset/sunrise, the 21:00–06:00 defaults are a fallback):
|
|
||||||
|
|
||||||
- **0 `capture`** — keep working, using the `cam_night` tuning profile and the
|
|
||||||
illuminator if one is fitted.
|
|
||||||
- **1 `idle`** — stay awake and reachable, capture nothing.
|
|
||||||
- **2 `sleep`** (default) — deep sleep until morning, **even when
|
|
||||||
`deep_sleep_enabled` is false**. A camera with no illuminator has nothing to
|
|
||||||
do at 03:00 whether it is mains-powered or not. The cost: unreachable until
|
|
||||||
dawn, so a config change made at 23:00 lands in the morning.
|
|
||||||
|
|
||||||
Night sleep never wakes on the radar. The point is to ignore the night, not to
|
|
||||||
photograph every cat that walks past.
|
|
||||||
|
|
||||||
### Read this before buying an illuminator
|
|
||||||
|
|
||||||
The obvious choice is 850 nm or 940 nm IR, because birds barely perceive it and
|
|
||||||
white light at a feeder at night is disruptive. But **the OV2640 module on the
|
|
||||||
XIAO Sense has an IR cut filter bonded over the sensor**, which blocks exactly
|
|
||||||
those wavelengths. An IR LED on an unmodified Sense gives you a black frame.
|
|
||||||
|
|
||||||
In the order I would try them:
|
|
||||||
|
|
||||||
1. Accept no night capture (`night_behaviour: 2`). Most garden birds are
|
|
||||||
diurnal; you lose very little and the whole problem goes away.
|
|
||||||
2. Dim, warm, continuous white light (`nightlight_mode: 2`). Continuous beats a
|
|
||||||
flash per burst — animals habituate to steady light and startle at sudden
|
|
||||||
light — and auto-exposure is already settled when a bird arrives. Still
|
|
||||||
disturbs wildlife.
|
|
||||||
3. Remove the IR filter and use 850 nm. Best images, irreversible, and it
|
|
||||||
wrecks daytime colour unless you fit a switchable filter.
|
|
||||||
|
|
||||||
The firmware supports all three; option 3 needs no code change.
|
|
||||||
|
|
||||||
## Battery sensing
|
|
||||||
|
|
||||||
Off by default: the XIAO does not bring its battery rail out to a pin you can
|
|
||||||
simply read, so this needs an external divider from BAT+ to `PIN_BATTERY_ADC`.
|
|
||||||
The wiring is documented at the top of `include/battery.h`. Until it is wired,
|
|
||||||
readings report `valid: false` — which the endpoint must render as "not
|
|
||||||
measured", never as 0 V.
|
|
||||||
|
|
||||||
Once wired, set `battery_divider_x100` from your *measured* resistor values
|
|
||||||
(not their printed ones) and trim `battery_offset_mv` against a multimeter.
|
|
||||||
Percentage comes from a piecewise curve per chemistry. For LiFePO4 be warned
|
|
||||||
that the curve is nearly flat between 20 % and 90 % — the percentage there is
|
|
||||||
close to meaningless, which is a property of the chemistry, not of the code.
|
|
||||||
|
|
||||||
This also arms SPEC C6's OTA battery gate. One deliberate choice worth
|
|
||||||
knowing: with **no** sensing hardware the gate allows the flash rather than
|
|
||||||
blocking it, on the grounds that refusing every OTA on a mains-powered device
|
|
||||||
because an optional sensor is absent is worse than the risk it guards against.
|
|
||||||
|
|
||||||
## Tuning the radar for birds
|
|
||||||
|
|
||||||
The LD2410 is designed to detect *humans*. A blue tit has a far smaller radar
|
|
||||||
cross-section, and swaying branches and heavy rain both register. Expect to
|
|
||||||
spend an evening on this. Everything below is a config push, not a reflash:
|
|
||||||
|
|
||||||
- `max_distance_cm` — window it tightly to the feeder. The single most
|
|
||||||
effective false-positive filter.
|
|
||||||
- `min_energy` — raise until branches stop triggering, lower until birds start.
|
|
||||||
- `accept_stationary` — a bird sitting on a perch is a stationary target. On
|
|
||||||
for a feeder, off if you only care about arrivals.
|
|
||||||
- `radar_mode` — `0` ignores the UART entirely and trusts the OUT pin. Useful
|
|
||||||
to isolate whether a problem is the protocol decode or the sensor itself.
|
|
||||||
|
|
||||||
If it cannot be made to work, `PIN_AUX_ADC` is free for an AM312 and the
|
|
||||||
trigger logic is one function (`radarIsTrigger`).
|
|
||||||
|
|
||||||
## What is deliberately not here
|
|
||||||
|
|
||||||
- **Local SD buffering.** Uploads that fail are lost rather than queued to the
|
|
||||||
microSD. Worth adding if the WiFi link turns out to be marginal; the pins are
|
|
||||||
free.
|
|
||||||
- **On-device frame differencing** (SPEC Option C). The ring buffer makes this
|
|
||||||
much easier to add later — you already have consecutive frames in PSRAM.
|
|
||||||
- **TLS.** Deliberate, SPEC C2.
|
|
||||||
|
|
||||||
## Open items in the code
|
|
||||||
|
|
||||||
- `ld2410.cpp` frame offsets are from the datasheet, not verified.
|
|
||||||
- Battery percentage curves are generic open-circuit approximations at room
|
|
||||||
temperature. Good enough for a low banner and the OTA gate, not for a
|
|
||||||
runtime estimate.
|
|
||||||
- `nightlight.cpp` allocates an LEDC channel after the camera has taken
|
|
||||||
channel 0 for XCLK. That should route around it, but it is untested.
|
|
||||||
- Daily counters live in RTC memory and reset on power loss, by design. The
|
|
||||||
endpoint's own count is authoritative.
|
|
||||||
- `radarSetGateSensitivity` sends the command but only checks that *something*
|
|
||||||
came back, not that the ACK matches.
|
|
||||||
- `PIN_STATUS_LED` (GPIO21) has moved between XIAO board revisions — verify.
|
|
||||||
- The LD2410's logic level on a 5 V supply is unverified on this hardware.
|
|
||||||
Measure before connecting; see Wiring.
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
// api_client.h — everything the device says to the Pi.
|
|
||||||
//
|
|
||||||
// TRANSPORT DECISION (answers "standard REST API, I guess?")
|
|
||||||
// Yes, REST over plain HTTP with a bearer token (SPEC C2 — TLS stays on the
|
|
||||||
// Pi). One deviation from SPEC §4.1, and it is worth making:
|
|
||||||
//
|
|
||||||
// SPEC says: POST /ingest multipart/form-data: image + JSON meta
|
|
||||||
// we do: POST /ingest Content-Type: image/jpeg, raw body, meta in headers
|
|
||||||
//
|
|
||||||
// Why: multipart means the device assembles a body with boundaries, so the
|
|
||||||
// JPEG gets copied into a second buffer purely to add a wrapper the server
|
|
||||||
// immediately strips. Raw body + headers hands esp_http_client the framebuffer
|
|
||||||
// pointer directly — no copy, no assembly, less heap, and one fewer thing to
|
|
||||||
// get wrong at 3 a.m. It is still an ordinary REST call; `curl --data-binary
|
|
||||||
// @frame.jpg -H 'X-Trigger: radar'` reproduces it exactly.
|
|
||||||
//
|
|
||||||
// The metadata is small and flat (a dozen scalars), which is precisely the
|
|
||||||
// case headers handle well. If it ever grows nested structure, switch that one
|
|
||||||
// endpoint to multipart and keep the rest.
|
|
||||||
//
|
|
||||||
// AUTH DECISION (answers "the token comes from the endpoint, I guess?")
|
|
||||||
// Yes. Two-step, and the long-lived token is never in source or in a build
|
|
||||||
// flag:
|
|
||||||
// 1. A *shared enrollment secret* is compiled in (or typed once). The device
|
|
||||||
// POSTs /enroll with its eFuse-derived UID.
|
|
||||||
// 2. The Pi creates the device row, returns a per-device token, and the
|
|
||||||
// device stores it in NVS and wipes the enrollment secret.
|
|
||||||
// From then on every request carries `Authorization: Bearer <token>`. Rotating
|
|
||||||
// a token in the admin UI just means the next request 401s and the device
|
|
||||||
// re-enrolls. The Pi stores only the hash (SPEC §3 `devices.token_hash`).
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <ArduinoJson.h>
|
|
||||||
|
|
||||||
#include "frame_ring.h"
|
|
||||||
|
|
||||||
// What the endpoint sends back on ingest/heartbeat. SPEC §4.1: the upload
|
|
||||||
// response carries the command queue, so a capture that was going to happen
|
|
||||||
// anyway also delivers pending commands at no extra cost.
|
|
||||||
struct ServerEnvelope {
|
|
||||||
bool ok;
|
|
||||||
int http_status;
|
|
||||||
int64_t server_time_ms; // authoritative clock (SPEC C7)
|
|
||||||
uint32_t config_version; // if it differs from ours, pull config
|
|
||||||
bool has_firmware;
|
|
||||||
char fw_version[24];
|
|
||||||
char fw_url[160];
|
|
||||||
char fw_sha256[65];
|
|
||||||
uint32_t fw_size;
|
|
||||||
// Commands are handled inside the parse callback rather than copied out,
|
|
||||||
// so this struct stays a fixed-size value type.
|
|
||||||
uint8_t command_count;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct CaptureMeta {
|
|
||||||
const char* trigger; // radar | timer | manual | prebuffer | stream_grab
|
|
||||||
const char* burst_id; // groups the frames of one event
|
|
||||||
uint8_t burst_index;
|
|
||||||
uint8_t burst_count;
|
|
||||||
int8_t pre_trigger; // 1 if this frame predates the trigger
|
|
||||||
uint16_t radar_distance_cm;
|
|
||||||
uint8_t radar_energy;
|
|
||||||
uint8_t radar_state;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Called once per command in a response envelope.
|
|
||||||
typedef void (*CommandHandler)(JsonObjectConst cmd);
|
|
||||||
|
|
||||||
void apiBegin();
|
|
||||||
|
|
||||||
// Exchange the enrollment secret for a device token. No-op if already enrolled.
|
|
||||||
// Returns true when g_cfg.device_token is populated and persisted.
|
|
||||||
bool apiEnroll();
|
|
||||||
|
|
||||||
// POST one JPEG. `meta` rides in headers.
|
|
||||||
ServerEnvelope apiIngest(const FrameCopy& frame, const CaptureMeta& meta, CommandHandler on_cmd);
|
|
||||||
|
|
||||||
// POST device conditions; the response carries the same envelope as ingest.
|
|
||||||
// This is the call that drains the command queue, so it is also the one that
|
|
||||||
// must not be made from somewhere the device cannot then act on a command.
|
|
||||||
ServerEnvelope apiHeartbeat(CommandHandler on_cmd);
|
|
||||||
|
|
||||||
// POST the same conditions body to /status, which returns 204 and no command
|
|
||||||
// queue. For pushes where picking up commands would be wrong or wasteful:
|
|
||||||
// immediately before deep sleep (the device is about to become unable to act),
|
|
||||||
// after an upload burst, or on an explicit report_status command.
|
|
||||||
// Returns true on a 2xx.
|
|
||||||
bool apiPostStatus(const char* reason);
|
|
||||||
|
|
||||||
// GET the full device config and merge it into g_cfg. Returns true if changed.
|
|
||||||
bool apiFetchConfig();
|
|
||||||
|
|
||||||
// Report a command's outcome so the WebUI can stop showing it as pending.
|
|
||||||
bool apiAckCommand(uint32_t command_id, const char* status, const char* detail);
|
|
||||||
|
|
||||||
// Open a chunked MJPEG push for a streaming session. See stream_session.cpp.
|
|
||||||
bool apiStreamOpen(const char* session_id, uint8_t mode, uint16_t duration_s);
|
|
||||||
bool apiStreamSendFrame(const uint8_t* jpeg, size_t len, int64_t epoch_ms);
|
|
||||||
void apiStreamClose();
|
|
||||||
|
|
||||||
// True when the last request returned 401 — the caller should re-enroll.
|
|
||||||
bool apiTokenRejected();
|
|
||||||
@@ -1,193 +0,0 @@
|
|||||||
// app_config.h — the device's entire runtime configuration.
|
|
||||||
//
|
|
||||||
// Three layers, later ones win:
|
|
||||||
// 1. compile-time defaults (platformio.ini -D flags)
|
|
||||||
// 2. NVS, written on first boot and on every accepted config push
|
|
||||||
// 3. `apply_config` command from the endpoint, carrying a config_version
|
|
||||||
//
|
|
||||||
// The endpoint is the source of truth. The device reports the config_version it
|
|
||||||
// is running in every request; the endpoint pushes a new config whenever those
|
|
||||||
// disagree. That keeps SPEC §3.4 ("Device settings pushed via apply_config")
|
|
||||||
// working without a separate settings-fetch round trip.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <ArduinoJson.h>
|
|
||||||
|
|
||||||
enum StreamMode : uint8_t {
|
|
||||||
STREAM_WATCH = 0, // relay to viewers, do not persist
|
|
||||||
STREAM_RECORD = 1, // persist on the Pi, no live viewers
|
|
||||||
STREAM_BOTH = 2,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum RadarMode : uint8_t {
|
|
||||||
RADAR_OUT_PIN_ONLY = 0, // trust the module's presence pin, ignore UART
|
|
||||||
RADAR_UART_ONLY = 1, // decode reports, apply distance/energy windows
|
|
||||||
RADAR_BOTH = 2, // OUT pin arms, UART report confirms (default)
|
|
||||||
};
|
|
||||||
|
|
||||||
enum NightBehaviour : uint8_t {
|
|
||||||
NIGHT_CAPTURE = 0, // keep working, using the night camera profile
|
|
||||||
NIGHT_IDLE = 1, // stay awake and reachable, but capture nothing
|
|
||||||
NIGHT_SLEEP = 2, // deep sleep until morning, even if deep sleep is off
|
|
||||||
};
|
|
||||||
|
|
||||||
enum NightlightMode : uint8_t {
|
|
||||||
NIGHTLIGHT_OFF = 0,
|
|
||||||
NIGHTLIGHT_ON_BURST = 1, // illuminate only while a burst is being captured
|
|
||||||
NIGHTLIGHT_ALWAYS = 2, // on for the whole night; kinder to wildlife
|
|
||||||
};
|
|
||||||
|
|
||||||
enum BatteryChemistry : uint8_t {
|
|
||||||
BATT_NONE = 0, // no cell wired; report voltage only, no percentage
|
|
||||||
BATT_LIION = 1, // Li-ion / LiPo, 4.20 V full
|
|
||||||
BATT_LIFEPO4 = 2, // LiFePO4, 3.65 V full — flat curve, see battery.cpp
|
|
||||||
};
|
|
||||||
|
|
||||||
// OV2640 tuning. Held twice (day and night) so the device can switch profiles
|
|
||||||
// at dusk without a round trip to the endpoint. Ranges are the sensor's own;
|
|
||||||
// see camera_mgr.cpp for what each one is worth on a bird camera.
|
|
||||||
struct CamTuning {
|
|
||||||
int8_t brightness; // -2..2
|
|
||||||
int8_t contrast; // -2..2
|
|
||||||
int8_t saturation; // -2..2
|
|
||||||
int8_t sharpness; // -2..2 (OV2640 support is patchy)
|
|
||||||
int8_t ae_level; // -2..2 exposure bias
|
|
||||||
uint8_t special_effect; // 0 none 1 negative 2 grayscale 3 red 4 green 5 blue 6 sepia
|
|
||||||
uint8_t wb_mode; // 0 auto 1 sunny 2 cloudy 3 office 4 home
|
|
||||||
uint8_t gainceiling; // 0=2x 1=4x 2=8x 3=16x 4=32x 5=64x 6=128x
|
|
||||||
uint8_t agc_gain; // 0..30, only used when gain_ctrl = 0
|
|
||||||
uint16_t aec_value; // 0..1200, only used when exposure_ctrl = 0
|
|
||||||
bool whitebal;
|
|
||||||
bool awb_gain;
|
|
||||||
bool exposure_ctrl; // false = manual, use aec_value
|
|
||||||
bool aec2; // DSP-assisted auto exposure
|
|
||||||
bool gain_ctrl; // false = manual, use agc_gain
|
|
||||||
bool bpc; // black pixel correction
|
|
||||||
bool wpc; // white pixel correction
|
|
||||||
bool raw_gma;
|
|
||||||
bool lenc; // lens shading correction
|
|
||||||
bool dcw; // downsize/crop enable
|
|
||||||
bool colorbar; // test pattern — bring-up only
|
|
||||||
};
|
|
||||||
|
|
||||||
struct AppConfig {
|
|
||||||
// --- identity & endpoint ---------------------------------------------
|
|
||||||
char device_name[32];
|
|
||||||
char wifi_ssid[33];
|
|
||||||
char wifi_pass[64];
|
|
||||||
char api_host[64]; // Pi's IP. Use a DHCP reservation, not mDNS.
|
|
||||||
uint16_t api_port;
|
|
||||||
char api_base[24]; // "/api/v1"
|
|
||||||
char device_token[65]; // issued by the endpoint at enrollment
|
|
||||||
// The secret used to (re-)enroll. Starts as the shared bootstrap secret
|
|
||||||
// from secrets.ini and is replaced, at first enrollment, by a per-device
|
|
||||||
// one issued by the endpoint. Deliberately NOT wiped: the device must be
|
|
||||||
// able to recover from a token rotation on its own, because reaching it
|
|
||||||
// over USB is not an option once it is mounted. See api_client.h.
|
|
||||||
char enroll_secret[65];
|
|
||||||
|
|
||||||
// --- time (SPEC C7: the endpoint is the time server) -------------------
|
|
||||||
char ntp_host[64]; // empty => use api_host
|
|
||||||
char tz[48]; // POSIX TZ string
|
|
||||||
|
|
||||||
// --- camera ------------------------------------------------------------
|
|
||||||
uint8_t frame_size; // framesize_t
|
|
||||||
uint8_t jpeg_quality; // 4..40, lower is better
|
|
||||||
bool vflip;
|
|
||||||
bool hmirror;
|
|
||||||
CamTuning cam_day;
|
|
||||||
CamTuning cam_night; // applied automatically between dusk and dawn
|
|
||||||
|
|
||||||
// --- capture / trigger ---------------------------------------------------
|
|
||||||
uint8_t ring_frames; // PSRAM history depth
|
|
||||||
uint8_t pre_roll; // frames sent from before the trigger
|
|
||||||
uint8_t post_roll; // frames sent after
|
|
||||||
uint16_t post_roll_gap_ms; // spacing between post-roll frames
|
|
||||||
uint16_t cooldown_s; // minimum gap between two trigger events
|
|
||||||
uint16_t idle_period_ms; // ring refresh period when nothing is happening
|
|
||||||
|
|
||||||
// --- radar ---------------------------------------------------------------
|
|
||||||
uint8_t radar_mode; // RadarMode
|
|
||||||
bool accept_stationary; // a motionless bird still counts
|
|
||||||
uint16_t min_distance_cm;
|
|
||||||
uint16_t max_distance_cm;
|
|
||||||
uint8_t min_energy; // 0..100, per-report energy floor
|
|
||||||
uint32_t radar_baud; // 0 = autodetect (recommended)
|
|
||||||
|
|
||||||
// --- live stream (SPEC C9 — plumbing built, off by default) --------------
|
|
||||||
bool stream_enabled;
|
|
||||||
uint8_t stream_frame_size; // usually lower than stills
|
|
||||||
uint8_t stream_jpeg_quality;
|
|
||||||
uint16_t stream_duration_s; // hard cap; the device stops itself
|
|
||||||
uint8_t stream_fps;
|
|
||||||
uint8_t stream_mode; // StreamMode
|
|
||||||
|
|
||||||
// Streaming and sleeping are mutually exclusive: a sleeping device cannot
|
|
||||||
// be told to start a stream (SPEC C1). With this set, enabling streaming
|
|
||||||
// keeps the device awake and reachable so `stream_start` arrives promptly.
|
|
||||||
// Clear it to let the device sleep anyway and accept the wake latency.
|
|
||||||
bool stream_blocks_sleep;
|
|
||||||
|
|
||||||
// --- night ---------------------------------------------------------------
|
|
||||||
// The window is minutes from local midnight. The endpoint knows the site's
|
|
||||||
// latitude, so the intended use is for the Pi to push real sunset/sunrise
|
|
||||||
// daily; the fixed defaults are only a fallback.
|
|
||||||
uint16_t night_start_min; // default 21:00
|
|
||||||
uint16_t night_end_min; // default 06:00
|
|
||||||
uint8_t night_behaviour; // NightBehaviour
|
|
||||||
uint8_t nightlight_mode; // NightlightMode
|
|
||||||
uint8_t nightlight_brightness; // 0..255 PWM duty
|
|
||||||
|
|
||||||
// --- battery / supply -----------------------------------------------------
|
|
||||||
uint8_t battery_chemistry; // BatteryChemistry
|
|
||||||
uint16_t battery_divider_x100; // divider ratio x100, e.g. 200 = 2.00:1
|
|
||||||
int16_t battery_offset_mv; // calibration trim, added after scaling
|
|
||||||
uint8_t battery_min_pct_ota; // SPEC C6: refuse to flash below this
|
|
||||||
uint8_t battery_warn_pct; // surfaced to the WebUI as a low alarm
|
|
||||||
|
|
||||||
// --- ops -----------------------------------------------------------------
|
|
||||||
uint16_t heartbeat_interval_s;
|
|
||||||
uint16_t status_interval_s; // POST /status cadence; 0 = only on events
|
|
||||||
bool ota_enabled;
|
|
||||||
|
|
||||||
// --- power (see power_mgr.h for what each mode gives up) ------------------
|
|
||||||
bool deep_sleep_enabled; // the master on/off switch
|
|
||||||
uint16_t deep_sleep_s; // timer wake interval while asleep
|
|
||||||
bool sleep_wake_on_radar; // also wake on the LD2410 OUT pin
|
|
||||||
uint16_t sleep_idle_timeout_s; // stay awake this long after the last event
|
|
||||||
uint16_t sleep_max_awake_s; // hard cap: sleep even if something is stuck
|
|
||||||
|
|
||||||
uint32_t config_version;
|
|
||||||
};
|
|
||||||
|
|
||||||
extern AppConfig g_cfg;
|
|
||||||
|
|
||||||
// Load from NVS, filling anything missing from the compile-time defaults.
|
|
||||||
void configLoad();
|
|
||||||
|
|
||||||
// Persist the current g_cfg to NVS. Returns false if the write failed.
|
|
||||||
bool configSave();
|
|
||||||
|
|
||||||
// Merge a config document pushed by the endpoint into g_cfg. Only keys present
|
|
||||||
// in `doc` are touched, so the endpoint can send partial updates. Returns true
|
|
||||||
// if anything actually changed (caller decides whether a reboot is needed).
|
|
||||||
bool configApplyJson(JsonObjectConst doc);
|
|
||||||
|
|
||||||
// True when a change needs the camera re-initialised rather than just applied.
|
|
||||||
bool configNeedsCameraRestart(const AppConfig& before, const AppConfig& after);
|
|
||||||
|
|
||||||
// Stable per-device identifier derived from the eFuse MAC. Survives reflashing,
|
|
||||||
// which is what makes it usable as the enrollment key.
|
|
||||||
const char* deviceUid();
|
|
||||||
|
|
||||||
// The shared bootstrap secret compiled in from secrets.ini. Kept reachable as
|
|
||||||
// a last-resort fallback: if the per-device re-enrollment secret in NVS is
|
|
||||||
// ever rejected, the device can still get back in with this one rather than
|
|
||||||
// needing a USB cable.
|
|
||||||
const char* configBootstrapSecret();
|
|
||||||
|
|
||||||
// Base URL without trailing slash, e.g. "http://192.168.1.50:8080/api/v1".
|
|
||||||
String apiBaseUrl();
|
|
||||||
|
|
||||||
void configDump();
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
// battery.h — supply / battery voltage sensing.
|
|
||||||
//
|
|
||||||
// WIRING (nothing is wired by default; reads report invalid until it is)
|
|
||||||
// The XIAO ESP32S3 does not bring the battery rail out to an ADC pin you can
|
|
||||||
// simply read — the documented approaches involve soldering, and the divider
|
|
||||||
// differs between board revisions. So this driver assumes an *external*
|
|
||||||
// divider you add yourself:
|
|
||||||
//
|
|
||||||
// BAT+ ──[ R1 ]──┬──[ R2 ]── GND
|
|
||||||
// └── PIN_BATTERY_ADC (default D3 / GPIO4)
|
|
||||||
//
|
|
||||||
// Two 1 MΩ resistors give a 2.00:1 ratio and ~2 µA of continuous drain, which
|
|
||||||
// is negligible on mains and tolerable on battery. If you care about the last
|
|
||||||
// microamp, gate the low side with a MOSFET on PIN_BATTERY_EN — SPEC §9 is
|
|
||||||
// right that an always-connected divider is a permanent load.
|
|
||||||
//
|
|
||||||
// Set `battery_divider_x100` to your actual ratio: measure the real resistors
|
|
||||||
// rather than trusting their printed value, then trim with
|
|
||||||
// `battery_offset_mv` against a multimeter. The ESP32 ADC is not linear and
|
|
||||||
// `analogReadMilliVolts()` only corrects for the part of that Espressif
|
|
||||||
// characterised at the factory.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
struct BatteryReading {
|
|
||||||
bool valid; // false when no divider is configured or the read failed
|
|
||||||
uint16_t mv; // battery terminal voltage in millivolts
|
|
||||||
uint8_t pct; // 0..100, 0 when chemistry is BATT_NONE
|
|
||||||
uint16_t raw_mv; // at the pin, before the divider ratio is applied
|
|
||||||
};
|
|
||||||
|
|
||||||
void batteryBegin();
|
|
||||||
|
|
||||||
// Averaged, calibrated read. Powers the divider for the measurement if
|
|
||||||
// PIN_BATTERY_EN is wired, then turns it off again.
|
|
||||||
BatteryReading batteryRead();
|
|
||||||
|
|
||||||
// Last reading without touching the ADC. Cheap; use this in status payloads
|
|
||||||
// that are built more often than the voltage can meaningfully change.
|
|
||||||
BatteryReading batteryLast();
|
|
||||||
|
|
||||||
// Refresh the cached reading. Called on a timer from the main loop.
|
|
||||||
void batteryPoll();
|
|
||||||
|
|
||||||
// SPEC C6 gate, registered with otaSetBatteryCheck().
|
|
||||||
bool batteryAboveOtaThreshold(uint8_t min_pct);
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
// board_pins.h — single place where physical wiring is declared.
|
|
||||||
//
|
|
||||||
// Hardware is not in hand yet, so every free-pin assignment here is a default
|
|
||||||
// that can be overridden with a -D build flag without touching source. The
|
|
||||||
// camera pins are fixed by the XIAO ESP32S3 Sense expansion board and are not
|
|
||||||
// overridable; they are listed so the wiring is documented in one place.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// XIAO ESP32S3 Sense — OV2640 on the expansion board. Fixed by the PCB.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
#define CAM_PIN_PWDN -1
|
|
||||||
#define CAM_PIN_RESET -1
|
|
||||||
#define CAM_PIN_XCLK 10
|
|
||||||
#define CAM_PIN_SIOD 40 // SCCB SDA
|
|
||||||
#define CAM_PIN_SIOC 39 // SCCB SCL
|
|
||||||
#define CAM_PIN_D7 48
|
|
||||||
#define CAM_PIN_D6 11
|
|
||||||
#define CAM_PIN_D5 12
|
|
||||||
#define CAM_PIN_D4 14
|
|
||||||
#define CAM_PIN_D3 16
|
|
||||||
#define CAM_PIN_D2 18
|
|
||||||
#define CAM_PIN_D1 17
|
|
||||||
#define CAM_PIN_D0 15
|
|
||||||
#define CAM_PIN_VSYNC 38
|
|
||||||
#define CAM_PIN_HREF 47
|
|
||||||
#define CAM_PIN_PCLK 13
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// HLK-LD2410 24 GHz radar
|
|
||||||
//
|
|
||||||
// Wiring (module -> XIAO):
|
|
||||||
// VCC -> 5V (plain LD2410, no Bluetooth)
|
|
||||||
// GND -> GND
|
|
||||||
// TX -> D1 / GPIO2 (ESP RX)
|
|
||||||
// RX -> D0 / GPIO1 (ESP TX)
|
|
||||||
// OUT -> D2 / GPIO3 (presence, active HIGH; RTC-capable so it can also
|
|
||||||
// serve as a deep-sleep wake source later)
|
|
||||||
//
|
|
||||||
// MEASURE THE LOGIC LEVELS BEFORE CONNECTING. The LD2410's logic is supposed
|
|
||||||
// to be 3.3 V even when VCC is 5 V (it regulates internally), but this varies
|
|
||||||
// between batches and clones, and the ESP32-S3 is not 5 V tolerant. A 5 V OUT
|
|
||||||
// into GPIO3 damages the pin, and on a camera you cannot physically reach
|
|
||||||
// that is an expensive way to find out.
|
|
||||||
//
|
|
||||||
// Two minutes with a multimeter on OUT and TX (wave a hand in front of the
|
|
||||||
// module so OUT asserts) settles it. If either reads ~5 V, drop it with a
|
|
||||||
// divider -- 10k from the module into the GPIO, 20k from the GPIO to GND
|
|
||||||
// gives 3.3 V from 5 V. The ESP's TX into the module's RX needs nothing:
|
|
||||||
// 3.3 V comfortably clears the module's input threshold.
|
|
||||||
//
|
|
||||||
// Baud rate is autodetected (see radarBegin), so a module at the factory
|
|
||||||
// 256000 and one reconfigured to 115200 both just work, and a factory reset
|
|
||||||
// does not take the trigger offline.
|
|
||||||
//
|
|
||||||
// Deliberately NOT on D6/D7 (GPIO43/44): those are UART0, which the ROM
|
|
||||||
// bootloader spews boot logs onto at every reset. Harmless for the radar, but
|
|
||||||
// it costs you the one easy hardware debug port. Keep 43/44 free.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
#ifndef PIN_RADAR_TX
|
|
||||||
#define PIN_RADAR_TX 1 // D0 — ESP transmits, goes to LD2410 RX
|
|
||||||
#endif
|
|
||||||
#ifndef PIN_RADAR_RX
|
|
||||||
#define PIN_RADAR_RX 2 // D1 — ESP receives, comes from LD2410 TX
|
|
||||||
#endif
|
|
||||||
#ifndef PIN_RADAR_OUT
|
|
||||||
#define PIN_RADAR_OUT 3 // D2 — presence output
|
|
||||||
#endif
|
|
||||||
#ifndef RADAR_UART_NUM
|
|
||||||
#define RADAR_UART_NUM 1 // UART1 via the GPIO matrix
|
|
||||||
#endif
|
|
||||||
#ifndef RADAR_BAUD
|
|
||||||
#define RADAR_BAUD 256000 // LD2410 factory default
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Optional high-side MOSFET gating the radar's supply. -1 = permanently powered.
|
|
||||||
// Only worth wiring if you run deep sleep with sleep_wake_on_radar = false:
|
|
||||||
// the LD2410 draws ~80 mA continuously, which dwarfs anything the ESP saves by
|
|
||||||
// sleeping. See the note at the top of power_mgr.h.
|
|
||||||
#ifndef PIN_RADAR_EN
|
|
||||||
#define PIN_RADAR_EN -1
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Spare I/O — reserved, nothing wired yet.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
#ifndef PIN_AUX_ADC
|
|
||||||
#define PIN_AUX_ADC 4 // D3 / A3 — spare ADC, or a PIR fallback
|
|
||||||
#endif
|
|
||||||
#ifndef PIN_I2C_SDA
|
|
||||||
#define PIN_I2C_SDA 5 // D4 — future BME280 / DS3231
|
|
||||||
#endif
|
|
||||||
#ifndef PIN_I2C_SCL
|
|
||||||
#define PIN_I2C_SCL 6 // D5
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Battery / supply sensing. Defaults to the spare ADC pin above. The XIAO
|
|
||||||
// does not expose its battery rail on a readable pin, so this needs an
|
|
||||||
// external divider — see the wiring diagram at the top of battery.h.
|
|
||||||
// Set to -1 to disable; voltage then reports as invalid rather than as zero.
|
|
||||||
#ifndef PIN_BATTERY_ADC
|
|
||||||
#define PIN_BATTERY_ADC PIN_AUX_ADC
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Optional MOSFET on the divider's low side, so it only draws current during
|
|
||||||
// a measurement (SPEC §9). -1 = divider permanently connected.
|
|
||||||
#ifndef PIN_BATTERY_EN
|
|
||||||
#define PIN_BATTERY_EN -1
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Nightlight / illuminator, PWM driven. -1 = not fitted.
|
|
||||||
// Drive a MOSFET or a constant-current module, never the LED directly: an
|
|
||||||
// ESP32 pin is good for ~20 mA short-term and an illuminator worth having
|
|
||||||
// draws far more. Read the warning at the top of nightlight.h before choosing
|
|
||||||
// between IR and white.
|
|
||||||
#ifndef PIN_NIGHTLIGHT
|
|
||||||
#define PIN_NIGHTLIGHT -1
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// D8/D9/D10 (GPIO7/8/9) are the Sense board's microSD (SD_MMC 1-bit:
|
|
||||||
// CLK=7, D0=8, CMD=9). Leave them alone if you ever want local buffering.
|
|
||||||
|
|
||||||
// Onboard user LED. Active LOW on the XIAO ESP32S3.
|
|
||||||
// NOTE: verify against your board revision before trusting it — Seeed has
|
|
||||||
// moved this pin between revisions.
|
|
||||||
#ifndef PIN_STATUS_LED
|
|
||||||
#define PIN_STATUS_LED 21
|
|
||||||
#endif
|
|
||||||
#ifndef STATUS_LED_ACTIVE_LOW
|
|
||||||
#define STATUS_LED_ACTIVE_LOW 1
|
|
||||||
#endif
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
// camera_mgr.h — OV2640 lifecycle.
|
|
||||||
//
|
|
||||||
// Unlike the battery design in SPEC §4.3, the camera stays initialised for the
|
|
||||||
// life of the boot. That removes the 300-600 ms sensor init and auto-exposure
|
|
||||||
// settle from the trigger path entirely (SPEC C4) and is what makes the
|
|
||||||
// pre-trigger ring possible.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <esp_camera.h>
|
|
||||||
|
|
||||||
bool cameraBegin();
|
|
||||||
void cameraEnd();
|
|
||||||
bool cameraRestart(); // after a frame_size change
|
|
||||||
|
|
||||||
// Push the current g_cfg (quality, flip, mirror) plus the active tuning
|
|
||||||
// profile onto a running sensor. Frame size is deliberately excluded — see
|
|
||||||
// configNeedsCameraRestart().
|
|
||||||
void cameraApplyConfig();
|
|
||||||
|
|
||||||
// Apply the day or night tuning profile. Called on dusk/dawn transitions and
|
|
||||||
// whenever the endpoint pushes new tuning.
|
|
||||||
void cameraApplyTuning(bool night);
|
|
||||||
|
|
||||||
// Which profile is currently loaded.
|
|
||||||
bool cameraNightProfileActive();
|
|
||||||
|
|
||||||
// --- frame sizes ------------------------------------------------------------
|
|
||||||
// Resolutions are configured BY NAME ("SVGA", "UXGA"), not by the numeric
|
|
||||||
// framesize_t index, and these two functions are the only place the mapping
|
|
||||||
// lives. The reason is not cosmetic: esp32-camera has inserted entries into
|
|
||||||
// framesize_t between releases — FRAMESIZE_128X128 and FRAMESIZE_320X320 were
|
|
||||||
// added mid-enum — so a hardcoded index silently means a different resolution
|
|
||||||
// after a driver update. The tables below are built from the enum symbols, so
|
|
||||||
// they stay correct by construction.
|
|
||||||
//
|
|
||||||
// Numeric values are still accepted from the endpoint for compatibility, but
|
|
||||||
// names are what the settings UI should send.
|
|
||||||
uint8_t framesizeFromName(const char* name, uint8_t fallback);
|
|
||||||
const char* framesizeName(uint8_t fs);
|
|
||||||
void framesizeDims(uint8_t fs, uint16_t* w, uint16_t* h);
|
|
||||||
|
|
||||||
// Temporarily switch resolution for a streaming session, then put it back.
|
|
||||||
bool cameraSetFrameSize(uint8_t framesize);
|
|
||||||
|
|
||||||
// Grab one JPEG. Returns nullptr on failure. Caller must esp_camera_fb_return().
|
|
||||||
camera_fb_t* cameraGrab();
|
|
||||||
|
|
||||||
// Throw away the first frames after init so auto-exposure has settled before
|
|
||||||
// anything is uploaded (SPEC C4).
|
|
||||||
void cameraDiscardFrames(uint8_t n);
|
|
||||||
|
|
||||||
bool cameraReady();
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
// commands.h — the WebUI -> device channel (SPEC C1).
|
|
||||||
//
|
|
||||||
// The device is never contacted directly. The WebUI writes a row into
|
|
||||||
// `device_commands`; the endpoint attaches pending rows to the next
|
|
||||||
// ingest/heartbeat response; this module executes them and acks.
|
|
||||||
//
|
|
||||||
// Deferred execution: some commands must not run inside the HTTP response
|
|
||||||
// callback (OTA reboots, streaming blocks for a minute). Those are queued and
|
|
||||||
// run from the main loop, which is also where sleep decisions are made.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <ArduinoJson.h>
|
|
||||||
|
|
||||||
// Pass this to apiIngest/apiHeartbeat. Parses and either executes immediately
|
|
||||||
// or defers. Cheap commands ack from here; deferred ones ack on completion.
|
|
||||||
void commandOnReceived(JsonObjectConst cmd);
|
|
||||||
|
|
||||||
// Run anything that was deferred. Call once per main-loop tick.
|
|
||||||
void commandRunDeferred();
|
|
||||||
|
|
||||||
bool commandHasPending();
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
// device_stats.h — the counters reported in the conditions payload.
|
|
||||||
//
|
|
||||||
// Kept in RTC slow memory, so they survive deep sleep. They do NOT survive a
|
|
||||||
// power cycle, which is deliberate: the endpoint already has the authoritative
|
|
||||||
// count of what arrived, and a device-side counter that claimed to be durable
|
|
||||||
// would just be a second source of truth to disagree with the first. Treat
|
|
||||||
// these as "what this device believes it did today" and reconcile against the
|
|
||||||
// database, not the other way round.
|
|
||||||
//
|
|
||||||
// "Today" is local-midnight to local-midnight, using the TZ pushed from the
|
|
||||||
// endpoint. Rollover needs a synced clock; before the first sync the counters
|
|
||||||
// accumulate under day 0 and roll over once when time arrives.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
struct DeviceStats {
|
|
||||||
uint16_t captured_today; // frames handed to the uploader
|
|
||||||
uint16_t delivered_today; // frames the endpoint accepted (2xx)
|
|
||||||
uint16_t failed_today; // upload attempts that did not get a 2xx
|
|
||||||
uint16_t events_today; // trigger events, not frames
|
|
||||||
uint32_t day_index; // days since epoch, local — the rollover key
|
|
||||||
|
|
||||||
uint16_t captured_boot; // since this boot, for spotting a reset
|
|
||||||
uint16_t delivered_boot;
|
|
||||||
};
|
|
||||||
|
|
||||||
void statsBegin();
|
|
||||||
|
|
||||||
// Roll the daily counters over if the local date has changed. Cheap; call
|
|
||||||
// from the main loop and before building any status payload.
|
|
||||||
void statsRollover();
|
|
||||||
|
|
||||||
void statsCountEvent();
|
|
||||||
void statsCountCaptured(uint16_t frames);
|
|
||||||
void statsCountDelivered(uint16_t frames);
|
|
||||||
void statsCountFailed(uint16_t frames);
|
|
||||||
|
|
||||||
DeviceStats statsGet();
|
|
||||||
|
|
||||||
// Ticks since the device last woke, in ms — "ticks since last sleep".
|
|
||||||
uint32_t statsAwakeMs();
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
// frame_ring.h — pre-trigger history in PSRAM.
|
|
||||||
//
|
|
||||||
// THE POINT OF THIS FILE
|
|
||||||
// SPEC C4 says the first usable frame lands 1-3 s after the bird arrives, by
|
|
||||||
// which time a small bird is gone. That is only true if capture *starts* at the
|
|
||||||
// trigger. With mains power we can instead capture continuously into a ring and,
|
|
||||||
// on a trigger, ship the frames from *before* it. Effective latency goes
|
|
||||||
// negative and C4 stops being a problem.
|
|
||||||
//
|
|
||||||
// Cost: ring_frames * ~45 KB of the 8 MB PSRAM. At depth 24 that is ~1 MB for
|
|
||||||
// roughly 10 s of history at the default 400 ms cadence.
|
|
||||||
//
|
|
||||||
// Ownership: the ring owns its buffers and recycles them in place. Anything
|
|
||||||
// handed to the uploader is a *copy*, so a slow network cannot stall capture
|
|
||||||
// and there is no refcounting to get wrong.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
struct RingFrame {
|
|
||||||
uint8_t* data; // PSRAM, owned by the ring
|
|
||||||
size_t len;
|
|
||||||
size_t cap; // allocated size, >= len
|
|
||||||
uint32_t seq; // monotonic, 0 = never filled
|
|
||||||
uint32_t at_ms; // millis() at capture
|
|
||||||
int64_t at_epoch; // wall-clock ms, 0 if time not yet synced
|
|
||||||
};
|
|
||||||
|
|
||||||
// A frame copied out for upload. Caller owns `data` and must free() it.
|
|
||||||
struct FrameCopy {
|
|
||||||
uint8_t* data;
|
|
||||||
size_t len;
|
|
||||||
uint32_t seq;
|
|
||||||
uint32_t at_ms;
|
|
||||||
int64_t at_epoch;
|
|
||||||
};
|
|
||||||
|
|
||||||
bool ringBegin(uint8_t depth);
|
|
||||||
void ringEnd();
|
|
||||||
|
|
||||||
// Store a frame. Copies into the ring's own PSRAM buffer, growing it if the
|
|
||||||
// JPEG is larger than the slot currently holds.
|
|
||||||
bool ringPush(const uint8_t* data, size_t len, int64_t epoch_ms);
|
|
||||||
|
|
||||||
// Copy out the newest `n` frames, oldest first. Returns how many were written
|
|
||||||
// into `out` (may be fewer than n if the ring has not filled yet).
|
|
||||||
// Every returned FrameCopy.data must be free()d by the caller.
|
|
||||||
size_t ringTakeNewest(size_t n, FrameCopy* out, size_t out_cap);
|
|
||||||
|
|
||||||
uint32_t ringSeq(); // sequence of the most recent frame
|
|
||||||
size_t ringCount(); // frames currently held
|
|
||||||
size_t ringBytesUsed();
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
// ld2410.h — HLK-LD2410 24 GHz presence radar.
|
|
||||||
//
|
|
||||||
// The module streams a report frame a few times a second on UART (256000 8N1 by
|
|
||||||
// factory default) and simultaneously drives an active-high OUT pin. We use
|
|
||||||
// both: the pin is a zero-latency "something is there", the UART report carries
|
|
||||||
// the distance and energy needed to reject swaying branches and passing people.
|
|
||||||
//
|
|
||||||
// Frame formats (HLK datasheet):
|
|
||||||
// report F4 F3 F2 F1 | len(2,LE) | payload | F8 F7 F6 F5
|
|
||||||
// command FD FC FB FA | len(2,LE) | payload | 04 03 02 01
|
|
||||||
//
|
|
||||||
// Basic report payload (type 0x02):
|
|
||||||
// [0] 0x02 type [1] 0xAA head
|
|
||||||
// [2] target state: 0=none 1=moving 2=stationary 3=both
|
|
||||||
// [3..4] moving distance cm (LE) [5] moving energy 0..100
|
|
||||||
// [6..7] stationary distance cm (LE) [8] stationary energy 0..100
|
|
||||||
// [9..10] detection distance cm (LE)
|
|
||||||
// [11] 0x55 tail [12] 0x00 check
|
|
||||||
//
|
|
||||||
// These offsets are transcribed from the datasheet, not verified against real
|
|
||||||
// hardware. Run `radarSelfTest()` once the module is wired and check the log
|
|
||||||
// before trusting the parsed values.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
enum RadarTarget : uint8_t {
|
|
||||||
TARGET_NONE = 0,
|
|
||||||
TARGET_MOVING = 1,
|
|
||||||
TARGET_STATIONARY = 2,
|
|
||||||
TARGET_BOTH = 3,
|
|
||||||
};
|
|
||||||
|
|
||||||
struct RadarReading {
|
|
||||||
bool valid; // a well-formed frame was decoded
|
|
||||||
uint8_t target; // RadarTarget
|
|
||||||
uint16_t moving_cm;
|
|
||||||
uint8_t moving_energy; // 0..100
|
|
||||||
uint16_t stationary_cm;
|
|
||||||
uint8_t stationary_energy; // 0..100
|
|
||||||
uint16_t detect_cm;
|
|
||||||
bool out_pin; // raw presence pin, independent of UART
|
|
||||||
uint32_t at_ms; // millis() when decoded
|
|
||||||
};
|
|
||||||
|
|
||||||
// Bring up UART1 on the configured pins and set the OUT pin as an input.
|
|
||||||
//
|
|
||||||
// Probes for the module's baud rate rather than assuming one: the LD2410
|
|
||||||
// ships at 256000 and can be reconfigured to 115200 and others, and a factory
|
|
||||||
// reset puts it back. Autodetecting means neither event takes the trigger
|
|
||||||
// offline on a device you cannot physically reach. Pin it with
|
|
||||||
// `g_cfg.radar_baud` to skip the probe.
|
|
||||||
//
|
|
||||||
// Returns false if no baud produced a valid frame. That is not fatal — the
|
|
||||||
// OUT pin path (radar_mode = RADAR_OUT_PIN_ONLY) needs no UART at all.
|
|
||||||
bool radarBegin();
|
|
||||||
|
|
||||||
// The baud actually in use, or 0 if nothing was decoded.
|
|
||||||
uint32_t radarBaud();
|
|
||||||
|
|
||||||
// Pump the UART. Call often (the radar task does, every few ms). Returns true
|
|
||||||
// when a new report frame was decoded since the last call.
|
|
||||||
bool radarPoll();
|
|
||||||
|
|
||||||
// Most recent decoded report, plus a live read of the OUT pin.
|
|
||||||
RadarReading radarLast();
|
|
||||||
|
|
||||||
// Apply the configured distance window, energy floor and stationary policy.
|
|
||||||
// This is the single place that decides "is this worth waking the camera for",
|
|
||||||
// so tuning it in the field is one config push, not a firmware change.
|
|
||||||
bool radarIsTrigger(const RadarReading& r);
|
|
||||||
|
|
||||||
// Log raw bytes for a few seconds so you can confirm baud rate and framing
|
|
||||||
// when the hardware arrives. Blocking; bring-up only.
|
|
||||||
void radarSelfTest(uint32_t duration_ms = 5000);
|
|
||||||
|
|
||||||
// Enter/leave the module's configuration mode. Needed before any parameter
|
|
||||||
// write; the module stops reporting while in config mode.
|
|
||||||
bool radarEnterConfig();
|
|
||||||
bool radarExitConfig();
|
|
||||||
|
|
||||||
// Per-gate sensitivity. gate 0..8 (~0.75 m each), values 0..100.
|
|
||||||
// Only call between radarEnterConfig()/radarExitConfig().
|
|
||||||
bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary);
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
// net_mgr.h — WiFi association and clock.
|
|
||||||
//
|
|
||||||
// TIME (SPEC C7, and "timeserver is on endpoint")
|
|
||||||
// Two sources, in order of preference:
|
|
||||||
// 1. SNTP against the Pi. Cheap, standard, works before any HTTP call.
|
|
||||||
// 2. The `server_time` field every ingest/heartbeat response carries. This
|
|
||||||
// is the fallback that matters: if SNTP is blocked or the Pi is not
|
|
||||||
// running an NTP daemon after all, the device still converges on the
|
|
||||||
// endpoint's clock without extra configuration.
|
|
||||||
// Either way `received_at` on the Pi stays authoritative for ordering. The
|
|
||||||
// device timestamp is a hint, and it is explicitly 0 when unsynced rather than
|
|
||||||
// silently 1970.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
bool netBegin();
|
|
||||||
|
|
||||||
// Associate, with bounded retries and backoff. SPEC §4.3: never loop forever
|
|
||||||
// on a WiFi outage. Returns false after `max_attempts` failures; the caller
|
|
||||||
// decides whether that means sleep or retry later.
|
|
||||||
bool netConnect(uint8_t max_attempts = 3);
|
|
||||||
|
|
||||||
bool netIsConnected();
|
|
||||||
void netDisconnect();
|
|
||||||
|
|
||||||
// Start SNTP against ntp_host (or api_host if unset) and wait up to
|
|
||||||
// `timeout_ms` for the first sync.
|
|
||||||
bool netSyncTime(uint32_t timeout_ms = 5000);
|
|
||||||
|
|
||||||
// Accept the endpoint's clock from a response envelope. Only steps the RTC if
|
|
||||||
// we are unsynced or off by more than 2 s, so normal jitter does not cause a
|
|
||||||
// timestamp discontinuity mid-burst.
|
|
||||||
void netAdoptServerTime(int64_t server_ms);
|
|
||||||
|
|
||||||
bool netTimeValid();
|
|
||||||
int64_t netEpochMs(); // 0 when not yet synced — never a fake 1970 value
|
|
||||||
|
|
||||||
// "2026-09-20T14:31:07Z" into `out`. Empty string when unsynced.
|
|
||||||
void netIsoTime(char* out, size_t cap);
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
// nightlight.h — illuminator control and what the device does after dark.
|
|
||||||
//
|
|
||||||
// A HARDWARE WARNING WORTH READING BEFORE YOU BUY ANYTHING
|
|
||||||
// The obvious choice for a wildlife camera is an infrared illuminator (850 nm
|
|
||||||
// or 940 nm), because birds barely perceive it and white light at a feeder at
|
|
||||||
// night is disruptive. But the OV2640 module on the XIAO Sense ships with an
|
|
||||||
// **IR cut filter bonded over the sensor**, which blocks exactly those
|
|
||||||
// wavelengths. An IR LED on an unmodified Sense produces a black frame.
|
|
||||||
//
|
|
||||||
// So, three options, in the order I would try them:
|
|
||||||
// 1. Accept no night capture. Set night_behaviour = NIGHT_SLEEP. Most garden
|
|
||||||
// birds are diurnal; you lose very little and save the whole problem.
|
|
||||||
// 2. Warm, dim, continuous white light (NIGHTLIGHT_ALWAYS at low duty).
|
|
||||||
// Continuous is markedly better than a flash per burst: animals habituate
|
|
||||||
// to steady light and startle at sudden light. Still disturbs wildlife.
|
|
||||||
// 3. Remove the IR filter and use 850 nm. Best images, irreversible, and it
|
|
||||||
// wrecks daytime colour rendition unless you fit a switchable filter.
|
|
||||||
//
|
|
||||||
// The firmware supports all three. Option 2 is what NIGHTLIGHT_ON_BURST and
|
|
||||||
// NIGHTLIGHT_ALWAYS drive; option 3 needs no code change at all.
|
|
||||||
//
|
|
||||||
// NIGHT WINDOW
|
|
||||||
// `night_start_min` / `night_end_min` are minutes from local midnight. The Pi
|
|
||||||
// knows the site latitude, so the intended use is for it to push real
|
|
||||||
// sunset/sunrise daily via apply_config. The defaults (21:00-06:00) are a
|
|
||||||
// fallback for before that exists.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
void nightBegin();
|
|
||||||
|
|
||||||
// Is the current local time inside the configured night window?
|
|
||||||
// Always false while the clock is unsynced — better to capture pointless dark
|
|
||||||
// frames than to sleep through a day because the device thinks it is 03:00.
|
|
||||||
bool nightIsNight();
|
|
||||||
|
|
||||||
// Call every loop tick. Handles dusk/dawn transitions: swaps the camera
|
|
||||||
// profile, and drives the illuminator for NIGHTLIGHT_ALWAYS.
|
|
||||||
void nightTick();
|
|
||||||
|
|
||||||
// Bracket a capture burst. No-ops unless mode is NIGHTLIGHT_ON_BURST and it
|
|
||||||
// is actually night; includes the settle delay the sensor needs to adapt.
|
|
||||||
void nightIlluminateBurstBegin();
|
|
||||||
void nightIlluminateBurstEnd();
|
|
||||||
|
|
||||||
bool nightlightIsOn();
|
|
||||||
|
|
||||||
// Seconds until night_end_min, for NIGHT_SLEEP. 0 if it is not night.
|
|
||||||
uint32_t nightSecondsUntilMorning();
|
|
||||||
|
|
||||||
// Should the capture pipeline be running right now? False at night under
|
|
||||||
// NIGHT_IDLE and NIGHT_SLEEP.
|
|
||||||
bool nightCaptureAllowed();
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
// ota_mgr.h — OTA with SHA-256 verification and trial-boot rollback (SPEC C6).
|
|
||||||
//
|
|
||||||
// The rules from the spec, implemented here:
|
|
||||||
// - dual OTA slots exist from the first flash (partitions CSV)
|
|
||||||
// - verify SHA-256 of the downloaded image before activating the slot
|
|
||||||
// - boot the new image ONCE in a trial state
|
|
||||||
// - if the trial image cannot check in with the endpoint, roll back
|
|
||||||
// automatically on the next reset
|
|
||||||
// - never sleep mid-flash (INHIBIT_OTA)
|
|
||||||
//
|
|
||||||
// The battery gate from SPEC C6 is kept as a hook (`otaBatteryOkFn`) but has
|
|
||||||
// no default sensor: this build is mains-powered and the XIAO's battery-sense
|
|
||||||
// divider is not wired. Register a callback if that changes.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
struct OtaTarget {
|
|
||||||
char version[24];
|
|
||||||
char url[160]; // absolute, or a path relative to the API base
|
|
||||||
char sha256[65]; // lowercase hex
|
|
||||||
uint32_t size;
|
|
||||||
};
|
|
||||||
|
|
||||||
void otaBegin();
|
|
||||||
|
|
||||||
// True when this boot is the first run of a freshly flashed image and has not
|
|
||||||
// yet been confirmed. Until otaMarkValid() is called, a reset rolls back.
|
|
||||||
bool otaPendingVerify();
|
|
||||||
|
|
||||||
// Call once the device has proven the new image works — we use "a heartbeat
|
|
||||||
// was accepted by the endpoint", which exercises WiFi, HTTP, auth and config
|
|
||||||
// in one go. Anything less and a firmware that boots but cannot talk would be
|
|
||||||
// marked good.
|
|
||||||
void otaMarkValid();
|
|
||||||
|
|
||||||
// Give up on the trial image and reboot into the previous slot.
|
|
||||||
void otaRollback(const char* reason);
|
|
||||||
|
|
||||||
// Is `target.version` different from what we are running?
|
|
||||||
bool otaIsNewer(const OtaTarget& target);
|
|
||||||
|
|
||||||
// Download, verify, activate, reboot. Blocks for the duration. Returns only on
|
|
||||||
// failure — on success the device restarts into the new slot.
|
|
||||||
// Holds INHIBIT_OTA for the whole operation.
|
|
||||||
bool otaApply(const OtaTarget& target);
|
|
||||||
|
|
||||||
// Optional battery gate (SPEC C6: refuse to flash below a threshold).
|
|
||||||
typedef bool (*OtaBatteryOkFn)(uint8_t min_pct);
|
|
||||||
void otaSetBatteryCheck(OtaBatteryOkFn fn, uint8_t min_pct);
|
|
||||||
|
|
||||||
const char* otaRunningVersion();
|
|
||||||
const char* otaRunningPartition();
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
// power_mgr.h — the deep-sleep on/off switch and everything it interferes with.
|
|
||||||
//
|
|
||||||
// TWO MODES, ONE FLAG (`g_cfg.deep_sleep_enabled`, pushable from the WebUI)
|
|
||||||
//
|
|
||||||
// AWAKE (default, mains powered)
|
|
||||||
// Camera stays initialised, the PSRAM ring holds ~10 s of pre-trigger
|
|
||||||
// history, commands execute within a loop tick, streaming works on demand.
|
|
||||||
// This is the mode that makes good bird photos.
|
|
||||||
//
|
|
||||||
// SLEEP (battery / solar)
|
|
||||||
// Wake on the LD2410 OUT pin (EXT1) or the timer, capture a post-trigger
|
|
||||||
// burst, upload, drain the command queue, sleep again.
|
|
||||||
// You give up, unavoidably:
|
|
||||||
// - the pre-trigger ring: the camera is off, so there is no history.
|
|
||||||
// Back to SPEC C4's 1-3 s latency; expect to miss fast arrivals.
|
|
||||||
// - on-demand streaming: a stream_start command is only seen at the next
|
|
||||||
// wake. The device then holds itself awake for the session and sleeps
|
|
||||||
// after (see powerInhibit below).
|
|
||||||
// - command latency: worst case equals deep_sleep_s (SPEC C1).
|
|
||||||
//
|
|
||||||
// HONEST NOTE ON WHAT DEEP SLEEP ACTUALLY SAVES HERE
|
|
||||||
// The XIAO ESP32S3 sleeps at tens of µA, but the LD2410 draws roughly 80 mA
|
|
||||||
// continuously and must stay powered to act as a wake source. So with
|
|
||||||
// sleep_wake_on_radar = true, system current is dominated by the radar and the
|
|
||||||
// ESP sleeping buys you very little. Deep sleep is only a real power win if you
|
|
||||||
// either (a) set sleep_wake_on_radar = false and wake on the timer alone, with
|
|
||||||
// the radar power-gated via PIN_RADAR_EN, or (b) fit a low-quiescent PIR such
|
|
||||||
// as the AM312 on PIN_AUX_ADC as the wake source and use the radar only for
|
|
||||||
// confirmation once awake. The switch is implemented either way; this is a
|
|
||||||
// wiring decision, not a firmware one.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
enum WakeCause : uint8_t {
|
|
||||||
WAKE_POWER_ON = 0, // cold boot, or reset
|
|
||||||
WAKE_RADAR = 1, // EXT1 on the LD2410 OUT pin
|
|
||||||
WAKE_TIMER = 2,
|
|
||||||
WAKE_OTHER = 3,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reasons the device must not sleep right now. Refcounted, so nested holders
|
|
||||||
// (a stream inside a wake_and_hold, say) cannot cut each other short.
|
|
||||||
enum SleepInhibit : uint8_t {
|
|
||||||
INHIBIT_BOOT = 0, // released once the first heartbeat succeeds
|
|
||||||
INHIBIT_UPLOAD = 1,
|
|
||||||
INHIBIT_STREAM = 2, // the "stream interferes with sleep" case
|
|
||||||
INHIBIT_OTA = 3, // sleeping mid-flash bricks the device (SPEC C6)
|
|
||||||
INHIBIT_HOLD = 4, // wake_and_hold command
|
|
||||||
INHIBIT_COUNT
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reads the wake cause and restores the counters kept in RTC memory.
|
|
||||||
// Call first in setup(), before anything else looks at boot state.
|
|
||||||
void powerBegin();
|
|
||||||
|
|
||||||
WakeCause powerWakeCause();
|
|
||||||
const char* powerWakeCauseName();
|
|
||||||
uint32_t powerBootCount(); // survives deep sleep, resets on power loss
|
|
||||||
uint32_t powerLastSleepSeconds(); // how long the most recent sleep lasted
|
|
||||||
uint32_t powerTotalSleepSeconds(); // cumulative since power-on
|
|
||||||
|
|
||||||
// Is sleeping permitted at all right now, ignoring the idle timer?
|
|
||||||
//
|
|
||||||
// This is where streaming and sleeping are reconciled. A sleeping device
|
|
||||||
// cannot be told to start a stream (SPEC C1), so with `stream_blocks_sleep`
|
|
||||||
// set — the default — merely *enabling* streaming keeps the device awake and
|
|
||||||
// reachable, whether or not a session is running. Clear that flag to let it
|
|
||||||
// sleep anyway and accept that `stream_start` waits for the next wake.
|
|
||||||
//
|
|
||||||
// Returns false, with a reason, when: deep sleep is switched off, streaming
|
|
||||||
// is enabled and blocks sleep, or an inhibit is held.
|
|
||||||
bool powerSleepAllowed();
|
|
||||||
const char* powerSleepBlockedReason();
|
|
||||||
|
|
||||||
// Sleep inhibits. Always pair them; prefer the RAII guard below.
|
|
||||||
void powerInhibit(SleepInhibit reason);
|
|
||||||
void powerRelease(SleepInhibit reason);
|
|
||||||
bool powerIsInhibited();
|
|
||||||
const char* powerInhibitSummary(); // for logs and heartbeats
|
|
||||||
|
|
||||||
struct SleepGuard {
|
|
||||||
SleepInhibit r;
|
|
||||||
explicit SleepGuard(SleepInhibit reason) : r(reason) { powerInhibit(r); }
|
|
||||||
~SleepGuard() { powerRelease(r); }
|
|
||||||
};
|
|
||||||
|
|
||||||
// Mark that something worth staying awake for just happened. Resets the idle
|
|
||||||
// timer, so a busy feeder keeps the device up instead of thrashing sleep/wake.
|
|
||||||
void powerNoteActivity();
|
|
||||||
|
|
||||||
// Hold awake for at least `seconds` (the wake_and_hold command).
|
|
||||||
void powerHoldAwake(uint32_t seconds);
|
|
||||||
|
|
||||||
// Would the next powerMaybeSleep() actually sleep? Lets the caller do the
|
|
||||||
// things that must happen before the radio goes off — a final status push,
|
|
||||||
// say — without doing them on every loop tick.
|
|
||||||
bool powerWouldSleepNow();
|
|
||||||
|
|
||||||
// Called every loop tick. Sleeps if, and only if:
|
|
||||||
// deep_sleep_enabled && no inhibit && idle longer than sleep_idle_timeout_s
|
|
||||||
// Returns false if it decided to stay awake; does not return if it slept.
|
|
||||||
bool powerMaybeSleep();
|
|
||||||
|
|
||||||
// Sleep now regardless of the idle timer, but still never while inhibited.
|
|
||||||
// `seconds` == 0 uses g_cfg.deep_sleep_s. Used by the `sleep_now` command and
|
|
||||||
// by the "every failure path ends in sleep" rule of SPEC §4.3.
|
|
||||||
void powerSleepNow(uint32_t seconds = 0);
|
|
||||||
|
|
||||||
// Sleep through the night (NIGHT_SLEEP). Unlike powerSleepNow() this works
|
|
||||||
// even when deep_sleep_enabled is false, because "sleep at night" is a
|
|
||||||
// separate decision from "sleep between events" — a mains-powered camera
|
|
||||||
// still has no reason to be awake at 03:00 with no illuminator fitted.
|
|
||||||
// Never wakes on the radar: the point is to ignore the night, not to
|
|
||||||
// photograph every cat that walks past. No-op if it is not night.
|
|
||||||
void powerSleepUntilMorning();
|
|
||||||
|
|
||||||
// True while the device is running in SLEEP mode. Other subsystems consult
|
|
||||||
// this to decide whether the ring buffer is worth maintaining.
|
|
||||||
bool powerSleepModeActive();
|
|
||||||
|
|
||||||
// Applies a change to deep_sleep_enabled that arrived from the endpoint.
|
|
||||||
// Turning sleep ON never takes effect instantly: the device first finishes the
|
|
||||||
// current wake so the ack for the config command still reaches the Pi.
|
|
||||||
void powerOnConfigChanged(bool was_enabled);
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
// stream_session.h — time-boxed MJPEG push (SPEC C9).
|
|
||||||
//
|
|
||||||
// WHAT IS BUILT
|
|
||||||
// The full path: a `stream_start` command opens a chunked POST to the Pi, the
|
|
||||||
// device pushes JPEGs at the configured rate and resolution, and the session
|
|
||||||
// ends itself at the duration cap. Mode (watch / record / both) rides in a
|
|
||||||
// header; what the Pi does with the bytes is the Pi's decision, so the device
|
|
||||||
// never needs to change when you add recording or a public relay.
|
|
||||||
//
|
|
||||||
// WHAT IS NOT BUILT
|
|
||||||
// Anything outward-facing. Per SPEC C3 the ESP32 never serves a stream and is
|
|
||||||
// never reachable from outside the LAN; relaying to a browser or to a public
|
|
||||||
// domain is the Pi's job (MediaMTX, or plain MJPEG passthrough).
|
|
||||||
//
|
|
||||||
// INTERACTION WITH DEEP SLEEP
|
|
||||||
// A session holds INHIBIT_STREAM, so the device cannot sleep underneath it.
|
|
||||||
// In SLEEP mode a stream_start command is only seen at the next wake; the
|
|
||||||
// device then serves the session and sleeps once it ends. That latency is
|
|
||||||
// inherent (SPEC C1), not a gap in the implementation.
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
bool streamActive();
|
|
||||||
|
|
||||||
// Start a session. `session_id` comes from the endpoint so both sides agree on
|
|
||||||
// a name for it. Overrides are optional: 0 means "use the configured value".
|
|
||||||
bool streamStart(const char* session_id,
|
|
||||||
uint8_t mode_override = 0xFF,
|
|
||||||
uint8_t framesize_override = 0,
|
|
||||||
uint16_t duration_override = 0);
|
|
||||||
|
|
||||||
// Pump one frame if it is time. Call from the main loop; cheap when idle.
|
|
||||||
// Ends the session automatically at the duration cap.
|
|
||||||
void streamTick();
|
|
||||||
|
|
||||||
void streamStop(const char* reason);
|
|
||||||
|
|
||||||
uint32_t streamFramesSent();
|
|
||||||
uint32_t streamSecondsLeft();
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
# poorBird partition table — 8 MB flash, dual OTA slots + rollback (SPEC C6)
|
|
||||||
#
|
|
||||||
# Two app slots of 3.1 MB each. This MUST be right on the very first flash:
|
|
||||||
# retrofitting OTA onto a device that is already mounted outdoors means taking
|
|
||||||
# it down and reflashing over USB.
|
|
||||||
#
|
|
||||||
# Name, Type, SubType, Offset, Size, Flags
|
|
||||||
nvs, data, nvs, 0x9000, 0x5000,
|
|
||||||
otadata, data, ota, 0xE000, 0x2000,
|
|
||||||
app0, app, ota_0, 0x10000, 0x330000,
|
|
||||||
app1, app, ota_1, 0x340000, 0x330000,
|
|
||||||
spiffs, data, spiffs, 0x670000, 0x180000,
|
|
||||||
coredump, data, coredump, 0x7F0000, 0x10000,
|
|
||||||
|
@@ -1,78 +0,0 @@
|
|||||||
; poorBird - ESP32-S3 camera node
|
|
||||||
; Board: Seeed Studio XIAO ESP32S3 Sense (ESP32-S3R8, 8 MB flash, 8 MB PSRAM, OV2640)
|
|
||||||
;
|
|
||||||
; PLATFORM NOTE
|
|
||||||
; The official `espressif32` platform in the PlatformIO registry lags well behind
|
|
||||||
; Arduino-ESP32 3.x / ESP-IDF 5.x and has poor ESP32-S3 support. The community fork
|
|
||||||
; `pioarduino` is what current S3 work uses.
|
|
||||||
;
|
|
||||||
; The pin below (53.03.13 = Arduino core 3.1.x / IDF 5.3) is chosen to match
|
|
||||||
; PlatformIO Core 6.1.x. The `stable` release alias now requires Core >= 6.2.0;
|
|
||||||
; if you upgrade Core, you can switch to:
|
|
||||||
; https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip
|
|
||||||
|
|
||||||
[platformio]
|
|
||||||
default_envs = xiao_s3_sense
|
|
||||||
|
|
||||||
; ---------------------------------------------------------------------------
|
|
||||||
; Everything you are likely to edit lives in [common]. Secrets belong in
|
|
||||||
; secrets.ini (gitignored) - see secrets.ini.example.
|
|
||||||
; ---------------------------------------------------------------------------
|
|
||||||
[common]
|
|
||||||
fw_version = 0.1.0
|
|
||||||
|
|
||||||
build_flags =
|
|
||||||
-DFW_VERSION=\"${common.fw_version}\"
|
|
||||||
-DHW_REVISION=\"xiao-esp32s3-sense-ld2410\"
|
|
||||||
-DCORE_DEBUG_LEVEL=3
|
|
||||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
|
||||||
-DARDUINO_USB_MODE=1
|
|
||||||
-DBOARD_HAS_PSRAM
|
|
||||||
; --- camera defaults (runtime-overridable from the endpoint) ----------
|
|
||||||
; Use the enum SYMBOLS, never the numbers: esp32-camera has inserted
|
|
||||||
; entries into framesize_t between releases, so a literal index silently
|
|
||||||
; changes resolution after a driver update.
|
|
||||||
-DCFG_FRAME_SIZE=FRAMESIZE_SVGA ; 800x600 stills
|
|
||||||
-DCFG_STREAM_FRAME_SIZE=FRAMESIZE_VGA ; 640x480 while streaming
|
|
||||||
-DCFG_JPEG_QUALITY=12 ; 4..40, lower = better = bigger
|
|
||||||
; --- pre-trigger ring buffer (the reason mains power is worth it) -----
|
|
||||||
-DCFG_RING_FRAMES=24 ; PSRAM history depth
|
|
||||||
-DCFG_PRE_ROLL=4 ; frames sent from *before* the trigger
|
|
||||||
-DCFG_POST_ROLL=6 ; frames sent after the trigger
|
|
||||||
; --- ops --------------------------------------------------------------
|
|
||||||
-DCFG_HEARTBEAT_S=300
|
|
||||||
-DCFG_COOLDOWN_S=5
|
|
||||||
|
|
||||||
; ---------------------------------------------------------------------------
|
|
||||||
[env:xiao_s3_sense]
|
|
||||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.13/platform-espressif32.zip
|
|
||||||
board = seeed_xiao_esp32s3
|
|
||||||
framework = arduino
|
|
||||||
|
|
||||||
board_build.partitions = partitions/poorbird_8mb_ota.csv
|
|
||||||
board_build.flash_mode = qio
|
|
||||||
board_upload.flash_size = 8MB
|
|
||||||
|
|
||||||
; PSRAM is mandatory: the frame ring and the camera framebuffers both live there.
|
|
||||||
board_build.arduino.memory_type = qio_opi
|
|
||||||
|
|
||||||
monitor_speed = 115200
|
|
||||||
monitor_filters = esp32_exception_decoder, time
|
|
||||||
|
|
||||||
lib_deps =
|
|
||||||
bblanchon/ArduinoJson @ ^7.2.0
|
|
||||||
|
|
||||||
build_flags =
|
|
||||||
${common.build_flags}
|
|
||||||
|
|
||||||
extra_scripts = pre:scripts/load_secrets.py
|
|
||||||
|
|
||||||
; ---------------------------------------------------------------------------
|
|
||||||
; Same firmware, verbose logging - for bring-up on the bench.
|
|
||||||
[env:xiao_s3_sense_debug]
|
|
||||||
extends = env:xiao_s3_sense
|
|
||||||
build_type = debug
|
|
||||||
build_flags =
|
|
||||||
${common.build_flags}
|
|
||||||
-DCORE_DEBUG_LEVEL=5
|
|
||||||
-DPB_VERBOSE_RADAR=1
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
"""Inject secrets.ini into the build as -D flags.
|
|
||||||
|
|
||||||
Keeps WiFi credentials and the enrollment secret out of git and out of
|
|
||||||
platformio.ini. Copy secrets.ini.example to secrets.ini and fill it in; the
|
|
||||||
build works without the file, it just produces an unconfigured device that
|
|
||||||
cannot associate.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import configparser
|
|
||||||
import os
|
|
||||||
|
|
||||||
Import("env") # noqa: F821 (provided by SCons/PlatformIO)
|
|
||||||
|
|
||||||
SECRETS = os.path.join(env.subst("$PROJECT_DIR"), "secrets.ini") # noqa: F821
|
|
||||||
|
|
||||||
# key in secrets.ini -> build flag. Strings are quoted, numbers are not.
|
|
||||||
STRING_KEYS = {
|
|
||||||
"wifi_ssid": "CFG_WIFI_SSID",
|
|
||||||
"wifi_pass": "CFG_WIFI_PASS",
|
|
||||||
"api_host": "CFG_API_HOST",
|
|
||||||
"enroll_secret": "CFG_ENROLL_SECRET",
|
|
||||||
"tz": "CFG_TZ",
|
|
||||||
}
|
|
||||||
NUMERIC_KEYS = {
|
|
||||||
"api_port": "CFG_API_PORT",
|
|
||||||
"deep_sleep": "CFG_DEEP_SLEEP",
|
|
||||||
}
|
|
||||||
|
|
||||||
if not os.path.isfile(SECRETS):
|
|
||||||
print("load_secrets: no secrets.ini found — building with defaults.")
|
|
||||||
print(" copy secrets.ini.example to secrets.ini before flashing.")
|
|
||||||
else:
|
|
||||||
parser = configparser.ConfigParser()
|
|
||||||
parser.read(SECRETS)
|
|
||||||
if not parser.has_section("secrets"):
|
|
||||||
raise SystemExit("load_secrets: secrets.ini has no [secrets] section")
|
|
||||||
|
|
||||||
flags = []
|
|
||||||
for key, macro in STRING_KEYS.items():
|
|
||||||
if parser.has_option("secrets", key):
|
|
||||||
value = parser.get("secrets", key)
|
|
||||||
flags.append(f'-D{macro}=\\"{value}\\"')
|
|
||||||
for key, macro in NUMERIC_KEYS.items():
|
|
||||||
if parser.has_option("secrets", key):
|
|
||||||
flags.append(f"-D{macro}={parser.get('secrets', key)}")
|
|
||||||
|
|
||||||
env.Append(CPPDEFINES=[]) # noqa: F821
|
|
||||||
env.Append(BUILD_FLAGS=flags) # noqa: F821
|
|
||||||
|
|
||||||
# Do not print the values themselves.
|
|
||||||
print(f"load_secrets: applied {len(flags)} flag(s) from secrets.ini")
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
; Copy to secrets.ini (which is gitignored) and fill in.
|
|
||||||
;
|
|
||||||
; Only three of these really matter for a first flash: the WiFi credentials,
|
|
||||||
; the Pi's address, and the enrollment secret. Everything else the device
|
|
||||||
; learns from the endpoint after it enrolls.
|
|
||||||
|
|
||||||
[secrets]
|
|
||||||
wifi_ssid = YourNetwork
|
|
||||||
wifi_pass = YourPassword
|
|
||||||
|
|
||||||
; The endpoint — a Pi, a thin client, a NUC, a VM; the firmware does not care.
|
|
||||||
; Use a DHCP reservation and hardcode the address: mDNS on an ESP32 is one
|
|
||||||
; more thing that can fail silently at 4 a.m. (SPEC §9).
|
|
||||||
api_host = 192.168.1.50
|
|
||||||
api_port = 8080
|
|
||||||
|
|
||||||
; Bootstrap provisioning secret, shared with the endpoint. The device trades
|
|
||||||
; it for a bearer token plus a per-device re-enrollment secret on first boot,
|
|
||||||
; and keeps the latter so a token rotation heals itself without a USB cable.
|
|
||||||
; Generate with: openssl rand -hex 32
|
|
||||||
;
|
|
||||||
; It stays compiled into the image as a last-resort recovery path, so do not
|
|
||||||
; rotate it server-side without also shipping new firmware.
|
|
||||||
enroll_secret = replace-me
|
|
||||||
|
|
||||||
; POSIX TZ. Central Europe with DST.
|
|
||||||
tz = CET-1CEST,M3.5.0,M10.5.0/3
|
|
||||||
|
|
||||||
; 0 = stay awake (mains, pre-trigger ring, streaming works)
|
|
||||||
; 1 = deep sleep between events (battery; see power_mgr.h for the trade-offs)
|
|
||||||
; This is only the *initial* value — the endpoint can flip it at runtime.
|
|
||||||
deep_sleep = 0
|
|
||||||
@@ -1,583 +0,0 @@
|
|||||||
#include "api_client.h"
|
|
||||||
|
|
||||||
#include <WiFi.h>
|
|
||||||
#include <esp_http_client.h>
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "battery.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
#include "device_stats.h"
|
|
||||||
#include "ld2410.h"
|
|
||||||
#include "net_mgr.h"
|
|
||||||
#include "nightlight.h"
|
|
||||||
#include "power_mgr.h"
|
|
||||||
#include "stream_session.h"
|
|
||||||
|
|
||||||
static bool s_token_rejected = false;
|
|
||||||
static esp_http_client_handle_t s_stream = nullptr;
|
|
||||||
|
|
||||||
// One response buffer, reused. 4 KB comfortably holds an envelope with a
|
|
||||||
// handful of queued commands; anything larger is a server-side bug.
|
|
||||||
static const size_t kRespCap = 4096;
|
|
||||||
static char s_resp[kRespCap];
|
|
||||||
|
|
||||||
void apiBegin() { s_token_rejected = false; }
|
|
||||||
bool apiTokenRejected() { return s_token_rejected; }
|
|
||||||
|
|
||||||
static String url(const char* path) { return apiBaseUrl() + path; }
|
|
||||||
|
|
||||||
static void setAuth(esp_http_client_handle_t c) {
|
|
||||||
char bearer[80];
|
|
||||||
snprintf(bearer, sizeof(bearer), "Bearer %s", g_cfg.device_token);
|
|
||||||
esp_http_client_set_header(c, "Authorization", bearer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Headers present on every device request, so the Pi can spot a device that
|
|
||||||
// is behind on config or firmware without the device having to ask.
|
|
||||||
static void setCommonHeaders(esp_http_client_handle_t c) {
|
|
||||||
char buf[24];
|
|
||||||
esp_http_client_set_header(c, "X-Device-Uid", deviceUid());
|
|
||||||
esp_http_client_set_header(c, "X-Fw-Version", FW_VERSION);
|
|
||||||
esp_http_client_set_header(c, "X-Hw-Revision", HW_REVISION);
|
|
||||||
snprintf(buf, sizeof(buf), "%u", (unsigned)g_cfg.config_version);
|
|
||||||
esp_http_client_set_header(c, "X-Config-Version", buf);
|
|
||||||
snprintf(buf, sizeof(buf), "%d", WiFi.RSSI());
|
|
||||||
esp_http_client_set_header(c, "X-Rssi", buf);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read the body into s_resp. Returns bytes read, or -1.
|
|
||||||
static int readBody(esp_http_client_handle_t c) {
|
|
||||||
int len = esp_http_client_read_response(c, s_resp, kRespCap - 1);
|
|
||||||
if (len < 0) return -1;
|
|
||||||
s_resp[len] = '\0';
|
|
||||||
return len;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Shared response handling: pull the envelope fields out and fan the command
|
|
||||||
// array out to the handler. Used identically by ingest and heartbeat, which is
|
|
||||||
// the whole reason the two endpoints return the same shape (SPEC §4.1).
|
|
||||||
static void parseEnvelope(ServerEnvelope& env, int body_len, CommandHandler on_cmd) {
|
|
||||||
if (body_len <= 0) return;
|
|
||||||
|
|
||||||
JsonDocument doc;
|
|
||||||
DeserializationError err = deserializeJson(doc, s_resp, body_len);
|
|
||||||
if (err) {
|
|
||||||
log_w("response is not JSON: %s", err.c_str());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
env.server_time_ms = doc["server_time"] | (int64_t)0;
|
|
||||||
env.config_version = doc["config_version"] | (uint32_t)0;
|
|
||||||
|
|
||||||
JsonObjectConst fw = doc["firmware"];
|
|
||||||
if (!fw.isNull() && fw["version"].is<const char*>()) {
|
|
||||||
env.has_firmware = true;
|
|
||||||
strncpy(env.fw_version, fw["version"] | "", sizeof(env.fw_version) - 1);
|
|
||||||
strncpy(env.fw_url, fw["url"] | "", sizeof(env.fw_url) - 1);
|
|
||||||
strncpy(env.fw_sha256, fw["sha256"] | "", sizeof(env.fw_sha256) - 1);
|
|
||||||
env.fw_size = fw["size"] | (uint32_t)0;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonArrayConst cmds = doc["commands"];
|
|
||||||
if (!cmds.isNull()) {
|
|
||||||
for (JsonObjectConst cmd : cmds) {
|
|
||||||
env.command_count++;
|
|
||||||
if (on_cmd) on_cmd(cmd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Enrollment
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// One enrollment attempt with a specific secret.
|
|
||||||
static bool enrollWith(const char* secret, const char* which) {
|
|
||||||
if (!secret || !secret[0]) return false;
|
|
||||||
|
|
||||||
JsonDocument body;
|
|
||||||
body["device_uid"] = deviceUid();
|
|
||||||
body["device_name"] = g_cfg.device_name;
|
|
||||||
body["hw_revision"] = HW_REVISION;
|
|
||||||
body["fw_version"] = FW_VERSION;
|
|
||||||
body["mac"] = WiFi.macAddress();
|
|
||||||
|
|
||||||
String payload;
|
|
||||||
serializeJson(body, payload);
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url("/enroll");
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_POST;
|
|
||||||
cfg.timeout_ms = 8000;
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
|
||||||
esp_http_client_set_header(c, "X-Enroll-Secret", secret);
|
|
||||||
setCommonHeaders(c);
|
|
||||||
|
|
||||||
bool ok = false;
|
|
||||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
|
||||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
|
||||||
esp_http_client_fetch_headers(c);
|
|
||||||
int status = esp_http_client_get_status_code(c);
|
|
||||||
int len = readBody(c);
|
|
||||||
|
|
||||||
if (status == 200 || status == 201) {
|
|
||||||
JsonDocument doc;
|
|
||||||
if (!deserializeJson(doc, s_resp, len > 0 ? len : 0)) {
|
|
||||||
const char* tok = doc["token"] | "";
|
|
||||||
if (strlen(tok) > 0) {
|
|
||||||
strncpy(g_cfg.device_token, tok, sizeof(g_cfg.device_token) - 1);
|
|
||||||
g_cfg.device_token[sizeof(g_cfg.device_token) - 1] = '\0';
|
|
||||||
|
|
||||||
// Upgrade the shared bootstrap secret to a per-device one
|
|
||||||
// if the endpoint offers it. That keeps re-enrollment
|
|
||||||
// self-service without leaving a credential on the device
|
|
||||||
// that could enroll *other* identities.
|
|
||||||
const char* re = doc["reenroll_secret"] | "";
|
|
||||||
if (strlen(re) > 0) {
|
|
||||||
strncpy(g_cfg.enroll_secret, re, sizeof(g_cfg.enroll_secret) - 1);
|
|
||||||
g_cfg.enroll_secret[sizeof(g_cfg.enroll_secret) - 1] = '\0';
|
|
||||||
log_i("enrolled via %s: token + per-device re-enrollment secret stored", which);
|
|
||||||
} else {
|
|
||||||
// Endpoint does not implement it. Keep the secret we
|
|
||||||
// used rather than wiping it — a device that cannot
|
|
||||||
// re-enroll after a token rotation is a device that
|
|
||||||
// needs a ladder.
|
|
||||||
strncpy(g_cfg.enroll_secret, secret, sizeof(g_cfg.enroll_secret) - 1);
|
|
||||||
g_cfg.enroll_secret[sizeof(g_cfg.enroll_secret) - 1] = '\0';
|
|
||||||
log_i("enrolled via %s: token stored (endpoint sent no re-enrollment secret)", which);
|
|
||||||
}
|
|
||||||
|
|
||||||
configSave();
|
|
||||||
s_token_rejected = false;
|
|
||||||
ok = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log_w("enroll via %s rejected: HTTP %d", which, status);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log_e("enroll: cannot reach %s", u.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool apiEnroll() {
|
|
||||||
if (g_cfg.device_token[0]) return true;
|
|
||||||
|
|
||||||
// Stored secret first: after the first enrollment this is the per-device
|
|
||||||
// one, so a token rotation in the admin UI heals itself on the next
|
|
||||||
// request with no physical access.
|
|
||||||
if (enrollWith(g_cfg.enroll_secret, "stored secret")) return true;
|
|
||||||
|
|
||||||
// Last resort: the shared bootstrap secret compiled into the image. This
|
|
||||||
// is the escape hatch for a device whose stored secret has been
|
|
||||||
// invalidated — rotating the shared secret server-side without also
|
|
||||||
// reflashing is what would strand it, so don't do that.
|
|
||||||
const char* boot = configBootstrapSecret();
|
|
||||||
if (boot[0] && strcmp(boot, g_cfg.enroll_secret) != 0) {
|
|
||||||
log_w("enroll: stored secret failed, trying the compiled-in bootstrap secret");
|
|
||||||
if (enrollWith(boot, "bootstrap secret")) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!g_cfg.enroll_secret[0] && !boot[0]) {
|
|
||||||
log_e("not enrolled and no secret available — set enroll_secret in secrets.ini");
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Ingest — raw JPEG body, metadata in headers
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
ServerEnvelope apiIngest(const FrameCopy& frame, const CaptureMeta& meta, CommandHandler on_cmd) {
|
|
||||||
ServerEnvelope env = {};
|
|
||||||
if (!frame.data || frame.len == 0) return env;
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url("/ingest");
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_POST;
|
|
||||||
cfg.timeout_ms = 15000; // a 60 KB JPEG over marginal WiFi is not instant
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
esp_http_client_set_header(c, "Content-Type", "image/jpeg");
|
|
||||||
setAuth(c);
|
|
||||||
setCommonHeaders(c);
|
|
||||||
|
|
||||||
char b[32];
|
|
||||||
esp_http_client_set_header(c, "X-Trigger", meta.trigger);
|
|
||||||
esp_http_client_set_header(c, "X-Burst-Id", meta.burst_id);
|
|
||||||
snprintf(b, sizeof(b), "%u", meta.burst_index); esp_http_client_set_header(c, "X-Burst-Index", b);
|
|
||||||
snprintf(b, sizeof(b), "%u", meta.burst_count); esp_http_client_set_header(c, "X-Burst-Count", b);
|
|
||||||
snprintf(b, sizeof(b), "%d", meta.pre_trigger); esp_http_client_set_header(c, "X-Pre-Trigger", b);
|
|
||||||
snprintf(b, sizeof(b), "%lld", (long long)frame.at_epoch);
|
|
||||||
esp_http_client_set_header(c, "X-Captured-At", b); // ms since epoch, UTC, 0 if unsynced
|
|
||||||
snprintf(b, sizeof(b), "%u", (unsigned)frame.seq); esp_http_client_set_header(c, "X-Frame-Seq", b);
|
|
||||||
snprintf(b, sizeof(b), "%u", meta.radar_distance_cm); esp_http_client_set_header(c, "X-Radar-Distance-Cm", b);
|
|
||||||
snprintf(b, sizeof(b), "%u", meta.radar_energy); esp_http_client_set_header(c, "X-Radar-Energy", b);
|
|
||||||
snprintf(b, sizeof(b), "%u", meta.radar_state); esp_http_client_set_header(c, "X-Radar-State", b);
|
|
||||||
|
|
||||||
if (esp_http_client_open(c, frame.len) == ESP_OK) {
|
|
||||||
int written = esp_http_client_write(c, (const char*)frame.data, frame.len);
|
|
||||||
if (written == (int)frame.len) {
|
|
||||||
esp_http_client_fetch_headers(c);
|
|
||||||
env.http_status = esp_http_client_get_status_code(c);
|
|
||||||
int len = readBody(c);
|
|
||||||
|
|
||||||
if (env.http_status == 401) {
|
|
||||||
s_token_rejected = true;
|
|
||||||
log_w("ingest: 401, token rotated or revoked");
|
|
||||||
} else if (env.http_status >= 200 && env.http_status < 300) {
|
|
||||||
env.ok = true;
|
|
||||||
parseEnvelope(env, len, on_cmd);
|
|
||||||
} else {
|
|
||||||
log_w("ingest: HTTP %d", env.http_status);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log_w("ingest: short write %d of %u", written, (unsigned)frame.len);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log_w("ingest: connect failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
return env;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Device conditions
|
|
||||||
//
|
|
||||||
// One body, two endpoints: /heartbeat (returns the command envelope) and
|
|
||||||
// /status (returns 204, no commands). Built in one place so the two can never
|
|
||||||
// drift apart and the endpoint only has to parse one shape.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static void buildConditions(JsonDocument& body, const char* reason) {
|
|
||||||
statsRollover();
|
|
||||||
const DeviceStats st = statsGet();
|
|
||||||
const BatteryReading bt = batteryLast();
|
|
||||||
const RadarReading rd = radarLast();
|
|
||||||
|
|
||||||
body["reason"] = reason;
|
|
||||||
body["fw_version"] = FW_VERSION;
|
|
||||||
body["hw_revision"] = HW_REVISION;
|
|
||||||
body["config_version"] = g_cfg.config_version;
|
|
||||||
|
|
||||||
// --- uptime and sleep ---------------------------------------------------
|
|
||||||
JsonObject p = body["power"].to<JsonObject>();
|
|
||||||
p["uptime_ms"] = (uint32_t)millis();
|
|
||||||
p["awake_ms"] = statsAwakeMs(); // ticks since the last sleep
|
|
||||||
p["boot_count"] = powerBootCount();
|
|
||||||
p["wake_cause"] = powerWakeCauseName();
|
|
||||||
p["last_sleep_s"] = powerLastSleepSeconds();
|
|
||||||
p["total_sleep_s"] = powerTotalSleepSeconds();
|
|
||||||
p["sleep_enabled"] = g_cfg.deep_sleep_enabled;
|
|
||||||
p["sleep_allowed"] = powerSleepAllowed();
|
|
||||||
p["inhibits"] = powerInhibitSummary();
|
|
||||||
|
|
||||||
// --- battery ------------------------------------------------------------
|
|
||||||
// `valid: false` means no divider is wired. The endpoint should render
|
|
||||||
// that as "not measured", never as 0 V — a low-battery alarm that fires
|
|
||||||
// because a sensor is absent is worse than no alarm.
|
|
||||||
JsonObject b = body["battery"].to<JsonObject>();
|
|
||||||
b["valid"] = bt.valid;
|
|
||||||
b["mv"] = bt.mv;
|
|
||||||
b["pct"] = bt.pct;
|
|
||||||
b["raw_mv"] = bt.raw_mv;
|
|
||||||
b["chemistry"] = g_cfg.battery_chemistry;
|
|
||||||
b["low"] = bt.valid && g_cfg.battery_chemistry != BATT_NONE &&
|
|
||||||
bt.pct < g_cfg.battery_warn_pct;
|
|
||||||
|
|
||||||
// --- counters -----------------------------------------------------------
|
|
||||||
// Reset on power cycle, not on reboot-from-sleep. The endpoint's own count
|
|
||||||
// is authoritative; these are the device's view, useful mainly as a
|
|
||||||
// delivery-gap detector (captured_today >> delivered_today = upload trouble).
|
|
||||||
JsonObject c = body["counters"].to<JsonObject>();
|
|
||||||
c["captured_today"] = st.captured_today;
|
|
||||||
c["delivered_today"] = st.delivered_today;
|
|
||||||
c["failed_today"] = st.failed_today;
|
|
||||||
c["events_today"] = st.events_today;
|
|
||||||
c["day_index"] = st.day_index;
|
|
||||||
c["captured_boot"] = st.captured_boot;
|
|
||||||
c["delivered_boot"] = st.delivered_boot;
|
|
||||||
|
|
||||||
// --- camera / night -----------------------------------------------------
|
|
||||||
uint16_t cw = 0, ch = 0;
|
|
||||||
framesizeDims(g_cfg.frame_size, &cw, &ch);
|
|
||||||
JsonObject cam = body["camera"].to<JsonObject>();
|
|
||||||
cam["frame_size"] = framesizeName(g_cfg.frame_size); // name, not index
|
|
||||||
cam["frame_size_id"] = g_cfg.frame_size;
|
|
||||||
cam["width"] = cw;
|
|
||||||
cam["height"] = ch;
|
|
||||||
cam["jpeg_quality"] = g_cfg.jpeg_quality;
|
|
||||||
cam["profile"] = cameraNightProfileActive() ? "night" : "day";
|
|
||||||
cam["ready"] = cameraReady();
|
|
||||||
// Sensor PID identifies what is actually fitted: 0x2640 OV2640,
|
|
||||||
// 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have shipped with
|
|
||||||
// OV3660 rather than OV2640, so do not assume.
|
|
||||||
sensor_t* sens = esp_camera_sensor_get();
|
|
||||||
cam["sensor_pid"] = sens ? sens->id.PID : 0;
|
|
||||||
|
|
||||||
JsonObject n = body["night"].to<JsonObject>();
|
|
||||||
n["is_night"] = nightIsNight();
|
|
||||||
n["nightlight_on"] = nightlightIsOn();
|
|
||||||
n["behaviour"] = g_cfg.night_behaviour;
|
|
||||||
n["capture_allowed"] = nightCaptureAllowed();
|
|
||||||
|
|
||||||
// --- stream -------------------------------------------------------------
|
|
||||||
JsonObject s = body["stream"].to<JsonObject>();
|
|
||||||
s["enabled"] = g_cfg.stream_enabled;
|
|
||||||
s["active"] = streamActive();
|
|
||||||
s["frames_sent"] = streamFramesSent();
|
|
||||||
s["seconds_left"] = streamSecondsLeft();
|
|
||||||
|
|
||||||
// --- radar --------------------------------------------------------------
|
|
||||||
JsonObject r = body["radar"].to<JsonObject>();
|
|
||||||
r["baud"] = radarBaud(); // 0 = no frames decoded at any baud
|
|
||||||
r["uart_ok"] = rd.valid;
|
|
||||||
r["out_pin"] = rd.out_pin;
|
|
||||||
r["state"] = rd.target;
|
|
||||||
r["moving_cm"] = rd.moving_cm;
|
|
||||||
r["moving_energy"] = rd.moving_energy;
|
|
||||||
r["stationary_cm"] = rd.stationary_cm;
|
|
||||||
r["stationary_energy"] = rd.stationary_energy;
|
|
||||||
|
|
||||||
// --- network / memory ---------------------------------------------------
|
|
||||||
JsonObject sys = body["system"].to<JsonObject>();
|
|
||||||
sys["rssi"] = WiFi.RSSI();
|
|
||||||
sys["ip"] = WiFi.localIP().toString();
|
|
||||||
sys["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
|
||||||
sys["free_psram"] = (uint32_t)ESP.getFreePsram();
|
|
||||||
sys["ring_depth"] = (uint32_t)ringCount();
|
|
||||||
sys["ring_bytes"] = (uint32_t)ringBytesUsed();
|
|
||||||
|
|
||||||
char iso[32];
|
|
||||||
netIsoTime(iso, sizeof(iso));
|
|
||||||
body["time_synced"] = netTimeValid();
|
|
||||||
body["device_time"] = iso; // empty string when unsynced
|
|
||||||
}
|
|
||||||
|
|
||||||
bool apiPostStatus(const char* reason) {
|
|
||||||
JsonDocument body;
|
|
||||||
buildConditions(body, reason);
|
|
||||||
|
|
||||||
String payload;
|
|
||||||
serializeJson(body, payload);
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url("/status");
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_POST;
|
|
||||||
cfg.timeout_ms = 6000;
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
|
||||||
setAuth(c);
|
|
||||||
setCommonHeaders(c);
|
|
||||||
|
|
||||||
bool ok = false;
|
|
||||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
|
||||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
|
||||||
esp_http_client_fetch_headers(c);
|
|
||||||
int st = esp_http_client_get_status_code(c);
|
|
||||||
readBody(c);
|
|
||||||
if (st == 401) s_token_rejected = true;
|
|
||||||
ok = (st >= 200 && st < 300);
|
|
||||||
if (!ok) log_w("status: HTTP %d", st);
|
|
||||||
} else {
|
|
||||||
log_w("status: connect failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
ServerEnvelope apiHeartbeat(CommandHandler on_cmd) {
|
|
||||||
ServerEnvelope env = {};
|
|
||||||
|
|
||||||
JsonDocument body;
|
|
||||||
buildConditions(body, "heartbeat");
|
|
||||||
|
|
||||||
String payload;
|
|
||||||
serializeJson(body, payload);
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url("/heartbeat");
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_POST;
|
|
||||||
cfg.timeout_ms = 8000;
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
|
||||||
setAuth(c);
|
|
||||||
setCommonHeaders(c);
|
|
||||||
|
|
||||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
|
||||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
|
||||||
esp_http_client_fetch_headers(c);
|
|
||||||
env.http_status = esp_http_client_get_status_code(c);
|
|
||||||
int len = readBody(c);
|
|
||||||
|
|
||||||
if (env.http_status == 401) {
|
|
||||||
s_token_rejected = true;
|
|
||||||
} else if (env.http_status >= 200 && env.http_status < 300) {
|
|
||||||
env.ok = true;
|
|
||||||
parseEnvelope(env, len, on_cmd);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
return env;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
bool apiFetchConfig() {
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url("/config");
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_GET;
|
|
||||||
cfg.timeout_ms = 8000;
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
setAuth(c);
|
|
||||||
setCommonHeaders(c);
|
|
||||||
|
|
||||||
bool changed = false;
|
|
||||||
if (esp_http_client_open(c, 0) == ESP_OK) {
|
|
||||||
esp_http_client_fetch_headers(c);
|
|
||||||
int status = esp_http_client_get_status_code(c);
|
|
||||||
int len = readBody(c);
|
|
||||||
if (status == 401) s_token_rejected = true;
|
|
||||||
if (status >= 200 && status < 300 && len > 0) {
|
|
||||||
JsonDocument doc;
|
|
||||||
if (!deserializeJson(doc, s_resp, len)) {
|
|
||||||
changed = configApplyJson(doc.as<JsonObjectConst>());
|
|
||||||
if (changed) {
|
|
||||||
configSave();
|
|
||||||
log_i("config updated to version %u", g_cfg.config_version);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
return changed;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool apiAckCommand(uint32_t command_id, const char* status, const char* detail) {
|
|
||||||
JsonDocument body;
|
|
||||||
body["status"] = status;
|
|
||||||
body["detail"] = detail ? detail : "";
|
|
||||||
|
|
||||||
String payload;
|
|
||||||
serializeJson(body, payload);
|
|
||||||
|
|
||||||
char path[64];
|
|
||||||
snprintf(path, sizeof(path), "/commands/%u/ack", (unsigned)command_id);
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url(path);
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_POST;
|
|
||||||
cfg.timeout_ms = 6000;
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
|
||||||
setAuth(c);
|
|
||||||
setCommonHeaders(c);
|
|
||||||
|
|
||||||
bool ok = false;
|
|
||||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
|
||||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
|
||||||
esp_http_client_fetch_headers(c);
|
|
||||||
int st = esp_http_client_get_status_code(c);
|
|
||||||
readBody(c);
|
|
||||||
ok = (st >= 200 && st < 300);
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Stream push — chunked multipart/x-mixed-replace, device -> Pi.
|
|
||||||
//
|
|
||||||
// The device pushes and the Pi relays (SPEC C3: the ESP32 is never reachable
|
|
||||||
// from outside the LAN, and here not even from outside the Pi). The Pi decides
|
|
||||||
// per X-Stream-Mode whether to relay to viewers, write to disk, or both.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static const char* kBoundary = "poorbirdframe";
|
|
||||||
|
|
||||||
bool apiStreamOpen(const char* session_id, uint8_t mode, uint16_t duration_s) {
|
|
||||||
if (s_stream) apiStreamClose();
|
|
||||||
|
|
||||||
char path[96];
|
|
||||||
snprintf(path, sizeof(path), "/stream/%s", session_id);
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
String u = url(path);
|
|
||||||
cfg.url = u.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_POST;
|
|
||||||
cfg.timeout_ms = 10000;
|
|
||||||
|
|
||||||
s_stream = esp_http_client_init(&cfg);
|
|
||||||
esp_http_client_set_header(s_stream, "Content-Type",
|
|
||||||
"multipart/x-mixed-replace; boundary=" "poorbirdframe");
|
|
||||||
setAuth(s_stream);
|
|
||||||
setCommonHeaders(s_stream);
|
|
||||||
|
|
||||||
const char* mode_s = (mode == 1) ? "record" : (mode == 2) ? "both" : "watch";
|
|
||||||
esp_http_client_set_header(s_stream, "X-Stream-Mode", mode_s);
|
|
||||||
|
|
||||||
char b[16];
|
|
||||||
snprintf(b, sizeof(b), "%u", duration_s);
|
|
||||||
esp_http_client_set_header(s_stream, "X-Duration-S", b);
|
|
||||||
|
|
||||||
// -1 == chunked transfer encoding: we do not know the total length.
|
|
||||||
if (esp_http_client_open(s_stream, -1) != ESP_OK) {
|
|
||||||
log_e("stream: cannot open %s", u.c_str());
|
|
||||||
esp_http_client_cleanup(s_stream);
|
|
||||||
s_stream = nullptr;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_i("stream %s open, mode=%s, cap %us", session_id, mode_s, duration_s);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool apiStreamSendFrame(const uint8_t* jpeg, size_t len, int64_t epoch_ms) {
|
|
||||||
if (!s_stream || !jpeg || len == 0) return false;
|
|
||||||
|
|
||||||
char head[192];
|
|
||||||
int hl = snprintf(head, sizeof(head),
|
|
||||||
"\r\n--%s\r\n"
|
|
||||||
"Content-Type: image/jpeg\r\n"
|
|
||||||
"Content-Length: %u\r\n"
|
|
||||||
"X-Timestamp: %lld\r\n\r\n",
|
|
||||||
kBoundary, (unsigned)len, (long long)epoch_ms);
|
|
||||||
|
|
||||||
if (esp_http_client_write(s_stream, head, hl) != hl) return false;
|
|
||||||
return esp_http_client_write(s_stream, (const char*)jpeg, len) == (int)len;
|
|
||||||
}
|
|
||||||
|
|
||||||
void apiStreamClose() {
|
|
||||||
if (!s_stream) return;
|
|
||||||
char tail[64];
|
|
||||||
int tl = snprintf(tail, sizeof(tail), "\r\n--%s--\r\n", kBoundary);
|
|
||||||
esp_http_client_write(s_stream, tail, tl);
|
|
||||||
|
|
||||||
esp_http_client_fetch_headers(s_stream);
|
|
||||||
int st = esp_http_client_get_status_code(s_stream);
|
|
||||||
esp_http_client_close(s_stream);
|
|
||||||
esp_http_client_cleanup(s_stream);
|
|
||||||
s_stream = nullptr;
|
|
||||||
log_i("stream closed, HTTP %d", st);
|
|
||||||
}
|
|
||||||
@@ -1,475 +0,0 @@
|
|||||||
#include "app_config.h"
|
|
||||||
|
|
||||||
#include <Preferences.h>
|
|
||||||
#include <esp_camera.h>
|
|
||||||
#include <esp_mac.h>
|
|
||||||
|
|
||||||
#include "board_pins.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
|
|
||||||
AppConfig g_cfg;
|
|
||||||
|
|
||||||
static Preferences s_nvs;
|
|
||||||
static const char* kNamespace = "poorbird";
|
|
||||||
static char s_uid[13] = {0};
|
|
||||||
|
|
||||||
// Compile-time fallbacks. Anything secret comes in via secrets.ini, never here.
|
|
||||||
#ifndef CFG_WIFI_SSID
|
|
||||||
#define CFG_WIFI_SSID ""
|
|
||||||
#endif
|
|
||||||
#ifndef CFG_WIFI_PASS
|
|
||||||
#define CFG_WIFI_PASS ""
|
|
||||||
#endif
|
|
||||||
#ifndef CFG_API_HOST
|
|
||||||
#define CFG_API_HOST "192.168.1.50"
|
|
||||||
#endif
|
|
||||||
#ifndef CFG_API_PORT
|
|
||||||
#define CFG_API_PORT 8080
|
|
||||||
#endif
|
|
||||||
#ifndef CFG_ENROLL_SECRET
|
|
||||||
#define CFG_ENROLL_SECRET ""
|
|
||||||
#endif
|
|
||||||
#ifndef CFG_TZ
|
|
||||||
#define CFG_TZ "CET-1CEST,M3.5.0,M10.5.0/3"
|
|
||||||
#endif
|
|
||||||
#ifndef CFG_DEEP_SLEEP
|
|
||||||
#define CFG_DEEP_SLEEP 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
static void setStr(char* dst, size_t cap, const char* src) {
|
|
||||||
strncpy(dst, src ? src : "", cap - 1);
|
|
||||||
dst[cap - 1] = '\0';
|
|
||||||
}
|
|
||||||
|
|
||||||
static void loadDefaults(AppConfig& c) {
|
|
||||||
memset(&c, 0, sizeof(c));
|
|
||||||
|
|
||||||
setStr(c.device_name, sizeof(c.device_name), "poorbird-cam-1");
|
|
||||||
setStr(c.wifi_ssid, sizeof(c.wifi_ssid), CFG_WIFI_SSID);
|
|
||||||
setStr(c.wifi_pass, sizeof(c.wifi_pass), CFG_WIFI_PASS);
|
|
||||||
setStr(c.api_host, sizeof(c.api_host), CFG_API_HOST);
|
|
||||||
c.api_port = CFG_API_PORT;
|
|
||||||
setStr(c.api_base, sizeof(c.api_base), "/api/v1");
|
|
||||||
setStr(c.device_token, sizeof(c.device_token), "");
|
|
||||||
setStr(c.enroll_secret, sizeof(c.enroll_secret), CFG_ENROLL_SECRET);
|
|
||||||
|
|
||||||
setStr(c.ntp_host, sizeof(c.ntp_host), ""); // empty => api_host
|
|
||||||
setStr(c.tz, sizeof(c.tz), CFG_TZ);
|
|
||||||
|
|
||||||
c.frame_size = CFG_FRAME_SIZE;
|
|
||||||
c.jpeg_quality = CFG_JPEG_QUALITY;
|
|
||||||
c.vflip = false;
|
|
||||||
c.hmirror = false;
|
|
||||||
|
|
||||||
// Day: everything automatic, exposure biased up for birds backlit against
|
|
||||||
// sky, gain capped at 4x so the sensor prefers a short shutter over a
|
|
||||||
// noisy one. Motion blur is the enemy, not noise.
|
|
||||||
c.cam_day.brightness = 0;
|
|
||||||
c.cam_day.contrast = 1;
|
|
||||||
c.cam_day.saturation = 0;
|
|
||||||
c.cam_day.sharpness = 0;
|
|
||||||
c.cam_day.ae_level = 1;
|
|
||||||
c.cam_day.special_effect = 0;
|
|
||||||
c.cam_day.wb_mode = 0; // auto
|
|
||||||
c.cam_day.gainceiling = 1; // 4x
|
|
||||||
c.cam_day.agc_gain = 0;
|
|
||||||
c.cam_day.aec_value = 300;
|
|
||||||
c.cam_day.whitebal = true;
|
|
||||||
c.cam_day.awb_gain = true;
|
|
||||||
c.cam_day.exposure_ctrl = true;
|
|
||||||
c.cam_day.aec2 = true;
|
|
||||||
c.cam_day.gain_ctrl = true;
|
|
||||||
c.cam_day.bpc = true;
|
|
||||||
c.cam_day.wpc = true;
|
|
||||||
c.cam_day.raw_gma = true;
|
|
||||||
c.cam_day.lenc = true;
|
|
||||||
c.cam_day.dcw = true;
|
|
||||||
c.cam_day.colorbar = false;
|
|
||||||
|
|
||||||
// Night: the trade reverses. A noisy identifiable bird beats a clean black
|
|
||||||
// rectangle, so the gain ceiling goes up and saturation comes down
|
|
||||||
// (colour under artificial light is wrong anyway).
|
|
||||||
c.cam_night = c.cam_day;
|
|
||||||
c.cam_night.brightness = 1;
|
|
||||||
c.cam_night.contrast = 0;
|
|
||||||
c.cam_night.saturation = -1;
|
|
||||||
c.cam_night.ae_level = 2;
|
|
||||||
c.cam_night.gainceiling = 4; // 32x
|
|
||||||
|
|
||||||
c.ring_frames = CFG_RING_FRAMES;
|
|
||||||
c.pre_roll = CFG_PRE_ROLL;
|
|
||||||
c.post_roll = CFG_POST_ROLL;
|
|
||||||
c.post_roll_gap_ms = 250;
|
|
||||||
c.cooldown_s = CFG_COOLDOWN_S;
|
|
||||||
c.idle_period_ms = 400; // ~2.5 fps into the ring; ~10 s of history at depth 24
|
|
||||||
|
|
||||||
c.radar_mode = RADAR_BOTH;
|
|
||||||
c.accept_stationary = true;
|
|
||||||
c.min_distance_cm = 20;
|
|
||||||
c.max_distance_cm = 300; // a feeder at 1-3 m; widen after field testing
|
|
||||||
c.min_energy = 20;
|
|
||||||
c.radar_baud = 0; // autodetect
|
|
||||||
|
|
||||||
c.stream_enabled = false;
|
|
||||||
c.stream_frame_size = CFG_STREAM_FRAME_SIZE;
|
|
||||||
c.stream_jpeg_quality = 15;
|
|
||||||
c.stream_duration_s = 60; // SPEC C9: always time-boxed
|
|
||||||
c.stream_fps = 10;
|
|
||||||
c.stream_mode = STREAM_WATCH;
|
|
||||||
c.stream_blocks_sleep = true;
|
|
||||||
|
|
||||||
c.night_start_min = 21 * 60; // 21:00, overridden by pushed sunset
|
|
||||||
c.night_end_min = 6 * 60; // 06:00
|
|
||||||
c.night_behaviour = NIGHT_SLEEP; // most garden birds are diurnal
|
|
||||||
c.nightlight_mode = NIGHTLIGHT_OFF;
|
|
||||||
c.nightlight_brightness = 128;
|
|
||||||
|
|
||||||
c.battery_chemistry = BATT_NONE; // mains by default; no cell wired
|
|
||||||
c.battery_divider_x100 = 200; // two equal resistors
|
|
||||||
c.battery_offset_mv = 0;
|
|
||||||
c.battery_min_pct_ota = 50; // SPEC C6
|
|
||||||
c.battery_warn_pct = 20;
|
|
||||||
|
|
||||||
c.heartbeat_interval_s = CFG_HEARTBEAT_S;
|
|
||||||
c.status_interval_s = 900;
|
|
||||||
c.ota_enabled = true;
|
|
||||||
|
|
||||||
c.deep_sleep_enabled = CFG_DEEP_SLEEP; // 0 = mains powered, stay awake
|
|
||||||
c.deep_sleep_s = 300;
|
|
||||||
c.sleep_wake_on_radar = true;
|
|
||||||
c.sleep_idle_timeout_s = 20;
|
|
||||||
c.sleep_max_awake_s = 300;
|
|
||||||
|
|
||||||
c.config_version = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void configLoad() {
|
|
||||||
loadDefaults(g_cfg);
|
|
||||||
|
|
||||||
if (!s_nvs.begin(kNamespace, /*readOnly=*/true)) {
|
|
||||||
log_w("no NVS namespace yet, running on compile-time defaults");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stored as one blob. The size check means a struct change during
|
|
||||||
// development degrades to "fall back to defaults" instead of reading
|
|
||||||
// garbage into half the fields.
|
|
||||||
size_t stored = s_nvs.getBytesLength("cfg");
|
|
||||||
if (stored == sizeof(AppConfig)) {
|
|
||||||
AppConfig tmp;
|
|
||||||
s_nvs.getBytes("cfg", &tmp, sizeof(tmp));
|
|
||||||
g_cfg = tmp;
|
|
||||||
log_i("config loaded from NVS (version %u)", g_cfg.config_version);
|
|
||||||
} else if (stored > 0) {
|
|
||||||
log_w("NVS config is %u bytes, expected %u — layout changed, using defaults",
|
|
||||||
(unsigned)stored, (unsigned)sizeof(AppConfig));
|
|
||||||
}
|
|
||||||
s_nvs.end();
|
|
||||||
|
|
||||||
// Credentials are stored outside the blob so that a struct layout change
|
|
||||||
// during development never costs you the enrollment — which, on a device
|
|
||||||
// you cannot reach over USB, would mean a ladder.
|
|
||||||
if (s_nvs.begin(kNamespace, true)) {
|
|
||||||
String tok = s_nvs.getString("token", "");
|
|
||||||
if (tok.length()) setStr(g_cfg.device_token, sizeof(g_cfg.device_token), tok.c_str());
|
|
||||||
|
|
||||||
String sec = s_nvs.getString("enroll", "");
|
|
||||||
if (sec.length()) setStr(g_cfg.enroll_secret, sizeof(g_cfg.enroll_secret), sec.c_str());
|
|
||||||
s_nvs.end();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool configSave() {
|
|
||||||
if (!s_nvs.begin(kNamespace, /*readOnly=*/false)) {
|
|
||||||
log_e("NVS open for write failed");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
bool ok = s_nvs.putBytes("cfg", &g_cfg, sizeof(g_cfg)) == sizeof(g_cfg);
|
|
||||||
ok &= s_nvs.putString("token", g_cfg.device_token) >= 0;
|
|
||||||
ok &= s_nvs.putString("enroll", g_cfg.enroll_secret) >= 0;
|
|
||||||
s_nvs.end();
|
|
||||||
if (!ok) log_e("NVS write failed");
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- JSON merge -------------------------------------------------------------
|
|
||||||
// Helpers keep configApplyJson readable and make "only touch keys that are
|
|
||||||
// present" the default behaviour rather than something each field repeats.
|
|
||||||
|
|
||||||
#define MERGE_NUM(field, key) \
|
|
||||||
if (!doc[key].isNull()) { \
|
|
||||||
auto v = doc[key].as<decltype(g_cfg.field)>();\
|
|
||||||
if (v != g_cfg.field) { g_cfg.field = v; changed = true; } \
|
|
||||||
}
|
|
||||||
|
|
||||||
#define MERGE_BOOL(field, key) \
|
|
||||||
if (!doc[key].isNull()) { \
|
|
||||||
bool v = doc[key].as<bool>(); \
|
|
||||||
if (v != g_cfg.field) { g_cfg.field = v; changed = true; } \
|
|
||||||
}
|
|
||||||
|
|
||||||
#define MERGE_STR(field, key) \
|
|
||||||
if (!doc[key].isNull()) { \
|
|
||||||
const char* v = doc[key].as<const char*>(); \
|
|
||||||
if (v && strcmp(v, g_cfg.field) != 0) { \
|
|
||||||
setStr(g_cfg.field, sizeof(g_cfg.field), v); \
|
|
||||||
changed = true; \
|
|
||||||
} \
|
|
||||||
}
|
|
||||||
|
|
||||||
// A frame size may arrive as a name ("SVGA") or as a raw framesize_t index.
|
|
||||||
// Names are the supported form; the numeric path exists so an older endpoint
|
|
||||||
// keeps working, and because a number is unambiguous once you know the
|
|
||||||
// driver version.
|
|
||||||
static bool mergeFrameSize(uint8_t& field, JsonVariantConst v) {
|
|
||||||
if (v.isNull()) return false;
|
|
||||||
|
|
||||||
uint8_t next = field;
|
|
||||||
if (v.is<const char*>()) {
|
|
||||||
next = framesizeFromName(v.as<const char*>(), field);
|
|
||||||
} else if (v.is<unsigned int>() || v.is<int>()) {
|
|
||||||
int n = v.as<int>();
|
|
||||||
if (n < 0 || n >= FRAMESIZE_INVALID) {
|
|
||||||
log_w("config: frame size index %d out of range, ignoring", n);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
next = (uint8_t)n;
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (next == field) return false;
|
|
||||||
field = next;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Camera tuning arrives as a nested object ("cam_day" / "cam_night") so the
|
|
||||||
// two profiles stay visually distinct in the endpoint's settings UI.
|
|
||||||
static bool mergeTuning(CamTuning& t, JsonObjectConst d) {
|
|
||||||
if (d.isNull()) return false;
|
|
||||||
bool changed = false;
|
|
||||||
|
|
||||||
#define T_NUM(field, key) \
|
|
||||||
if (!d[key].isNull()) { \
|
|
||||||
auto v = d[key].as<decltype(t.field)>(); \
|
|
||||||
if (v != t.field) { t.field = v; changed = true; } \
|
|
||||||
}
|
|
||||||
#define T_BOOL(field, key) \
|
|
||||||
if (!d[key].isNull()) { \
|
|
||||||
bool v = d[key].as<bool>(); \
|
|
||||||
if (v != t.field) { t.field = v; changed = true; } \
|
|
||||||
}
|
|
||||||
|
|
||||||
T_NUM(brightness, "brightness");
|
|
||||||
T_NUM(contrast, "contrast");
|
|
||||||
T_NUM(saturation, "saturation");
|
|
||||||
T_NUM(sharpness, "sharpness");
|
|
||||||
T_NUM(ae_level, "ae_level");
|
|
||||||
T_NUM(special_effect, "special_effect");
|
|
||||||
T_NUM(wb_mode, "wb_mode");
|
|
||||||
T_NUM(gainceiling, "gainceiling");
|
|
||||||
T_NUM(agc_gain, "agc_gain");
|
|
||||||
T_NUM(aec_value, "aec_value");
|
|
||||||
T_BOOL(whitebal, "whitebal");
|
|
||||||
T_BOOL(awb_gain, "awb_gain");
|
|
||||||
T_BOOL(exposure_ctrl, "exposure_ctrl");
|
|
||||||
T_BOOL(aec2, "aec2");
|
|
||||||
T_BOOL(gain_ctrl, "gain_ctrl");
|
|
||||||
T_BOOL(bpc, "bpc");
|
|
||||||
T_BOOL(wpc, "wpc");
|
|
||||||
T_BOOL(raw_gma, "raw_gma");
|
|
||||||
T_BOOL(lenc, "lenc");
|
|
||||||
T_BOOL(dcw, "dcw");
|
|
||||||
T_BOOL(colorbar, "colorbar");
|
|
||||||
|
|
||||||
#undef T_NUM
|
|
||||||
#undef T_BOOL
|
|
||||||
|
|
||||||
// Sensor ranges. Out-of-range values are rejected silently by the driver,
|
|
||||||
// which makes a typo in the settings UI look like the device ignored it.
|
|
||||||
if (t.brightness < -2) t.brightness = -2; if (t.brightness > 2) t.brightness = 2;
|
|
||||||
if (t.contrast < -2) t.contrast = -2; if (t.contrast > 2) t.contrast = 2;
|
|
||||||
if (t.saturation < -2) t.saturation = -2; if (t.saturation > 2) t.saturation = 2;
|
|
||||||
if (t.sharpness < -2) t.sharpness = -2; if (t.sharpness > 2) t.sharpness = 2;
|
|
||||||
if (t.ae_level < -2) t.ae_level = -2; if (t.ae_level > 2) t.ae_level = 2;
|
|
||||||
if (t.special_effect > 6) t.special_effect = 0;
|
|
||||||
if (t.wb_mode > 4) t.wb_mode = 0;
|
|
||||||
if (t.gainceiling > 6) t.gainceiling = 6;
|
|
||||||
if (t.agc_gain > 30) t.agc_gain = 30;
|
|
||||||
if (t.aec_value > 1200) t.aec_value = 1200;
|
|
||||||
|
|
||||||
return changed;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool configApplyJson(JsonObjectConst doc) {
|
|
||||||
bool changed = false;
|
|
||||||
|
|
||||||
MERGE_STR(device_name, "device_name");
|
|
||||||
MERGE_STR(api_host, "api_host");
|
|
||||||
MERGE_NUM(api_port, "api_port");
|
|
||||||
MERGE_STR(ntp_host, "ntp_host");
|
|
||||||
MERGE_STR(tz, "tz");
|
|
||||||
|
|
||||||
// Frame sizes accept "SVGA" or a raw index. Names are preferred and are
|
|
||||||
// what the settings UI should send — see framesizeFromName().
|
|
||||||
changed |= mergeFrameSize(g_cfg.frame_size, doc["frame_size"]);
|
|
||||||
changed |= mergeFrameSize(g_cfg.stream_frame_size, doc["stream_frame_size"]);
|
|
||||||
|
|
||||||
MERGE_NUM(jpeg_quality, "jpeg_quality");
|
|
||||||
MERGE_BOOL(vflip, "vflip");
|
|
||||||
MERGE_BOOL(hmirror, "hmirror");
|
|
||||||
|
|
||||||
changed |= mergeTuning(g_cfg.cam_day, doc["cam_day"]);
|
|
||||||
changed |= mergeTuning(g_cfg.cam_night, doc["cam_night"]);
|
|
||||||
|
|
||||||
MERGE_NUM(ring_frames, "ring_frames");
|
|
||||||
MERGE_NUM(pre_roll, "pre_roll");
|
|
||||||
MERGE_NUM(post_roll, "post_roll");
|
|
||||||
MERGE_NUM(post_roll_gap_ms, "post_roll_gap_ms");
|
|
||||||
MERGE_NUM(cooldown_s, "cooldown_s");
|
|
||||||
MERGE_NUM(idle_period_ms, "idle_period_ms");
|
|
||||||
|
|
||||||
MERGE_NUM(radar_mode, "radar_mode");
|
|
||||||
MERGE_BOOL(accept_stationary,"accept_stationary");
|
|
||||||
MERGE_NUM(min_distance_cm, "min_distance_cm");
|
|
||||||
MERGE_NUM(max_distance_cm, "max_distance_cm");
|
|
||||||
MERGE_NUM(min_energy, "min_energy");
|
|
||||||
MERGE_NUM(radar_baud, "radar_baud");
|
|
||||||
|
|
||||||
MERGE_BOOL(stream_enabled, "stream_enabled");
|
|
||||||
MERGE_NUM(stream_frame_size, "stream_frame_size");
|
|
||||||
MERGE_NUM(stream_jpeg_quality, "stream_jpeg_quality");
|
|
||||||
MERGE_NUM(stream_duration_s, "stream_duration_s");
|
|
||||||
MERGE_NUM(stream_fps, "stream_fps");
|
|
||||||
MERGE_NUM(stream_mode, "stream_mode");
|
|
||||||
MERGE_BOOL(stream_blocks_sleep,"stream_blocks_sleep");
|
|
||||||
|
|
||||||
MERGE_NUM(night_start_min, "night_start_min");
|
|
||||||
MERGE_NUM(night_end_min, "night_end_min");
|
|
||||||
MERGE_NUM(night_behaviour, "night_behaviour");
|
|
||||||
MERGE_NUM(nightlight_mode, "nightlight_mode");
|
|
||||||
MERGE_NUM(nightlight_brightness, "nightlight_brightness");
|
|
||||||
|
|
||||||
MERGE_NUM(battery_chemistry, "battery_chemistry");
|
|
||||||
MERGE_NUM(battery_divider_x100, "battery_divider_x100");
|
|
||||||
MERGE_NUM(battery_offset_mv, "battery_offset_mv");
|
|
||||||
MERGE_NUM(battery_min_pct_ota, "battery_min_pct_ota");
|
|
||||||
MERGE_NUM(battery_warn_pct, "battery_warn_pct");
|
|
||||||
|
|
||||||
MERGE_NUM(heartbeat_interval_s, "heartbeat_interval_s");
|
|
||||||
MERGE_NUM(status_interval_s, "status_interval_s");
|
|
||||||
MERGE_BOOL(ota_enabled, "ota_enabled");
|
|
||||||
|
|
||||||
MERGE_BOOL(deep_sleep_enabled, "deep_sleep_enabled");
|
|
||||||
MERGE_NUM(deep_sleep_s, "deep_sleep_s");
|
|
||||||
MERGE_BOOL(sleep_wake_on_radar, "sleep_wake_on_radar");
|
|
||||||
MERGE_NUM(sleep_idle_timeout_s, "sleep_idle_timeout_s");
|
|
||||||
MERGE_NUM(sleep_max_awake_s, "sleep_max_awake_s");
|
|
||||||
|
|
||||||
// Clamp the things that brick the device or the battery if the endpoint
|
|
||||||
// sends nonsense. The device is the last line of defence here, because a
|
|
||||||
// bad config push reaches a box that is mounted outdoors.
|
|
||||||
if (g_cfg.jpeg_quality < 4) g_cfg.jpeg_quality = 4;
|
|
||||||
if (g_cfg.jpeg_quality > 40) g_cfg.jpeg_quality = 40;
|
|
||||||
if (g_cfg.ring_frames < 2) g_cfg.ring_frames = 2;
|
|
||||||
if (g_cfg.ring_frames > 60) g_cfg.ring_frames = 60;
|
|
||||||
if (g_cfg.pre_roll >= g_cfg.ring_frames) g_cfg.pre_roll = g_cfg.ring_frames - 1;
|
|
||||||
if (g_cfg.stream_duration_s > 600) g_cfg.stream_duration_s = 600; // C9 hard cap
|
|
||||||
if (g_cfg.stream_fps < 1) g_cfg.stream_fps = 1;
|
|
||||||
if (g_cfg.stream_fps > 25) g_cfg.stream_fps = 25;
|
|
||||||
if (g_cfg.heartbeat_interval_s < 30) g_cfg.heartbeat_interval_s = 30;
|
|
||||||
if (g_cfg.idle_period_ms < 100) g_cfg.idle_period_ms = 100;
|
|
||||||
|
|
||||||
// Sleep floors. A device that sleeps too eagerly can become unreachable
|
|
||||||
// before it has drained the command queue that would turn sleep back off.
|
|
||||||
if (g_cfg.deep_sleep_s < 30) g_cfg.deep_sleep_s = 30;
|
|
||||||
if (g_cfg.deep_sleep_s > 3600) g_cfg.deep_sleep_s = 3600;
|
|
||||||
if (g_cfg.sleep_idle_timeout_s < 10) g_cfg.sleep_idle_timeout_s = 10;
|
|
||||||
if (g_cfg.sleep_max_awake_s < g_cfg.sleep_idle_timeout_s)
|
|
||||||
g_cfg.sleep_max_awake_s = g_cfg.sleep_idle_timeout_s;
|
|
||||||
|
|
||||||
if (g_cfg.night_start_min > 1439) g_cfg.night_start_min = 1439;
|
|
||||||
if (g_cfg.night_end_min > 1439) g_cfg.night_end_min = 1439;
|
|
||||||
if (g_cfg.night_behaviour > NIGHT_SLEEP) g_cfg.night_behaviour = NIGHT_CAPTURE;
|
|
||||||
if (g_cfg.nightlight_mode > NIGHTLIGHT_ALWAYS) g_cfg.nightlight_mode = NIGHTLIGHT_OFF;
|
|
||||||
|
|
||||||
if (g_cfg.battery_chemistry > BATT_LIFEPO4) g_cfg.battery_chemistry = BATT_NONE;
|
|
||||||
// A zero divider would report the pin voltage as the battery voltage and
|
|
||||||
// silently trip the OTA gate at the worst possible moment.
|
|
||||||
if (g_cfg.battery_divider_x100 < 100) g_cfg.battery_divider_x100 = 100;
|
|
||||||
if (g_cfg.battery_divider_x100 > 2000) g_cfg.battery_divider_x100 = 2000;
|
|
||||||
if (g_cfg.battery_min_pct_ota > 95) g_cfg.battery_min_pct_ota = 95;
|
|
||||||
|
|
||||||
// config_version last, so it only advances if the payload was processed.
|
|
||||||
if (!doc["config_version"].isNull()) {
|
|
||||||
uint32_t v = doc["config_version"].as<uint32_t>();
|
|
||||||
if (v != g_cfg.config_version) { g_cfg.config_version = v; changed = true; }
|
|
||||||
}
|
|
||||||
|
|
||||||
return changed;
|
|
||||||
}
|
|
||||||
|
|
||||||
#undef MERGE_NUM
|
|
||||||
#undef MERGE_BOOL
|
|
||||||
#undef MERGE_STR
|
|
||||||
|
|
||||||
bool configNeedsCameraRestart(const AppConfig& a, const AppConfig& b) {
|
|
||||||
// Frame size changes the framebuffer allocation, so it cannot be applied
|
|
||||||
// to a running sensor without tearing the driver down.
|
|
||||||
return a.frame_size != b.frame_size;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* configBootstrapSecret() { return CFG_ENROLL_SECRET; }
|
|
||||||
|
|
||||||
const char* deviceUid() {
|
|
||||||
if (s_uid[0]) return s_uid;
|
|
||||||
uint8_t mac[6] = {0};
|
|
||||||
esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
|
||||||
snprintf(s_uid, sizeof(s_uid), "%02x%02x%02x%02x%02x%02x",
|
|
||||||
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
|
||||||
return s_uid;
|
|
||||||
}
|
|
||||||
|
|
||||||
String apiBaseUrl() {
|
|
||||||
String u = "http://";
|
|
||||||
u += g_cfg.api_host;
|
|
||||||
u += ":";
|
|
||||||
u += String(g_cfg.api_port);
|
|
||||||
u += g_cfg.api_base;
|
|
||||||
return u;
|
|
||||||
}
|
|
||||||
|
|
||||||
void configDump() {
|
|
||||||
log_i("--- poorBird config ------------------------------");
|
|
||||||
log_i(" uid %s name %s", deviceUid(), g_cfg.device_name);
|
|
||||||
log_i(" fw %s cfg_version %u", FW_VERSION, g_cfg.config_version);
|
|
||||||
log_i(" endpoint %s", apiBaseUrl().c_str());
|
|
||||||
log_i(" enrolled %s", g_cfg.device_token[0] ? "yes" : "NO");
|
|
||||||
uint16_t cw = 0, ch = 0, sw = 0, sh = 0;
|
|
||||||
framesizeDims(g_cfg.frame_size, &cw, &ch);
|
|
||||||
framesizeDims(g_cfg.stream_frame_size, &sw, &sh);
|
|
||||||
log_i(" camera %s (%ux%u) quality=%u | stream %s (%ux%u)",
|
|
||||||
framesizeName(g_cfg.frame_size), cw, ch, g_cfg.jpeg_quality,
|
|
||||||
framesizeName(g_cfg.stream_frame_size), sw, sh);
|
|
||||||
log_i(" ring depth=%u pre=%u post=%u period=%ums",
|
|
||||||
g_cfg.ring_frames, g_cfg.pre_roll, g_cfg.post_roll, g_cfg.idle_period_ms);
|
|
||||||
log_i(" radar mode=%u window=%u..%ucm energy>=%u stationary=%d",
|
|
||||||
g_cfg.radar_mode, g_cfg.min_distance_cm, g_cfg.max_distance_cm,
|
|
||||||
g_cfg.min_energy, g_cfg.accept_stationary);
|
|
||||||
log_i(" stream enabled=%d mode=%u %us @%ufps size=%u",
|
|
||||||
g_cfg.stream_enabled, g_cfg.stream_mode, g_cfg.stream_duration_s,
|
|
||||||
g_cfg.stream_fps, g_cfg.stream_frame_size);
|
|
||||||
log_i(" night %02u:%02u-%02u:%02u behaviour=%u light=%u/%u",
|
|
||||||
g_cfg.night_start_min / 60, g_cfg.night_start_min % 60,
|
|
||||||
g_cfg.night_end_min / 60, g_cfg.night_end_min % 60,
|
|
||||||
g_cfg.night_behaviour, g_cfg.nightlight_mode, g_cfg.nightlight_brightness);
|
|
||||||
log_i(" battery chem=%u divider=%.2f:1 trim=%dmV ota_min=%u%%",
|
|
||||||
g_cfg.battery_chemistry, g_cfg.battery_divider_x100 / 100.0f,
|
|
||||||
g_cfg.battery_offset_mv, g_cfg.battery_min_pct_ota);
|
|
||||||
log_i(" heartbeat %us status %us ota=%d",
|
|
||||||
g_cfg.heartbeat_interval_s, g_cfg.status_interval_s, g_cfg.ota_enabled);
|
|
||||||
log_i(" power deep_sleep=%s wake_on_radar=%d every=%us idle=%us max_awake=%us",
|
|
||||||
g_cfg.deep_sleep_enabled ? "ON" : "off", g_cfg.sleep_wake_on_radar,
|
|
||||||
g_cfg.deep_sleep_s, g_cfg.sleep_idle_timeout_s, g_cfg.sleep_max_awake_s);
|
|
||||||
log_i("--------------------------------------------------");
|
|
||||||
}
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
#include "battery.h"
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "board_pins.h"
|
|
||||||
|
|
||||||
static BatteryReading s_last = {};
|
|
||||||
|
|
||||||
// Discharge curves, millivolts at 100/90/…/0 %. Both are open-circuit
|
|
||||||
// approximations at moderate load and room temperature; they are good enough
|
|
||||||
// to drive a "low battery" banner and the OTA gate, and not good enough to
|
|
||||||
// promise a runtime estimate.
|
|
||||||
static const uint16_t kLiIon[11] = {
|
|
||||||
4200, 4060, 3980, 3920, 3870, 3820, 3790, 3700, 3620, 3500, 3300
|
|
||||||
};
|
|
||||||
// LiFePO4 sits on a plateau near 3.2 V for most of its discharge. Percentage
|
|
||||||
// from voltage is genuinely unreliable here — treat anything between 20 % and
|
|
||||||
// 90 % as "somewhere in the middle" (SPEC §9 suggests this chemistry).
|
|
||||||
static const uint16_t kLiFePO4[11] = {
|
|
||||||
3650, 3350, 3320, 3300, 3280, 3260, 3240, 3220, 3200, 3100, 2800
|
|
||||||
};
|
|
||||||
|
|
||||||
static uint8_t pctFromCurve(const uint16_t* curve, uint16_t mv) {
|
|
||||||
if (mv >= curve[0]) return 100;
|
|
||||||
if (mv <= curve[10]) return 0;
|
|
||||||
for (int i = 0; i < 10; i++) {
|
|
||||||
if (mv <= curve[i] && mv > curve[i + 1]) {
|
|
||||||
const uint16_t hi = curve[i], lo = curve[i + 1];
|
|
||||||
const int top = 100 - i * 10;
|
|
||||||
return (uint8_t)(top - (10 * (hi - mv)) / (hi - lo));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void batteryBegin() {
|
|
||||||
#if PIN_BATTERY_ADC >= 0
|
|
||||||
analogSetPinAttenuation(PIN_BATTERY_ADC, ADC_11db); // full ~0-3.1 V range
|
|
||||||
#if PIN_BATTERY_EN >= 0
|
|
||||||
pinMode(PIN_BATTERY_EN, OUTPUT);
|
|
||||||
digitalWrite(PIN_BATTERY_EN, LOW); // divider off by default
|
|
||||||
#endif
|
|
||||||
log_i("battery: sensing on GPIO%d, divider %.2f:1",
|
|
||||||
PIN_BATTERY_ADC, g_cfg.battery_divider_x100 / 100.0f);
|
|
||||||
batteryPoll();
|
|
||||||
#else
|
|
||||||
log_i("battery: no sense pin configured, voltage will report as invalid");
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
BatteryReading batteryRead() {
|
|
||||||
BatteryReading r = {};
|
|
||||||
|
|
||||||
#if PIN_BATTERY_ADC < 0
|
|
||||||
return r; // not wired; valid stays false
|
|
||||||
#else
|
|
||||||
if (g_cfg.battery_divider_x100 == 0) return r;
|
|
||||||
|
|
||||||
#if PIN_BATTERY_EN >= 0
|
|
||||||
digitalWrite(PIN_BATTERY_EN, HIGH);
|
|
||||||
delayMicroseconds(200); // let the divider settle
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Average several samples: a single ESP32 ADC read is noisy enough to move
|
|
||||||
// the reported percentage by a point or two between calls.
|
|
||||||
uint32_t acc = 0;
|
|
||||||
const uint8_t samples = 16;
|
|
||||||
for (uint8_t i = 0; i < samples; i++) acc += analogReadMilliVolts(PIN_BATTERY_ADC);
|
|
||||||
|
|
||||||
#if PIN_BATTERY_EN >= 0
|
|
||||||
digitalWrite(PIN_BATTERY_EN, LOW);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
r.raw_mv = (uint16_t)(acc / samples);
|
|
||||||
|
|
||||||
int32_t mv = (int32_t)r.raw_mv * g_cfg.battery_divider_x100 / 100;
|
|
||||||
mv += g_cfg.battery_offset_mv;
|
|
||||||
if (mv < 0) mv = 0;
|
|
||||||
r.mv = (uint16_t)mv;
|
|
||||||
r.valid = true;
|
|
||||||
|
|
||||||
switch (g_cfg.battery_chemistry) {
|
|
||||||
case BATT_LIION: r.pct = pctFromCurve(kLiIon, r.mv); break;
|
|
||||||
case BATT_LIFEPO4: r.pct = pctFromCurve(kLiFePO4, r.mv); break;
|
|
||||||
default: r.pct = 0; break; // BATT_NONE: voltage only
|
|
||||||
}
|
|
||||||
return r;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void batteryPoll() {
|
|
||||||
BatteryReading r = batteryRead();
|
|
||||||
if (r.valid) s_last = r;
|
|
||||||
}
|
|
||||||
|
|
||||||
BatteryReading batteryLast() { return s_last; }
|
|
||||||
|
|
||||||
bool batteryAboveOtaThreshold(uint8_t min_pct) {
|
|
||||||
BatteryReading r = batteryRead();
|
|
||||||
|
|
||||||
// No sensing hardware, or no chemistry configured, means we cannot judge.
|
|
||||||
// Allow the flash: this build is mains-powered by default, and refusing
|
|
||||||
// every OTA because an optional sensor is absent would be worse than the
|
|
||||||
// risk it guards against. Wire the divider if you want the gate to bite.
|
|
||||||
if (!r.valid || g_cfg.battery_chemistry == BATT_NONE) {
|
|
||||||
log_w("battery: no reading, OTA battery gate not enforced");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (r.pct < min_pct) {
|
|
||||||
log_w("battery: %u%% (%umV) is below the %u%% OTA threshold",
|
|
||||||
r.pct, r.mv, min_pct);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
#include "camera_mgr.h"
|
|
||||||
|
|
||||||
#include <strings.h> // strcasecmp
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "board_pins.h"
|
|
||||||
|
|
||||||
static bool s_ready = false;
|
|
||||||
|
|
||||||
// Built from the enum symbols rather than literal indices, so this table
|
|
||||||
// cannot drift when esp32-camera renumbers framesize_t.
|
|
||||||
struct FsName { framesize_t fs; const char* name; };
|
|
||||||
static const FsName kFsNames[] = {
|
|
||||||
{FRAMESIZE_96X96, "96X96"}, {FRAMESIZE_QQVGA, "QQVGA"},
|
|
||||||
{FRAMESIZE_128X128, "128X128"}, {FRAMESIZE_QCIF, "QCIF"},
|
|
||||||
{FRAMESIZE_HQVGA, "HQVGA"}, {FRAMESIZE_240X240, "240X240"},
|
|
||||||
{FRAMESIZE_QVGA, "QVGA"}, {FRAMESIZE_320X320, "320X320"},
|
|
||||||
{FRAMESIZE_CIF, "CIF"}, {FRAMESIZE_HVGA, "HVGA"},
|
|
||||||
{FRAMESIZE_VGA, "VGA"}, {FRAMESIZE_SVGA, "SVGA"},
|
|
||||||
{FRAMESIZE_XGA, "XGA"}, {FRAMESIZE_HD, "HD"},
|
|
||||||
{FRAMESIZE_SXGA, "SXGA"}, {FRAMESIZE_UXGA, "UXGA"},
|
|
||||||
{FRAMESIZE_FHD, "FHD"}, {FRAMESIZE_QXGA, "QXGA"},
|
|
||||||
{FRAMESIZE_QHD, "QHD"}, {FRAMESIZE_WQXGA, "WQXGA"},
|
|
||||||
{FRAMESIZE_QSXGA, "QSXGA"}, {FRAMESIZE_5MP, "5MP"},
|
|
||||||
};
|
|
||||||
|
|
||||||
uint8_t framesizeFromName(const char* name, uint8_t fallback) {
|
|
||||||
if (!name || !name[0]) return fallback;
|
|
||||||
for (const FsName& e : kFsNames) {
|
|
||||||
if (strcasecmp(name, e.name) == 0) return (uint8_t)e.fs;
|
|
||||||
}
|
|
||||||
log_w("camera: unknown frame size '%s', keeping %s", name, framesizeName(fallback));
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* framesizeName(uint8_t fs) {
|
|
||||||
for (const FsName& e : kFsNames) {
|
|
||||||
if ((uint8_t)e.fs == fs) return e.name;
|
|
||||||
}
|
|
||||||
return "?";
|
|
||||||
}
|
|
||||||
|
|
||||||
void framesizeDims(uint8_t fs, uint16_t* w, uint16_t* h) {
|
|
||||||
if (w) *w = 0;
|
|
||||||
if (h) *h = 0;
|
|
||||||
if (fs >= FRAMESIZE_INVALID) return;
|
|
||||||
// resolution[] is the driver's own table, so these always match reality.
|
|
||||||
if (w) *w = resolution[fs].width;
|
|
||||||
if (h) *h = resolution[fs].height;
|
|
||||||
}
|
|
||||||
|
|
||||||
static camera_config_t buildConfig() {
|
|
||||||
camera_config_t c = {};
|
|
||||||
c.ledc_channel = LEDC_CHANNEL_0;
|
|
||||||
c.ledc_timer = LEDC_TIMER_0;
|
|
||||||
c.pin_d0 = CAM_PIN_D0;
|
|
||||||
c.pin_d1 = CAM_PIN_D1;
|
|
||||||
c.pin_d2 = CAM_PIN_D2;
|
|
||||||
c.pin_d3 = CAM_PIN_D3;
|
|
||||||
c.pin_d4 = CAM_PIN_D4;
|
|
||||||
c.pin_d5 = CAM_PIN_D5;
|
|
||||||
c.pin_d6 = CAM_PIN_D6;
|
|
||||||
c.pin_d7 = CAM_PIN_D7;
|
|
||||||
c.pin_xclk = CAM_PIN_XCLK;
|
|
||||||
c.pin_pclk = CAM_PIN_PCLK;
|
|
||||||
c.pin_vsync = CAM_PIN_VSYNC;
|
|
||||||
c.pin_href = CAM_PIN_HREF;
|
|
||||||
c.pin_sccb_sda = CAM_PIN_SIOD;
|
|
||||||
c.pin_sccb_scl = CAM_PIN_SIOC;
|
|
||||||
c.pin_pwdn = CAM_PIN_PWDN;
|
|
||||||
c.pin_reset = CAM_PIN_RESET;
|
|
||||||
c.xclk_freq_hz = 20000000;
|
|
||||||
c.pixel_format = PIXFORMAT_JPEG;
|
|
||||||
c.frame_size = (framesize_t)g_cfg.frame_size;
|
|
||||||
c.jpeg_quality = g_cfg.jpeg_quality;
|
|
||||||
|
|
||||||
// Two framebuffers in PSRAM with CAM_GRAB_LATEST: the driver keeps
|
|
||||||
// capturing while we are busy copying the previous frame into the ring,
|
|
||||||
// and a grab always returns the newest frame rather than a queued stale
|
|
||||||
// one. On a trigger, "newest" is what you want.
|
|
||||||
c.fb_location = CAMERA_FB_IN_PSRAM;
|
|
||||||
c.fb_count = 2;
|
|
||||||
c.grab_mode = CAMERA_GRAB_LATEST;
|
|
||||||
return c;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool cameraBegin() {
|
|
||||||
if (s_ready) return true;
|
|
||||||
|
|
||||||
if (!psramFound()) {
|
|
||||||
// Without PSRAM there is no ring buffer and no SVGA framebuffer.
|
|
||||||
// Fail loudly rather than silently running a crippled node.
|
|
||||||
log_e("PSRAM not found — check board_build.arduino.memory_type=qio_opi");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
camera_config_t c = buildConfig();
|
|
||||||
esp_err_t err = esp_camera_init(&c);
|
|
||||||
if (err != ESP_OK) {
|
|
||||||
log_e("esp_camera_init failed: 0x%x", err);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
s_ready = true;
|
|
||||||
cameraApplyConfig();
|
|
||||||
cameraDiscardFrames(3);
|
|
||||||
|
|
||||||
uint16_t w = 0, h = 0;
|
|
||||||
framesizeDims(g_cfg.frame_size, &w, &h);
|
|
||||||
sensor_t* s = esp_camera_sensor_get();
|
|
||||||
log_i("camera ready: sensor PID 0x%04x, %s (%ux%u) quality=%u psram_free=%uKB",
|
|
||||||
s ? s->id.PID : 0, framesizeName(g_cfg.frame_size), w, h,
|
|
||||||
g_cfg.jpeg_quality,
|
|
||||||
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void cameraEnd() {
|
|
||||||
if (!s_ready) return;
|
|
||||||
esp_camera_deinit();
|
|
||||||
s_ready = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool cameraRestart() {
|
|
||||||
cameraEnd();
|
|
||||||
delay(50);
|
|
||||||
return cameraBegin();
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool s_night_profile = false;
|
|
||||||
|
|
||||||
bool cameraNightProfileActive() { return s_night_profile; }
|
|
||||||
|
|
||||||
// Everything the OV2640 exposes that is worth touching on a bird camera.
|
|
||||||
// Notes on the ones that actually matter here:
|
|
||||||
//
|
|
||||||
// gainceiling The single most important setting for small fast birds.
|
|
||||||
// High gain lets the sensor pick a shorter exposure in poor
|
|
||||||
// light, but amplifies noise; low gain forces a longer
|
|
||||||
// exposure and smears a moving bird into a streak. 4x by day
|
|
||||||
// is a good compromise; the night profile raises it because a
|
|
||||||
// noisy photo beats a black one.
|
|
||||||
// exposure_ctrl Leave auto by day. Set false + aec_value to force a fixed
|
|
||||||
// short shutter if you find motion blur is the limiting
|
|
||||||
// factor at your feeder — that is the tuning lever.
|
|
||||||
// ae_level Exposure bias. Birds are usually backlit against bright sky,
|
|
||||||
// which fools metering into underexposing the bird; +1 helps.
|
|
||||||
// lenc Lens shading correction. On, unless you are stitching.
|
|
||||||
// colorbar Test pattern. Set true to prove the data path works before
|
|
||||||
// you have optics or light.
|
|
||||||
void cameraApplyTuning(bool night) {
|
|
||||||
sensor_t* s = esp_camera_sensor_get();
|
|
||||||
if (!s) return;
|
|
||||||
|
|
||||||
const CamTuning& t = night ? g_cfg.cam_night : g_cfg.cam_day;
|
|
||||||
s_night_profile = night;
|
|
||||||
|
|
||||||
s->set_brightness(s, t.brightness);
|
|
||||||
s->set_contrast(s, t.contrast);
|
|
||||||
s->set_saturation(s, t.saturation);
|
|
||||||
s->set_sharpness(s, t.sharpness);
|
|
||||||
s->set_special_effect(s, t.special_effect);
|
|
||||||
|
|
||||||
s->set_whitebal(s, t.whitebal ? 1 : 0);
|
|
||||||
s->set_awb_gain(s, t.awb_gain ? 1 : 0);
|
|
||||||
s->set_wb_mode(s, t.wb_mode);
|
|
||||||
|
|
||||||
s->set_exposure_ctrl(s, t.exposure_ctrl ? 1 : 0);
|
|
||||||
s->set_aec2(s, t.aec2 ? 1 : 0);
|
|
||||||
s->set_ae_level(s, t.ae_level);
|
|
||||||
if (!t.exposure_ctrl) s->set_aec_value(s, t.aec_value);
|
|
||||||
|
|
||||||
s->set_gain_ctrl(s, t.gain_ctrl ? 1 : 0);
|
|
||||||
if (!t.gain_ctrl) s->set_agc_gain(s, t.agc_gain);
|
|
||||||
s->set_gainceiling(s, (gainceiling_t)t.gainceiling);
|
|
||||||
|
|
||||||
s->set_bpc(s, t.bpc ? 1 : 0);
|
|
||||||
s->set_wpc(s, t.wpc ? 1 : 0);
|
|
||||||
s->set_raw_gma(s, t.raw_gma ? 1 : 0);
|
|
||||||
s->set_lenc(s, t.lenc ? 1 : 0);
|
|
||||||
s->set_dcw(s, t.dcw ? 1 : 0);
|
|
||||||
s->set_colorbar(s, t.colorbar ? 1 : 0);
|
|
||||||
|
|
||||||
// The sensor needs a couple of frames to act on an exposure change.
|
|
||||||
cameraDiscardFrames(2);
|
|
||||||
|
|
||||||
log_i("camera: %s profile applied (gainceiling=%u ae_level=%d aec=%s)",
|
|
||||||
night ? "night" : "day", t.gainceiling, t.ae_level,
|
|
||||||
t.exposure_ctrl ? "auto" : "manual");
|
|
||||||
}
|
|
||||||
|
|
||||||
void cameraApplyConfig() {
|
|
||||||
sensor_t* s = esp_camera_sensor_get();
|
|
||||||
if (!s) return;
|
|
||||||
s->set_quality(s, g_cfg.jpeg_quality);
|
|
||||||
s->set_vflip(s, g_cfg.vflip ? 1 : 0);
|
|
||||||
s->set_hmirror(s, g_cfg.hmirror ? 1 : 0);
|
|
||||||
cameraApplyTuning(s_night_profile);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool cameraSetFrameSize(uint8_t framesize) {
|
|
||||||
sensor_t* s = esp_camera_sensor_get();
|
|
||||||
if (!s) return false;
|
|
||||||
|
|
||||||
// set_framesize refuses anything above the sensor's own maximum, which is
|
|
||||||
// how an OV2640 (max UXGA) tells you it cannot do the QXGA an OV5640
|
|
||||||
// would manage. Report it rather than silently keeping the old size.
|
|
||||||
if (s->set_framesize(s, (framesize_t)framesize) != 0) {
|
|
||||||
log_w("camera: sensor rejected frame size %s — above its maximum?",
|
|
||||||
framesizeName(framesize));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
cameraDiscardFrames(2);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
camera_fb_t* cameraGrab() {
|
|
||||||
if (!s_ready) return nullptr;
|
|
||||||
camera_fb_t* fb = esp_camera_fb_get();
|
|
||||||
if (!fb) log_w("camera grab failed");
|
|
||||||
return fb;
|
|
||||||
}
|
|
||||||
|
|
||||||
void cameraDiscardFrames(uint8_t n) {
|
|
||||||
for (uint8_t i = 0; i < n; i++) {
|
|
||||||
camera_fb_t* fb = esp_camera_fb_get();
|
|
||||||
if (fb) esp_camera_fb_return(fb);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool cameraReady() { return s_ready; }
|
|
||||||
@@ -1,200 +0,0 @@
|
|||||||
#include "commands.h"
|
|
||||||
|
|
||||||
#include "api_client.h"
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
#include "ota_mgr.h"
|
|
||||||
#include "power_mgr.h"
|
|
||||||
#include "stream_session.h"
|
|
||||||
|
|
||||||
// main.cpp owns the capture pipeline; this is how a command reaches it.
|
|
||||||
extern void requestManualCapture();
|
|
||||||
|
|
||||||
// A deferred command, kept as a fixed-size record so the queue needs no heap.
|
|
||||||
struct Deferred {
|
|
||||||
bool used;
|
|
||||||
uint32_t id;
|
|
||||||
char type[20];
|
|
||||||
char s_arg[64]; // session id, or firmware url
|
|
||||||
char s_arg2[65]; // sha256
|
|
||||||
uint32_t n_arg; // seconds, size
|
|
||||||
uint8_t u_arg[3]; // mode, framesize, spare
|
|
||||||
};
|
|
||||||
|
|
||||||
static const size_t kQueueDepth = 4;
|
|
||||||
static Deferred s_queue[kQueueDepth] = {};
|
|
||||||
|
|
||||||
static bool enqueue(const Deferred& d) {
|
|
||||||
for (size_t i = 0; i < kQueueDepth; i++) {
|
|
||||||
if (!s_queue[i].used) { s_queue[i] = d; s_queue[i].used = true; return true; }
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void commandOnReceived(JsonObjectConst cmd) {
|
|
||||||
const uint32_t id = cmd["id"] | (uint32_t)0;
|
|
||||||
const char* type = cmd["type"] | "";
|
|
||||||
JsonObjectConst p = cmd["payload"];
|
|
||||||
|
|
||||||
log_i("cmd #%u: %s", (unsigned)id, type);
|
|
||||||
powerNoteActivity();
|
|
||||||
|
|
||||||
// --- immediate, cheap ---------------------------------------------------
|
|
||||||
|
|
||||||
if (strcmp(type, "apply_config") == 0) {
|
|
||||||
const bool was_sleeping = g_cfg.deep_sleep_enabled;
|
|
||||||
const AppConfig before = g_cfg;
|
|
||||||
|
|
||||||
bool changed = false;
|
|
||||||
if (!p.isNull()) {
|
|
||||||
changed = configApplyJson(p);
|
|
||||||
} else {
|
|
||||||
// No inline payload: the endpoint wants us to pull the full doc.
|
|
||||||
changed = apiFetchConfig();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (changed) {
|
|
||||||
configSave();
|
|
||||||
cameraApplyConfig();
|
|
||||||
powerOnConfigChanged(was_sleeping);
|
|
||||||
if (configNeedsCameraRestart(before, g_cfg)) {
|
|
||||||
log_i("cmd: frame size changed, restarting camera");
|
|
||||||
cameraRestart();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
apiAckCommand(id, "done", changed ? "config applied" : "no change");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "capture_now") == 0) {
|
|
||||||
requestManualCapture();
|
|
||||||
apiAckCommand(id, "done", "capture queued");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "report_status") == 0) {
|
|
||||||
// Deferred: we are currently inside the heartbeat's response handler,
|
|
||||||
// and opening a second connection from here would nest HTTP clients.
|
|
||||||
Deferred d = {};
|
|
||||||
d.id = id;
|
|
||||||
strncpy(d.type, "report_status", sizeof(d.type) - 1);
|
|
||||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "wake_and_hold") == 0) {
|
|
||||||
uint32_t secs = p["seconds"] | (uint32_t)60;
|
|
||||||
if (secs > 900) secs = 900; // bounded, per SPEC §4.3
|
|
||||||
powerHoldAwake(secs);
|
|
||||||
apiAckCommand(id, "done", "holding awake");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "sleep_now") == 0) {
|
|
||||||
// Deferred: we want the ack to reach the Pi before the radio goes off.
|
|
||||||
Deferred d = {};
|
|
||||||
d.id = id;
|
|
||||||
d.n_arg = p["seconds"] | (uint32_t)0;
|
|
||||||
strncpy(d.type, "sleep_now", sizeof(d.type) - 1);
|
|
||||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "stream_stop") == 0) {
|
|
||||||
streamStop("stopped by command");
|
|
||||||
apiAckCommand(id, "done", "stream stopped");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "reboot") == 0) {
|
|
||||||
apiAckCommand(id, "done", "rebooting");
|
|
||||||
delay(200);
|
|
||||||
ESP.restart();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- deferred: these block, so they run from the main loop ---------------
|
|
||||||
|
|
||||||
if (strcmp(type, "stream_start") == 0) {
|
|
||||||
Deferred d = {};
|
|
||||||
d.id = id;
|
|
||||||
strncpy(d.type, "stream_start", sizeof(d.type) - 1);
|
|
||||||
strncpy(d.s_arg, p["session_id"] | "", sizeof(d.s_arg) - 1);
|
|
||||||
d.n_arg = p["duration_s"] | (uint32_t)0;
|
|
||||||
d.u_arg[0] = p["mode"] | (uint8_t)0xFF;
|
|
||||||
d.u_arg[1] = p["frame_size"] | (uint8_t)0;
|
|
||||||
if (!d.s_arg[0]) { apiAckCommand(id, "rejected", "no session_id"); return; }
|
|
||||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strcmp(type, "ota_update") == 0) {
|
|
||||||
Deferred d = {};
|
|
||||||
d.id = id;
|
|
||||||
strncpy(d.type, "ota_update", sizeof(d.type) - 1);
|
|
||||||
strncpy(d.s_arg, p["url"] | "", sizeof(d.s_arg) - 1);
|
|
||||||
strncpy(d.s_arg2, p["sha256"] | "", sizeof(d.s_arg2) - 1);
|
|
||||||
d.n_arg = p["size"] | (uint32_t)0;
|
|
||||||
// The version lands in s_arg's tail via the firmware envelope instead;
|
|
||||||
// an ota_update command without a url means "use the target from the
|
|
||||||
// envelope", which main.cpp already tracks.
|
|
||||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_w("cmd #%u: unknown type '%s'", (unsigned)id, type);
|
|
||||||
apiAckCommand(id, "rejected", "unknown command type");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The firmware target from the most recent response envelope, so an
|
|
||||||
// `ota_update` command with no explicit url still knows what to fetch.
|
|
||||||
extern OtaTarget g_fw_target;
|
|
||||||
|
|
||||||
void commandRunDeferred() {
|
|
||||||
for (size_t i = 0; i < kQueueDepth; i++) {
|
|
||||||
if (!s_queue[i].used) continue;
|
|
||||||
|
|
||||||
Deferred d = s_queue[i];
|
|
||||||
s_queue[i].used = false; // clear first: a reboot must not replay it
|
|
||||||
|
|
||||||
if (strcmp(d.type, "stream_start") == 0) {
|
|
||||||
bool ok = streamStart(d.s_arg, d.u_arg[0], d.u_arg[1], (uint16_t)d.n_arg);
|
|
||||||
apiAckCommand(d.id, ok ? "done" : "failed",
|
|
||||||
ok ? "streaming" : "could not start stream");
|
|
||||||
|
|
||||||
} else if (strcmp(d.type, "ota_update") == 0) {
|
|
||||||
OtaTarget t = g_fw_target;
|
|
||||||
if (d.s_arg[0]) strncpy(t.url, d.s_arg, sizeof(t.url) - 1);
|
|
||||||
if (d.s_arg2[0]) strncpy(t.sha256, d.s_arg2, sizeof(t.sha256) - 1);
|
|
||||||
if (d.n_arg) t.size = d.n_arg;
|
|
||||||
|
|
||||||
if (!t.url[0]) {
|
|
||||||
apiAckCommand(d.id, "rejected", "no firmware url");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// Ack before flashing: otaApply() reboots on success and would
|
|
||||||
// never get the chance to report it.
|
|
||||||
apiAckCommand(d.id, "done", "flashing");
|
|
||||||
if (!otaApply(t)) {
|
|
||||||
apiAckCommand(d.id, "failed", "ota failed, still on old image");
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if (strcmp(d.type, "report_status") == 0) {
|
|
||||||
bool ok = apiPostStatus("on_request");
|
|
||||||
apiAckCommand(d.id, ok ? "done" : "failed", ok ? "status posted" : "status post failed");
|
|
||||||
|
|
||||||
} else if (strcmp(d.type, "sleep_now") == 0) {
|
|
||||||
apiAckCommand(d.id, "done", "sleeping");
|
|
||||||
powerSleepNow(d.n_arg);
|
|
||||||
// Returns only if sleep is switched off or OTA is in flight.
|
|
||||||
apiAckCommand(d.id, "rejected", "deep sleep is off");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool commandHasPending() {
|
|
||||||
for (size_t i = 0; i < kQueueDepth; i++) {
|
|
||||||
if (s_queue[i].used) return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
#include "device_stats.h"
|
|
||||||
|
|
||||||
#include <time.h>
|
|
||||||
|
|
||||||
#include "net_mgr.h"
|
|
||||||
|
|
||||||
// RTC slow memory: survives deep sleep, lost on power cycle.
|
|
||||||
RTC_DATA_ATTR static uint16_t s_captured_today = 0;
|
|
||||||
RTC_DATA_ATTR static uint16_t s_delivered_today = 0;
|
|
||||||
RTC_DATA_ATTR static uint16_t s_failed_today = 0;
|
|
||||||
RTC_DATA_ATTR static uint16_t s_events_today = 0;
|
|
||||||
RTC_DATA_ATTR static uint32_t s_day_index = 0;
|
|
||||||
|
|
||||||
static uint16_t s_captured_boot = 0;
|
|
||||||
static uint16_t s_delivered_boot = 0;
|
|
||||||
static uint32_t s_wake_ms = 0;
|
|
||||||
|
|
||||||
// Days since epoch in *local* time. localtime_r honours the TZ set by
|
|
||||||
// net_mgr, so this rolls over at local midnight rather than at UTC midnight —
|
|
||||||
// which matters in CEST, where UTC midnight is 02:00 the next morning.
|
|
||||||
static uint32_t localDayIndex() {
|
|
||||||
const int64_t ms = netEpochMs();
|
|
||||||
if (ms == 0) return 0; // unsynced: everything is "day 0"
|
|
||||||
|
|
||||||
time_t t = (time_t)(ms / 1000);
|
|
||||||
struct tm lt;
|
|
||||||
localtime_r(&t, <);
|
|
||||||
|
|
||||||
// mktime of local midnight, divided into days. Simpler than date maths and
|
|
||||||
// correct across DST, because mktime resolves the offset for that date.
|
|
||||||
struct tm midnight = lt;
|
|
||||||
midnight.tm_hour = 0;
|
|
||||||
midnight.tm_min = 0;
|
|
||||||
midnight.tm_sec = 0;
|
|
||||||
time_t m = mktime(&midnight);
|
|
||||||
return (uint32_t)(m / 86400);
|
|
||||||
}
|
|
||||||
|
|
||||||
void statsBegin() {
|
|
||||||
s_wake_ms = millis();
|
|
||||||
s_captured_boot = 0;
|
|
||||||
s_delivered_boot = 0;
|
|
||||||
statsRollover();
|
|
||||||
}
|
|
||||||
|
|
||||||
void statsRollover() {
|
|
||||||
const uint32_t today = localDayIndex();
|
|
||||||
if (today == 0) return; // clock not yet trustworthy
|
|
||||||
|
|
||||||
if (today != s_day_index) {
|
|
||||||
if (s_day_index != 0) {
|
|
||||||
log_i("stats: new day, resetting counters (was %u captured, %u delivered)",
|
|
||||||
s_captured_today, s_delivered_today);
|
|
||||||
}
|
|
||||||
s_day_index = today;
|
|
||||||
s_captured_today = 0;
|
|
||||||
s_delivered_today = 0;
|
|
||||||
s_failed_today = 0;
|
|
||||||
s_events_today = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void statsCountEvent() { statsRollover(); s_events_today++; }
|
|
||||||
|
|
||||||
void statsCountCaptured(uint16_t frames) {
|
|
||||||
statsRollover();
|
|
||||||
s_captured_today += frames;
|
|
||||||
s_captured_boot += frames;
|
|
||||||
}
|
|
||||||
|
|
||||||
void statsCountDelivered(uint16_t frames) {
|
|
||||||
statsRollover();
|
|
||||||
s_delivered_today += frames;
|
|
||||||
s_delivered_boot += frames;
|
|
||||||
}
|
|
||||||
|
|
||||||
void statsCountFailed(uint16_t frames) {
|
|
||||||
statsRollover();
|
|
||||||
s_failed_today += frames;
|
|
||||||
}
|
|
||||||
|
|
||||||
DeviceStats statsGet() {
|
|
||||||
DeviceStats s = {};
|
|
||||||
s.captured_today = s_captured_today;
|
|
||||||
s.delivered_today = s_delivered_today;
|
|
||||||
s.failed_today = s_failed_today;
|
|
||||||
s.events_today = s_events_today;
|
|
||||||
s.day_index = s_day_index;
|
|
||||||
s.captured_boot = s_captured_boot;
|
|
||||||
s.delivered_boot = s_delivered_boot;
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t statsAwakeMs() { return millis() - s_wake_ms; }
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
#include "frame_ring.h"
|
|
||||||
|
|
||||||
#include <esp_heap_caps.h>
|
|
||||||
|
|
||||||
static RingFrame* s_ring = nullptr;
|
|
||||||
static size_t s_depth = 0;
|
|
||||||
static size_t s_head = 0; // next slot to write
|
|
||||||
static size_t s_count = 0;
|
|
||||||
static uint32_t s_seq = 0;
|
|
||||||
static SemaphoreHandle_t s_mtx = nullptr;
|
|
||||||
|
|
||||||
// Slots start at a plausible SVGA JPEG size and grow if a frame does not fit.
|
|
||||||
// Growing costs one realloc; shrinking is never worth the churn.
|
|
||||||
static const size_t kInitialSlotBytes = 48 * 1024;
|
|
||||||
|
|
||||||
bool ringBegin(uint8_t depth) {
|
|
||||||
ringEnd();
|
|
||||||
if (depth == 0) return false;
|
|
||||||
|
|
||||||
s_mtx = xSemaphoreCreateMutex();
|
|
||||||
if (!s_mtx) return false;
|
|
||||||
|
|
||||||
s_ring = (RingFrame*)heap_caps_calloc(depth, sizeof(RingFrame), MALLOC_CAP_SPIRAM);
|
|
||||||
if (!s_ring) {
|
|
||||||
log_e("ring: cannot allocate slot table in PSRAM");
|
|
||||||
vSemaphoreDelete(s_mtx);
|
|
||||||
s_mtx = nullptr;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (size_t i = 0; i < depth; i++) {
|
|
||||||
s_ring[i].data = (uint8_t*)heap_caps_malloc(kInitialSlotBytes, MALLOC_CAP_SPIRAM);
|
|
||||||
if (!s_ring[i].data) {
|
|
||||||
log_e("ring: PSRAM exhausted at slot %u of %u", (unsigned)i, depth);
|
|
||||||
// Run with the slots we got rather than failing outright — a
|
|
||||||
// shallower ring is still far better than none.
|
|
||||||
depth = i;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
s_ring[i].cap = kInitialSlotBytes;
|
|
||||||
}
|
|
||||||
if (depth == 0) { ringEnd(); return false; }
|
|
||||||
|
|
||||||
s_depth = depth;
|
|
||||||
s_head = s_count = 0;
|
|
||||||
s_seq = 0;
|
|
||||||
log_i("ring: %u slots x %uKB = %uKB PSRAM (free %uKB)",
|
|
||||||
(unsigned)s_depth, (unsigned)(kInitialSlotBytes / 1024),
|
|
||||||
(unsigned)(s_depth * kInitialSlotBytes / 1024),
|
|
||||||
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void ringEnd() {
|
|
||||||
if (s_mtx) xSemaphoreTake(s_mtx, portMAX_DELAY);
|
|
||||||
if (s_ring) {
|
|
||||||
for (size_t i = 0; i < s_depth; i++) free(s_ring[i].data);
|
|
||||||
free(s_ring);
|
|
||||||
s_ring = nullptr;
|
|
||||||
}
|
|
||||||
s_depth = s_head = s_count = 0;
|
|
||||||
s_seq = 0;
|
|
||||||
if (s_mtx) {
|
|
||||||
xSemaphoreGive(s_mtx);
|
|
||||||
vSemaphoreDelete(s_mtx);
|
|
||||||
s_mtx = nullptr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool ringPush(const uint8_t* data, size_t len, int64_t epoch_ms) {
|
|
||||||
if (!s_ring || !data || len == 0) return false;
|
|
||||||
if (xSemaphoreTake(s_mtx, pdMS_TO_TICKS(100)) != pdTRUE) return false;
|
|
||||||
|
|
||||||
RingFrame& f = s_ring[s_head];
|
|
||||||
|
|
||||||
if (len > f.cap) {
|
|
||||||
uint8_t* bigger = (uint8_t*)heap_caps_realloc(f.data, len, MALLOC_CAP_SPIRAM);
|
|
||||||
if (!bigger) {
|
|
||||||
xSemaphoreGive(s_mtx);
|
|
||||||
log_w("ring: cannot grow slot to %u bytes, dropping frame", (unsigned)len);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
f.data = bigger;
|
|
||||||
f.cap = len;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(f.data, data, len);
|
|
||||||
f.len = len;
|
|
||||||
f.at_ms = millis();
|
|
||||||
f.at_epoch = epoch_ms;
|
|
||||||
f.seq = ++s_seq;
|
|
||||||
|
|
||||||
s_head = (s_head + 1) % s_depth;
|
|
||||||
if (s_count < s_depth) s_count++;
|
|
||||||
|
|
||||||
xSemaphoreGive(s_mtx);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t ringTakeNewest(size_t n, FrameCopy* out, size_t out_cap) {
|
|
||||||
if (!s_ring || !out || out_cap == 0) return 0;
|
|
||||||
if (xSemaphoreTake(s_mtx, pdMS_TO_TICKS(500)) != pdTRUE) return 0;
|
|
||||||
|
|
||||||
if (n > s_count) n = s_count;
|
|
||||||
if (n > out_cap) n = out_cap;
|
|
||||||
|
|
||||||
size_t written = 0;
|
|
||||||
for (size_t i = 0; i < n; i++) {
|
|
||||||
// Walk oldest-of-the-newest-n forward to newest.
|
|
||||||
size_t back = n - i; // 1 == newest
|
|
||||||
size_t idx = (s_head + s_depth - back) % s_depth;
|
|
||||||
RingFrame& f = s_ring[idx];
|
|
||||||
if (f.seq == 0 || f.len == 0) continue;
|
|
||||||
|
|
||||||
// Copies live in PSRAM. A ten-frame event is ~450 KB, which would
|
|
||||||
// exhaust internal RAM and starve the WiFi stack exactly when it is
|
|
||||||
// about to do the most work.
|
|
||||||
uint8_t* buf = (uint8_t*)heap_caps_malloc(f.len, MALLOC_CAP_SPIRAM);
|
|
||||||
if (!buf) {
|
|
||||||
log_w("ring: out of memory copying frame for upload");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
memcpy(buf, f.data, f.len);
|
|
||||||
|
|
||||||
out[written++] = FrameCopy{buf, f.len, f.seq, f.at_ms, f.at_epoch};
|
|
||||||
}
|
|
||||||
|
|
||||||
xSemaphoreGive(s_mtx);
|
|
||||||
return written;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t ringSeq() { return s_seq; }
|
|
||||||
size_t ringCount() { return s_count; }
|
|
||||||
|
|
||||||
size_t ringBytesUsed() {
|
|
||||||
if (!s_ring) return 0;
|
|
||||||
size_t total = 0;
|
|
||||||
for (size_t i = 0; i < s_depth; i++) total += s_ring[i].cap;
|
|
||||||
return total;
|
|
||||||
}
|
|
||||||
@@ -1,296 +0,0 @@
|
|||||||
#include "ld2410.h"
|
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "board_pins.h"
|
|
||||||
|
|
||||||
static HardwareSerial s_uart(RADAR_UART_NUM);
|
|
||||||
static RadarReading s_last = {};
|
|
||||||
|
|
||||||
// Incremental frame assembler. The radar streams continuously and we share the
|
|
||||||
// core with the camera, so parsing has to tolerate being called late and
|
|
||||||
// finding several frames queued in the driver buffer.
|
|
||||||
static uint8_t s_buf[64];
|
|
||||||
static size_t s_len = 0;
|
|
||||||
static bool s_sync = false;
|
|
||||||
|
|
||||||
static const uint8_t kReportHead[4] = {0xF4, 0xF3, 0xF2, 0xF1};
|
|
||||||
static const uint8_t kReportTail[4] = {0xF8, 0xF7, 0xF6, 0xF5};
|
|
||||||
static const uint8_t kCmdHead[4] = {0xFD, 0xFC, 0xFB, 0xFA};
|
|
||||||
static const uint8_t kCmdTail[4] = {0x04, 0x03, 0x02, 0x01};
|
|
||||||
|
|
||||||
static inline uint16_t rd16(const uint8_t* p) {
|
|
||||||
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Baud rates to probe, most likely first. The LD2410 leaves the factory at
|
|
||||||
// 256000; 115200 is the usual choice when someone has reconfigured it.
|
|
||||||
static const uint32_t kBaudCandidates[] = {256000, 115200, 57600, 38400, 9600};
|
|
||||||
static uint32_t s_baud = 0;
|
|
||||||
|
|
||||||
uint32_t radarBaud() { return s_baud; }
|
|
||||||
|
|
||||||
// Open at `baud` and listen for a well-formed report frame.
|
|
||||||
static bool tryBaud(uint32_t baud, uint32_t listen_ms) {
|
|
||||||
s_uart.end();
|
|
||||||
delay(20);
|
|
||||||
s_uart.setRxBufferSize(512); // must precede begin()
|
|
||||||
s_uart.begin(baud, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX);
|
|
||||||
|
|
||||||
s_len = 0;
|
|
||||||
s_sync = false;
|
|
||||||
memset(&s_last, 0, sizeof(s_last));
|
|
||||||
|
|
||||||
const uint32_t end = millis() + listen_ms;
|
|
||||||
while ((int32_t)(end - millis()) > 0) {
|
|
||||||
if (radarPoll()) return true; // decoded a real frame: right baud
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool radarBegin() {
|
|
||||||
pinMode(PIN_RADAR_OUT, INPUT);
|
|
||||||
|
|
||||||
// Autodetect rather than hardcode. The module reports a few times a
|
|
||||||
// second, so a wrong baud is obvious within a second — and detecting it
|
|
||||||
// means a factory reset (which returns the module to 256000) does not
|
|
||||||
// silently take the camera's trigger offline on a device you cannot
|
|
||||||
// easily reach. Pin it with `radar_baud` if you would rather it not probe.
|
|
||||||
if (g_cfg.radar_baud != 0) {
|
|
||||||
if (tryBaud(g_cfg.radar_baud, 1500)) {
|
|
||||||
s_baud = g_cfg.radar_baud;
|
|
||||||
log_i("radar: UART%d @%u baud (pinned) rx=%d tx=%d out=%d",
|
|
||||||
RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
log_w("radar: no frames at the pinned %u baud, falling back to autodetect",
|
|
||||||
(unsigned)g_cfg.radar_baud);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (uint32_t cand : kBaudCandidates) {
|
|
||||||
if (tryBaud(cand, 900)) {
|
|
||||||
s_baud = cand;
|
|
||||||
log_i("radar: UART%d @%u baud (detected) rx=%d tx=%d out=%d",
|
|
||||||
RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing decoded. Leave the port open at the default so radarSelfTest()
|
|
||||||
// can still dump raw bytes, and so the OUT pin path keeps working —
|
|
||||||
// RADAR_OUT_PIN_ONLY mode does not need the UART at all.
|
|
||||||
s_baud = 0;
|
|
||||||
s_uart.end();
|
|
||||||
delay(20);
|
|
||||||
s_uart.setRxBufferSize(512);
|
|
||||||
s_uart.begin(RADAR_BAUD, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX);
|
|
||||||
log_w("radar: no UART frames at any baud — check TX/RX are crossed. "
|
|
||||||
"The OUT pin still works; radar_mode=0 uses it alone.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode a complete report payload (header and tail already stripped).
|
|
||||||
static bool decodeReport(const uint8_t* p, size_t n) {
|
|
||||||
// Basic report: 13 payload bytes. Engineering mode reports are longer and
|
|
||||||
// start the same way, so we accept anything >= 13 and read the common head.
|
|
||||||
if (n < 13) return false;
|
|
||||||
if (p[0] != 0x02 || p[1] != 0xAA) return false;
|
|
||||||
|
|
||||||
RadarReading r = {};
|
|
||||||
r.valid = true;
|
|
||||||
r.target = p[2];
|
|
||||||
r.moving_cm = rd16(&p[3]);
|
|
||||||
r.moving_energy = p[5];
|
|
||||||
r.stationary_cm = rd16(&p[6]);
|
|
||||||
r.stationary_energy = p[8];
|
|
||||||
r.detect_cm = rd16(&p[9]);
|
|
||||||
r.at_ms = millis();
|
|
||||||
r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
|
|
||||||
s_last = r;
|
|
||||||
|
|
||||||
#ifdef PB_VERBOSE_RADAR
|
|
||||||
log_d("radar: state=%u mov=%ucm/%u stat=%ucm/%u det=%ucm out=%d",
|
|
||||||
r.target, r.moving_cm, r.moving_energy,
|
|
||||||
r.stationary_cm, r.stationary_energy, r.detect_cm, r.out_pin);
|
|
||||||
#endif
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool radarPoll() {
|
|
||||||
bool got = false;
|
|
||||||
|
|
||||||
while (s_uart.available()) {
|
|
||||||
uint8_t b = (uint8_t)s_uart.read();
|
|
||||||
|
|
||||||
if (!s_sync) {
|
|
||||||
// Slide a 4-byte window until it matches either header.
|
|
||||||
if (s_len < 4) {
|
|
||||||
s_buf[s_len++] = b;
|
|
||||||
} else {
|
|
||||||
memmove(s_buf, s_buf + 1, 3);
|
|
||||||
s_buf[3] = b;
|
|
||||||
}
|
|
||||||
if (s_len == 4 &&
|
|
||||||
(memcmp(s_buf, kReportHead, 4) == 0 || memcmp(s_buf, kCmdHead, 4) == 0)) {
|
|
||||||
s_sync = true;
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (s_len >= sizeof(s_buf)) { // runaway frame: resynchronise
|
|
||||||
s_len = 0;
|
|
||||||
s_sync = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
s_buf[s_len++] = b;
|
|
||||||
|
|
||||||
// Need header(4) + length(2) before we know how much to expect.
|
|
||||||
if (s_len < 6) continue;
|
|
||||||
|
|
||||||
const uint16_t payload_len = rd16(&s_buf[4]);
|
|
||||||
const size_t total = 4 + 2 + payload_len + 4;
|
|
||||||
if (payload_len > sizeof(s_buf) - 10) { // implausible length
|
|
||||||
s_len = 0;
|
|
||||||
s_sync = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (s_len < total) continue;
|
|
||||||
|
|
||||||
const uint8_t* tail = &s_buf[6 + payload_len];
|
|
||||||
const bool is_rpt = memcmp(s_buf, kReportHead, 4) == 0;
|
|
||||||
const uint8_t* expect = is_rpt ? kReportTail : kCmdTail;
|
|
||||||
|
|
||||||
if (memcmp(tail, expect, 4) == 0 && is_rpt) {
|
|
||||||
got |= decodeReport(&s_buf[6], payload_len);
|
|
||||||
}
|
|
||||||
// Command ACKs are consumed silently; the write helpers below poll for
|
|
||||||
// them separately rather than routing them through this path.
|
|
||||||
|
|
||||||
s_len = 0;
|
|
||||||
s_sync = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep the pin fresh even when the UART is silent (or absent).
|
|
||||||
s_last.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
|
|
||||||
return got;
|
|
||||||
}
|
|
||||||
|
|
||||||
RadarReading radarLast() {
|
|
||||||
RadarReading r = s_last;
|
|
||||||
r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool radarIsTrigger(const RadarReading& r) {
|
|
||||||
switch (g_cfg.radar_mode) {
|
|
||||||
case RADAR_OUT_PIN_ONLY:
|
|
||||||
return r.out_pin;
|
|
||||||
|
|
||||||
case RADAR_UART_ONLY:
|
|
||||||
break; // fall through to the windowed check
|
|
||||||
|
|
||||||
case RADAR_BOTH:
|
|
||||||
default:
|
|
||||||
// The pin arms; the report has to agree. If the UART has gone
|
|
||||||
// quiet (bad wiring, wrong baud) we would otherwise never trigger,
|
|
||||||
// so a stale report degrades to pin-only rather than to silence.
|
|
||||||
if (!r.out_pin) return false;
|
|
||||||
if (!r.valid || (millis() - r.at_ms) > 3000) return true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!r.valid) return false;
|
|
||||||
if (r.target == TARGET_NONE) return false;
|
|
||||||
|
|
||||||
const bool moving = (r.target == TARGET_MOVING || r.target == TARGET_BOTH);
|
|
||||||
const bool stationary = (r.target == TARGET_STATIONARY || r.target == TARGET_BOTH);
|
|
||||||
|
|
||||||
if (moving &&
|
|
||||||
r.moving_energy >= g_cfg.min_energy &&
|
|
||||||
r.moving_cm >= g_cfg.min_distance_cm &&
|
|
||||||
r.moving_cm <= g_cfg.max_distance_cm) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stationary && g_cfg.accept_stationary &&
|
|
||||||
r.stationary_energy >= g_cfg.min_energy &&
|
|
||||||
r.stationary_cm >= g_cfg.min_distance_cm &&
|
|
||||||
r.stationary_cm <= g_cfg.max_distance_cm) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void radarSelfTest(uint32_t duration_ms) {
|
|
||||||
log_i("radar self-test: dumping raw UART for %u ms", duration_ms);
|
|
||||||
const uint32_t end = millis() + duration_ms;
|
|
||||||
size_t bytes = 0;
|
|
||||||
uint32_t frames = 0;
|
|
||||||
while ((int32_t)(end - millis()) > 0) {
|
|
||||||
while (s_uart.available()) { s_uart.read(); bytes++; }
|
|
||||||
if (radarPoll()) frames++;
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
log_i("radar self-test: %u bytes, %u decoded frames, OUT=%d",
|
|
||||||
(unsigned)bytes, (unsigned)frames, digitalRead(PIN_RADAR_OUT));
|
|
||||||
if (bytes == 0) {
|
|
||||||
log_w(" no UART data. Check TX/RX are crossed and the baud rate "
|
|
||||||
"(factory 256000, some units ship at 115200).");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- command path -----------------------------------------------------------
|
|
||||||
// Minimal: enough to raise sensitivity if the default rejects small targets.
|
|
||||||
|
|
||||||
static bool sendCommand(const uint8_t* payload, uint16_t len, uint32_t timeout_ms = 300) {
|
|
||||||
uint8_t frame[32];
|
|
||||||
if (len + 10 > sizeof(frame)) return false;
|
|
||||||
|
|
||||||
memcpy(frame, kCmdHead, 4);
|
|
||||||
frame[4] = len & 0xFF;
|
|
||||||
frame[5] = (len >> 8) & 0xFF;
|
|
||||||
memcpy(frame + 6, payload, len);
|
|
||||||
memcpy(frame + 6 + len, kCmdTail, 4);
|
|
||||||
|
|
||||||
while (s_uart.available()) s_uart.read(); // drop queued reports
|
|
||||||
s_uart.write(frame, len + 10);
|
|
||||||
s_uart.flush();
|
|
||||||
|
|
||||||
// The ACK mirrors the command word with bit 8 set. We only check that
|
|
||||||
// *something* well-formed came back; the module is not chatty enough for
|
|
||||||
// a mismatched ACK to be ambiguous in practice.
|
|
||||||
const uint32_t end = millis() + timeout_ms;
|
|
||||||
while ((int32_t)(end - millis()) > 0) {
|
|
||||||
if (s_uart.available() >= 10) return true;
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
log_w("radar: no ACK for command 0x%02X%02X", payload[1], payload[0]);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool radarEnterConfig() {
|
|
||||||
const uint8_t p[] = {0xFF, 0x00, 0x01, 0x00};
|
|
||||||
return sendCommand(p, sizeof(p));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool radarExitConfig() {
|
|
||||||
const uint8_t p[] = {0xFE, 0x00};
|
|
||||||
bool ok = sendCommand(p, sizeof(p));
|
|
||||||
s_len = 0; s_sync = false; // report stream resumes; drop partial state
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary) {
|
|
||||||
if (gate > 8) return false;
|
|
||||||
// Command 0x0064: three (param-id, uint32 value) pairs.
|
|
||||||
const uint8_t p[] = {
|
|
||||||
0x64, 0x00,
|
|
||||||
0x00, 0x00, gate, 0x00, 0x00, 0x00,
|
|
||||||
0x01, 0x00, moving, 0x00, 0x00, 0x00,
|
|
||||||
0x02, 0x00, stationary, 0x00, 0x00, 0x00,
|
|
||||||
};
|
|
||||||
return sendCommand(p, sizeof(p));
|
|
||||||
}
|
|
||||||
@@ -1,562 +0,0 @@
|
|||||||
// poorBird — ESP32-S3 camera node
|
|
||||||
//
|
|
||||||
// Two operating modes, selected by g_cfg.deep_sleep_enabled and switchable
|
|
||||||
// from the WebUI. See power_mgr.h for what each one costs you.
|
|
||||||
//
|
|
||||||
// AWAKE MODE (default, mains powered)
|
|
||||||
// capture task (core 1) camera + PSRAM ring + stream frames
|
|
||||||
// loop() (core 0) uploads, heartbeat, commands, OTA, sleep check
|
|
||||||
//
|
|
||||||
// Splitting it this way means a 3-second upload over marginal WiFi never
|
|
||||||
// stops the ring from filling, so the pre-trigger history stays continuous
|
|
||||||
// even while the previous event is still being sent. Exactly one task ever
|
|
||||||
// touches the camera, which is the only threading rule esp32-camera cares
|
|
||||||
// about.
|
|
||||||
//
|
|
||||||
// SLEEP MODE (battery)
|
|
||||||
// One linear pass in setup(): wake -> capture burst -> upload -> drain
|
|
||||||
// commands -> sleep. No tasks, no ring, no pre-trigger frames.
|
|
||||||
//
|
|
||||||
// Every failure path ends in sleep when sleep is on, and in a retry with
|
|
||||||
// backoff when it is not (SPEC §4.3).
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
#include "api_client.h"
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "battery.h"
|
|
||||||
#include "board_pins.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
#include "commands.h"
|
|
||||||
#include "device_stats.h"
|
|
||||||
#include "frame_ring.h"
|
|
||||||
#include "ld2410.h"
|
|
||||||
#include "net_mgr.h"
|
|
||||||
#include "nightlight.h"
|
|
||||||
#include "ota_mgr.h"
|
|
||||||
#include "power_mgr.h"
|
|
||||||
#include "stream_session.h"
|
|
||||||
|
|
||||||
// Firmware target from the most recent response envelope. commands.cpp reads it.
|
|
||||||
OtaTarget g_fw_target = {};
|
|
||||||
|
|
||||||
// --- capture event handoff --------------------------------------------------
|
|
||||||
struct CaptureEvent {
|
|
||||||
uint32_t at_ms;
|
|
||||||
const char* trigger;
|
|
||||||
RadarReading radar;
|
|
||||||
};
|
|
||||||
|
|
||||||
static QueueHandle_t s_events = nullptr;
|
|
||||||
static TaskHandle_t s_capture_task = nullptr;
|
|
||||||
static volatile bool s_manual_req = false;
|
|
||||||
static uint32_t s_last_trigger_ms = 0;
|
|
||||||
static uint32_t s_next_heartbeat_ms = 0;
|
|
||||||
static uint32_t s_next_status_ms = 0;
|
|
||||||
static uint32_t s_next_battery_ms = 0;
|
|
||||||
static uint32_t s_burst_light_until_ms = 0;
|
|
||||||
static uint8_t s_upload_failures = 0;
|
|
||||||
|
|
||||||
void requestManualCapture() { s_manual_req = true; }
|
|
||||||
|
|
||||||
static void statusLed(bool on) {
|
|
||||||
#if STATUS_LED_ACTIVE_LOW
|
|
||||||
digitalWrite(PIN_STATUS_LED, on ? LOW : HIGH);
|
|
||||||
#else
|
|
||||||
digitalWrite(PIN_STATUS_LED, on ? HIGH : LOW);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
// A burst id the Pi can group frames by. Device uid + boot + millis is unique
|
|
||||||
// without needing a random source or a synced clock.
|
|
||||||
static void makeBurstId(char* out, size_t cap) {
|
|
||||||
snprintf(out, cap, "%s-%u-%u", deviceUid(), (unsigned)powerBootCount(), (unsigned)millis());
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Response handling shared by every API call
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static void handleEnvelope(const ServerEnvelope& env) {
|
|
||||||
if (!env.ok) return;
|
|
||||||
|
|
||||||
netAdoptServerTime(env.server_time_ms);
|
|
||||||
|
|
||||||
if (env.config_version != g_cfg.config_version) {
|
|
||||||
log_i("config: endpoint is at v%u, we are at v%u — pulling",
|
|
||||||
(unsigned)env.config_version, (unsigned)g_cfg.config_version);
|
|
||||||
const bool was_sleeping = g_cfg.deep_sleep_enabled;
|
|
||||||
const AppConfig before = g_cfg;
|
|
||||||
if (apiFetchConfig()) {
|
|
||||||
cameraApplyConfig();
|
|
||||||
powerOnConfigChanged(was_sleeping);
|
|
||||||
if (configNeedsCameraRestart(before, g_cfg)) cameraRestart();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (env.has_firmware) {
|
|
||||||
strncpy(g_fw_target.version, env.fw_version, sizeof(g_fw_target.version) - 1);
|
|
||||||
strncpy(g_fw_target.url, env.fw_url, sizeof(g_fw_target.url) - 1);
|
|
||||||
strncpy(g_fw_target.sha256, env.fw_sha256, sizeof(g_fw_target.sha256) - 1);
|
|
||||||
g_fw_target.size = env.fw_size;
|
|
||||||
|
|
||||||
// The endpoint naming a different target is itself the instruction;
|
|
||||||
// an explicit ota_update command is only needed for staged rollouts.
|
|
||||||
if (otaIsNewer(g_fw_target) && g_cfg.ota_enabled) {
|
|
||||||
log_i("ota: endpoint targets %s, we run %s", g_fw_target.version, FW_VERSION);
|
|
||||||
otaApply(g_fw_target); // reboots on success
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recover from a rotated or revoked token without physical access: clear it,
|
|
||||||
// re-enroll with the stored per-device secret, and carry on. This is why
|
|
||||||
// enrollment does not wipe its secret — see apiEnroll().
|
|
||||||
static bool reenrollAfterRejection() {
|
|
||||||
log_w("auth: token rejected, re-enrolling");
|
|
||||||
g_cfg.device_token[0] = '\0';
|
|
||||||
configSave();
|
|
||||||
|
|
||||||
if (apiEnroll()) {
|
|
||||||
log_i("auth: recovered, new token in use");
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
log_e("auth: re-enrollment failed, will retry at the next check-in");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool sendHeartbeat() {
|
|
||||||
// A token cleared by a failed upload earlier in the loop gets replaced
|
|
||||||
// here rather than waiting for a reboot.
|
|
||||||
if (!g_cfg.device_token[0]) apiEnroll();
|
|
||||||
|
|
||||||
ServerEnvelope env = apiHeartbeat(commandOnReceived);
|
|
||||||
|
|
||||||
if (!env.ok && apiTokenRejected() && reenrollAfterRejection()) {
|
|
||||||
env = apiHeartbeat(commandOnReceived); // one retry with the new token
|
|
||||||
}
|
|
||||||
|
|
||||||
if (env.ok) {
|
|
||||||
handleEnvelope(env);
|
|
||||||
// A heartbeat the endpoint accepted proves WiFi, HTTP, auth and JSON
|
|
||||||
// all work on this image. That is the bar for confirming a trial boot.
|
|
||||||
otaMarkValid();
|
|
||||||
powerRelease(INHIBIT_BOOT); // no-op after the first time
|
|
||||||
s_upload_failures = 0;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Upload one event's worth of frames
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static void uploadEvent(const CaptureEvent& ev, FrameCopy* frames, size_t n) {
|
|
||||||
if (n == 0) return;
|
|
||||||
|
|
||||||
SleepGuard guard(INHIBIT_UPLOAD);
|
|
||||||
statusLed(true);
|
|
||||||
|
|
||||||
char burst[48];
|
|
||||||
makeBurstId(burst, sizeof(burst));
|
|
||||||
|
|
||||||
// pre_roll is how many of these frames predate the trigger, capped at what
|
|
||||||
// the ring actually had.
|
|
||||||
const size_t pre = (g_cfg.pre_roll < n) ? g_cfg.pre_roll : 0;
|
|
||||||
|
|
||||||
statsCountCaptured((uint16_t)n);
|
|
||||||
|
|
||||||
size_t sent = 0;
|
|
||||||
for (size_t i = 0; i < n; i++) {
|
|
||||||
CaptureMeta meta = {};
|
|
||||||
meta.trigger = ev.trigger;
|
|
||||||
meta.burst_id = burst;
|
|
||||||
meta.burst_index = (uint8_t)i;
|
|
||||||
meta.burst_count = (uint8_t)n;
|
|
||||||
meta.pre_trigger = (i < pre) ? 1 : 0;
|
|
||||||
meta.radar_distance_cm = ev.radar.moving_cm ? ev.radar.moving_cm : ev.radar.stationary_cm;
|
|
||||||
meta.radar_energy = ev.radar.moving_energy ? ev.radar.moving_energy
|
|
||||||
: ev.radar.stationary_energy;
|
|
||||||
meta.radar_state = ev.radar.target;
|
|
||||||
|
|
||||||
ServerEnvelope env = apiIngest(frames[i], meta, commandOnReceived);
|
|
||||||
if (env.ok) {
|
|
||||||
sent++;
|
|
||||||
// Only the first response needs acting on; the rest of the burst
|
|
||||||
// would just repeat the same commands.
|
|
||||||
if (i == 0) handleEnvelope(env);
|
|
||||||
} else if (apiTokenRejected()) {
|
|
||||||
// Recover in place and finish the burst rather than losing the
|
|
||||||
// whole event to a token that was rotated a second ago.
|
|
||||||
if (reenrollAfterRejection()) {
|
|
||||||
ServerEnvelope retry = apiIngest(frames[i], meta, commandOnReceived);
|
|
||||||
if (retry.ok) { sent++; continue; }
|
|
||||||
}
|
|
||||||
log_w("auth: cannot recover mid-burst, abandoning the remaining frames");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (size_t i = 0; i < n; i++) free(frames[i].data);
|
|
||||||
|
|
||||||
statsCountDelivered((uint16_t)sent);
|
|
||||||
statsCountFailed((uint16_t)(n - sent));
|
|
||||||
|
|
||||||
statusLed(false);
|
|
||||||
log_i("event: %s, %u/%u frames uploaded (%u pre-trigger)",
|
|
||||||
ev.trigger, (unsigned)sent, (unsigned)n, (unsigned)pre);
|
|
||||||
|
|
||||||
if (sent == 0) s_upload_failures++;
|
|
||||||
else s_upload_failures = 0;
|
|
||||||
|
|
||||||
// Push conditions after a burst so the WebUI's delivered-today counter
|
|
||||||
// tracks reality without waiting for the next heartbeat. /status carries
|
|
||||||
// no command queue, so this costs one small POST and nothing else.
|
|
||||||
if (g_cfg.status_interval_s) {
|
|
||||||
apiPostStatus("after_event");
|
|
||||||
s_next_status_ms = millis() + g_cfg.status_interval_s * 1000UL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pull pre+post roll out of the ring and ship it. In AWAKE mode the ring is
|
|
||||||
// still being filled by the capture task while we wait, so the post-roll
|
|
||||||
// frames are real frames from after the trigger, not re-sent history.
|
|
||||||
static void serviceEvent(const CaptureEvent& ev) {
|
|
||||||
const size_t pre = g_cfg.pre_roll;
|
|
||||||
const size_t post = g_cfg.post_roll;
|
|
||||||
|
|
||||||
// Let the capture task collect the post-roll before we take the slice.
|
|
||||||
const uint32_t settle_ms = post * g_cfg.idle_period_ms;
|
|
||||||
if (settle_ms) vTaskDelay(pdMS_TO_TICKS(settle_ms));
|
|
||||||
|
|
||||||
const size_t want = pre + post;
|
|
||||||
FrameCopy frames[64];
|
|
||||||
size_t n = ringTakeNewest(want, frames, sizeof(frames) / sizeof(frames[0]));
|
|
||||||
if (n == 0) {
|
|
||||||
log_w("event: ring was empty, nothing to upload");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
uploadEvent(ev, frames, n);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// AWAKE MODE — capture task
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static void captureTask(void*) {
|
|
||||||
log_i("capture task running on core %d", xPortGetCoreID());
|
|
||||||
|
|
||||||
for (;;) {
|
|
||||||
// Streaming takes over the camera entirely; the ring pauses for the
|
|
||||||
// session. You are watching live, so history is not the point.
|
|
||||||
if (streamActive()) {
|
|
||||||
streamTick();
|
|
||||||
radarPoll();
|
|
||||||
vTaskDelay(pdMS_TO_TICKS(5));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
radarPoll();
|
|
||||||
RadarReading r = radarLast();
|
|
||||||
|
|
||||||
nightTick();
|
|
||||||
|
|
||||||
// NIGHT_IDLE / NIGHT_SLEEP: stop feeding the ring after dark. A manual
|
|
||||||
// capture_now still works — an operator asking for a frame should get
|
|
||||||
// one, dark or not.
|
|
||||||
if (!nightCaptureAllowed() && !s_manual_req) {
|
|
||||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
camera_fb_t* fb = cameraGrab();
|
|
||||||
if (fb) {
|
|
||||||
ringPush(fb->buf, fb->len, netEpochMs());
|
|
||||||
esp_camera_fb_return(fb);
|
|
||||||
}
|
|
||||||
|
|
||||||
const bool manual = s_manual_req;
|
|
||||||
const bool trigger = manual || radarIsTrigger(r);
|
|
||||||
const bool cooled = (millis() - s_last_trigger_ms) > (g_cfg.cooldown_s * 1000UL);
|
|
||||||
|
|
||||||
if (trigger && (cooled || manual)) {
|
|
||||||
s_last_trigger_ms = millis();
|
|
||||||
s_manual_req = false;
|
|
||||||
|
|
||||||
// NIGHTLIGHT_ON_BURST: light up and let exposure settle before the
|
|
||||||
// post-roll frames are grabbed. Costs ~120 ms of trigger latency,
|
|
||||||
// which is why NIGHTLIGHT_ALWAYS is the better option if you are
|
|
||||||
// willing to run the light all night.
|
|
||||||
nightIlluminateBurstBegin();
|
|
||||||
|
|
||||||
CaptureEvent ev = {millis(), manual ? "manual" : "radar", r};
|
|
||||||
statsCountEvent();
|
|
||||||
if (xQueueSend(s_events, &ev, 0) != pdTRUE) {
|
|
||||||
log_w("event queue full, dropping trigger");
|
|
||||||
} else {
|
|
||||||
log_i("TRIGGER (%s) dist=%ucm energy=%u state=%u ring=%u",
|
|
||||||
ev.trigger, r.moving_cm, r.moving_energy, r.target,
|
|
||||||
(unsigned)ringCount());
|
|
||||||
}
|
|
||||||
// Keep the light on until the post-roll frames have been grabbed;
|
|
||||||
// serviceEvent() takes its slice of the ring at about that point.
|
|
||||||
s_burst_light_until_ms =
|
|
||||||
millis() + g_cfg.post_roll * g_cfg.idle_period_ms + 300;
|
|
||||||
|
|
||||||
powerNoteActivity();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (s_burst_light_until_ms &&
|
|
||||||
(int32_t)(s_burst_light_until_ms - millis()) <= 0) {
|
|
||||||
s_burst_light_until_ms = 0;
|
|
||||||
nightIlluminateBurstEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
vTaskDelay(pdMS_TO_TICKS(g_cfg.idle_period_ms));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// SLEEP MODE — one linear pass, then sleep
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static void runSleepCycle() {
|
|
||||||
log_i("=== sleep-mode wake (%s) ===", powerWakeCauseName());
|
|
||||||
|
|
||||||
const bool radar_wake = (powerWakeCause() == WAKE_RADAR);
|
|
||||||
|
|
||||||
if (radar_wake && !nightCaptureAllowed()) {
|
|
||||||
log_i("woken by radar during the night window, not capturing");
|
|
||||||
sendHeartbeat();
|
|
||||||
commandRunDeferred();
|
|
||||||
if (g_cfg.night_behaviour == NIGHT_SLEEP && !powerIsInhibited()) {
|
|
||||||
apiPostStatus("before_night_sleep");
|
|
||||||
powerSleepUntilMorning();
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (radar_wake) {
|
|
||||||
// No ring in this mode: the camera was off. This is SPEC C4's
|
|
||||||
// 1-3 second latency, unavoidable without continuous capture.
|
|
||||||
if (!cameraBegin()) {
|
|
||||||
log_e("camera init failed, sleeping");
|
|
||||||
powerSleepNow();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
nightBegin(); // selects the day/night tuning profile for this wake
|
|
||||||
|
|
||||||
// A shallow ring just to reuse the same upload path. Depth = the burst
|
|
||||||
// size; frames are grabbed back to back rather than at idle_period_ms.
|
|
||||||
const uint8_t burst = g_cfg.post_roll ? g_cfg.post_roll : 5;
|
|
||||||
ringBegin(burst);
|
|
||||||
|
|
||||||
radarPoll();
|
|
||||||
RadarReading r = radarLast();
|
|
||||||
statsCountEvent();
|
|
||||||
|
|
||||||
nightIlluminateBurstBegin();
|
|
||||||
for (uint8_t i = 0; i < burst; i++) {
|
|
||||||
camera_fb_t* fb = cameraGrab();
|
|
||||||
if (fb) {
|
|
||||||
ringPush(fb->buf, fb->len, netEpochMs());
|
|
||||||
esp_camera_fb_return(fb);
|
|
||||||
}
|
|
||||||
if (g_cfg.post_roll_gap_ms) delay(g_cfg.post_roll_gap_ms);
|
|
||||||
}
|
|
||||||
nightIlluminateBurstEnd();
|
|
||||||
|
|
||||||
FrameCopy frames[64];
|
|
||||||
size_t n = ringTakeNewest(burst, frames, sizeof(frames) / sizeof(frames[0]));
|
|
||||||
if (n) {
|
|
||||||
CaptureEvent ev = {millis(), "radar", r};
|
|
||||||
// Nothing here predates the trigger, so pre_roll must not claim
|
|
||||||
// otherwise in the metadata.
|
|
||||||
const uint8_t saved_pre = g_cfg.pre_roll;
|
|
||||||
g_cfg.pre_roll = 0;
|
|
||||||
uploadEvent(ev, frames, n);
|
|
||||||
g_cfg.pre_roll = saved_pre;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always check in, whatever woke us: this is how commands, config and
|
|
||||||
// firmware targets reach a sleeping device (SPEC C1).
|
|
||||||
sendHeartbeat();
|
|
||||||
commandRunDeferred();
|
|
||||||
|
|
||||||
// A stream_start or wake_and_hold command may have just arrived. Stay up
|
|
||||||
// and let loop() handle it; powerMaybeSleep() will put us back down.
|
|
||||||
if (powerIsInhibited() || streamActive() || commandHasPending()) {
|
|
||||||
log_i("sleep deferred: %s", powerInhibitSummary());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The endpoint may have switched sleep off in the heartbeat we just did.
|
|
||||||
if (!g_cfg.deep_sleep_enabled) {
|
|
||||||
log_i("deep sleep switched off by the endpoint, continuing in awake mode");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (g_cfg.night_behaviour == NIGHT_SLEEP && nightIsNight()) {
|
|
||||||
apiPostStatus("before_night_sleep");
|
|
||||||
powerSleepUntilMorning();
|
|
||||||
}
|
|
||||||
|
|
||||||
apiPostStatus("before_sleep");
|
|
||||||
powerSleepNow();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
static void startAwakeMode() {
|
|
||||||
if (s_capture_task) return;
|
|
||||||
|
|
||||||
if (!cameraBegin()) {
|
|
||||||
log_e("camera init failed — retrying in 5 s");
|
|
||||||
delay(5000);
|
|
||||||
ESP.restart();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ringBegin(g_cfg.ring_frames)) {
|
|
||||||
log_w("ring buffer unavailable, running without pre-trigger history");
|
|
||||||
}
|
|
||||||
|
|
||||||
nightBegin(); // after cameraBegin(): LEDC channel 0 is the camera's XCLK
|
|
||||||
|
|
||||||
s_events = xQueueCreate(4, sizeof(CaptureEvent));
|
|
||||||
xTaskCreatePinnedToCore(captureTask, "capture", 6144, nullptr, 5, &s_capture_task, 1);
|
|
||||||
log_i("awake mode: pre-trigger ring active (%u frames, ~%.1f s of history)",
|
|
||||||
(unsigned)ringCount(), g_cfg.ring_frames * g_cfg.idle_period_ms / 1000.0f);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
delay(300); // let USB CDC enumerate so the boot banner is not lost
|
|
||||||
|
|
||||||
pinMode(PIN_STATUS_LED, OUTPUT);
|
|
||||||
statusLed(true);
|
|
||||||
|
|
||||||
log_i("");
|
|
||||||
log_i("poorBird %s (%s)", FW_VERSION, HW_REVISION);
|
|
||||||
|
|
||||||
powerBegin(); // first: reads the wake cause before anything resets it
|
|
||||||
configLoad();
|
|
||||||
otaBegin();
|
|
||||||
statsBegin();
|
|
||||||
configDump();
|
|
||||||
|
|
||||||
batteryBegin();
|
|
||||||
otaSetBatteryCheck(batteryAboveOtaThreshold, g_cfg.battery_min_pct_ota);
|
|
||||||
|
|
||||||
radarBegin();
|
|
||||||
if (powerWakeCause() == WAKE_POWER_ON) {
|
|
||||||
// Only on a cold boot: it is noisy and pointless on every timer wake.
|
|
||||||
radarSelfTest(2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
netBegin();
|
|
||||||
apiBegin();
|
|
||||||
|
|
||||||
if (!netConnect()) {
|
|
||||||
log_e("no network on boot");
|
|
||||||
if (g_cfg.deep_sleep_enabled) powerSleepNow();
|
|
||||||
else { delay(10000); ESP.restart(); }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!apiEnroll()) {
|
|
||||||
log_e("not enrolled — cannot talk to the endpoint");
|
|
||||||
if (g_cfg.deep_sleep_enabled) powerSleepNow();
|
|
||||||
else { delay(30000); ESP.restart(); }
|
|
||||||
}
|
|
||||||
|
|
||||||
netSyncTime();
|
|
||||||
|
|
||||||
statusLed(false);
|
|
||||||
|
|
||||||
if (g_cfg.deep_sleep_enabled) {
|
|
||||||
runSleepCycle();
|
|
||||||
// Only reached if sleep was deferred or switched off.
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!g_cfg.deep_sleep_enabled) startAwakeMode();
|
|
||||||
|
|
||||||
s_next_heartbeat_ms = millis();
|
|
||||||
s_next_status_ms = millis() + 5000;
|
|
||||||
s_next_battery_ms = millis();
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
// In sleep mode with a deferred sleep, the capture task does not exist and
|
|
||||||
// loop() is just servicing whatever held us awake.
|
|
||||||
if (s_events) {
|
|
||||||
CaptureEvent ev;
|
|
||||||
while (xQueueReceive(s_events, &ev, 0) == pdTRUE) {
|
|
||||||
if (streamActive()) {
|
|
||||||
log_i("event dropped: a stream is running");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
serviceEvent(ev);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
commandRunDeferred();
|
|
||||||
|
|
||||||
if ((int32_t)(s_next_heartbeat_ms - millis()) <= 0) {
|
|
||||||
if (!netIsConnected()) netConnect();
|
|
||||||
if (netIsConnected()) sendHeartbeat();
|
|
||||||
|
|
||||||
// Back off when the endpoint is unreachable so a Pi that is down for
|
|
||||||
// an hour does not mean an hour of failed requests every 5 minutes.
|
|
||||||
uint32_t interval = g_cfg.heartbeat_interval_s;
|
|
||||||
if (s_upload_failures > 3) {
|
|
||||||
uint8_t shift = s_upload_failures - 3;
|
|
||||||
if (shift > 4) shift = 4;
|
|
||||||
interval <<= shift;
|
|
||||||
if (interval > 3600) interval = 3600;
|
|
||||||
log_w("endpoint unreachable, next check-in in %us", (unsigned)interval);
|
|
||||||
}
|
|
||||||
s_next_heartbeat_ms = millis() + interval * 1000UL;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Battery is read on its own slower timer: the ADC read powers the divider
|
|
||||||
// and averages 16 samples, so there is no point doing it per loop tick.
|
|
||||||
if ((int32_t)(s_next_battery_ms - millis()) <= 0) {
|
|
||||||
batteryPoll();
|
|
||||||
s_next_battery_ms = millis() + 60000;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Conditions push. Distinct from the heartbeat because it carries no
|
|
||||||
// command queue — see apiPostStatus().
|
|
||||||
if (g_cfg.status_interval_s && (int32_t)(s_next_status_ms - millis()) <= 0) {
|
|
||||||
if (netIsConnected()) apiPostStatus("periodic");
|
|
||||||
s_next_status_ms = millis() + g_cfg.status_interval_s * 1000UL;
|
|
||||||
}
|
|
||||||
|
|
||||||
statsRollover();
|
|
||||||
|
|
||||||
// Night policy. NIGHT_SLEEP overrides the deep-sleep switch: a camera with
|
|
||||||
// no illuminator has nothing to do at 03:00 whether it is on mains or not.
|
|
||||||
if (g_cfg.night_behaviour == NIGHT_SLEEP && nightIsNight() && !streamActive()) {
|
|
||||||
if (netIsConnected()) apiPostStatus("before_night_sleep");
|
|
||||||
powerSleepUntilMorning(); // does not return if it sleeps
|
|
||||||
}
|
|
||||||
|
|
||||||
if (g_cfg.deep_sleep_enabled) {
|
|
||||||
// Turning sleep on at runtime: tear the awake-mode machinery down
|
|
||||||
// cleanly, then let powerMaybeSleep() take us under.
|
|
||||||
if (s_capture_task) {
|
|
||||||
log_i("deep sleep switched on, stopping capture task");
|
|
||||||
vTaskDelete(s_capture_task);
|
|
||||||
s_capture_task = nullptr;
|
|
||||||
ringEnd();
|
|
||||||
}
|
|
||||||
// Tell the endpoint where we stand before the radio goes off. /status
|
|
||||||
// carries no command queue, which is exactly right here: picking up a
|
|
||||||
// command we are about to become unable to execute would just make it
|
|
||||||
// look delivered.
|
|
||||||
if (powerWouldSleepNow() && netIsConnected()) apiPostStatus("before_sleep");
|
|
||||||
|
|
||||||
powerMaybeSleep(); // does not return if it sleeps
|
|
||||||
} else if (!s_capture_task) {
|
|
||||||
// Sleep was switched off while we were running a sleep cycle.
|
|
||||||
startAwakeMode();
|
|
||||||
}
|
|
||||||
|
|
||||||
delay(20);
|
|
||||||
}
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
#include "net_mgr.h"
|
|
||||||
|
|
||||||
#include <WiFi.h>
|
|
||||||
#include <esp_sntp.h>
|
|
||||||
#include <sys/time.h>
|
|
||||||
#include <time.h>
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
|
|
||||||
static bool s_time_valid = false;
|
|
||||||
|
|
||||||
// Anything before this is obviously not a real clock reading.
|
|
||||||
static const int64_t kSaneEpochMs = 1735689600000LL; // 2025-01-01
|
|
||||||
|
|
||||||
bool netBegin() {
|
|
||||||
WiFi.persistent(false);
|
|
||||||
WiFi.mode(WIFI_STA);
|
|
||||||
WiFi.setSleep(true); // DTIM-based modem sleep; harmless on mains
|
|
||||||
WiFi.setAutoReconnect(true);
|
|
||||||
WiFi.setHostname(g_cfg.device_name);
|
|
||||||
|
|
||||||
setenv("TZ", g_cfg.tz, 1); // SPEC C7: set TZ explicitly, everywhere
|
|
||||||
tzset();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool netConnect(uint8_t max_attempts) {
|
|
||||||
if (WiFi.status() == WL_CONNECTED) return true;
|
|
||||||
|
|
||||||
if (!g_cfg.wifi_ssid[0]) {
|
|
||||||
log_e("no WiFi SSID configured — set CFG_WIFI_SSID in secrets.ini");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (uint8_t attempt = 1; attempt <= max_attempts; attempt++) {
|
|
||||||
log_i("wifi: connecting to '%s' (attempt %u/%u)",
|
|
||||||
g_cfg.wifi_ssid, attempt, max_attempts);
|
|
||||||
|
|
||||||
WiFi.begin(g_cfg.wifi_ssid, g_cfg.wifi_pass);
|
|
||||||
|
|
||||||
const uint32_t deadline = millis() + 10000;
|
|
||||||
while (WiFi.status() != WL_CONNECTED && (int32_t)(deadline - millis()) > 0) {
|
|
||||||
delay(100);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (WiFi.status() == WL_CONNECTED) {
|
|
||||||
log_i("wifi: %s rssi %d dBm", WiFi.localIP().toString().c_str(), WiFi.RSSI());
|
|
||||||
if (WiFi.RSSI() < -75) {
|
|
||||||
// Worth surfacing: weak signal lengthens every transmit, which
|
|
||||||
// on battery is a direct runtime cost (SPEC C5).
|
|
||||||
log_w("wifi: RSSI %d dBm is marginal at this mounting point", WiFi.RSSI());
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
WiFi.disconnect(true, false);
|
|
||||||
// Exponential backoff, bounded. Never a tight retry loop (SPEC §4.3).
|
|
||||||
if (attempt < max_attempts) delay(1000UL << attempt);
|
|
||||||
}
|
|
||||||
|
|
||||||
log_w("wifi: giving up after %u attempts", max_attempts);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool netIsConnected() { return WiFi.status() == WL_CONNECTED; }
|
|
||||||
|
|
||||||
void netDisconnect() {
|
|
||||||
WiFi.disconnect(true, false);
|
|
||||||
WiFi.mode(WIFI_OFF);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool netSyncTime(uint32_t timeout_ms) {
|
|
||||||
const char* host = g_cfg.ntp_host[0] ? g_cfg.ntp_host : g_cfg.api_host;
|
|
||||||
log_i("time: SNTP against %s", host);
|
|
||||||
|
|
||||||
esp_sntp_stop();
|
|
||||||
esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
|
|
||||||
esp_sntp_setservername(0, host);
|
|
||||||
esp_sntp_init();
|
|
||||||
|
|
||||||
const uint32_t deadline = millis() + timeout_ms;
|
|
||||||
while ((int32_t)(deadline - millis()) > 0) {
|
|
||||||
if (esp_sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED || netEpochMs() > kSaneEpochMs) {
|
|
||||||
s_time_valid = true;
|
|
||||||
char iso[32];
|
|
||||||
netIsoTime(iso, sizeof(iso));
|
|
||||||
log_i("time: synced, %s", iso);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
delay(100);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not fatal. The next ingest/heartbeat response will carry server_time and
|
|
||||||
// netAdoptServerTime() picks it up from there.
|
|
||||||
log_w("time: SNTP did not complete, falling back to the API response clock");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
void netAdoptServerTime(int64_t server_ms) {
|
|
||||||
if (server_ms < kSaneEpochMs) return;
|
|
||||||
|
|
||||||
const int64_t now = netEpochMs();
|
|
||||||
const int64_t drift = (now > server_ms) ? (now - server_ms) : (server_ms - now);
|
|
||||||
|
|
||||||
if (s_time_valid && drift < 2000) return; // within tolerance, leave it
|
|
||||||
|
|
||||||
struct timeval tv = {
|
|
||||||
.tv_sec = (time_t)(server_ms / 1000),
|
|
||||||
.tv_usec = (suseconds_t)((server_ms % 1000) * 1000),
|
|
||||||
};
|
|
||||||
settimeofday(&tv, nullptr);
|
|
||||||
s_time_valid = true;
|
|
||||||
|
|
||||||
char iso[32];
|
|
||||||
netIsoTime(iso, sizeof(iso));
|
|
||||||
log_i("time: adopted endpoint clock (%s, drift was %lld ms)", iso, (long long)drift);
|
|
||||||
}
|
|
||||||
|
|
||||||
int64_t netEpochMs() {
|
|
||||||
struct timeval tv;
|
|
||||||
if (gettimeofday(&tv, nullptr) != 0) return 0;
|
|
||||||
int64_t ms = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
|
|
||||||
return (ms > kSaneEpochMs) ? ms : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool netTimeValid() { return s_time_valid && netEpochMs() > 0; }
|
|
||||||
|
|
||||||
void netIsoTime(char* out, size_t cap) {
|
|
||||||
if (!cap) return;
|
|
||||||
out[0] = '\0';
|
|
||||||
int64_t ms = netEpochMs();
|
|
||||||
if (ms == 0) return;
|
|
||||||
time_t t = (time_t)(ms / 1000);
|
|
||||||
struct tm gm;
|
|
||||||
gmtime_r(&t, &gm);
|
|
||||||
strftime(out, cap, "%Y-%m-%dT%H:%M:%SZ", &gm);
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
#include "nightlight.h"
|
|
||||||
|
|
||||||
#include <time.h>
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "board_pins.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
#include "net_mgr.h"
|
|
||||||
|
|
||||||
static bool s_led_on = false;
|
|
||||||
static bool s_was_night = false;
|
|
||||||
static bool s_pwm_ready = false;
|
|
||||||
|
|
||||||
static const uint32_t kPwmFreq = 5000;
|
|
||||||
static const uint8_t kPwmBits = 8;
|
|
||||||
|
|
||||||
static void ledSet(bool on, uint8_t duty) {
|
|
||||||
#if PIN_NIGHTLIGHT >= 0
|
|
||||||
if (!s_pwm_ready) return;
|
|
||||||
ledcWrite(PIN_NIGHTLIGHT, on ? duty : 0);
|
|
||||||
s_led_on = on;
|
|
||||||
#else
|
|
||||||
(void)on; (void)duty;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void nightBegin() {
|
|
||||||
#if PIN_NIGHTLIGHT >= 0
|
|
||||||
// ledcAttach picks a free LEDC channel. The camera driver has already
|
|
||||||
// taken channel 0 / timer 0 for XCLK by this point, so call nightBegin()
|
|
||||||
// after cameraBegin() and let the allocator route around it.
|
|
||||||
s_pwm_ready = ledcAttach(PIN_NIGHTLIGHT, kPwmFreq, kPwmBits);
|
|
||||||
if (!s_pwm_ready) {
|
|
||||||
log_e("nightlight: LEDC attach failed on GPIO%d (channel exhausted?)", PIN_NIGHTLIGHT);
|
|
||||||
} else {
|
|
||||||
ledcWrite(PIN_NIGHTLIGHT, 0);
|
|
||||||
log_i("nightlight: PWM on GPIO%d", PIN_NIGHTLIGHT);
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
log_i("nightlight: no LED pin configured");
|
|
||||||
#endif
|
|
||||||
s_was_night = nightIsNight();
|
|
||||||
cameraApplyTuning(s_was_night);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool nightIsNight() {
|
|
||||||
if (!netTimeValid()) return false;
|
|
||||||
|
|
||||||
const int64_t ms = netEpochMs();
|
|
||||||
if (ms == 0) return false;
|
|
||||||
|
|
||||||
time_t t = (time_t)(ms / 1000);
|
|
||||||
struct tm lt;
|
|
||||||
localtime_r(&t, <);
|
|
||||||
const uint16_t now_min = lt.tm_hour * 60 + lt.tm_min;
|
|
||||||
|
|
||||||
const uint16_t start = g_cfg.night_start_min;
|
|
||||||
const uint16_t end = g_cfg.night_end_min;
|
|
||||||
if (start == end) return false; // window disabled
|
|
||||||
|
|
||||||
// The normal case wraps midnight (21:00 -> 06:00); the non-wrapping case
|
|
||||||
// is only reachable from a deliberately odd config, but costs one branch.
|
|
||||||
return (start > end) ? (now_min >= start || now_min < end)
|
|
||||||
: (now_min >= start && now_min < end);
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t nightSecondsUntilMorning() {
|
|
||||||
if (!nightIsNight()) return 0;
|
|
||||||
|
|
||||||
const int64_t ms = netEpochMs();
|
|
||||||
time_t t = (time_t)(ms / 1000);
|
|
||||||
struct tm lt;
|
|
||||||
localtime_r(&t, <);
|
|
||||||
const int32_t now_s = lt.tm_hour * 3600 + lt.tm_min * 60 + lt.tm_sec;
|
|
||||||
const int32_t end_s = (int32_t)g_cfg.night_end_min * 60;
|
|
||||||
|
|
||||||
int32_t delta = end_s - now_s;
|
|
||||||
if (delta <= 0) delta += 86400; // morning is tomorrow
|
|
||||||
|
|
||||||
// Wake a minute early: the first frames after a long sleep are throwaway
|
|
||||||
// while auto-exposure settles, and being late for dawn is worse than
|
|
||||||
// being early for it.
|
|
||||||
if (delta > 60) delta -= 60;
|
|
||||||
return (uint32_t)delta;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool nightCaptureAllowed() {
|
|
||||||
if (!nightIsNight()) return true;
|
|
||||||
return g_cfg.night_behaviour == NIGHT_CAPTURE;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool nightlightIsOn() { return s_led_on; }
|
|
||||||
|
|
||||||
void nightTick() {
|
|
||||||
const bool is_night = nightIsNight();
|
|
||||||
|
|
||||||
if (is_night != s_was_night) {
|
|
||||||
log_i("night: %s", is_night ? "dusk — switching to the night profile"
|
|
||||||
: "dawn — back to the day profile");
|
|
||||||
s_was_night = is_night;
|
|
||||||
cameraApplyTuning(is_night);
|
|
||||||
}
|
|
||||||
|
|
||||||
// NIGHTLIGHT_ALWAYS keeps the illuminator on for the whole night. Steady
|
|
||||||
// light is easier on wildlife than a burst per trigger, and it also means
|
|
||||||
// auto-exposure is already settled when a bird arrives.
|
|
||||||
const bool want_on = is_night &&
|
|
||||||
g_cfg.nightlight_mode == NIGHTLIGHT_ALWAYS &&
|
|
||||||
g_cfg.night_behaviour == NIGHT_CAPTURE;
|
|
||||||
|
|
||||||
if (want_on != s_led_on) ledSet(want_on, g_cfg.nightlight_brightness);
|
|
||||||
}
|
|
||||||
|
|
||||||
void nightIlluminateBurstBegin() {
|
|
||||||
if (!nightIsNight()) return;
|
|
||||||
if (g_cfg.nightlight_mode != NIGHTLIGHT_ON_BURST) return;
|
|
||||||
if (g_cfg.night_behaviour != NIGHT_CAPTURE) return;
|
|
||||||
|
|
||||||
ledSet(true, g_cfg.nightlight_brightness);
|
|
||||||
// Auto-exposure needs a moment to react to the light appearing. Without
|
|
||||||
// this the first frames of the burst are the blown-out ones.
|
|
||||||
delay(120);
|
|
||||||
cameraDiscardFrames(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
void nightIlluminateBurstEnd() {
|
|
||||||
if (g_cfg.nightlight_mode != NIGHTLIGHT_ON_BURST) return;
|
|
||||||
ledSet(false, 0);
|
|
||||||
}
|
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
#include "ota_mgr.h"
|
|
||||||
|
|
||||||
#include <esp_http_client.h>
|
|
||||||
#include <esp_ota_ops.h>
|
|
||||||
#include <esp_partition.h>
|
|
||||||
#include <mbedtls/sha256.h>
|
|
||||||
#include <strings.h> // strcasecmp
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "power_mgr.h"
|
|
||||||
|
|
||||||
static bool s_pending_verify = false;
|
|
||||||
static OtaBatteryOkFn s_battery_fn = nullptr;
|
|
||||||
static uint8_t s_battery_min = 50;
|
|
||||||
|
|
||||||
void otaBegin() {
|
|
||||||
const esp_partition_t* running = esp_ota_get_running_partition();
|
|
||||||
esp_ota_img_states_t state;
|
|
||||||
|
|
||||||
if (esp_ota_get_state_partition(running, &state) == ESP_OK) {
|
|
||||||
s_pending_verify = (state == ESP_OTA_IMG_PENDING_VERIFY);
|
|
||||||
}
|
|
||||||
|
|
||||||
log_i("ota: running %s from %s%s", FW_VERSION, running->label,
|
|
||||||
s_pending_verify ? " [TRIAL BOOT - unconfirmed]" : "");
|
|
||||||
}
|
|
||||||
|
|
||||||
bool otaPendingVerify() { return s_pending_verify; }
|
|
||||||
|
|
||||||
void otaMarkValid() {
|
|
||||||
if (!s_pending_verify) return;
|
|
||||||
if (esp_ota_mark_app_valid_cancel_rollback() == ESP_OK) {
|
|
||||||
s_pending_verify = false;
|
|
||||||
log_i("ota: trial image confirmed good, rollback cancelled");
|
|
||||||
} else {
|
|
||||||
log_e("ota: failed to confirm trial image");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void otaRollback(const char* reason) {
|
|
||||||
log_e("ota: rolling back — %s", reason);
|
|
||||||
delay(200);
|
|
||||||
esp_ota_mark_app_invalid_rollback_and_reboot();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool otaIsNewer(const OtaTarget& t) {
|
|
||||||
// Deliberately a string inequality, not a semver comparison: the endpoint
|
|
||||||
// decides which version a device should run (SPEC §3 `firmware.is_target`),
|
|
||||||
// so "different from target" is the correct trigger. That also makes
|
|
||||||
// deliberate downgrades work, which semver ordering would block.
|
|
||||||
return t.version[0] && strcmp(t.version, FW_VERSION) != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void otaSetBatteryCheck(OtaBatteryOkFn fn, uint8_t min_pct) {
|
|
||||||
s_battery_fn = fn;
|
|
||||||
s_battery_min = min_pct;
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool hexEq(const uint8_t* digest, const char* expect_hex) {
|
|
||||||
char hex[65];
|
|
||||||
for (int i = 0; i < 32; i++) snprintf(hex + i * 2, 3, "%02x", digest[i]);
|
|
||||||
hex[64] = '\0';
|
|
||||||
return strcasecmp(hex, expect_hex) == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool otaApply(const OtaTarget& t) {
|
|
||||||
if (!g_cfg.ota_enabled) {
|
|
||||||
log_w("ota: disabled in config, ignoring target %s", t.version);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// SPEC C6: a brownout mid-write bricks the device.
|
|
||||||
if (s_battery_fn && !s_battery_fn(s_battery_min)) {
|
|
||||||
log_w("ota: refused, battery below %u%%", s_battery_min);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (strlen(t.sha256) != 64) {
|
|
||||||
log_e("ota: refused, target has no usable SHA-256");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Never sleep while flashing.
|
|
||||||
SleepGuard guard(INHIBIT_OTA);
|
|
||||||
|
|
||||||
String url = (strncmp(t.url, "http", 4) == 0) ? String(t.url) : (apiBaseUrl() + t.url);
|
|
||||||
log_i("ota: %s -> %s (%u bytes) from %s", FW_VERSION, t.version, (unsigned)t.size, url.c_str());
|
|
||||||
|
|
||||||
esp_http_client_config_t cfg = {};
|
|
||||||
cfg.url = url.c_str();
|
|
||||||
cfg.method = HTTP_METHOD_GET;
|
|
||||||
cfg.timeout_ms = 30000;
|
|
||||||
|
|
||||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
|
||||||
char bearer[80];
|
|
||||||
snprintf(bearer, sizeof(bearer), "Bearer %s", g_cfg.device_token);
|
|
||||||
esp_http_client_set_header(c, "Authorization", bearer);
|
|
||||||
|
|
||||||
bool ok = false;
|
|
||||||
esp_ota_handle_t ota = 0;
|
|
||||||
const esp_partition_t* target_part = nullptr;
|
|
||||||
mbedtls_sha256_context sha;
|
|
||||||
mbedtls_sha256_init(&sha);
|
|
||||||
|
|
||||||
do {
|
|
||||||
if (esp_http_client_open(c, 0) != ESP_OK) { log_e("ota: connect failed"); break; }
|
|
||||||
|
|
||||||
int content_len = esp_http_client_fetch_headers(c);
|
|
||||||
int status = esp_http_client_get_status_code(c);
|
|
||||||
if (status != 200) { log_e("ota: HTTP %d", status); break; }
|
|
||||||
if (content_len <= 0) {
|
|
||||||
// Chunked responses are legal but we want the length to sanity
|
|
||||||
// check against the manifest before erasing a partition.
|
|
||||||
log_e("ota: server did not send Content-Length");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (t.size && (uint32_t)content_len != t.size) {
|
|
||||||
log_e("ota: size mismatch, manifest %u vs body %d", (unsigned)t.size, content_len);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
target_part = esp_ota_get_next_update_partition(nullptr);
|
|
||||||
if (!target_part) { log_e("ota: no free OTA slot"); break; }
|
|
||||||
if ((uint32_t)content_len > target_part->size) {
|
|
||||||
log_e("ota: image %d does not fit in %s (%u)", content_len,
|
|
||||||
target_part->label, (unsigned)target_part->size);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_i("ota: erasing %s", target_part->label);
|
|
||||||
if (esp_ota_begin(target_part, content_len, &ota) != ESP_OK) {
|
|
||||||
log_e("ota: esp_ota_begin failed");
|
|
||||||
ota = 0;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
mbedtls_sha256_starts(&sha, 0);
|
|
||||||
|
|
||||||
static uint8_t buf[4096];
|
|
||||||
int written = 0, last_pct = -10;
|
|
||||||
bool io_error = false;
|
|
||||||
|
|
||||||
while (written < content_len) {
|
|
||||||
int n = esp_http_client_read(c, (char*)buf, sizeof(buf));
|
|
||||||
if (n <= 0) { log_e("ota: download truncated at %d/%d", written, content_len); io_error = true; break; }
|
|
||||||
|
|
||||||
if (esp_ota_write(ota, buf, n) != ESP_OK) { log_e("ota: flash write failed"); io_error = true; break; }
|
|
||||||
mbedtls_sha256_update(&sha, buf, n);
|
|
||||||
written += n;
|
|
||||||
|
|
||||||
int pct = (int)((int64_t)written * 100 / content_len);
|
|
||||||
if (pct >= last_pct + 10) { log_i("ota: %d%%", pct); last_pct = pct; }
|
|
||||||
}
|
|
||||||
if (io_error) break;
|
|
||||||
|
|
||||||
uint8_t digest[32];
|
|
||||||
mbedtls_sha256_finish(&sha, digest);
|
|
||||||
if (!hexEq(digest, t.sha256)) {
|
|
||||||
log_e("ota: SHA-256 mismatch, discarding image");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
log_i("ota: SHA-256 verified");
|
|
||||||
|
|
||||||
if (esp_ota_end(ota) != ESP_OK) { log_e("ota: esp_ota_end failed"); ota = 0; break; }
|
|
||||||
ota = 0;
|
|
||||||
|
|
||||||
if (esp_ota_set_boot_partition(target_part) != ESP_OK) {
|
|
||||||
log_e("ota: set_boot_partition failed");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
ok = true;
|
|
||||||
} while (false);
|
|
||||||
|
|
||||||
if (ota) esp_ota_abort(ota);
|
|
||||||
mbedtls_sha256_free(&sha);
|
|
||||||
esp_http_client_close(c);
|
|
||||||
esp_http_client_cleanup(c);
|
|
||||||
|
|
||||||
if (ok) {
|
|
||||||
// The new image boots in PENDING_VERIFY. If it cannot reach the
|
|
||||||
// endpoint it never calls otaMarkValid(), and the next reset returns
|
|
||||||
// to this slot automatically.
|
|
||||||
log_i("ota: activated %s, restarting into trial boot", target_part->label);
|
|
||||||
delay(300);
|
|
||||||
esp_restart();
|
|
||||||
}
|
|
||||||
return ok;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* otaRunningVersion() { return FW_VERSION; }
|
|
||||||
const char* otaRunningPartition() { return esp_ota_get_running_partition()->label; }
|
|
||||||
@@ -1,247 +0,0 @@
|
|||||||
#include "power_mgr.h"
|
|
||||||
|
|
||||||
#include <WiFi.h>
|
|
||||||
#include <esp_sleep.h>
|
|
||||||
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "board_pins.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
#include "nightlight.h"
|
|
||||||
#include "stream_session.h"
|
|
||||||
|
|
||||||
// RTC slow memory survives deep sleep but not a power cycle — exactly the
|
|
||||||
// semantics SPEC C7 assumes for the boot counter.
|
|
||||||
RTC_DATA_ATTR static uint32_t s_boot_count = 0;
|
|
||||||
RTC_DATA_ATTR static uint32_t s_sleep_epoch = 0; // seconds slept, cumulative
|
|
||||||
RTC_DATA_ATTR static uint32_t s_last_sleep_s = 0; // duration of the last sleep
|
|
||||||
|
|
||||||
static WakeCause s_cause = WAKE_POWER_ON;
|
|
||||||
static uint8_t s_inhibit[INHIBIT_COUNT] = {0};
|
|
||||||
static uint32_t s_last_activity_ms = 0;
|
|
||||||
static uint32_t s_awake_since_ms = 0;
|
|
||||||
static uint32_t s_hold_until_ms = 0;
|
|
||||||
|
|
||||||
static const char* kInhibitNames[INHIBIT_COUNT] = {
|
|
||||||
"boot", "upload", "stream", "ota", "hold"
|
|
||||||
};
|
|
||||||
|
|
||||||
void powerBegin() {
|
|
||||||
s_boot_count++;
|
|
||||||
s_awake_since_ms = millis();
|
|
||||||
s_last_activity_ms = millis();
|
|
||||||
|
|
||||||
switch (esp_sleep_get_wakeup_cause()) {
|
|
||||||
case ESP_SLEEP_WAKEUP_EXT1: s_cause = WAKE_RADAR; break;
|
|
||||||
case ESP_SLEEP_WAKEUP_TIMER: s_cause = WAKE_TIMER; break;
|
|
||||||
case ESP_SLEEP_WAKEUP_UNDEFINED: s_cause = WAKE_POWER_ON; break;
|
|
||||||
default: s_cause = WAKE_OTHER; break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hold the device awake until the first successful check-in. Without this
|
|
||||||
// a device configured with a bad endpoint would sleep before it could ever
|
|
||||||
// be told otherwise, and the only fix would be USB.
|
|
||||||
memset(s_inhibit, 0, sizeof(s_inhibit));
|
|
||||||
powerInhibit(INHIBIT_BOOT);
|
|
||||||
|
|
||||||
log_i("power: boot #%u, wake cause %s, %us slept so far",
|
|
||||||
(unsigned)s_boot_count, powerWakeCauseName(), (unsigned)s_sleep_epoch);
|
|
||||||
}
|
|
||||||
|
|
||||||
WakeCause powerWakeCause() { return s_cause; }
|
|
||||||
uint32_t powerBootCount() { return s_boot_count; }
|
|
||||||
uint32_t powerLastSleepSeconds() { return s_last_sleep_s; }
|
|
||||||
uint32_t powerTotalSleepSeconds() { return s_sleep_epoch; }
|
|
||||||
|
|
||||||
const char* powerWakeCauseName() {
|
|
||||||
switch (s_cause) {
|
|
||||||
case WAKE_RADAR: return "radar";
|
|
||||||
case WAKE_TIMER: return "timer";
|
|
||||||
case WAKE_POWER_ON: return "power-on";
|
|
||||||
default: return "other";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void powerInhibit(SleepInhibit r) {
|
|
||||||
if (r < INHIBIT_COUNT && s_inhibit[r] < 255) s_inhibit[r]++;
|
|
||||||
}
|
|
||||||
|
|
||||||
void powerRelease(SleepInhibit r) {
|
|
||||||
if (r < INHIBIT_COUNT && s_inhibit[r] > 0) s_inhibit[r]--;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool powerIsInhibited() {
|
|
||||||
for (uint8_t i = 0; i < INHIBIT_COUNT; i++) {
|
|
||||||
if (s_inhibit[i]) return true;
|
|
||||||
}
|
|
||||||
return (int32_t)(s_hold_until_ms - millis()) > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char* powerInhibitSummary() {
|
|
||||||
static char buf[64];
|
|
||||||
buf[0] = '\0';
|
|
||||||
for (uint8_t i = 0; i < INHIBIT_COUNT; i++) {
|
|
||||||
if (!s_inhibit[i]) continue;
|
|
||||||
if (buf[0]) strncat(buf, ",", sizeof(buf) - strlen(buf) - 1);
|
|
||||||
strncat(buf, kInhibitNames[i], sizeof(buf) - strlen(buf) - 1);
|
|
||||||
}
|
|
||||||
if (!buf[0]) strncpy(buf, "none", sizeof(buf));
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
|
|
||||||
void powerNoteActivity() { s_last_activity_ms = millis(); }
|
|
||||||
|
|
||||||
void powerHoldAwake(uint32_t seconds) {
|
|
||||||
uint32_t until = millis() + seconds * 1000UL;
|
|
||||||
if ((int32_t)(until - s_hold_until_ms) > 0) s_hold_until_ms = until;
|
|
||||||
powerNoteActivity();
|
|
||||||
log_i("power: holding awake for %us", (unsigned)seconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool powerSleepModeActive() { return g_cfg.deep_sleep_enabled; }
|
|
||||||
|
|
||||||
const char* powerSleepBlockedReason() {
|
|
||||||
if (!g_cfg.deep_sleep_enabled) return "deep sleep switched off";
|
|
||||||
if (g_cfg.stream_enabled && g_cfg.stream_blocks_sleep)
|
|
||||||
return "streaming enabled (stream_blocks_sleep)";
|
|
||||||
if (powerIsInhibited()) return powerInhibitSummary();
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
bool powerSleepAllowed() { return powerSleepBlockedReason()[0] == '\0'; }
|
|
||||||
|
|
||||||
// Configure wake sources and go. Does not return.
|
|
||||||
// `wake_on_radar` is separate from the config flag so the night sleep can
|
|
||||||
// force it off without mutating config.
|
|
||||||
static void enterDeepSleep(uint32_t seconds, bool wake_on_radar) {
|
|
||||||
if (seconds == 0) seconds = g_cfg.deep_sleep_s;
|
|
||||||
|
|
||||||
log_i("power: sleeping %us (wake: timer%s)", (unsigned)seconds,
|
|
||||||
wake_on_radar ? " + radar" : "");
|
|
||||||
|
|
||||||
// Flush the camera and radio explicitly. Letting deep sleep cut power out
|
|
||||||
// from under an initialised camera has been a reliable source of failures
|
|
||||||
// to re-init on the next boot.
|
|
||||||
cameraEnd();
|
|
||||||
WiFi.disconnect(true, /*eraseap=*/false);
|
|
||||||
WiFi.mode(WIFI_OFF);
|
|
||||||
delay(20);
|
|
||||||
|
|
||||||
esp_sleep_enable_timer_wakeup((uint64_t)seconds * 1000000ULL);
|
|
||||||
|
|
||||||
if (wake_on_radar) {
|
|
||||||
// ESP32-S3 has no EXT0; EXT1 with ANY_HIGH is the supported way to
|
|
||||||
// wake on an active-high presence pin. PIN_RADAR_OUT must be an RTC
|
|
||||||
// GPIO (0-21 on the S3) — GPIO3 is.
|
|
||||||
esp_sleep_enable_ext1_wakeup(1ULL << PIN_RADAR_OUT, ESP_EXT1_WAKEUP_ANY_HIGH);
|
|
||||||
|
|
||||||
// If the radar is *already* asserting when we try to sleep we would
|
|
||||||
// wake instantly and spin. Wait briefly for it to clear; if it does
|
|
||||||
// not, drop to a timer-only sleep for this cycle.
|
|
||||||
uint32_t wait_until = millis() + 3000;
|
|
||||||
while (digitalRead(PIN_RADAR_OUT) == HIGH && (int32_t)(wait_until - millis()) > 0) {
|
|
||||||
delay(50);
|
|
||||||
}
|
|
||||||
if (digitalRead(PIN_RADAR_OUT) == HIGH) {
|
|
||||||
log_w("power: radar still asserted, sleeping on timer only this cycle");
|
|
||||||
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_EXT1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
s_sleep_epoch += seconds;
|
|
||||||
s_last_sleep_s = seconds;
|
|
||||||
Serial.flush();
|
|
||||||
esp_deep_sleep_start();
|
|
||||||
// unreachable
|
|
||||||
}
|
|
||||||
|
|
||||||
void powerSleepUntilMorning() {
|
|
||||||
const uint32_t secs = nightSecondsUntilMorning();
|
|
||||||
if (secs == 0) return; // not night, or clock unsynced
|
|
||||||
|
|
||||||
// Night sleep overrides the deep_sleep_enabled switch, but never an OTA.
|
|
||||||
if (s_inhibit[INHIBIT_OTA]) {
|
|
||||||
log_w("power: night sleep deferred, OTA in progress");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (streamActive()) {
|
|
||||||
log_i("power: night sleep deferred, a stream is running");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
log_i("power: night — sleeping %u min until morning", (unsigned)(secs / 60));
|
|
||||||
enterDeepSleep(secs, /*wake_on_radar=*/false);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool powerWouldSleepNow() {
|
|
||||||
if (!powerSleepAllowed()) return false;
|
|
||||||
return (millis() - s_last_activity_ms) >= g_cfg.sleep_idle_timeout_s * 1000UL;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool powerMaybeSleep() {
|
|
||||||
if (!g_cfg.deep_sleep_enabled) return false;
|
|
||||||
|
|
||||||
const uint32_t now = millis();
|
|
||||||
const uint32_t idle_ms = now - s_last_activity_ms;
|
|
||||||
const uint32_t awake_ms = now - s_awake_since_ms;
|
|
||||||
|
|
||||||
// The hard cap is a deadlock escape, not a normal path: if something holds
|
|
||||||
// an inhibit forever (a stream whose socket never closes, an OTA that
|
|
||||||
// stalled) the device would otherwise stay awake until the battery is flat.
|
|
||||||
// OTA is the one inhibit we never override — sleeping mid-flash bricks it.
|
|
||||||
if (awake_ms > g_cfg.sleep_max_awake_s * 1000UL) {
|
|
||||||
if (s_inhibit[INHIBIT_OTA]) {
|
|
||||||
log_w("power: past max_awake but OTA in progress, staying up");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
log_w("power: max_awake %us exceeded (inhibits: %s), sleeping anyway",
|
|
||||||
g_cfg.sleep_max_awake_s, powerInhibitSummary());
|
|
||||||
enterDeepSleep(0, g_cfg.sleep_wake_on_radar);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Streaming enabled means "keep me reachable", not just "a session is
|
|
||||||
// running" — a sleeping device cannot be told to start one (SPEC C1).
|
|
||||||
if (!powerSleepAllowed()) return false;
|
|
||||||
if (idle_ms < g_cfg.sleep_idle_timeout_s * 1000UL) return false;
|
|
||||||
|
|
||||||
enterDeepSleep(0, g_cfg.sleep_wake_on_radar);
|
|
||||||
return true; // unreachable
|
|
||||||
}
|
|
||||||
|
|
||||||
void powerSleepNow(uint32_t seconds) {
|
|
||||||
// Deliberately laxer than powerSleepAllowed(): an explicit sleep request
|
|
||||||
// overrides "streaming is enabled" and the boot hold, because something
|
|
||||||
// asked for it on purpose. It does NOT override an OTA (bricks the device)
|
|
||||||
// or a live stream (cutting a viewer off mid-frame is never what was meant
|
|
||||||
// — send stream_stop first).
|
|
||||||
if (!g_cfg.deep_sleep_enabled) {
|
|
||||||
log_w("power: sleep_now ignored, deep sleep is switched off");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (s_inhibit[INHIBIT_OTA]) {
|
|
||||||
log_w("power: sleep_now refused, OTA in progress");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (streamActive()) {
|
|
||||||
log_w("power: sleep_now refused, a stream is running");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
enterDeepSleep(seconds, g_cfg.sleep_wake_on_radar);
|
|
||||||
}
|
|
||||||
|
|
||||||
void powerOnConfigChanged(bool was_enabled) {
|
|
||||||
if (was_enabled == g_cfg.deep_sleep_enabled) return;
|
|
||||||
|
|
||||||
if (g_cfg.deep_sleep_enabled) {
|
|
||||||
// Do not slam the door on the way out: finish this wake so the ack for
|
|
||||||
// the config command reaches the Pi, and so an operator who flipped the
|
|
||||||
// switch by mistake still has sleep_idle_timeout_s to flip it back.
|
|
||||||
log_i("power: deep sleep switched ON, will sleep after %us idle",
|
|
||||||
g_cfg.sleep_idle_timeout_s);
|
|
||||||
powerNoteActivity();
|
|
||||||
} else {
|
|
||||||
log_i("power: deep sleep switched OFF, staying awake");
|
|
||||||
s_hold_until_ms = 0;
|
|
||||||
// The ring and camera are brought back up by the caller in main.cpp,
|
|
||||||
// which owns their lifecycle.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
#include "stream_session.h"
|
|
||||||
|
|
||||||
#include "api_client.h"
|
|
||||||
#include "app_config.h"
|
|
||||||
#include "camera_mgr.h"
|
|
||||||
#include "net_mgr.h"
|
|
||||||
#include "power_mgr.h"
|
|
||||||
|
|
||||||
static bool s_active = false;
|
|
||||||
static char s_id[40] = {0};
|
|
||||||
static uint32_t s_end_ms = 0;
|
|
||||||
static uint32_t s_next_ms = 0;
|
|
||||||
static uint32_t s_period_ms = 100;
|
|
||||||
static uint32_t s_frames = 0;
|
|
||||||
static uint8_t s_prev_size = 0;
|
|
||||||
static uint8_t s_fail_streak = 0;
|
|
||||||
|
|
||||||
bool streamActive() { return s_active; }
|
|
||||||
|
|
||||||
bool streamStart(const char* session_id, uint8_t mode_override,
|
|
||||||
uint8_t framesize_override, uint16_t duration_override) {
|
|
||||||
if (s_active) {
|
|
||||||
log_w("stream: already running as %s", s_id);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!g_cfg.stream_enabled) {
|
|
||||||
log_w("stream: refused, streaming is disabled in config");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!netIsConnected() || !cameraReady()) {
|
|
||||||
log_w("stream: refused, network or camera not ready");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const uint8_t mode = (mode_override == 0xFF) ? g_cfg.stream_mode : mode_override;
|
|
||||||
const uint8_t fsize = framesize_override ? framesize_override : g_cfg.stream_frame_size;
|
|
||||||
uint16_t duration = duration_override ? duration_override : g_cfg.stream_duration_s;
|
|
||||||
if (duration > 600) duration = 600; // SPEC C9: always time-boxed
|
|
||||||
|
|
||||||
strncpy(s_id, session_id, sizeof(s_id) - 1);
|
|
||||||
s_id[sizeof(s_id) - 1] = '\0';
|
|
||||||
|
|
||||||
if (!apiStreamOpen(s_id, mode, duration)) return false;
|
|
||||||
|
|
||||||
// Drop to the stream resolution for the session and restore it after, so
|
|
||||||
// a stream never silently changes the resolution of stills.
|
|
||||||
s_prev_size = g_cfg.frame_size;
|
|
||||||
if (fsize != s_prev_size) cameraSetFrameSize(fsize);
|
|
||||||
|
|
||||||
s_period_ms = 1000UL / (g_cfg.stream_fps ? g_cfg.stream_fps : 10);
|
|
||||||
s_end_ms = millis() + duration * 1000UL;
|
|
||||||
s_next_ms = millis();
|
|
||||||
s_frames = 0;
|
|
||||||
s_fail_streak = 0;
|
|
||||||
s_active = true;
|
|
||||||
|
|
||||||
powerInhibit(INHIBIT_STREAM); // released in streamStop()
|
|
||||||
powerNoteActivity();
|
|
||||||
|
|
||||||
log_i("stream: %s started, %us @ %ufps, size %u", s_id, duration, g_cfg.stream_fps, fsize);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void streamTick() {
|
|
||||||
if (!s_active) return;
|
|
||||||
|
|
||||||
if ((int32_t)(s_end_ms - millis()) <= 0) { streamStop("duration reached"); return; }
|
|
||||||
if (!netIsConnected()) { streamStop("wifi lost"); return; }
|
|
||||||
if ((int32_t)(s_next_ms - millis()) > 0) return;
|
|
||||||
|
|
||||||
s_next_ms += s_period_ms;
|
|
||||||
// If we fell behind (a slow upload, a burst of uploads competing for the
|
|
||||||
// radio) do not try to catch up by bursting — just resync to now.
|
|
||||||
if ((int32_t)(s_next_ms - millis()) < 0) s_next_ms = millis() + s_period_ms;
|
|
||||||
|
|
||||||
camera_fb_t* fb = cameraGrab();
|
|
||||||
if (!fb) {
|
|
||||||
if (++s_fail_streak > 10) streamStop("camera keeps failing");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool sent = apiStreamSendFrame(fb->buf, fb->len, netEpochMs());
|
|
||||||
esp_camera_fb_return(fb);
|
|
||||||
|
|
||||||
if (sent) {
|
|
||||||
s_frames++;
|
|
||||||
s_fail_streak = 0;
|
|
||||||
powerNoteActivity();
|
|
||||||
} else if (++s_fail_streak > 5) {
|
|
||||||
// The Pi closed the connection — a viewer navigated away, or the
|
|
||||||
// session was cancelled server-side. Treat that as a normal end.
|
|
||||||
streamStop("endpoint stopped accepting frames");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void streamStop(const char* reason) {
|
|
||||||
if (!s_active) return;
|
|
||||||
s_active = false;
|
|
||||||
|
|
||||||
apiStreamClose();
|
|
||||||
if (s_prev_size && s_prev_size != g_cfg.stream_frame_size) {
|
|
||||||
cameraSetFrameSize(s_prev_size);
|
|
||||||
}
|
|
||||||
|
|
||||||
powerRelease(INHIBIT_STREAM);
|
|
||||||
powerNoteActivity(); // give the idle timer a fresh start before sleeping
|
|
||||||
|
|
||||||
log_i("stream: %s ended after %u frames — %s", s_id, (unsigned)s_frames, reason);
|
|
||||||
s_id[0] = '\0';
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t streamFramesSent() { return s_frames; }
|
|
||||||
|
|
||||||
uint32_t streamSecondsLeft() {
|
|
||||||
if (!s_active) return 0;
|
|
||||||
int32_t left = (int32_t)(s_end_ms - millis());
|
|
||||||
return left > 0 ? (uint32_t)(left / 1000) : 0;
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
.venv/
|
|
||||||
venv/
|
|
||||||
__pycache__/
|
|
||||||
*.py[cod]
|
|
||||||
*.egg-info/
|
|
||||||
build/
|
|
||||||
dist/
|
|
||||||
.pytest_cache/
|
|
||||||
.ruff_cache/
|
|
||||||
.env
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
# poorBird server
|
|
||||||
|
|
||||||
Phases 1 and 2 plus the Phase 3 server half: configuration, schema, health, job
|
|
||||||
queue, scheduler, every endpoint the camera calls, and user auth with the
|
|
||||||
gallery's API behind it.
|
|
||||||
|
|
||||||
**Device endpoints** — bearer token, no cookies:
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /api/v1/enroll X-Enroll-Secret, returns a bearer token
|
|
||||||
POST /api/v1/ingest raw JPEG body, metadata in headers
|
|
||||||
POST /api/v1/heartbeat conditions in, envelope + commands out
|
|
||||||
POST /api/v1/status conditions in, 204 out
|
|
||||||
GET /api/v1/config ~40 optional keys the device merges
|
|
||||||
POST /api/v1/commands/{id}/ack 204
|
|
||||||
GET /api/v1/firmware/{version}.bin OTA image, exact Content-Length
|
|
||||||
GET /api/v1/health
|
|
||||||
```
|
|
||||||
|
|
||||||
**Operator endpoints** — session cookie + CSRF, never a bearer token:
|
|
||||||
|
|
||||||
```
|
|
||||||
POST /api/v1/auth/login password + TOTP, sets the session cookie
|
|
||||||
POST /api/v1/auth/logout 204, and the session row is deleted
|
|
||||||
GET /api/v1/auth/session who am I, or 401
|
|
||||||
GET /api/v1/captures cursor-paged, filterable
|
|
||||||
GET /api/v1/captures/{id} detail incl. observations and tags
|
|
||||||
GET /api/v1/captures/{id}/image authorized, then handed to Caddy
|
|
||||||
GET /api/v1/captures/{id}/thumb 404 when the thumbnail job has not run
|
|
||||||
```
|
|
||||||
|
|
||||||
[`../firmware/API.md`](../firmware/API.md) is the contract for the device half,
|
|
||||||
and it wins over anything here: it is what the firmware already does, and the
|
|
||||||
camera is the side that cannot be patched from a laptop once it is mounted
|
|
||||||
outdoors. Of the operator half, auth and the gallery exist; firmware *upload*
|
|
||||||
and device management are Phase 4.
|
|
||||||
|
|
||||||
Stack per SPEC §6, deployed natively per [`../TODO.md`](../TODO.md) Phase 1.2:
|
|
||||||
FastAPI + PostgreSQL 17 + SQLAlchemy 2.0 + Alembic, run as systemd units
|
|
||||||
behind Caddy. No containers — but nothing here blocks them either.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Developing on Windows (uv + Podman)
|
|
||||||
|
|
||||||
This is the verified setup on the dev machine. Python is managed by `uv`, so
|
|
||||||
nothing touches the system PATH or the registry, and PostgreSQL runs in a
|
|
||||||
throwaway Podman container. Neither changes how the project deploys — the app
|
|
||||||
still talks loopback TCP exactly as it will on the server.
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
winget install astral-sh.uv
|
|
||||||
uv python install 3.14.7
|
|
||||||
|
|
||||||
podman machine start
|
|
||||||
podman run -d --name poorbird-db -p 127.0.0.1:5432:5432 `
|
|
||||||
-e POSTGRES_USER=poorbird -e POSTGRES_PASSWORD=poorbird -e POSTGRES_DB=poorbird `
|
|
||||||
docker.io/library/postgres:17
|
|
||||||
|
|
||||||
cd server
|
|
||||||
uv venv --python 3.14.7
|
|
||||||
uv pip install -e ".[dev]"
|
|
||||||
# write .env (see the Linux section below; use Windows paths for the roots)
|
|
||||||
|
|
||||||
.venv\Scripts\poorbird check
|
|
||||||
.venv\Scripts\poorbird migrate
|
|
||||||
.venv\Scripts\python -m pytest
|
|
||||||
```
|
|
||||||
|
|
||||||
Later sessions only need `podman machine start` and `podman start poorbird-db`.
|
|
||||||
|
|
||||||
## Try it on any Linux machine
|
|
||||||
|
|
||||||
Needs Python ≥ 3.11 and a PostgreSQL you can reach. Production targets 3.13;
|
|
||||||
the floor is lower so this runs on a stock Debian 12 or Ubuntu 24.04 box.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo apt install -y python3-venv postgresql
|
|
||||||
|
|
||||||
sudo -u postgres psql <<'SQL'
|
|
||||||
CREATE ROLE poorbird LOGIN PASSWORD 'poorbird';
|
|
||||||
CREATE DATABASE poorbird OWNER poorbird;
|
|
||||||
SQL
|
|
||||||
|
|
||||||
cd server
|
|
||||||
python3 -m venv .venv && . .venv/bin/activate
|
|
||||||
pip install -e '.[dev]'
|
|
||||||
|
|
||||||
cat > .env <<'ENV'
|
|
||||||
POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird
|
|
||||||
POORBIRD_IMAGE_ROOT=/tmp/poorbird/images
|
|
||||||
POORBIRD_THUMB_ROOT=/tmp/poorbird/thumbs
|
|
||||||
POORBIRD_STATE_DIR=/tmp/poorbird/state
|
|
||||||
POORBIRD_API_PORT=8090
|
|
||||||
ENV
|
|
||||||
mkdir -p /tmp/poorbird/{images,thumbs,state}
|
|
||||||
|
|
||||||
poorbird check # config, paths, database — before starting anything
|
|
||||||
poorbird migrate # alembic upgrade head
|
|
||||||
poorbird serve # http://127.0.0.1:8090/api/v1/health
|
|
||||||
```
|
|
||||||
|
|
||||||
In a second shell:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd server && . .venv/bin/activate
|
|
||||||
poorbird worker &
|
|
||||||
poorbird enqueue noop '{"hello": "world"}' # the worker logs it within ~2s
|
|
||||||
```
|
|
||||||
|
|
||||||
`poorbird check` is the fast answer to "is this machine set up correctly" — it
|
|
||||||
validates config, storage paths and database connectivity and prints what it
|
|
||||||
found, without starting a service.
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pytest # everything reachable
|
|
||||||
pytest -m 'not db' # no PostgreSQL needed
|
|
||||||
```
|
|
||||||
|
|
||||||
Queue and schema tests need a real PostgreSQL — `FOR UPDATE SKIP LOCKED` has
|
|
||||||
no equivalent elsewhere, and mocking it would test nothing. They skip
|
|
||||||
automatically when the database is unreachable, so a green run with no
|
|
||||||
Postgres proves less than it looks. **Check for `skipped` in the summary**;
|
|
||||||
a complete run is 308 passed, 0 skipped.
|
|
||||||
|
|
||||||
`test_schema_matches_models.py` creates and drops a `poorbird_schema_check`
|
|
||||||
database on the same server. It needs a role that may `CREATE DATABASE`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Layout
|
|
||||||
|
|
||||||
```
|
|
||||||
src/poorbird/
|
|
||||||
config.py every value from the environment, nothing baked in
|
|
||||||
logging_setup.py stdout only; journald or a log driver catches it
|
|
||||||
db.py engine + session factory (sync, deliberately)
|
|
||||||
models/ SPEC §3 schema + the SPEC §0 additions
|
|
||||||
images.py JPEG sniffing, atomic writes, thumbnails
|
|
||||||
passwords.py Argon2id — slow on purpose, unlike the device tokens
|
|
||||||
totp.py 2FA secrets, provisioning URIs, code verification
|
|
||||||
seed.py synthetic captures, so the gallery has volume to face
|
|
||||||
api/ FastAPI app, device + operator routes, auth, rate limiting
|
|
||||||
worker/ queue (SKIP LOCKED), handlers, scheduler
|
|
||||||
cli.py serve | worker | migrate | check | enqueue | user | seed
|
|
||||||
migrations/ Alembic
|
|
||||||
deploy/ systemd units, Caddyfile, env template, INSTALL.md
|
|
||||||
tests/
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Decisions worth knowing before you read the code
|
|
||||||
|
|
||||||
**Sync SQLAlchemy, not async.** At one camera and a few thousand frames a day
|
|
||||||
the async machinery buys nothing and costs clarity, and the worker's claim
|
|
||||||
loop is far easier to reason about synchronously. FastAPI runs `def` handlers
|
|
||||||
in a threadpool, so this does not block the event loop. The one thing that may
|
|
||||||
argue otherwise later is the MJPEG relay in Phase 6.
|
|
||||||
|
|
||||||
**Device config is one JSONB column, not forty.** `GET /config` returns ~40
|
|
||||||
optional keys and the firmware merges and clamps partial documents, so a
|
|
||||||
column per key would mean a migration every time the firmware gains a tunable.
|
|
||||||
Validation belongs in a Pydantic model, not in the DDL. The trade: you cannot
|
|
||||||
index or constrain an individual setting in SQL. If one ever needs querying
|
|
||||||
across devices, promote just that key to a column.
|
|
||||||
|
|
||||||
**Server defaults are compared through a normaliser.** Postgres reflects a
|
|
||||||
varchar default as `'viewer'::character varying` while the model renders
|
|
||||||
`'viewer'`. Compared literally, every string default in the schema reads as
|
|
||||||
drift forever — which trains you to ignore the one time it isn't. See
|
|
||||||
`schema_compare.py`; autogenerate and the drift test share it, so the tool and
|
|
||||||
the test can never disagree about what counts as a difference.
|
|
||||||
|
|
||||||
**Migration 0001 builds from `Base.metadata`.** A bounded exception, and
|
|
||||||
`tests/test_schema_matches_models.py` migrates a scratch database and asserts
|
|
||||||
an empty autogenerate diff, so the models and the migration cannot silently
|
|
||||||
diverge. Every later revision is a normal autogenerated one. If you prefer
|
|
||||||
explicit DDL in the baseline, autogenerate it against an empty database and
|
|
||||||
replace the file — the drift test passes either way.
|
|
||||||
|
|
||||||
**The scheduler only enqueues, never executes.** Every unit of work goes
|
|
||||||
through the queue, where it is visible, retried and auditable, rather than
|
|
||||||
running inside a timer callback where a failure disappears.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Two things the code already guards, and the UI must too
|
|
||||||
|
|
||||||
- `battery_valid = false` means **not measured** — no divider is wired by
|
|
||||||
default. Render it as "—", never as a low-battery alarm.
|
|
||||||
- The daily counters live in the device's RTC memory and reset on power loss.
|
|
||||||
`captures` is authoritative. The counters' value is the *gap* between
|
|
||||||
captured and delivered, which is an upload-health signal.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Deploying for real
|
|
||||||
|
|
||||||
See [`deploy/INSTALL.md`](deploy/INSTALL.md).
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
[alembic]
|
|
||||||
script_location = migrations
|
|
||||||
prepend_sys_path = src
|
|
||||||
# The URL is NOT set here. migrations/env.py takes it from POORBIRD_DATABASE_URL
|
|
||||||
# so that config comes from exactly one place (TODO.md Phase 1.2).
|
|
||||||
|
|
||||||
[loggers]
|
|
||||||
keys = root,sqlalchemy,alembic
|
|
||||||
|
|
||||||
[handlers]
|
|
||||||
keys = console
|
|
||||||
|
|
||||||
[formatters]
|
|
||||||
keys = generic
|
|
||||||
|
|
||||||
[logger_root]
|
|
||||||
level = WARNING
|
|
||||||
handlers = console
|
|
||||||
qualname =
|
|
||||||
|
|
||||||
[logger_sqlalchemy]
|
|
||||||
level = WARNING
|
|
||||||
handlers =
|
|
||||||
qualname = sqlalchemy.engine
|
|
||||||
|
|
||||||
[logger_alembic]
|
|
||||||
level = INFO
|
|
||||||
handlers =
|
|
||||||
qualname = alembic
|
|
||||||
|
|
||||||
[handler_console]
|
|
||||||
class = StreamHandler
|
|
||||||
args = (sys.stdout,)
|
|
||||||
level = NOTSET
|
|
||||||
formatter = generic
|
|
||||||
|
|
||||||
[formatter_generic]
|
|
||||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
|
||||||
datefmt = %H:%M:%S
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
# poorBird reverse proxy. Install to /etc/caddy/Caddyfile.
|
|
||||||
#
|
|
||||||
# Ports, so nothing collides:
|
|
||||||
# 127.0.0.1:8090 uvicorn (POORBIRD_API_PORT) -- never exposed
|
|
||||||
# :8080 plain HTTP for the camera (SPEC C2, firmware/API.md)
|
|
||||||
# :443 TLS for humans
|
|
||||||
#
|
|
||||||
# TLS: Caddy gets a real Let's Encrypt certificate for a LAN-only hostname via
|
|
||||||
# DNS-01, so there is no port forwarding and no browser warning. That needs a
|
|
||||||
# Caddy build with your DNS provider's plugin:
|
|
||||||
#
|
|
||||||
# caddy add-package github.com/caddy-dns/cloudflare
|
|
||||||
#
|
|
||||||
# For a first test on any Linux box you can skip the whole human-facing block
|
|
||||||
# and just use the :8080 one.
|
|
||||||
|
|
||||||
(protected_files) {
|
|
||||||
# Auth-checked image serving (SPEC 3.3).
|
|
||||||
#
|
|
||||||
# An unguessable URL is not access control. The app authorizes the
|
|
||||||
# request, then replies with an empty body and
|
|
||||||
# X-Accel-Redirect: /images/2026/09/08/<uuid>.jpg
|
|
||||||
# and Caddy serves the bytes from disk. The browser never receives a
|
|
||||||
# directly fetchable URL.
|
|
||||||
#
|
|
||||||
# The root below is the PARENT of POORBIRD_IMAGE_ROOT and
|
|
||||||
# POORBIRD_THUMB_ROOT in /etc/poorbird/poorbird.env. One value, two
|
|
||||||
# readers -- keep them in step.
|
|
||||||
@accel header X-Accel-Redirect *
|
|
||||||
handle_response @accel {
|
|
||||||
rewrite * {rp.header.X-Accel-Redirect}
|
|
||||||
file_server {
|
|
||||||
root /srv/poorbird
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- humans -----------------------------------------------------------------
|
|
||||||
poorbird.example.internal {
|
|
||||||
tls {
|
|
||||||
dns cloudflare {env.CLOUDFLARE_API_TOKEN}
|
|
||||||
}
|
|
||||||
|
|
||||||
encode zstd gzip
|
|
||||||
|
|
||||||
# The API, and with it the auth-checked image handoff.
|
|
||||||
handle /api/* {
|
|
||||||
reverse_proxy 127.0.0.1:8090 {
|
|
||||||
header_up X-Real-IP {remote_host}
|
|
||||||
import protected_files
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# The WebUI: built on the dev machine with `npm run build` and copied here
|
|
||||||
# as static files. Nothing in web/ runs on the server (SPEC 6), so this is
|
|
||||||
# a file_server and not a second application.
|
|
||||||
handle {
|
|
||||||
root * /srv/poorbird/web
|
|
||||||
|
|
||||||
# The router does client-side routing, so a reload on /devices or a
|
|
||||||
# pasted deep link arrives as a path with no file behind it. Without
|
|
||||||
# this fallback those are 404s and only the entry page ever works.
|
|
||||||
try_files {path} /index.html
|
|
||||||
file_server
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- the camera --------------------------------------------------------------
|
|
||||||
# Plain HTTP on the LAN, deliberately (SPEC C2): TLS on the ESP32 means a CA
|
|
||||||
# baked into firmware, and a mounted camera that silently stops uploading when
|
|
||||||
# the chain rotates.
|
|
||||||
:8080 {
|
|
||||||
handle /api/v1/* {
|
|
||||||
request_body {
|
|
||||||
# A burst frame at UXGA can be a few hundred KB; an OTA image is
|
|
||||||
# ~1-2 MB. The default limit is too small for both.
|
|
||||||
max_size 12MB
|
|
||||||
}
|
|
||||||
reverse_proxy 127.0.0.1:8090 {
|
|
||||||
# Required, not cosmetic. Rate limiting keys enrollment on the
|
|
||||||
# caller's address, and without this every camera arrives as
|
|
||||||
# 127.0.0.1 and they all share one bucket - one noisy device
|
|
||||||
# would lock the rest out. The app trusts this header only
|
|
||||||
# because uvicorn binds loopback and nothing else can reach it.
|
|
||||||
header_up X-Real-IP {remote_host}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
handle /healthz {
|
|
||||||
reverse_proxy 127.0.0.1:8090
|
|
||||||
}
|
|
||||||
|
|
||||||
handle {
|
|
||||||
respond 404
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
# Installing poorBird on the thin client
|
|
||||||
|
|
||||||
Written for: whoever sets up the server host — assumes comfort with systemd
|
|
||||||
and `psql`, but not with this project.
|
|
||||||
|
|
||||||
Target is an x86 Linux box on the same LAN as the camera (SPEC §0). Native
|
|
||||||
packages and systemd units, no containers. Commands below assume Debian or
|
|
||||||
Ubuntu; adjust the package manager otherwise.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Packages and user
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo apt update
|
|
||||||
sudo apt install -y postgresql python3-venv python3-pip git caddy
|
|
||||||
|
|
||||||
sudo useradd --system --home-dir /opt/poorbird --shell /usr/sbin/nologin poorbird
|
|
||||||
sudo mkdir -p /opt/poorbird /etc/poorbird /srv/poorbird/{images,thumbs,web} /var/lib/poorbird
|
|
||||||
sudo chown -R poorbird:poorbird /srv/poorbird /var/lib/poorbird /opt/poorbird
|
|
||||||
```
|
|
||||||
|
|
||||||
`images/` and `thumbs/` must stay siblings under `/srv/poorbird`: that is the
|
|
||||||
directory the Caddyfile's `file_server` serves, and the auth-checked image
|
|
||||||
handoff needs both sides to agree on it. `poorbird check` verifies the layout,
|
|
||||||
because getting it wrong produces 404s from Caddy and nothing in the app's log.
|
|
||||||
`web/` is where the built UI goes (step 7).
|
|
||||||
|
|
||||||
## 2. Database
|
|
||||||
|
|
||||||
Loopback TCP with `scram-sha-256`, deliberately not a Unix socket — see
|
|
||||||
`TODO.md` Phase 1.2.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo -u postgres psql <<'SQL'
|
|
||||||
CREATE ROLE poorbird LOGIN PASSWORD 'PUT_A_REAL_PASSWORD_HERE';
|
|
||||||
CREATE DATABASE poorbird OWNER poorbird;
|
|
||||||
SQL
|
|
||||||
```
|
|
||||||
|
|
||||||
Confirm `pg_hba.conf` has a `host all all 127.0.0.1/32 scram-sha-256`
|
|
||||||
line before any `trust` line, then `sudo systemctl reload postgresql`.
|
|
||||||
|
|
||||||
Verify the path the app will actually use, not the socket:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
psql "postgresql://poorbird:PUT_A_REAL_PASSWORD_HERE@127.0.0.1:5432/poorbird" -c 'SELECT 1'
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3. Application
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo -u poorbird git clone <your-remote> /opt/poorbird/src
|
|
||||||
sudo ln -sfn /opt/poorbird/src/server /opt/poorbird/app
|
|
||||||
sudo -u poorbird python3 -m venv /opt/poorbird/venv
|
|
||||||
sudo -u poorbird /opt/poorbird/venv/bin/pip install -e /opt/poorbird/app
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Configuration
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo cp /opt/poorbird/app/deploy/poorbird.env.example /etc/poorbird/poorbird.env
|
|
||||||
sudo chown root:poorbird /etc/poorbird/poorbird.env
|
|
||||||
sudo chmod 0640 /etc/poorbird/poorbird.env
|
|
||||||
sudo -e /etc/poorbird/poorbird.env # set the DB password and the enroll secret
|
|
||||||
```
|
|
||||||
|
|
||||||
Generate the enroll secret with `openssl rand -hex 32`.
|
|
||||||
|
|
||||||
> **Before you ever rotate `POORBIRD_ENROLL_SECRET`:** it is compiled into the
|
|
||||||
> firmware image as the last-resort recovery path for a camera that cannot be
|
|
||||||
> reached over USB once mounted. Rotating it here without also shipping new
|
|
||||||
> firmware removes that escape hatch (`firmware/API.md`).
|
|
||||||
|
|
||||||
Check the machine before starting anything:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo -u poorbird env $(sudo cat /etc/poorbird/poorbird.env | grep -v '^#' | xargs) \
|
|
||||||
/opt/poorbird/venv/bin/poorbird check
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. Services
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo cp /opt/poorbird/app/deploy/poorbird-*.service /etc/systemd/system/
|
|
||||||
sudo systemctl daemon-reload
|
|
||||||
sudo systemctl enable --now poorbird-api poorbird-worker
|
|
||||||
systemctl status poorbird-api poorbird-worker
|
|
||||||
journalctl -u poorbird-api -f
|
|
||||||
```
|
|
||||||
|
|
||||||
The API unit runs `poorbird migrate` in `ExecStartPre`. The worker unit
|
|
||||||
deliberately does not, so two units never race to apply the same revision.
|
|
||||||
|
|
||||||
Smoke test:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -s localhost:8090/api/v1/health | python3 -m json.tool
|
|
||||||
```
|
|
||||||
|
|
||||||
## 6. Reverse proxy
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo cp /opt/poorbird/app/deploy/Caddyfile /etc/caddy/Caddyfile
|
|
||||||
sudo -e /etc/caddy/Caddyfile # set your hostname and DNS provider
|
|
||||||
sudo systemctl reload caddy
|
|
||||||
```
|
|
||||||
|
|
||||||
Ports, so nothing collides:
|
|
||||||
|
|
||||||
| Port | Who |
|
|
||||||
|---|---|
|
|
||||||
| `127.0.0.1:8090` | uvicorn — never exposed |
|
|
||||||
| `:8080` | plain HTTP for the camera (SPEC C2) |
|
|
||||||
| `:443` | TLS for humans |
|
|
||||||
|
|
||||||
DNS-01 needs a Caddy build with your provider's plugin:
|
|
||||||
`caddy add-package github.com/caddy-dns/cloudflare`. For a first test, replace
|
|
||||||
the human-facing site block with `http://:8081` and drop the `tls` block.
|
|
||||||
|
|
||||||
> **If you do that, you cannot sign in until you also set
|
|
||||||
> `POORBIRD_SESSION_COOKIE_SECURE=false`.** The session cookie is `Secure` by
|
|
||||||
> default, and a browser silently discards a `Secure` cookie over plain HTTP:
|
|
||||||
> the login returns 200, and you are never signed in, with nothing in any log
|
|
||||||
> to explain it. Set it back to `true` the moment TLS is on.
|
|
||||||
|
|
||||||
## 7. The WebUI
|
|
||||||
|
|
||||||
The UI is built on your dev machine and copied here as static files. Nothing
|
|
||||||
in `web/` runs on the server (SPEC §6) — Caddy serves it, and there is no Node
|
|
||||||
on this host.
|
|
||||||
|
|
||||||
On the dev machine:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd web
|
|
||||||
npm ci
|
|
||||||
npm run build # typechecks, then writes dist/
|
|
||||||
```
|
|
||||||
|
|
||||||
Then copy it over, and let Caddy read it:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
rsync -a --delete dist/ youruser@poorbird-host:/tmp/poorbird-web/
|
|
||||||
# on the host:
|
|
||||||
sudo rsync -a --delete /tmp/poorbird-web/ /srv/poorbird/web/
|
|
||||||
sudo chown -R poorbird:poorbird /srv/poorbird/web
|
|
||||||
```
|
|
||||||
|
|
||||||
`--delete` matters on an upgrade: Vite writes content-hashed filenames, so
|
|
||||||
without it every old bundle stays behind forever.
|
|
||||||
|
|
||||||
Re-run this after any UI change. There is no build step on the server, so
|
|
||||||
`git pull` alone never updates the UI.
|
|
||||||
|
|
||||||
## 8. Your first account
|
|
||||||
|
|
||||||
**There is no sign-up page, and a fresh install has no accounts** — so without
|
|
||||||
this step the login screen has nothing you can type into it.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo -u poorbird env $(sudo cat /etc/poorbird/poorbird.env | grep -v '^#' | xargs) \
|
|
||||||
/opt/poorbird/venv/bin/poorbird user add yourname --role admin
|
|
||||||
```
|
|
||||||
|
|
||||||
It prompts for the password, then prints an `otpauth://` URI once. **Scan it
|
|
||||||
into your authenticator app before pressing on** — it is not shown again, and
|
|
||||||
TOTP is required on every login for an account that has a secret.
|
|
||||||
|
|
||||||
`--no-totp` skips the second factor and warns that it is doing so. There is
|
|
||||||
currently no command to add or remove TOTP later, and none to delete a user,
|
|
||||||
so this choice sticks for that account.
|
|
||||||
|
|
||||||
Roles are `viewer`, `editor` and `admin` (SPEC §3.1); Devices and System need
|
|
||||||
`admin`. Devices are not users and never appear here.
|
|
||||||
|
|
||||||
## 9. Network
|
|
||||||
|
|
||||||
Give the server a **DHCP reservation or a static IP, then hardcode that
|
|
||||||
address in the firmware** — simpler and more reliable than mDNS (SPEC §9).
|
|
||||||
The camera has no way to be told a new address once it is mounted and cannot
|
|
||||||
reach the endpoint.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Upgrading
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo -u poorbird git -C /opt/poorbird/src pull
|
|
||||||
sudo -u poorbird /opt/poorbird/venv/bin/pip install -e /opt/poorbird/app
|
|
||||||
sudo systemctl restart poorbird-api poorbird-worker
|
|
||||||
```
|
|
||||||
|
|
||||||
`ExecStartPre` applies migrations on restart.
|
|
||||||
|
|
||||||
**The UI is not part of that.** It is built on the dev machine, so a `git pull`
|
|
||||||
here leaves the old bundle in `/srv/poorbird/web` and you get a new API with an
|
|
||||||
old gallery. Repeat step 7 whenever `web/` changed.
|
|
||||||
|
|
||||||
> Restarting mid-OTA-rollout matters: a device on a trial image marks that
|
|
||||||
> image valid **only after a heartbeat the endpoint accepted**. Returning 5xx
|
|
||||||
> to a trial device rolls it back — correct behaviour, but know it before you
|
|
||||||
> restart the API during a rollout (`firmware/API.md`).
|
|
||||||
|
|
||||||
## Backups
|
|
||||||
|
|
||||||
Not built yet — TODO Phase 5, and blocked on open question 9 (whether the NAS
|
|
||||||
offers SFTP, or only SMB/NFS), which decides between restic and a mounted
|
|
||||||
path. Until then **this machine is not backed up.** Do not let real captures
|
|
||||||
accumulate here before that is done.
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=poorBird API
|
|
||||||
After=network-online.target postgresql.service
|
|
||||||
Wants=network-online.target
|
|
||||||
Requires=postgresql.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=exec
|
|
||||||
User=poorbird
|
|
||||||
Group=poorbird
|
|
||||||
WorkingDirectory=/opt/poorbird/app
|
|
||||||
EnvironmentFile=/etc/poorbird/poorbird.env
|
|
||||||
|
|
||||||
# Migrations run as a separate idempotent command, never at app import time.
|
|
||||||
# Same command a container entrypoint or init job would call.
|
|
||||||
ExecStartPre=/opt/poorbird/venv/bin/poorbird migrate
|
|
||||||
ExecStart=/opt/poorbird/venv/bin/poorbird serve
|
|
||||||
|
|
||||||
Restart=on-failure
|
|
||||||
RestartSec=5
|
|
||||||
TimeoutStopSec=20
|
|
||||||
|
|
||||||
# Logs go to stdout and journald picks them up. No app-managed log files.
|
|
||||||
StandardOutput=journal
|
|
||||||
StandardError=journal
|
|
||||||
SyslogIdentifier=poorbird-api
|
|
||||||
|
|
||||||
# --- hardening
|
|
||||||
NoNewPrivileges=yes
|
|
||||||
PrivateTmp=yes
|
|
||||||
PrivateDevices=yes
|
|
||||||
ProtectSystem=strict
|
|
||||||
ProtectHome=yes
|
|
||||||
ProtectKernelTunables=yes
|
|
||||||
ProtectKernelModules=yes
|
|
||||||
ProtectControlGroups=yes
|
|
||||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
|
||||||
RestrictSUIDSGID=yes
|
|
||||||
LockPersonality=yes
|
|
||||||
MemoryDenyWriteExecute=no
|
|
||||||
ReadWritePaths=/srv/poorbird /var/lib/poorbird
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=poorBird worker (job queue + scheduler)
|
|
||||||
After=network-online.target postgresql.service poorbird-api.service
|
|
||||||
Wants=network-online.target
|
|
||||||
Requires=postgresql.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=exec
|
|
||||||
User=poorbird
|
|
||||||
Group=poorbird
|
|
||||||
WorkingDirectory=/opt/poorbird/app
|
|
||||||
EnvironmentFile=/etc/poorbird/poorbird.env
|
|
||||||
|
|
||||||
# No ExecStartPre=migrate here: the API unit owns migrations, so two units
|
|
||||||
# never race to apply the same revision.
|
|
||||||
ExecStart=/opt/poorbird/venv/bin/poorbird worker
|
|
||||||
|
|
||||||
Restart=on-failure
|
|
||||||
RestartSec=5
|
|
||||||
# The worker finishes its current job on SIGTERM.
|
|
||||||
KillSignal=SIGTERM
|
|
||||||
TimeoutStopSec=60
|
|
||||||
|
|
||||||
StandardOutput=journal
|
|
||||||
StandardError=journal
|
|
||||||
SyslogIdentifier=poorbird-worker
|
|
||||||
|
|
||||||
# --- hardening
|
|
||||||
NoNewPrivileges=yes
|
|
||||||
PrivateTmp=yes
|
|
||||||
PrivateDevices=yes
|
|
||||||
ProtectSystem=strict
|
|
||||||
ProtectHome=yes
|
|
||||||
ProtectKernelTunables=yes
|
|
||||||
ProtectKernelModules=yes
|
|
||||||
ProtectControlGroups=yes
|
|
||||||
RestrictSUIDSGID=yes
|
|
||||||
LockPersonality=yes
|
|
||||||
ReadWritePaths=/srv/poorbird /var/lib/poorbird
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
# poorBird configuration.
|
|
||||||
#
|
|
||||||
# Install to /etc/poorbird/poorbird.env, owned by root:poorbird, mode 0640.
|
|
||||||
# systemd loads it via EnvironmentFile. This same file becomes a compose .env
|
|
||||||
# unchanged if containers ever happen (TODO.md Phase 1.2).
|
|
||||||
#
|
|
||||||
# Note: systemd's EnvironmentFile does NOT do shell quoting or expansion.
|
|
||||||
# Write VALUES literally, with no surrounding quotes.
|
|
||||||
|
|
||||||
# --- database ---------------------------------------------------------------
|
|
||||||
# Loopback TCP with scram-sha-256, deliberately not a Unix socket.
|
|
||||||
# Required: the app has no built-in default and refuses to start without it.
|
|
||||||
# The literal CHANGE_ME below is rejected at startup, so you cannot copy this
|
|
||||||
# file and forget to edit it.
|
|
||||||
POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird
|
|
||||||
#
|
|
||||||
# Connection pool. The API and the worker are separate processes and each gets
|
|
||||||
# its own pool, so the most either can open is POOL_SIZE + MAX_OVERFLOW and the
|
|
||||||
# most both together can open is twice that -- keep it under PostgreSQL's
|
|
||||||
# max_connections (100 by default). The worker opens connections lazily and
|
|
||||||
# needs about three, so the size below is really sizing the API.
|
|
||||||
POORBIRD_DB_POOL_SIZE=15
|
|
||||||
POORBIRD_DB_MAX_OVERFLOW=10
|
|
||||||
|
|
||||||
# --- http -------------------------------------------------------------------
|
|
||||||
# Bind to loopback only; Caddy is the only thing that talks to it.
|
|
||||||
# Caddy itself takes :8080 for the camera and :443 for humans, so uvicorn sits
|
|
||||||
# behind on 8090. See deploy/Caddyfile.
|
|
||||||
POORBIRD_API_HOST=127.0.0.1
|
|
||||||
POORBIRD_API_PORT=8090
|
|
||||||
|
|
||||||
# --- storage ----------------------------------------------------------------
|
|
||||||
# Read by the app AND referenced by the Caddyfile: the auth-checked image
|
|
||||||
# handoff needs both to agree on this path (SPEC 3.3).
|
|
||||||
POORBIRD_IMAGE_ROOT=/srv/poorbird/images
|
|
||||||
POORBIRD_THUMB_ROOT=/srv/poorbird/thumbs
|
|
||||||
POORBIRD_STATE_DIR=/var/lib/poorbird
|
|
||||||
|
|
||||||
# Who copies the image bytes (SPEC 3.3).
|
|
||||||
#
|
|
||||||
# Leave this FALSE in production. The app authorises the request and answers
|
|
||||||
# with X-Accel-Redirect, and Caddy reads the file, so a 3 MB JPEG never
|
|
||||||
# occupies a Python worker thread.
|
|
||||||
#
|
|
||||||
# Set it true ONLY for local development, where there is no Caddy to honour
|
|
||||||
# that header and every image in the gallery would otherwise arrive as an
|
|
||||||
# empty 200. It does NOT relax the authorisation -- the same check runs either
|
|
||||||
# way; it only changes how an already-authorised response is finished.
|
|
||||||
#
|
|
||||||
# NOTE: with this false, IMAGE_ROOT and THUMB_ROOT must be siblings named
|
|
||||||
# images/ and thumbs/ under the directory the Caddyfile's file_server serves
|
|
||||||
# (deploy/Caddyfile, the protected_files snippet). `poorbird check` verifies
|
|
||||||
# that, because getting it wrong produces 404s from Caddy and nothing in the
|
|
||||||
# app's log.
|
|
||||||
POORBIRD_SERVE_IMAGES_DIRECTLY=false
|
|
||||||
|
|
||||||
# --- devices ----------------------------------------------------------------
|
|
||||||
# Shared bootstrap secret the firmware presents in X-Enroll-Secret.
|
|
||||||
# Generate with: openssl rand -hex 32
|
|
||||||
#
|
|
||||||
# WARNING (firmware/API.md): this value is compiled into the firmware image as
|
|
||||||
# the last-resort recovery path for a camera that cannot be reached over USB.
|
|
||||||
# Rotating it here WITHOUT shipping new firmware removes that escape hatch.
|
|
||||||
POORBIRD_ENROLL_SECRET=
|
|
||||||
|
|
||||||
# --- user sessions ----------------------------------------------------------
|
|
||||||
# How long a signed-in browser stays signed in. SPEC 3.4 makes this a
|
|
||||||
# UI-editable server setting eventually; for now it is here.
|
|
||||||
POORBIRD_SESSION_LIFETIME_H=336
|
|
||||||
|
|
||||||
# Leave this TRUE in production. Caddy always terminates HTTPS, so the cookie
|
|
||||||
# can and must be Secure.
|
|
||||||
#
|
|
||||||
# Set it false ONLY for local development against the Vite dev server, which is
|
|
||||||
# plain http on localhost. A Secure cookie is silently discarded by the browser
|
|
||||||
# over http, and the symptom is "login returns 200 but I am never signed in",
|
|
||||||
# with nothing in any log to explain it. That is the only reason this is a
|
|
||||||
# setting rather than a constant.
|
|
||||||
POORBIRD_SESSION_COOKIE_SECURE=true
|
|
||||||
|
|
||||||
# --- rate limiting ------------------------------------------------------------
|
|
||||||
# In-process token buckets. Sized for ONE uvicorn process: if you ever run the
|
|
||||||
# API with workers, each gets its own buckets and the effective limit
|
|
||||||
# multiplies. Set false only for local development.
|
|
||||||
POORBIRD_RATE_LIMIT_ENABLED=true
|
|
||||||
|
|
||||||
# --- worker -----------------------------------------------------------------
|
|
||||||
# How long to wait after finding the queue empty. Does not delay a queue that
|
|
||||||
# already has work: the worker drains that without pausing.
|
|
||||||
POORBIRD_WORKER_POLL_INTERVAL_S=5
|
|
||||||
POORBIRD_JOB_MAX_ATTEMPTS=3
|
|
||||||
|
|
||||||
# --- logging ----------------------------------------------------------------
|
|
||||||
POORBIRD_LOG_LEVEL=INFO
|
|
||||||
# text for journalctl by eye, json once you are shipping logs somewhere.
|
|
||||||
POORBIRD_LOG_FORMAT=text
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from logging.config import fileConfig
|
|
||||||
|
|
||||||
from alembic import context
|
|
||||||
from sqlalchemy import engine_from_config, pool
|
|
||||||
|
|
||||||
from poorbird.config import get_settings
|
|
||||||
from poorbird.models import Base
|
|
||||||
from poorbird.schema_compare import COMPARE_OPTS
|
|
||||||
|
|
||||||
config = context.config
|
|
||||||
|
|
||||||
if config.config_file_name is not None:
|
|
||||||
fileConfig(config.config_file_name)
|
|
||||||
|
|
||||||
# One source of truth for the URL: the environment, via Settings. An explicit
|
|
||||||
# override still wins, so tests can point a run at a scratch database.
|
|
||||||
if not config.get_main_option("sqlalchemy.url", None):
|
|
||||||
config.set_main_option("sqlalchemy.url", get_settings().database_url)
|
|
||||||
|
|
||||||
target_metadata = Base.metadata
|
|
||||||
|
|
||||||
OPTS = COMPARE_OPTS
|
|
||||||
|
|
||||||
|
|
||||||
def run_migrations_offline() -> None:
|
|
||||||
context.configure(
|
|
||||||
url=config.get_main_option("sqlalchemy.url"),
|
|
||||||
target_metadata=target_metadata,
|
|
||||||
literal_binds=True,
|
|
||||||
dialect_opts={"paramstyle": "named"},
|
|
||||||
**OPTS,
|
|
||||||
)
|
|
||||||
with context.begin_transaction():
|
|
||||||
context.run_migrations()
|
|
||||||
|
|
||||||
|
|
||||||
def _run(connection) -> None:
|
|
||||||
context.configure(connection=connection, target_metadata=target_metadata, **OPTS)
|
|
||||||
with context.begin_transaction():
|
|
||||||
context.run_migrations()
|
|
||||||
|
|
||||||
|
|
||||||
def run_migrations_online() -> None:
|
|
||||||
# A caller may hand us a live connection (the schema-drift test does).
|
|
||||||
injected = config.attributes.get("connection", None)
|
|
||||||
if injected is not None:
|
|
||||||
_run(injected)
|
|
||||||
return
|
|
||||||
|
|
||||||
connectable = engine_from_config(
|
|
||||||
config.get_section(config.config_ini_section, {}),
|
|
||||||
prefix="sqlalchemy.",
|
|
||||||
poolclass=pool.NullPool,
|
|
||||||
)
|
|
||||||
with connectable.connect() as connection:
|
|
||||||
_run(connection)
|
|
||||||
|
|
||||||
|
|
||||||
if context.is_offline_mode():
|
|
||||||
run_migrations_offline()
|
|
||||||
else:
|
|
||||||
run_migrations_online()
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
"""${message}
|
|
||||||
|
|
||||||
Revision ID: ${up_revision}
|
|
||||||
Revises: ${down_revision | comma,n}
|
|
||||||
Create Date: ${create_date}
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from collections.abc import Sequence
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
import sqlalchemy as sa
|
|
||||||
${imports if imports else ""}
|
|
||||||
|
|
||||||
revision: str = ${repr(up_revision)}
|
|
||||||
down_revision: str | None = ${repr(down_revision)}
|
|
||||||
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
|
||||||
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
${upgrades if upgrades else "pass"}
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
${downgrades if downgrades else "pass"}
|
|
||||||
@@ -1,529 +0,0 @@
|
|||||||
"""Baseline schema: SPEC 3 plus the SPEC 0 additions.
|
|
||||||
|
|
||||||
Explicit DDL, and frozen.
|
|
||||||
|
|
||||||
This revision used to call ``Base.metadata.create_all()``. That could not drift
|
|
||||||
from the models, which was the point, but it also meant a fresh database got
|
|
||||||
the *current* models here and then had every later migration applied on top of
|
|
||||||
what it had already created -- so the first revision added after it failed with
|
|
||||||
"column token_hash of relation sessions already exists".
|
|
||||||
``tests/test_schema_matches_models.py`` caught that the moment one was added,
|
|
||||||
which is the only reason it did not reach a deployment.
|
|
||||||
|
|
||||||
So the baseline is now what Alembic expects a baseline to be: the schema as it
|
|
||||||
stood at the end of Phase 1, and nothing after it. Later revisions change it.
|
|
||||||
|
|
||||||
**Do not edit this file to reflect a model change -- add a revision.** Editing
|
|
||||||
it would reintroduce exactly the failure above, for anyone whose database is
|
|
||||||
already past this point.
|
|
||||||
|
|
||||||
Revision ID: 0001
|
|
||||||
Revises:
|
|
||||||
Create Date: 2026-09-20
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from collections.abc import Sequence
|
|
||||||
|
|
||||||
import sqlalchemy as sa
|
|
||||||
from alembic import op
|
|
||||||
from sqlalchemy.dialects import postgresql
|
|
||||||
|
|
||||||
revision: str = "0001"
|
|
||||||
down_revision: str | None = None
|
|
||||||
branch_labels: str | Sequence[str] | None = None
|
|
||||||
depends_on: str | Sequence[str] | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.create_table(
|
|
||||||
"backup_runs",
|
|
||||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"started_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("status", sa.String(length=16), nullable=False),
|
|
||||||
sa.Column("bytes", sa.BigInteger(), nullable=True),
|
|
||||||
sa.Column("snapshot_id", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("restore_tested_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("error", sa.Text(), nullable=True),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_backup_runs")),
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"devices",
|
|
||||||
sa.Column("id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("device_uid", sa.String(length=32), nullable=False),
|
|
||||||
sa.Column("name", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("mac", sa.String(length=32), nullable=True),
|
|
||||||
sa.Column("hw_revision", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("fw_version", sa.String(length=32), nullable=True),
|
|
||||||
sa.Column("token_hash", sa.String(length=128), nullable=True),
|
|
||||||
sa.Column("reenroll_secret_hash", sa.String(length=128), nullable=True),
|
|
||||||
sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("battery_mv", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("battery_pct", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("battery_valid", sa.Boolean(), nullable=False),
|
|
||||||
sa.Column("rssi", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("temp_c", sa.Float(), nullable=True),
|
|
||||||
sa.Column("awake", sa.Boolean(), nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"config", postgresql.JSONB(astext_type=sa.Text()), server_default="{}", nullable=False
|
|
||||||
),
|
|
||||||
sa.Column("config_version", sa.Integer(), server_default="1", nullable=False),
|
|
||||||
sa.Column("heartbeat_interval_s", sa.Integer(), server_default="300", nullable=False),
|
|
||||||
sa.Column("status_interval_s", sa.Integer(), server_default="900", nullable=False),
|
|
||||||
sa.Column("responsive_mode", sa.Boolean(), server_default="false", nullable=False),
|
|
||||||
sa.Column("enabled", sa.Boolean(), server_default="true", nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_devices")),
|
|
||||||
)
|
|
||||||
op.create_index(op.f("ix_devices_device_uid"), "devices", ["device_uid"], unique=True)
|
|
||||||
op.create_index(op.f("ix_devices_token_hash"), "devices", ["token_hash"], unique=True)
|
|
||||||
op.create_table(
|
|
||||||
"jobs",
|
|
||||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column("kind", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"payload", postgresql.JSONB(astext_type=sa.Text()), server_default="{}", nullable=False
|
|
||||||
),
|
|
||||||
sa.Column("status", sa.String(length=16), server_default="queued", nullable=False),
|
|
||||||
sa.Column("priority", sa.Integer(), server_default="0", nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"run_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False
|
|
||||||
),
|
|
||||||
sa.Column("attempts", sa.Integer(), server_default="0", nullable=False),
|
|
||||||
sa.Column("max_attempts", sa.Integer(), server_default="3", nullable=False),
|
|
||||||
sa.Column("locked_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("locked_by", sa.String(length=128), nullable=True),
|
|
||||||
sa.Column("last_error", sa.Text(), nullable=True),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"status IN ('queued', 'running', 'done', 'failed')", name=op.f("ck_jobs_status_valid")
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_jobs")),
|
|
||||||
)
|
|
||||||
op.create_index("ix_jobs_claimable", "jobs", ["status", "run_at", "priority"], unique=False)
|
|
||||||
op.create_table(
|
|
||||||
"tags",
|
|
||||||
sa.Column("id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("label", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("colour", sa.String(length=16), nullable=True),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_tags")),
|
|
||||||
sa.UniqueConstraint("label", name=op.f("uq_tags_label")),
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"taxa",
|
|
||||||
sa.Column("id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("gbif_key", sa.BigInteger(), nullable=True),
|
|
||||||
sa.Column("scientific_name", sa.String(length=128), nullable=False),
|
|
||||||
sa.Column("name_de", sa.String(length=128), nullable=True),
|
|
||||||
sa.Column("name_en", sa.String(length=128), nullable=True),
|
|
||||||
sa.Column("family", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("order", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("iucn_status", sa.String(length=8), nullable=True),
|
|
||||||
sa.Column("is_local_common", sa.Boolean(), server_default="false", nullable=False),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_taxa")),
|
|
||||||
sa.UniqueConstraint("gbif_key", name=op.f("uq_taxa_gbif_key")),
|
|
||||||
sa.UniqueConstraint("scientific_name", name=op.f("uq_taxa_scientific_name")),
|
|
||||||
)
|
|
||||||
op.create_index(op.f("ix_taxa_name_de"), "taxa", ["name_de"], unique=False)
|
|
||||||
op.create_index(op.f("ix_taxa_name_en"), "taxa", ["name_en"], unique=False)
|
|
||||||
op.create_table(
|
|
||||||
"users",
|
|
||||||
sa.Column("id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("username", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("email", sa.String(length=255), nullable=True),
|
|
||||||
sa.Column("password_hash", sa.String(length=255), nullable=True),
|
|
||||||
sa.Column("role", sa.String(length=16), server_default="viewer", nullable=False),
|
|
||||||
sa.Column("totp_secret", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("is_active", sa.Boolean(), server_default="true", nullable=False),
|
|
||||||
sa.Column("theme", sa.String(length=16), server_default="light", nullable=False),
|
|
||||||
sa.Column("locale", sa.String(length=8), server_default="de", nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("last_login_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"role IN ('admin', 'editor', 'viewer')", name=op.f("ck_users_role_valid")
|
|
||||||
),
|
|
||||||
sa.CheckConstraint("theme IN ('light', 'dark', 'blue')", name=op.f("ck_users_theme_valid")),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
|
|
||||||
sa.UniqueConstraint("username", name=op.f("uq_users_username")),
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"audit_log",
|
|
||||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False
|
|
||||||
),
|
|
||||||
sa.Column("user_id", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("action", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("entity", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("entity_id", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("before", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
|
||||||
sa.Column("after", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
|
||||||
sa.Column("ip", sa.String(length=45), nullable=True),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["user_id"], ["users.id"], name=op.f("fk_audit_log_user_id_users"), ondelete="SET NULL"
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_audit_log")),
|
|
||||||
)
|
|
||||||
op.create_index("ix_audit_log_entity", "audit_log", ["entity", "entity_id", "at"], unique=False)
|
|
||||||
op.create_table(
|
|
||||||
"captures",
|
|
||||||
sa.Column("id", sa.Uuid(), nullable=False),
|
|
||||||
sa.Column("device_id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("path", sa.Text(), nullable=False),
|
|
||||||
sa.Column("thumb_path", sa.Text(), nullable=True),
|
|
||||||
sa.Column("sha256", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("width", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("height", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("bytes", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column("captured_at_device", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column(
|
|
||||||
"received_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("trigger", sa.String(length=16), nullable=False),
|
|
||||||
sa.Column("burst_id", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("burst_index", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("burst_count", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("pre_trigger", sa.Boolean(), server_default="false", nullable=False),
|
|
||||||
sa.Column("frame_seq", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("radar_state", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("radar_distance_cm", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("radar_energy", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("battery_mv", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("rssi", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("temp_c", sa.Float(), nullable=True),
|
|
||||||
sa.Column("reviewed", sa.Boolean(), server_default="false", nullable=False),
|
|
||||||
sa.Column("kept", sa.Boolean(), server_default="true", nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"trigger IN ('radar', 'manual', 'timer', 'stream_grab')",
|
|
||||||
name=op.f("ck_captures_trigger_valid"),
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["device_id"],
|
|
||||||
["devices.id"],
|
|
||||||
name=op.f("fk_captures_device_id_devices"),
|
|
||||||
ondelete="CASCADE",
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_captures")),
|
|
||||||
)
|
|
||||||
op.create_index("ix_captures_burst", "captures", ["burst_id", "burst_index"], unique=False)
|
|
||||||
op.create_index(
|
|
||||||
"ix_captures_device_received", "captures", ["device_id", "received_at"], unique=False
|
|
||||||
)
|
|
||||||
op.create_index(op.f("ix_captures_sha256"), "captures", ["sha256"], unique=False)
|
|
||||||
op.create_index(
|
|
||||||
"ix_captures_triage", "captures", ["kept", "reviewed", "received_at"], unique=False
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"device_commands",
|
|
||||||
sa.Column("id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("device_id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("type", sa.String(length=32), nullable=False),
|
|
||||||
sa.Column("payload", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
|
||||||
sa.Column("created_by", sa.Integer(), nullable=True),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("acked_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("ack_status", sa.String(length=16), nullable=True),
|
|
||||||
sa.Column("result", sa.Text(), nullable=True),
|
|
||||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')",
|
|
||||||
name=op.f("ck_device_commands_ack_status_valid"),
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"type IN ('apply_config', 'capture_now', 'report_status', 'wake_and_hold', 'sleep_now', 'stream_start', 'stream_stop', 'ota_update', 'reboot')",
|
|
||||||
name=op.f("ck_device_commands_type_valid"),
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["created_by"],
|
|
||||||
["users.id"],
|
|
||||||
name=op.f("fk_device_commands_created_by_users"),
|
|
||||||
ondelete="SET NULL",
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["device_id"],
|
|
||||||
["devices.id"],
|
|
||||||
name=op.f("fk_device_commands_device_id_devices"),
|
|
||||||
ondelete="CASCADE",
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_device_commands")),
|
|
||||||
)
|
|
||||||
op.create_index(
|
|
||||||
"ix_device_commands_pending", "device_commands", ["device_id", "created_at"], unique=False
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"device_status",
|
|
||||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column("device_id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False
|
|
||||||
),
|
|
||||||
sa.Column("reason", sa.String(length=32), nullable=False),
|
|
||||||
sa.Column("battery_mv", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("battery_pct", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("battery_valid", sa.Boolean(), nullable=True),
|
|
||||||
sa.Column("awake_ms", sa.BigInteger(), nullable=True),
|
|
||||||
sa.Column("boot_count", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("wake_cause", sa.String(length=16), nullable=True),
|
|
||||||
sa.Column("last_sleep_s", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("total_sleep_s", sa.BigInteger(), nullable=True),
|
|
||||||
sa.Column("captured_today", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("delivered_today", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("failed_today", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("events_today", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("day_index", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("is_night", sa.Boolean(), nullable=True),
|
|
||||||
sa.Column("nightlight_on", sa.Boolean(), nullable=True),
|
|
||||||
sa.Column("cam_profile", sa.String(length=16), nullable=True),
|
|
||||||
sa.Column("radar_baud", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("radar_uart_ok", sa.Boolean(), nullable=True),
|
|
||||||
sa.Column("stream_active", sa.Boolean(), nullable=True),
|
|
||||||
sa.Column("rssi", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("ip", sa.String(length=45), nullable=True),
|
|
||||||
sa.Column("free_heap", sa.BigInteger(), nullable=True),
|
|
||||||
sa.Column("free_psram", sa.BigInteger(), nullable=True),
|
|
||||||
sa.Column("ring_depth", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("time_synced", sa.Boolean(), nullable=True),
|
|
||||||
sa.Column("device_time", sa.DateTime(timezone=True), nullable=True),
|
|
||||||
sa.Column("fw_version", sa.String(length=32), nullable=True),
|
|
||||||
sa.Column("config_version", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("raw", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"reason IN ('heartbeat', 'periodic', 'after_event', 'before_sleep', 'before_night_sleep', 'on_request')",
|
|
||||||
name=op.f("ck_device_status_reason_valid"),
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["device_id"],
|
|
||||||
["devices.id"],
|
|
||||||
name=op.f("fk_device_status_device_id_devices"),
|
|
||||||
ondelete="CASCADE",
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_device_status")),
|
|
||||||
)
|
|
||||||
op.create_index(
|
|
||||||
"ix_device_status_device_at", "device_status", ["device_id", "at"], unique=False
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"firmware",
|
|
||||||
sa.Column("id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column("version", sa.String(length=32), nullable=False),
|
|
||||||
sa.Column("semver", sa.String(length=32), nullable=True),
|
|
||||||
sa.Column("file_path", sa.Text(), nullable=False),
|
|
||||||
sa.Column("sha256", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column("release_notes", sa.Text(), nullable=True),
|
|
||||||
sa.Column("min_battery_pct", sa.Integer(), server_default="50", nullable=False),
|
|
||||||
sa.Column("uploaded_by", sa.Integer(), nullable=True),
|
|
||||||
sa.Column(
|
|
||||||
"uploaded_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("is_target", sa.Boolean(), server_default="false", nullable=False),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["uploaded_by"],
|
|
||||||
["users.id"],
|
|
||||||
name=op.f("fk_firmware_uploaded_by_users"),
|
|
||||||
ondelete="SET NULL",
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_firmware")),
|
|
||||||
sa.UniqueConstraint("version", name=op.f("uq_firmware_version")),
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"sessions",
|
|
||||||
sa.Column("id", sa.Uuid(), nullable=False),
|
|
||||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
|
||||||
sa.Column("ip", sa.String(length=45), nullable=True),
|
|
||||||
sa.Column("user_agent", sa.String(length=255), nullable=True),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["user_id"], ["users.id"], name=op.f("fk_sessions_user_id_users"), ondelete="CASCADE"
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_sessions")),
|
|
||||||
)
|
|
||||||
op.create_index(op.f("ix_sessions_expires_at"), "sessions", ["expires_at"], unique=False)
|
|
||||||
op.create_index(op.f("ix_sessions_user_id"), "sessions", ["user_id"], unique=False)
|
|
||||||
op.create_table(
|
|
||||||
"settings",
|
|
||||||
sa.Column("key", sa.String(length=64), nullable=False),
|
|
||||||
sa.Column("value", sa.Text(), nullable=True),
|
|
||||||
sa.Column("value_type", sa.String(length=16), server_default="str", nullable=False),
|
|
||||||
sa.Column("scope", sa.String(length=16), server_default="server", nullable=False),
|
|
||||||
sa.Column("updated_by", sa.Integer(), nullable=True),
|
|
||||||
sa.Column(
|
|
||||||
"updated_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.CheckConstraint("scope IN ('server', 'device')", name=op.f("ck_settings_scope_valid")),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["updated_by"],
|
|
||||||
["users.id"],
|
|
||||||
name=op.f("fk_settings_updated_by_users"),
|
|
||||||
ondelete="SET NULL",
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("key", name=op.f("pk_settings")),
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"capture_tags",
|
|
||||||
sa.Column("capture_id", sa.Uuid(), nullable=False),
|
|
||||||
sa.Column("tag_id", sa.Integer(), nullable=False),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["capture_id"],
|
|
||||||
["captures.id"],
|
|
||||||
name=op.f("fk_capture_tags_capture_id_captures"),
|
|
||||||
ondelete="CASCADE",
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["tag_id"], ["tags.id"], name=op.f("fk_capture_tags_tag_id_tags"), ondelete="CASCADE"
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("capture_id", "tag_id", name=op.f("pk_capture_tags")),
|
|
||||||
)
|
|
||||||
op.create_table(
|
|
||||||
"observations",
|
|
||||||
sa.Column("id", sa.BigInteger(), nullable=False),
|
|
||||||
sa.Column("capture_id", sa.Uuid(), nullable=False),
|
|
||||||
sa.Column("taxon_id", sa.Integer(), nullable=True),
|
|
||||||
sa.Column("individuals", sa.Integer(), server_default="1", nullable=False),
|
|
||||||
sa.Column("age", sa.String(length=16), server_default="unknown", nullable=False),
|
|
||||||
sa.Column("sex", sa.String(length=16), server_default="unknown", nullable=False),
|
|
||||||
sa.Column("behaviour", sa.String(length=16), nullable=True),
|
|
||||||
sa.Column("certainty", sa.String(length=16), server_default="certain", nullable=False),
|
|
||||||
sa.Column("notes", sa.Text(), nullable=True),
|
|
||||||
sa.Column("source", sa.String(length=8), server_default="human", nullable=False),
|
|
||||||
sa.Column("model_version", sa.String(length=64), nullable=True),
|
|
||||||
sa.Column("confidence", sa.Float(), nullable=True),
|
|
||||||
sa.Column("bbox", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
|
||||||
sa.Column("created_by", sa.Integer(), nullable=True),
|
|
||||||
sa.Column(
|
|
||||||
"created_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.Column(
|
|
||||||
"updated_at",
|
|
||||||
sa.DateTime(timezone=True),
|
|
||||||
server_default=sa.text("now()"),
|
|
||||||
nullable=False,
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"age IN ('adult', 'juvenile', 'unknown')", name=op.f("ck_observations_age_valid")
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')",
|
|
||||||
name=op.f("ck_observations_behaviour_valid"),
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"certainty IN ('certain', 'probable', 'uncertain')",
|
|
||||||
name=op.f("ck_observations_certainty_valid"),
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"sex IN ('male', 'female', 'unknown')", name=op.f("ck_observations_sex_valid")
|
|
||||||
),
|
|
||||||
sa.CheckConstraint(
|
|
||||||
"source IN ('human', 'model')", name=op.f("ck_observations_source_valid")
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["capture_id"],
|
|
||||||
["captures.id"],
|
|
||||||
name=op.f("fk_observations_capture_id_captures"),
|
|
||||||
ondelete="CASCADE",
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["created_by"],
|
|
||||||
["users.id"],
|
|
||||||
name=op.f("fk_observations_created_by_users"),
|
|
||||||
ondelete="SET NULL",
|
|
||||||
),
|
|
||||||
sa.ForeignKeyConstraint(
|
|
||||||
["taxon_id"],
|
|
||||||
["taxa.id"],
|
|
||||||
name=op.f("fk_observations_taxon_id_taxa"),
|
|
||||||
ondelete="RESTRICT",
|
|
||||||
),
|
|
||||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_observations")),
|
|
||||||
)
|
|
||||||
op.create_index(
|
|
||||||
op.f("ix_observations_capture_id"), "observations", ["capture_id"], unique=False
|
|
||||||
)
|
|
||||||
# ### end Alembic commands ###
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.drop_index(op.f("ix_observations_capture_id"), table_name="observations")
|
|
||||||
op.drop_table("observations")
|
|
||||||
op.drop_table("capture_tags")
|
|
||||||
op.drop_table("settings")
|
|
||||||
op.drop_index(op.f("ix_sessions_user_id"), table_name="sessions")
|
|
||||||
op.drop_index(op.f("ix_sessions_expires_at"), table_name="sessions")
|
|
||||||
op.drop_table("sessions")
|
|
||||||
op.drop_table("firmware")
|
|
||||||
op.drop_index("ix_device_status_device_at", table_name="device_status")
|
|
||||||
op.drop_table("device_status")
|
|
||||||
op.drop_index("ix_device_commands_pending", table_name="device_commands")
|
|
||||||
op.drop_table("device_commands")
|
|
||||||
op.drop_index("ix_captures_triage", table_name="captures")
|
|
||||||
op.drop_index(op.f("ix_captures_sha256"), table_name="captures")
|
|
||||||
op.drop_index("ix_captures_device_received", table_name="captures")
|
|
||||||
op.drop_index("ix_captures_burst", table_name="captures")
|
|
||||||
op.drop_table("captures")
|
|
||||||
op.drop_index("ix_audit_log_entity", table_name="audit_log")
|
|
||||||
op.drop_table("audit_log")
|
|
||||||
op.drop_table("users")
|
|
||||||
op.drop_index(op.f("ix_taxa_name_en"), table_name="taxa")
|
|
||||||
op.drop_index(op.f("ix_taxa_name_de"), table_name="taxa")
|
|
||||||
op.drop_table("taxa")
|
|
||||||
op.drop_table("tags")
|
|
||||||
op.drop_index("ix_jobs_claimable", table_name="jobs")
|
|
||||||
op.drop_table("jobs")
|
|
||||||
op.drop_index(op.f("ix_devices_token_hash"), table_name="devices")
|
|
||||||
op.drop_index(op.f("ix_devices_device_uid"), table_name="devices")
|
|
||||||
op.drop_table("devices")
|
|
||||||
op.drop_table("backup_runs")
|
|
||||||
# ### end Alembic commands ###
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
"""session token hash and csrf token
|
|
||||||
|
|
||||||
The cookie stops being the primary key. ``sessions.id`` becomes internal and the
|
|
||||||
browser carries a separate token of which only the SHA-256 is stored, so a
|
|
||||||
database dump no longer hands over every live session. ``csrf_token`` is per
|
|
||||||
session, which is what stops the double-submit check being satisfiable by
|
|
||||||
someone who can merely set a cookie on the domain.
|
|
||||||
|
|
||||||
Both columns are NOT NULL with no default, and that is deliberate: there is no
|
|
||||||
value that could be back-filled. A session row without a token hash cannot be
|
|
||||||
looked up by any request, so it is not a session -- it is a row that would sit
|
|
||||||
there until it expired. Existing rows are therefore deleted rather than given a
|
|
||||||
placeholder hash, which would be a credential nobody holds and the unique index
|
|
||||||
would reject on the second row anyway.
|
|
||||||
|
|
||||||
In practice this table is empty: nothing before Phase 3 ever wrote a session.
|
|
||||||
The DELETE is here so the migration is also correct on a database where that
|
|
||||||
turns out not to be true.
|
|
||||||
|
|
||||||
Revision ID: c00181d246b9
|
|
||||||
Revises: 0001
|
|
||||||
Create Date: 2026-09-21 17:57:33.783616
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from collections.abc import Sequence
|
|
||||||
|
|
||||||
import sqlalchemy as sa
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision: str = "c00181d246b9"
|
|
||||||
down_revision: str | None = "0001"
|
|
||||||
branch_labels: str | Sequence[str] | None = None
|
|
||||||
depends_on: str | Sequence[str] | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
# Any pre-existing row is unusable under the new scheme; signing those
|
|
||||||
# browsers out is the correct outcome, not a loss.
|
|
||||||
op.execute("DELETE FROM sessions")
|
|
||||||
op.add_column("sessions", sa.Column("token_hash", sa.String(length=64), nullable=False))
|
|
||||||
op.add_column("sessions", sa.Column("csrf_token", sa.String(length=64), nullable=False))
|
|
||||||
op.create_index(op.f("ix_sessions_token_hash"), "sessions", ["token_hash"], unique=True)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
# Going back makes every session unauthenticatable for the same reason, so
|
|
||||||
# clear them here too rather than leaving rows that resolve to nothing.
|
|
||||||
op.drop_index(op.f("ix_sessions_token_hash"), table_name="sessions")
|
|
||||||
op.drop_column("sessions", "csrf_token")
|
|
||||||
op.drop_column("sessions", "token_hash")
|
|
||||||
op.execute("DELETE FROM sessions")
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
[project]
|
|
||||||
name = "poorbird"
|
|
||||||
version = "0.1.0"
|
|
||||||
description = "poorBird server — ingest, gallery and device management for a radar-triggered bird camera"
|
|
||||||
requires-python = ">=3.11"
|
|
||||||
dependencies = [
|
|
||||||
"fastapi>=0.115",
|
|
||||||
"uvicorn[standard]>=0.32",
|
|
||||||
"pydantic>=2.9",
|
|
||||||
"pydantic-settings>=2.6",
|
|
||||||
"sqlalchemy>=2.0.36",
|
|
||||||
"psycopg[binary]>=3.2",
|
|
||||||
"alembic>=1.14",
|
|
||||||
"apscheduler>=3.11,<4",
|
|
||||||
# Thumbnails only, and only in the worker. The ingest path deliberately
|
|
||||||
# does not decode images -- see poorbird/images.py.
|
|
||||||
"pillow>=11.0",
|
|
||||||
# Argon2id for user passwords (SPEC 3.1). Device tokens stay on SHA-256 and
|
|
||||||
# deliberately so -- see api/deps.py.hash_credential for why the two differ.
|
|
||||||
"argon2-cffi>=23.1",
|
|
||||||
# TOTP. Hand-rolling RFC 6238 is 30 lines, and the two that matter -- the
|
|
||||||
# constant-time compare and the clock-skew window -- are the two easiest to
|
|
||||||
# get quietly wrong.
|
|
||||||
"pyotp>=2.9",
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.optional-dependencies]
|
|
||||||
dev = [
|
|
||||||
"pytest>=8.3",
|
|
||||||
"httpx>=0.28",
|
|
||||||
"ruff>=0.8",
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.scripts]
|
|
||||||
poorbird = "poorbird.cli:main"
|
|
||||||
|
|
||||||
[build-system]
|
|
||||||
requires = ["hatchling"]
|
|
||||||
build-backend = "hatchling.build"
|
|
||||||
|
|
||||||
[tool.hatch.build.targets.wheel]
|
|
||||||
packages = ["src/poorbird"]
|
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
|
||||||
testpaths = ["tests"]
|
|
||||||
markers = [
|
|
||||||
"db: integration test, needs a reachable PostgreSQL (deselect with -m 'not db')",
|
|
||||||
]
|
|
||||||
|
|
||||||
[tool.ruff]
|
|
||||||
line-length = 100
|
|
||||||
src = ["src"]
|
|
||||||
|
|
||||||
[tool.ruff.lint]
|
|
||||||
select = ["E", "F", "I", "UP", "B"]
|
|
||||||
|
|
||||||
[tool.ruff.lint.per-file-ignores]
|
|
||||||
# Migrations are generated, then linted like everything else -- except for line
|
|
||||||
# length. The over-long lines are CHECK constraint bodies, which are SQL string
|
|
||||||
# literals: wrapping one means editing the constraint, and a migration that has
|
|
||||||
# already run is not a file to edit for tidiness.
|
|
||||||
"migrations/versions/*.py" = ["E501"]
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
__version__ = "0.1.0"
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
from .app import create_app
|
|
||||||
|
|
||||||
__all__ = ["create_app"]
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from contextlib import asynccontextmanager
|
|
||||||
|
|
||||||
from fastapi import FastAPI
|
|
||||||
|
|
||||||
from .. import __version__
|
|
||||||
from ..config import get_settings
|
|
||||||
from ..logging_setup import configure_logging
|
|
||||||
from .routes import (
|
|
||||||
auth,
|
|
||||||
captures,
|
|
||||||
commands,
|
|
||||||
conditions,
|
|
||||||
device_config,
|
|
||||||
enroll,
|
|
||||||
firmware,
|
|
||||||
health,
|
|
||||||
ingest,
|
|
||||||
)
|
|
||||||
from .userauth import csrf_middleware
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
API_PREFIX = "/api/v1"
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
|
||||||
async def lifespan(app: FastAPI):
|
|
||||||
settings = get_settings()
|
|
||||||
log.info(
|
|
||||||
"poorbird api starting",
|
|
||||||
extra={"version": __version__, "image_root": str(settings.image_root)},
|
|
||||||
)
|
|
||||||
if not settings.enroll_secret_is_set:
|
|
||||||
# A warning rather than a refusal to start: an existing camera keeps
|
|
||||||
# working with the token it already holds, and taking the whole API
|
|
||||||
# down would also take down the gallery. Only enrollment breaks.
|
|
||||||
log.warning("POORBIRD_ENROLL_SECRET is not set; device enrollment will refuse requests")
|
|
||||||
yield
|
|
||||||
log.info("poorbird api stopping")
|
|
||||||
|
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
|
||||||
settings = get_settings()
|
|
||||||
configure_logging(settings.log_level, settings.log_format)
|
|
||||||
|
|
||||||
app = FastAPI(
|
|
||||||
title="poorBird",
|
|
||||||
version=__version__,
|
|
||||||
summary="Ingest, gallery and device management for a radar-triggered bird camera",
|
|
||||||
lifespan=lifespan,
|
|
||||||
)
|
|
||||||
|
|
||||||
# CSRF for cookie-authenticated mutations. Middleware rather than a
|
|
||||||
# per-route dependency so a new endpoint cannot forget it; it applies only
|
|
||||||
# to unsafe methods on requests that carry the session cookie, which is why
|
|
||||||
# the device endpoints -- bearer tokens, no cookies -- are unaffected. See
|
|
||||||
# userauth.csrf_middleware.
|
|
||||||
app.middleware("http")(csrf_middleware)
|
|
||||||
|
|
||||||
app.include_router(health.router, prefix=API_PREFIX, tags=["health"])
|
|
||||||
app.include_router(health.root_router)
|
|
||||||
|
|
||||||
# Phase 3 WebUI endpoints.
|
|
||||||
app.include_router(auth.router, prefix=API_PREFIX)
|
|
||||||
app.include_router(captures.router, prefix=API_PREFIX)
|
|
||||||
|
|
||||||
# Phase 2 device endpoints. See firmware/API.md for the contract.
|
|
||||||
app.include_router(enroll.router, prefix=API_PREFIX)
|
|
||||||
app.include_router(conditions.router, prefix=API_PREFIX)
|
|
||||||
app.include_router(device_config.router, prefix=API_PREFIX)
|
|
||||||
app.include_router(commands.router, prefix=API_PREFIX)
|
|
||||||
app.include_router(ingest.router, prefix=API_PREFIX)
|
|
||||||
app.include_router(firmware.router, prefix=API_PREFIX)
|
|
||||||
|
|
||||||
# The device contract (firmware/API.md) is complete apart from /stream,
|
|
||||||
# which is Phase 6. Still to come on the operator side: the admin-facing
|
|
||||||
# POST /firmware and device management, both Phase 4.
|
|
||||||
|
|
||||||
return app
|
|
||||||
|
|
||||||
|
|
||||||
app = create_app()
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
"""Auth-checked file delivery (SPEC 3.3).
|
|
||||||
|
|
||||||
"An unguessable URL is not access control." Every image byte goes through a
|
|
||||||
route that authorises first; only then is the file delivered. What differs
|
|
||||||
between environments is *who copies the bytes*, and deliberately nothing else:
|
|
||||||
|
|
||||||
* **Production.** The app answers empty with ``X-Accel-Redirect: /images/...``
|
|
||||||
and Caddy serves the file from disk (see deploy/Caddyfile, the
|
|
||||||
``protected_files`` snippet). Python never touches the payload, so a 3 MB
|
|
||||||
JPEG does not occupy a worker thread.
|
|
||||||
* **Development.** There is no Caddy -- the Vite dev server proxies straight to
|
|
||||||
uvicorn -- so that header would reach the browser as an empty 200 and every
|
|
||||||
image would silently be blank. With ``POORBIRD_SERVE_IMAGES_DIRECTLY=true``
|
|
||||||
the app sends the bytes itself.
|
|
||||||
|
|
||||||
The authorisation is the *same code either way*. This is not a route that
|
|
||||||
bypasses auth in development: it is one authorised route with two ways of
|
|
||||||
finishing. That distinction is the whole point -- a separate unauthenticated
|
|
||||||
file route "only reachable in dev" is exactly the kind of thing that survives
|
|
||||||
into production because it works.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from fastapi import HTTPException, Response, status
|
|
||||||
from fastapi.responses import FileResponse
|
|
||||||
|
|
||||||
from ..config import Settings
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# URL prefixes Caddy maps onto disk. These are coupled to deploy/Caddyfile,
|
|
||||||
# whose file_server root is the PARENT of image_root and thumb_root -- so the
|
|
||||||
# last segment of each root has to be exactly this. Change one, change both.
|
|
||||||
IMAGE_URL_PREFIX = "/images"
|
|
||||||
THUMB_URL_PREFIX = "/thumbs"
|
|
||||||
|
|
||||||
|
|
||||||
def _safe_absolute(root: Path, relative: str) -> Path:
|
|
||||||
"""Resolve ``relative`` under ``root``, or 404.
|
|
||||||
|
|
||||||
``captures.path`` is written by our own ingest code, so this should never
|
|
||||||
fire. It is here because the cost of being wrong is serving an arbitrary
|
|
||||||
file off the server, and "should never" is not a security control. A
|
|
||||||
traversal attempt is answered as a missing file rather than as a refusal,
|
|
||||||
because confirming that a path is interesting is itself information.
|
|
||||||
"""
|
|
||||||
root = root.resolve()
|
|
||||||
candidate = (root / relative).resolve()
|
|
||||||
if candidate != root and root not in candidate.parents:
|
|
||||||
log.error(
|
|
||||||
"refusing a path that escapes its root",
|
|
||||||
extra={"root": str(root), "relative": relative},
|
|
||||||
)
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found")
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
|
|
||||||
def deliver(
|
|
||||||
*,
|
|
||||||
settings: Settings,
|
|
||||||
root: Path,
|
|
||||||
url_prefix: str,
|
|
||||||
relative: str,
|
|
||||||
media_type: str,
|
|
||||||
filename: str,
|
|
||||||
) -> Response:
|
|
||||||
"""Hand an already-authorised file to the client.
|
|
||||||
|
|
||||||
Callers must have checked permission before reaching here; this function
|
|
||||||
knows nothing about who is asking.
|
|
||||||
"""
|
|
||||||
absolute = _safe_absolute(root, relative)
|
|
||||||
|
|
||||||
if settings.serve_images_directly:
|
|
||||||
if not absolute.is_file():
|
|
||||||
# The row says there is a file and there is not. Worth logging
|
|
||||||
# loudly: it means the database and the disk have diverged, which
|
|
||||||
# a backup restore or a half-finished retention run can do.
|
|
||||||
log.error("capture file is missing from disk", extra={"path": str(absolute)})
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found")
|
|
||||||
return FileResponse(
|
|
||||||
absolute,
|
|
||||||
media_type=media_type,
|
|
||||||
# Long and immutable: the filename contains the capture UUID and
|
|
||||||
# the bytes at that path never change. Private, because the whole
|
|
||||||
# point is that this response was authorised for one person.
|
|
||||||
headers={
|
|
||||||
"Cache-Control": "private, max-age=31536000, immutable",
|
|
||||||
"Content-Disposition": f'inline; filename="{filename}"',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
# Production: Caddy serves it. The body stays empty on purpose -- if this
|
|
||||||
# reaches a browser directly it is a deployment mistake, and an empty
|
|
||||||
# response is a louder symptom than a plausible-looking one.
|
|
||||||
#
|
|
||||||
# Existence is deliberately not checked here. Doing so would mean a stat()
|
|
||||||
# on the request path for a file the app is not going to open, and Caddy
|
|
||||||
# answers 404 by itself if it is gone.
|
|
||||||
return Response(
|
|
||||||
status_code=status.HTTP_200_OK,
|
|
||||||
headers={
|
|
||||||
"X-Accel-Redirect": f"{url_prefix}/{relative}",
|
|
||||||
"Cache-Control": "private, max-age=31536000, immutable",
|
|
||||||
"Content-Disposition": f'inline; filename="{filename}"',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
"""Shared dependencies: database sessions and device authentication.
|
|
||||||
|
|
||||||
Device auth is two-step (firmware/API.md). ``POST /enroll`` is guarded by a
|
|
||||||
shared bootstrap secret in ``X-Enroll-Secret``; everything else carries
|
|
||||||
``Authorization: Bearer <token>``. Only hashes are stored.
|
|
||||||
|
|
||||||
Two details here are easy to get wrong, and the reference code in
|
|
||||||
``docs/reviews/server-basic-implementation/REVIEW.AI.md`` got both wrong, so
|
|
||||||
they are spelled out:
|
|
||||||
|
|
||||||
1. The plaintext token is returned to the device exactly once, at enrollment,
|
|
||||||
and only its hash is persisted. Returning the stored hash would give the
|
|
||||||
device a credential the server cannot recognise and 401 every request after.
|
|
||||||
|
|
||||||
2. Re-enrollment must accept the device's *per-device* ``reenroll_secret`` as
|
|
||||||
well as the shared bootstrap secret. The firmware swaps the shared secret
|
|
||||||
for the per-device one the first time the server offers it, so from then on
|
|
||||||
that is what it presents. Checking only the shared secret would lock out
|
|
||||||
every device that had successfully enrolled, which is the exact failure the
|
|
||||||
re-enrollment path exists to prevent -- and the camera cannot be reached
|
|
||||||
over USB once mounted.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import hashlib
|
|
||||||
import secrets
|
|
||||||
import time
|
|
||||||
from collections.abc import Iterator
|
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from fastapi import Depends, Header, HTTPException, status
|
|
||||||
from sqlalchemy import select
|
|
||||||
from sqlalchemy.orm import Session
|
|
||||||
|
|
||||||
from ..config import Settings, get_settings
|
|
||||||
from ..db import SessionLocal
|
|
||||||
from ..models.devices import Device
|
|
||||||
from .schemas import TOKEN_CHARS
|
|
||||||
|
|
||||||
|
|
||||||
def get_db() -> Iterator[Session]:
|
|
||||||
with SessionLocal() as session:
|
|
||||||
yield session
|
|
||||||
|
|
||||||
|
|
||||||
DbDep = Annotated[Session, Depends(get_db)]
|
|
||||||
SettingsDep = Annotated[Settings, Depends(get_settings)]
|
|
||||||
|
|
||||||
|
|
||||||
def server_time_ms() -> int:
|
|
||||||
"""Epoch milliseconds, UTC.
|
|
||||||
|
|
||||||
Authoritative (SPEC C7). The device adopts this whenever it is unsynced or
|
|
||||||
more than 2 s out, so the endpoint is the clock even where SNTP is not
|
|
||||||
reachable -- which is why every device response carries it.
|
|
||||||
"""
|
|
||||||
return int(time.time() * 1000)
|
|
||||||
|
|
||||||
|
|
||||||
# --- credentials ------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def new_credential() -> str:
|
|
||||||
"""A fresh token or re-enrollment secret: exactly 64 hex characters.
|
|
||||||
|
|
||||||
The firmware stores these in ``char[65]`` (app_config.h), so 64 characters
|
|
||||||
plus a NUL fits exactly and cannot be silently truncated. API.md documents
|
|
||||||
"64 hex chars" for both. ``secrets.token_urlsafe(32)``, which REVIEW.AI.md
|
|
||||||
suggests, yields 43 non-hex characters -- it would fit the buffer but would
|
|
||||||
not match the documented contract.
|
|
||||||
"""
|
|
||||||
return secrets.token_hex(TOKEN_CHARS // 2)
|
|
||||||
|
|
||||||
|
|
||||||
def hash_credential(value: str) -> str:
|
|
||||||
"""SHA-256 hex.
|
|
||||||
|
|
||||||
A fast hash, deliberately. API.md: "the token is high-entropy, so a fast
|
|
||||||
hash is defensible here". These are 256 bits of CSPRNG output, not
|
|
||||||
passwords -- there is no dictionary to attack, and a per-request Argon2
|
|
||||||
would cost every heartbeat. Argon2id belongs on ``users.password_hash``
|
|
||||||
(SEC-008), which is a different problem.
|
|
||||||
"""
|
|
||||||
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
def _matches(presented: str | None, stored_hash: str | None) -> bool:
|
|
||||||
"""Constant-time compare of a presented credential against a stored hash."""
|
|
||||||
if not presented or not stored_hash:
|
|
||||||
return False
|
|
||||||
return secrets.compare_digest(hash_credential(presented), stored_hash)
|
|
||||||
|
|
||||||
|
|
||||||
# --- enrollment -------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def enroll_secret_accepted(
|
|
||||||
presented: str | None,
|
|
||||||
settings: Settings,
|
|
||||||
device: Device | None,
|
|
||||||
) -> bool:
|
|
||||||
"""True if ``presented`` may enroll (or re-enroll) ``device``.
|
|
||||||
|
|
||||||
Accepts the shared bootstrap secret, or -- for a device that has enrolled
|
|
||||||
before -- that device's own re-enrollment secret. Both comparisons are
|
|
||||||
constant-time, and both run even when the first has already succeeded, so
|
|
||||||
the answer takes the same time either way.
|
|
||||||
"""
|
|
||||||
if not presented:
|
|
||||||
return False
|
|
||||||
|
|
||||||
shared = settings.enroll_secret.get_secret_value()
|
|
||||||
by_shared = bool(shared) and secrets.compare_digest(presented, shared)
|
|
||||||
by_device = device is not None and _matches(presented, device.reenroll_secret_hash)
|
|
||||||
return by_shared or by_device
|
|
||||||
|
|
||||||
|
|
||||||
def require_enroll_secret_configured(settings: Settings) -> None:
|
|
||||||
"""503 rather than 500 when the server has no bootstrap secret (SEC-001).
|
|
||||||
|
|
||||||
A camera that gets this should retry later, not treat itself as rejected:
|
|
||||||
a 4xx would make the firmware clear a perfectly good token.
|
|
||||||
"""
|
|
||||||
if not settings.enroll_secret_is_set:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
||||||
detail="enrollment is not configured on this server",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# --- bearer token -----------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def verify_device_token(
|
|
||||||
db: DbDep,
|
|
||||||
authorization: Annotated[str | None, Header()] = None,
|
|
||||||
) -> Device:
|
|
||||||
"""Resolve ``Authorization: Bearer <token>`` to a Device, or 401.
|
|
||||||
|
|
||||||
401 is load-bearing: the firmware treats it as "clear the stored token and
|
|
||||||
re-enroll", which is how a rotated token heals itself without a ladder. A
|
|
||||||
disabled device gets 403 instead, precisely so that it does *not* re-enroll
|
|
||||||
in a loop (API.md, Behaviour the Pi should expect).
|
|
||||||
"""
|
|
||||||
unauthorized = HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="invalid or missing device token",
|
|
||||||
headers={"WWW-Authenticate": "Bearer"},
|
|
||||||
)
|
|
||||||
|
|
||||||
if not authorization:
|
|
||||||
raise unauthorized
|
|
||||||
scheme, _, token = authorization.partition(" ")
|
|
||||||
if scheme.lower() != "bearer" or not token.strip():
|
|
||||||
raise unauthorized
|
|
||||||
|
|
||||||
# Look the device up by hash. The hash is deterministic, so this is an
|
|
||||||
# indexed equality match, not a scan over every device.
|
|
||||||
device = db.scalar(select(Device).where(Device.token_hash == hash_credential(token.strip())))
|
|
||||||
if device is None:
|
|
||||||
raise unauthorized
|
|
||||||
if not device.enabled:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail="device is disabled",
|
|
||||||
)
|
|
||||||
return device
|
|
||||||
|
|
||||||
|
|
||||||
DeviceDep = Annotated[Device, Depends(verify_device_token)]
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
"""The response envelope shared by /ingest and /heartbeat.
|
|
||||||
|
|
||||||
SPEC 4.1 and firmware/API.md: both endpoints return the *same* shape, so a
|
|
||||||
capture that was going to happen anyway also delivers the command queue at no
|
|
||||||
extra cost. ``parseEnvelope`` in firmware/src/api_client.cpp handles both with
|
|
||||||
one function, which is why they must not drift.
|
|
||||||
|
|
||||||
``/status`` deliberately does not use this. The device posts status
|
|
||||||
immediately before deep sleep, and handing it commands there would mark them
|
|
||||||
delivered to a device that is about to be unable to run them.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
|
|
||||||
from sqlalchemy import or_, select
|
|
||||||
from sqlalchemy.orm import Session
|
|
||||||
|
|
||||||
from ..models.devices import Device, DeviceCommand, Firmware
|
|
||||||
from .deps import server_time_ms
|
|
||||||
from .schemas import Command, Envelope, FirmwareTarget
|
|
||||||
|
|
||||||
|
|
||||||
def _epoch_ms(value: datetime | None) -> int | None:
|
|
||||||
if value is None:
|
|
||||||
return None
|
|
||||||
if value.tzinfo is None:
|
|
||||||
value = value.replace(tzinfo=UTC)
|
|
||||||
return int(value.timestamp() * 1000)
|
|
||||||
|
|
||||||
|
|
||||||
def take_pending_commands(db: Session, device: Device) -> list[Command]:
|
|
||||||
"""Claim this device's queued commands and mark them delivered.
|
|
||||||
|
|
||||||
Delivery is recorded here rather than on ack, because the ack may never
|
|
||||||
come: the device runs ``reboot`` and ``sleep_now`` and is gone. ``acked_at``
|
|
||||||
is the separate, later signal that it actually ran.
|
|
||||||
|
|
||||||
Expired commands are skipped but left in place; the worker's
|
|
||||||
``prune_expired_commands`` job is what removes them, so the admin UI can
|
|
||||||
still show that a command timed out rather than silently losing it.
|
|
||||||
"""
|
|
||||||
now = datetime.now(UTC)
|
|
||||||
|
|
||||||
rows = list(
|
|
||||||
db.scalars(
|
|
||||||
select(DeviceCommand)
|
|
||||||
.where(
|
|
||||||
DeviceCommand.device_id == device.id,
|
|
||||||
DeviceCommand.delivered_at.is_(None),
|
|
||||||
or_(DeviceCommand.expires_at.is_(None), DeviceCommand.expires_at > now),
|
|
||||||
)
|
|
||||||
.order_by(DeviceCommand.created_at)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
for row in rows:
|
|
||||||
row.delivered_at = now
|
|
||||||
|
|
||||||
return [
|
|
||||||
Command(
|
|
||||||
id=row.id,
|
|
||||||
type=row.type,
|
|
||||||
payload=row.payload,
|
|
||||||
expires_at=_epoch_ms(row.expires_at),
|
|
||||||
)
|
|
||||||
for row in rows
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def firmware_target(db: Session, device: Device) -> FirmwareTarget | None:
|
|
||||||
"""The image this device should be running, or None when it is on target.
|
|
||||||
|
|
||||||
Naming a different version is itself the instruction to flash
|
|
||||||
(main.cpp:104); an explicit ``ota_update`` command is only for staged
|
|
||||||
rollouts. So "on target" must mean the key is absent, not null.
|
|
||||||
|
|
||||||
The URL is relative on purpose. ota_mgr.cpp:86 appends anything that does
|
|
||||||
not start with "http" to the API base, which already ends in /api/v1, so
|
|
||||||
"/firmware/0.2.0.bin" resolves to /api/v1/firmware/0.2.0.bin -- the
|
|
||||||
endpoint API.md documents.
|
|
||||||
"""
|
|
||||||
target = db.scalar(select(Firmware).where(Firmware.is_target.is_(True)))
|
|
||||||
if target is None or target.version == device.fw_version:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return FirmwareTarget(
|
|
||||||
version=target.version,
|
|
||||||
url=f"/firmware/{target.version}.bin",
|
|
||||||
sha256=target.sha256,
|
|
||||||
size=target.size_bytes,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def build_envelope(db: Session, device: Device, capture_id: str | None = None) -> Envelope:
|
|
||||||
"""Assemble the envelope, claiming any pending commands as a side effect.
|
|
||||||
|
|
||||||
The caller commits. Nothing here flushes, so a handler that fails after
|
|
||||||
this point does not leave commands marked delivered that never went out.
|
|
||||||
"""
|
|
||||||
return Envelope(
|
|
||||||
capture_id=capture_id,
|
|
||||||
server_time=server_time_ms(),
|
|
||||||
config_version=device.config_version,
|
|
||||||
firmware=firmware_target(db, device),
|
|
||||||
commands=take_pending_commands(db, device),
|
|
||||||
)
|
|
||||||
@@ -1,201 +0,0 @@
|
|||||||
"""Rate limiting (REVIEW SEC-004).
|
|
||||||
|
|
||||||
A token bucket per key, held in memory. No Redis and no slowapi, for the same
|
|
||||||
reason the job queue has no Redis (SPEC C8): this deployment is one uvicorn
|
|
||||||
process serving a handful of cameras on a LAN, and slowapi's default storage
|
|
||||||
is in-process anyway, so a dependency would buy convenience rather than
|
|
||||||
capability.
|
|
||||||
|
|
||||||
**That is an assumption with a name.** ``poorbird serve`` runs a single
|
|
||||||
uvicorn process (cli.py passes no ``workers``). If the deployment ever gains
|
|
||||||
workers, every worker gets its own buckets and the effective limit multiplies
|
|
||||||
by the worker count. Move the state to PostgreSQL or Redis at that point --
|
|
||||||
do not just widen the numbers.
|
|
||||||
|
|
||||||
Buckets allow a burst and then refill steadily, which is the right shape
|
|
||||||
here: a camera uploads three to five frames back to back when the radar
|
|
||||||
fires, then goes quiet. A fixed window would reject the tail of a legitimate
|
|
||||||
burst that happened to straddle a boundary.
|
|
||||||
|
|
||||||
The limits are deliberately loose. A throttled camera stops delivering
|
|
||||||
photographs, which on a private LAN is a worse outcome than the flooding the
|
|
||||||
limit is meant to prevent. These are here to stop something pathological --
|
|
||||||
a wedged device in a retry loop, or someone grinding at the enrollment
|
|
||||||
secret -- not to police normal use.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from collections import OrderedDict
|
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
from fastapi import HTTPException, Request, status
|
|
||||||
|
|
||||||
from ..config import Settings
|
|
||||||
from .deps import DeviceDep, SettingsDep
|
|
||||||
|
|
||||||
# Enough for a LAN's worth of cameras and then some. Bounded because the
|
|
||||||
# enrollment limiter keys on client address, and an unbounded dictionary
|
|
||||||
# keyed by something a caller influences is itself a way to exhaust memory.
|
|
||||||
MAX_TRACKED_KEYS = 4096
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class Limit:
|
|
||||||
"""``capacity`` requests available at once, refilled at ``per_second``."""
|
|
||||||
|
|
||||||
capacity: int
|
|
||||||
per_second: float
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def per_minute(cls, rate: int, *, burst: int | None = None) -> Limit:
|
|
||||||
return cls(capacity=burst or rate, per_second=rate / 60.0)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def per_hour(cls, rate: int, *, burst: int | None = None) -> Limit:
|
|
||||||
return cls(capacity=burst or rate, per_second=rate / 3600.0)
|
|
||||||
|
|
||||||
|
|
||||||
class TokenBuckets:
|
|
||||||
"""Thread-safe token buckets with an LRU bound.
|
|
||||||
|
|
||||||
Handlers are sync ``def``, so FastAPI runs them in a threadpool and two
|
|
||||||
requests really can land here at once.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, max_keys: int = MAX_TRACKED_KEYS) -> None:
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self._state: OrderedDict[str, tuple[float, float]] = OrderedDict()
|
|
||||||
self._max_keys = max_keys
|
|
||||||
|
|
||||||
def take(self, key: str, limit: Limit, *, now: float | None = None) -> float | None:
|
|
||||||
"""Spend one token. Returns None if allowed, else seconds to wait."""
|
|
||||||
now = time.monotonic() if now is None else now
|
|
||||||
|
|
||||||
with self._lock:
|
|
||||||
tokens, last = self._state.get(key, (float(limit.capacity), now))
|
|
||||||
tokens = min(limit.capacity, tokens + (now - last) * limit.per_second)
|
|
||||||
|
|
||||||
if tokens >= 1.0:
|
|
||||||
self._state[key] = (tokens - 1.0, now)
|
|
||||||
allowed: float | None = None
|
|
||||||
else:
|
|
||||||
self._state[key] = (tokens, now)
|
|
||||||
allowed = (1.0 - tokens) / limit.per_second
|
|
||||||
|
|
||||||
self._state.move_to_end(key)
|
|
||||||
while len(self._state) > self._max_keys:
|
|
||||||
self._state.popitem(last=False)
|
|
||||||
|
|
||||||
return allowed
|
|
||||||
|
|
||||||
def reset(self) -> None:
|
|
||||||
with self._lock:
|
|
||||||
self._state.clear()
|
|
||||||
|
|
||||||
|
|
||||||
BUCKETS = TokenBuckets()
|
|
||||||
|
|
||||||
|
|
||||||
def client_address(request: Request) -> str:
|
|
||||||
"""The camera's address, not Caddy's.
|
|
||||||
|
|
||||||
Caddy sets X-Real-IP (deploy/Caddyfile, both blocks). Without it every
|
|
||||||
camera would share one bucket, since they all arrive from 127.0.0.1 via
|
|
||||||
the proxy. Trusting the header is safe only because uvicorn binds
|
|
||||||
loopback and nothing but Caddy can reach it.
|
|
||||||
"""
|
|
||||||
forwarded = request.headers.get("x-real-ip")
|
|
||||||
if forwarded:
|
|
||||||
return forwarded.strip()
|
|
||||||
|
|
||||||
chain = request.headers.get("x-forwarded-for")
|
|
||||||
if chain:
|
|
||||||
return chain.split(",")[0].strip()
|
|
||||||
|
|
||||||
return request.client.host if request.client else "unknown"
|
|
||||||
|
|
||||||
|
|
||||||
def _enforce(key: str, limit: Limit, settings: Settings) -> None:
|
|
||||||
if not settings.rate_limit_enabled:
|
|
||||||
return
|
|
||||||
|
|
||||||
retry_after = BUCKETS.take(key, limit)
|
|
||||||
if retry_after is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
# 429 and not 401: the firmware clears its token on a 401, and being busy
|
|
||||||
# is not a credential problem. Retry-After gives it something better than
|
|
||||||
# a guess to back off by.
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
||||||
detail="too many requests",
|
|
||||||
headers={"Retry-After": str(max(1, int(retry_after + 0.5)))},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def by_address(name: str, limit: Limit):
|
|
||||||
"""Limit by caller address. For endpoints with no device yet."""
|
|
||||||
|
|
||||||
def dependency(request: Request, settings: SettingsDep) -> None:
|
|
||||||
_enforce(f"{name}:{client_address(request)}", limit, settings)
|
|
||||||
|
|
||||||
return dependency
|
|
||||||
|
|
||||||
|
|
||||||
def by_device(name: str, limit: Limit):
|
|
||||||
"""Limit per device.
|
|
||||||
|
|
||||||
Keyed on the authenticated device rather than the address so that one
|
|
||||||
misbehaving camera cannot spend another's allowance. Depends on
|
|
||||||
DeviceDep, which FastAPI resolves once per request, so this adds no
|
|
||||||
second token lookup.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def dependency(device: DeviceDep, settings: SettingsDep) -> None:
|
|
||||||
_enforce(f"{name}:{device.id}", limit, settings)
|
|
||||||
|
|
||||||
return dependency
|
|
||||||
|
|
||||||
|
|
||||||
# --- the limits -------------------------------------------------------------
|
|
||||||
#
|
|
||||||
# Each is set well above what the firmware does when healthy, with the
|
|
||||||
# relevant firmware behaviour noted so the number can be re-derived rather
|
|
||||||
# than guessed at next time.
|
|
||||||
|
|
||||||
# The device tries its stored secret and then the compiled-in bootstrap one,
|
|
||||||
# so a single enrollment attempt is up to two requests. Enrollment is rare --
|
|
||||||
# first boot, and a token rotation - so this is the one place worth being
|
|
||||||
# strict: it is where a shared secret could be ground at.
|
|
||||||
ENROLL = Limit.per_hour(20, burst=6)
|
|
||||||
|
|
||||||
# 5000 captures/day is ~3.5/min, arriving in bursts of three to five frames
|
|
||||||
# when the radar fires. 120/min with a burst of 40 leaves enormous headroom.
|
|
||||||
INGEST = Limit.per_minute(120, burst=40)
|
|
||||||
|
|
||||||
# heartbeat_interval_s defaults to 300 and the firmware clamps it to 30, so
|
|
||||||
# the fastest legitimate cadence is 2/min. Ten times that.
|
|
||||||
CONDITIONS = Limit.per_minute(20, burst=10)
|
|
||||||
|
|
||||||
# Pulled only when config_version changes, which is operator-driven.
|
|
||||||
CONFIG = Limit.per_minute(10, burst=5)
|
|
||||||
|
|
||||||
# Acks follow commands, which an operator queues by hand.
|
|
||||||
ACK = Limit.per_minute(30, burst=15)
|
|
||||||
|
|
||||||
# Whole firmware images. Expensive to serve, and a device needs one rarely;
|
|
||||||
# a loop here would be a device failing verification over and over.
|
|
||||||
FIRMWARE = Limit.per_hour(12, burst=3)
|
|
||||||
|
|
||||||
# --- people -----------------------------------------------------------------
|
|
||||||
|
|
||||||
# Login is the one endpoint where the secret is human-chosen and therefore
|
|
||||||
# guessable, so this is a real control rather than abuse protection. A person
|
|
||||||
# mistyping a password needs a handful of tries in quick succession; nobody
|
|
||||||
# needs sixty an hour. Argon2 already makes each attempt cost tens of
|
|
||||||
# milliseconds of CPU, which is itself a reason to cap the rate: without this,
|
|
||||||
# the login endpoint is also the cheapest way to spend the server's CPU.
|
|
||||||
LOGIN = Limit.per_hour(30, burst=8)
|
|
||||||
Whitespace-only changes.
@@ -1,216 +0,0 @@
|
|||||||
"""Sign in, sign out, and "who am I" (SPEC 3.1, REVIEW SEC-007).
|
|
||||||
|
|
||||||
The three endpoints ``web/src/auth/AuthProvider.tsx`` was written against, and
|
|
||||||
the ones it distinguishes carefully: a 404 there means "the server has no auth
|
|
||||||
yet" and shows a banner, whereas a 401 means "not signed in". Now that these
|
|
||||||
exist, 404 stops happening and the banner goes away.
|
|
||||||
|
|
||||||
There is no registration endpoint, on purpose. Accounts come from
|
|
||||||
``poorbird user add`` -- see the note in cli.py.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
|
||||||
from sqlalchemy import select
|
|
||||||
from sqlalchemy.orm import Session as DbSession
|
|
||||||
|
|
||||||
from ...models import AuditLog, User
|
|
||||||
from ...passwords import hash_password, needs_rehash, verify_password
|
|
||||||
from ...totp import verify as verify_totp
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import DbDep, SettingsDep
|
|
||||||
from ..ratelimit import client_address
|
|
||||||
from ..sessions import (
|
|
||||||
SESSION_COOKIE,
|
|
||||||
clear_session_cookies,
|
|
||||||
create_session,
|
|
||||||
resolve_session,
|
|
||||||
revoke_session,
|
|
||||||
set_session_cookies,
|
|
||||||
)
|
|
||||||
from ..ui_schemas import LoginRequest, SessionUser
|
|
||||||
from ..userauth import SessionDep
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
||||||
|
|
||||||
|
|
||||||
def _as_session_user(user: User) -> SessionUser:
|
|
||||||
return SessionUser(
|
|
||||||
id=user.id,
|
|
||||||
username=user.username,
|
|
||||||
role=user.role,
|
|
||||||
locale=user.locale,
|
|
||||||
theme=user.theme,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _audit(
|
|
||||||
db: DbSession,
|
|
||||||
*,
|
|
||||||
action: str,
|
|
||||||
user_id: int | None,
|
|
||||||
ip: str | None,
|
|
||||||
detail: dict | None = None,
|
|
||||||
) -> None:
|
|
||||||
"""Record an auth event (SPEC 3.1: audit_log on every mutation).
|
|
||||||
|
|
||||||
Failed attempts are recorded as well as successful ones. A log of only the
|
|
||||||
successes cannot answer the one question worth asking afterwards, which is
|
|
||||||
how many times someone tried before getting in.
|
|
||||||
"""
|
|
||||||
db.add(
|
|
||||||
AuditLog(
|
|
||||||
user_id=user_id,
|
|
||||||
action=action,
|
|
||||||
entity="session",
|
|
||||||
entity_id=str(user_id) if user_id is not None else None,
|
|
||||||
after=detail,
|
|
||||||
ip=ip[:45] if ip else None,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/login",
|
|
||||||
response_model=SessionUser,
|
|
||||||
summary="Sign in and open a session",
|
|
||||||
# By address, not by username: keying on the username would let an attacker
|
|
||||||
# lock a known account out by failing at it deliberately, turning a rate
|
|
||||||
# limit into a denial of service against exactly the person it protects.
|
|
||||||
dependencies=[Depends(ratelimit.by_address("login", ratelimit.LOGIN))],
|
|
||||||
)
|
|
||||||
def login(
|
|
||||||
body: LoginRequest,
|
|
||||||
request: Request,
|
|
||||||
response: Response,
|
|
||||||
db: DbDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
) -> SessionUser:
|
|
||||||
"""Verify a password and optional TOTP code, then set the session cookies.
|
|
||||||
|
|
||||||
Every failure answers with the same 401 and the same message. Saying "no
|
|
||||||
such user" would confirm which usernames exist, and saying "wrong code"
|
|
||||||
would confirm that the password was right -- which is most of what an
|
|
||||||
attacker wanted to know.
|
|
||||||
"""
|
|
||||||
ip = client_address(request)
|
|
||||||
rejected = HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="invalid credentials",
|
|
||||||
)
|
|
||||||
|
|
||||||
user = db.scalar(select(User).where(User.username == body.username))
|
|
||||||
|
|
||||||
# Verify against a hash even when there is no such user, by hashing the
|
|
||||||
# submitted password and throwing it away. Returning early would make a
|
|
||||||
# missing username measurably faster than a wrong password, which is a
|
|
||||||
# username oracle built out of timing.
|
|
||||||
stored = user.password_hash if user is not None else hash_password(body.password)
|
|
||||||
password_ok = verify_password(body.password, stored)
|
|
||||||
|
|
||||||
if user is None or not password_ok:
|
|
||||||
_audit(
|
|
||||||
db,
|
|
||||||
action="login_failed",
|
|
||||||
user_id=user.id if user is not None else None,
|
|
||||||
ip=ip,
|
|
||||||
detail={"username": body.username, "reason": "credentials"},
|
|
||||||
)
|
|
||||||
db.commit()
|
|
||||||
log.warning("login failed", extra={"username": body.username, "ip": ip})
|
|
||||||
raise rejected
|
|
||||||
|
|
||||||
if not user.is_active:
|
|
||||||
_audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "inactive"})
|
|
||||||
db.commit()
|
|
||||||
log.warning("login refused, account inactive", extra={"username": user.username, "ip": ip})
|
|
||||||
raise rejected
|
|
||||||
|
|
||||||
# TOTP is required exactly when the account has a secret. The policy that
|
|
||||||
# admins must have one is enforced at account creation (cli.py), not here:
|
|
||||||
# enforcing it at login would let the only admin be locked out by their own
|
|
||||||
# account, with no way back in through the UI.
|
|
||||||
if user.totp_secret and not verify_totp(user.totp_secret, body.totp):
|
|
||||||
_audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "totp"})
|
|
||||||
db.commit()
|
|
||||||
log.warning("login failed on second factor", extra={"username": user.username, "ip": ip})
|
|
||||||
raise rejected
|
|
||||||
|
|
||||||
# Login is the only moment the plaintext password exists, so it is the only
|
|
||||||
# moment the hash can be upgraded to current parameters.
|
|
||||||
if needs_rehash(user.password_hash or ""):
|
|
||||||
user.password_hash = hash_password(body.password)
|
|
||||||
log.info("password hash upgraded", extra={"username": user.username})
|
|
||||||
|
|
||||||
token, csrf = create_session(
|
|
||||||
db,
|
|
||||||
user,
|
|
||||||
settings=settings,
|
|
||||||
ip=ip,
|
|
||||||
user_agent=request.headers.get("user-agent"),
|
|
||||||
)
|
|
||||||
user.last_login_at = datetime.now(UTC)
|
|
||||||
_audit(db, action="login", user_id=user.id, ip=ip, detail={"totp": bool(user.totp_secret)})
|
|
||||||
db.commit()
|
|
||||||
|
|
||||||
set_session_cookies(response, token, csrf, settings=settings)
|
|
||||||
log.info("login", extra={"username": user.username, "role": user.role, "ip": ip})
|
|
||||||
return _as_session_user(user)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/logout",
|
|
||||||
status_code=status.HTTP_204_NO_CONTENT,
|
|
||||||
summary="End the current session",
|
|
||||||
)
|
|
||||||
def logout(
|
|
||||||
request: Request,
|
|
||||||
response: Response,
|
|
||||||
db: DbDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
) -> None:
|
|
||||||
"""Delete the session row and clear both cookies.
|
|
||||||
|
|
||||||
Deliberately succeeds whether or not there was a session. Signing out is
|
|
||||||
something a client should always be able to do, and a 401 here would leave a
|
|
||||||
browser holding a cookie it cannot get rid of.
|
|
||||||
|
|
||||||
The row is deleted rather than flagged, which is what makes this immediate:
|
|
||||||
the next request cannot resolve a session that is gone. That is the whole
|
|
||||||
reason sessions are server-side rather than a self-contained token.
|
|
||||||
"""
|
|
||||||
token = request.cookies.get(SESSION_COOKIE)
|
|
||||||
resolved = resolve_session(db, token) if token else None
|
|
||||||
|
|
||||||
revoke_session(db, token)
|
|
||||||
if resolved is not None:
|
|
||||||
_audit(db, action="logout", user_id=resolved[1].id, ip=client_address(request))
|
|
||||||
log.info("logout", extra={"username": resolved[1].username})
|
|
||||||
db.commit()
|
|
||||||
|
|
||||||
# Cookies are set on the injected Response, whose headers FastAPI merges
|
|
||||||
# into the 204 it sends. Returning a fresh Response here instead would
|
|
||||||
# discard them, and the logout would appear to work without clearing
|
|
||||||
# anything.
|
|
||||||
clear_session_cookies(response, settings=settings)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/session",
|
|
||||||
response_model=SessionUser,
|
|
||||||
summary="The signed-in user, or 401",
|
|
||||||
)
|
|
||||||
def whoami(resolved: SessionDep) -> SessionUser:
|
|
||||||
"""401 when not signed in, which the UI treats as "anonymous".
|
|
||||||
|
|
||||||
Not 200-with-null: the client already distinguishes 401 (signed out) from
|
|
||||||
404 (no auth on this server), and a 200 carrying null would collapse a
|
|
||||||
working server into the same shape as one that has no auth at all.
|
|
||||||
"""
|
|
||||||
return _as_session_user(resolved[1])
|
|
||||||
@@ -1,287 +0,0 @@
|
|||||||
"""The gallery: listing captures, and serving their bytes (SPEC 3.3).
|
|
||||||
|
|
||||||
Four routes, all behind a session. Any signed-in role may read the gallery --
|
|
||||||
that is what a ``viewer`` is for (SPEC 3.1) -- while a *device* never can: a
|
|
||||||
device token is scoped to the ingest endpoints and cannot resolve to a user at
|
|
||||||
all (api/deps.py vs api/userauth.py).
|
|
||||||
|
|
||||||
The image routes authorise and then hand off; see api/delivery.py for why the
|
|
||||||
bytes are Caddy's job in production and the app's in development.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import binascii
|
|
||||||
import logging
|
|
||||||
import uuid
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Query, Response, status
|
|
||||||
from sqlalchemy import Select, select, tuple_
|
|
||||||
from sqlalchemy.orm import selectinload
|
|
||||||
|
|
||||||
from ...models import Capture, Device
|
|
||||||
from ..delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX, deliver
|
|
||||||
from ..deps import DbDep, SettingsDep
|
|
||||||
from ..ui_schemas import CaptureDetail, CapturePage, CaptureSummary
|
|
||||||
from ..userauth import CurrentUser
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/captures", tags=["gallery"])
|
|
||||||
|
|
||||||
# A virtualised grid asks for a screenful at a time. 200 is about four
|
|
||||||
# screens on a large monitor; beyond that the response is bigger than the
|
|
||||||
# scroll it serves.
|
|
||||||
DEFAULT_LIMIT = 50
|
|
||||||
MAX_LIMIT = 200
|
|
||||||
|
|
||||||
|
|
||||||
def _encode_cursor(capture: Capture) -> str:
|
|
||||||
"""Opaque-ish cursor: the sort key of the last row on this page.
|
|
||||||
|
|
||||||
Base64 so it does not look like something to hand-edit, not because it is
|
|
||||||
a secret -- it is a timestamp and a UUID the caller was just given.
|
|
||||||
"""
|
|
||||||
raw = f"{capture.received_at.astimezone(UTC).isoformat()}|{capture.id}"
|
|
||||||
return base64.urlsafe_b64encode(raw.encode()).decode()
|
|
||||||
|
|
||||||
|
|
||||||
def _decode_cursor(cursor: str) -> tuple[datetime, uuid.UUID]:
|
|
||||||
"""Parse a cursor, or 422.
|
|
||||||
|
|
||||||
Everything here is caller-supplied, so every failure mode is a bad request
|
|
||||||
rather than a 500: bad base64, bad UTF-8, a missing separator, an
|
|
||||||
unparseable timestamp, a malformed UUID.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
raw = base64.urlsafe_b64decode(cursor.encode()).decode("utf-8")
|
|
||||||
stamp, _, ident = raw.partition("|")
|
|
||||||
if not ident:
|
|
||||||
raise ValueError("cursor has no id")
|
|
||||||
return datetime.fromisoformat(stamp), uuid.UUID(ident)
|
|
||||||
except (ValueError, binascii.Error, UnicodeDecodeError) as exc:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
||||||
detail="invalid cursor",
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
|
|
||||||
def _apply_filters(
|
|
||||||
stmt: Select,
|
|
||||||
*,
|
|
||||||
device_id: int | None,
|
|
||||||
received_from: datetime | None,
|
|
||||||
received_to: datetime | None,
|
|
||||||
kept: bool | None,
|
|
||||||
reviewed: bool | None,
|
|
||||||
pre_trigger: bool | None,
|
|
||||||
trigger: str | None,
|
|
||||||
) -> Select:
|
|
||||||
"""Filters over columns that exist today.
|
|
||||||
|
|
||||||
Taxon and tag filters are in TODO Phase 3 and are deliberately not here
|
|
||||||
yet: both need a join, and neither has any data to join to until the
|
|
||||||
observation editor and a seeded ``taxa`` table exist. A filter that can
|
|
||||||
only ever return nothing is worse than an absent one, because the UI would
|
|
||||||
offer it.
|
|
||||||
|
|
||||||
Dates filter on ``received_at``, never ``captured_at_device``, which is
|
|
||||||
NULL whenever the camera's clock was unsynced. Filtering on it would
|
|
||||||
silently drop exactly those frames.
|
|
||||||
"""
|
|
||||||
if device_id is not None:
|
|
||||||
stmt = stmt.where(Capture.device_id == device_id)
|
|
||||||
if received_from is not None:
|
|
||||||
stmt = stmt.where(Capture.received_at >= received_from)
|
|
||||||
if received_to is not None:
|
|
||||||
stmt = stmt.where(Capture.received_at <= received_to)
|
|
||||||
if kept is not None:
|
|
||||||
stmt = stmt.where(Capture.kept == kept)
|
|
||||||
if reviewed is not None:
|
|
||||||
stmt = stmt.where(Capture.reviewed == reviewed)
|
|
||||||
if pre_trigger is not None:
|
|
||||||
stmt = stmt.where(Capture.pre_trigger == pre_trigger)
|
|
||||||
if trigger is not None:
|
|
||||||
stmt = stmt.where(Capture.trigger == trigger)
|
|
||||||
return stmt
|
|
||||||
|
|
||||||
|
|
||||||
def _summary(capture: Capture) -> CaptureSummary:
|
|
||||||
return CaptureSummary(
|
|
||||||
id=capture.id,
|
|
||||||
device_id=capture.device_id,
|
|
||||||
received_at=capture.received_at,
|
|
||||||
captured_at_device=capture.captured_at_device,
|
|
||||||
width=capture.width,
|
|
||||||
height=capture.height,
|
|
||||||
bytes=capture.bytes,
|
|
||||||
trigger=capture.trigger,
|
|
||||||
pre_trigger=capture.pre_trigger,
|
|
||||||
burst_id=capture.burst_id,
|
|
||||||
burst_index=capture.burst_index,
|
|
||||||
burst_count=capture.burst_count,
|
|
||||||
reviewed=capture.reviewed,
|
|
||||||
kept=capture.kept,
|
|
||||||
has_thumb=capture.thumb_path is not None,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"",
|
|
||||||
response_model=CapturePage,
|
|
||||||
summary="List captures, newest first",
|
|
||||||
)
|
|
||||||
def list_captures(
|
|
||||||
db: DbDep,
|
|
||||||
_user: CurrentUser,
|
|
||||||
limit: Annotated[int, Query(ge=1, le=MAX_LIMIT)] = DEFAULT_LIMIT,
|
|
||||||
cursor: Annotated[str | None, Query()] = None,
|
|
||||||
device_id: Annotated[int | None, Query()] = None,
|
|
||||||
received_from: Annotated[datetime | None, Query()] = None,
|
|
||||||
received_to: Annotated[datetime | None, Query()] = None,
|
|
||||||
kept: Annotated[bool | None, Query()] = None,
|
|
||||||
reviewed: Annotated[bool | None, Query()] = None,
|
|
||||||
pre_trigger: Annotated[bool | None, Query()] = None,
|
|
||||||
trigger: Annotated[str | None, Query()] = None,
|
|
||||||
) -> CapturePage:
|
|
||||||
"""Newest first, keyset-paginated.
|
|
||||||
|
|
||||||
The sort is ``(received_at DESC, id DESC)``. The id is in the key not for
|
|
||||||
ordering's sake but because a burst arrives within the same fraction of a
|
|
||||||
second: on ties, a cursor that only carried the timestamp would either
|
|
||||||
repeat rows or skip them, and a gallery that loses a frame while scrolling
|
|
||||||
is a gallery you cannot trust.
|
|
||||||
"""
|
|
||||||
stmt = select(Capture)
|
|
||||||
stmt = _apply_filters(
|
|
||||||
stmt,
|
|
||||||
device_id=device_id,
|
|
||||||
received_from=received_from,
|
|
||||||
received_to=received_to,
|
|
||||||
kept=kept,
|
|
||||||
reviewed=reviewed,
|
|
||||||
pre_trigger=pre_trigger,
|
|
||||||
trigger=trigger,
|
|
||||||
)
|
|
||||||
|
|
||||||
if cursor is not None:
|
|
||||||
last_received, last_id = _decode_cursor(cursor)
|
|
||||||
# Row-value comparison, which maps onto the (device_id, received_at)
|
|
||||||
# index the same way a plain inequality would and needs no OR.
|
|
||||||
stmt = stmt.where(tuple_(Capture.received_at, Capture.id) < (last_received, last_id))
|
|
||||||
|
|
||||||
# One more than asked for, purely to learn whether another page exists
|
|
||||||
# without also running a COUNT over the whole filtered set.
|
|
||||||
rows = list(
|
|
||||||
db.scalars(
|
|
||||||
stmt.order_by(Capture.received_at.desc(), Capture.id.desc()).limit(limit + 1)
|
|
||||||
).all()
|
|
||||||
)
|
|
||||||
|
|
||||||
has_more = len(rows) > limit
|
|
||||||
page = rows[:limit]
|
|
||||||
return CapturePage(
|
|
||||||
items=[_summary(c) for c in page],
|
|
||||||
next_cursor=_encode_cursor(page[-1]) if has_more and page else None,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_capture(db: DbDep, capture_id: uuid.UUID) -> Capture:
|
|
||||||
capture = db.get(Capture, capture_id)
|
|
||||||
if capture is None:
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture")
|
|
||||||
return capture
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/{capture_id}",
|
|
||||||
response_model=CaptureDetail,
|
|
||||||
summary="One capture, with its observations and tags",
|
|
||||||
)
|
|
||||||
def get_capture(capture_id: uuid.UUID, db: DbDep, _user: CurrentUser) -> CaptureDetail:
|
|
||||||
capture = db.scalar(
|
|
||||||
select(Capture)
|
|
||||||
.where(Capture.id == capture_id)
|
|
||||||
# Eager, or rendering one capture with three observations is four
|
|
||||||
# queries and the pattern repeats per row the moment this is reused.
|
|
||||||
.options(
|
|
||||||
selectinload(Capture.observations),
|
|
||||||
selectinload(Capture.tags),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if capture is None:
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such capture")
|
|
||||||
|
|
||||||
device = db.get(Device, capture.device_id)
|
|
||||||
return CaptureDetail(
|
|
||||||
**_summary(capture).model_dump(),
|
|
||||||
# The device row is ON DELETE CASCADE from captures, so this is only
|
|
||||||
# None in a torn state. Naming it rather than crashing.
|
|
||||||
device_name=device.name if device is not None else "unknown",
|
|
||||||
sha256=capture.sha256,
|
|
||||||
radar_state=capture.radar_state,
|
|
||||||
radar_distance_cm=capture.radar_distance_cm,
|
|
||||||
radar_energy=capture.radar_energy,
|
|
||||||
battery_mv=capture.battery_mv,
|
|
||||||
rssi=capture.rssi,
|
|
||||||
temp_c=capture.temp_c,
|
|
||||||
frame_seq=capture.frame_seq,
|
|
||||||
observations=list(capture.observations),
|
|
||||||
tags=list(capture.tags),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/{capture_id}/image",
|
|
||||||
summary="The full JPEG, after an authorisation check",
|
|
||||||
response_class=Response,
|
|
||||||
)
|
|
||||||
def get_capture_image(
|
|
||||||
capture_id: uuid.UUID,
|
|
||||||
db: DbDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
_user: CurrentUser,
|
|
||||||
) -> Response:
|
|
||||||
capture = _get_capture(db, capture_id)
|
|
||||||
return deliver(
|
|
||||||
settings=settings,
|
|
||||||
root=settings.image_root,
|
|
||||||
url_prefix=IMAGE_URL_PREFIX,
|
|
||||||
relative=capture.path,
|
|
||||||
media_type="image/jpeg",
|
|
||||||
filename=f"{capture.id}.jpg",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/{capture_id}/thumb",
|
|
||||||
summary="The 400px WebP thumbnail, after an authorisation check",
|
|
||||||
response_class=Response,
|
|
||||||
)
|
|
||||||
def get_capture_thumb(
|
|
||||||
capture_id: uuid.UUID,
|
|
||||||
db: DbDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
_user: CurrentUser,
|
|
||||||
) -> Response:
|
|
||||||
capture = _get_capture(db, capture_id)
|
|
||||||
if capture.thumb_path is None:
|
|
||||||
# Either the job has not run yet or the frame could not be decoded.
|
|
||||||
# 404 rather than falling back to the full image: a grid that quietly
|
|
||||||
# served 200 full-size JPEGs would look like it worked and would be a
|
|
||||||
# hundred times the bytes.
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_404_NOT_FOUND,
|
|
||||||
detail="no thumbnail for this capture yet",
|
|
||||||
)
|
|
||||||
return deliver(
|
|
||||||
settings=settings,
|
|
||||||
root=settings.thumb_root,
|
|
||||||
url_prefix=THUMB_URL_PREFIX,
|
|
||||||
relative=capture.thumb_path,
|
|
||||||
media_type="image/webp",
|
|
||||||
filename=f"{capture.id}_400.webp",
|
|
||||||
)
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
"""POST /api/v1/commands/{command_id}/ack -- the other half of the queue.
|
|
||||||
|
|
||||||
/heartbeat and /ingest hand commands out and mark them delivered. This is
|
|
||||||
where the device reports what became of one. The two halves are deliberately
|
|
||||||
separate: delivery is recorded when the command goes out, because the ack may
|
|
||||||
never arrive -- ``reboot`` and ``sleep_now`` are acked and then the device is
|
|
||||||
gone, and a device that dies mid-command never acks at all. ``delivered_at``
|
|
||||||
therefore means "we handed it over" and ``acked_at`` means "it ran", and the
|
|
||||||
gap between them is the interesting operational signal.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from ...models.devices import DeviceCommand
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import DbDep, DeviceDep
|
|
||||||
from ..schemas import CommandAck
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/commands/{command_id}/ack",
|
|
||||||
status_code=status.HTTP_204_NO_CONTENT,
|
|
||||||
response_class=Response,
|
|
||||||
summary="Report the outcome of a command",
|
|
||||||
tags=["devices"],
|
|
||||||
dependencies=[Depends(ratelimit.by_device("ack", ratelimit.ACK))],
|
|
||||||
)
|
|
||||||
def ack_command(
|
|
||||||
command_id: int,
|
|
||||||
body: CommandAck,
|
|
||||||
db: DbDep,
|
|
||||||
device: DeviceDep,
|
|
||||||
) -> Response:
|
|
||||||
command = db.scalar(
|
|
||||||
select(DeviceCommand).where(
|
|
||||||
DeviceCommand.id == command_id,
|
|
||||||
# Scoped to the calling device. Command ids are sequential, so
|
|
||||||
# without this a device could ack -- and probe for -- every other
|
|
||||||
# device's queue.
|
|
||||||
DeviceCommand.device_id == device.id,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# 404 rather than 403 for someone else's command: a different code here
|
|
||||||
# would confirm that the id exists, which is the thing worth not saying.
|
|
||||||
if command is None:
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such command")
|
|
||||||
|
|
||||||
# Re-acking is allowed and the last word wins. The device retries on a
|
|
||||||
# timeout, and it cannot tell a lost response from a lost request, so
|
|
||||||
# refusing the second attempt would strand a command that did in fact run.
|
|
||||||
command.acked_at = datetime.now(UTC)
|
|
||||||
command.ack_status = body.status
|
|
||||||
# The firmware always sends the key, empty when it has nothing to say.
|
|
||||||
command.result = body.detail or None
|
|
||||||
|
|
||||||
db.commit()
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
"command acked",
|
|
||||||
extra={
|
|
||||||
"device_id": device.id,
|
|
||||||
"command_id": command.id,
|
|
||||||
"type": command.type,
|
|
||||||
"ack_status": command.ack_status,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
# Liveness stays with /heartbeat on purpose, so the device list has one
|
|
||||||
# source of truth for "when did we last hear from it".
|
|
||||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
"""POST /api/v1/heartbeat and POST /api/v1/status -- one body, two endpoints.
|
|
||||||
|
|
||||||
Both take the identical conditions payload (firmware/src/api_client.cpp builds
|
|
||||||
it once, in ``buildConditions``). They differ only in the response:
|
|
||||||
|
|
||||||
* ``/heartbeat`` -> 200 and the envelope: commands, config version, firmware
|
|
||||||
target.
|
|
||||||
* ``/status`` -> 204 and nothing.
|
|
||||||
|
|
||||||
The split is not cosmetic. The device posts status immediately before deep
|
|
||||||
sleep, and pulling down a command queue at that moment would mark commands
|
|
||||||
delivered that the device is about to become unable to execute. So /status
|
|
||||||
deliberately returns nothing actionable (API.md).
|
|
||||||
|
|
||||||
A heartbeat the endpoint *accepts* is also what confirms an OTA trial boot:
|
|
||||||
the device calls esp_ota_mark_app_valid only after one succeeds. Returning 5xx
|
|
||||||
to a device on a trial image will roll it back -- correct behaviour, but worth
|
|
||||||
knowing before restarting the server mid-rollout.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Response, status
|
|
||||||
|
|
||||||
from ...models.devices import DeviceStatus
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import DbDep, DeviceDep
|
|
||||||
from ..envelope import build_envelope
|
|
||||||
from ..schemas import DeviceConditions, Envelope
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
# Reasons that mean "this is the last thing I will say for a while".
|
|
||||||
_GOING_QUIET = {"before_sleep", "before_night_sleep"}
|
|
||||||
|
|
||||||
|
|
||||||
def _record(db: DbDep, device, body: DeviceConditions) -> None:
|
|
||||||
"""Append a telemetry row and refresh the device's last-known conditions.
|
|
||||||
|
|
||||||
The row is the time series; the columns on ``devices`` are a denormalised
|
|
||||||
copy so the device list does not need a correlated subquery per row.
|
|
||||||
"""
|
|
||||||
raw = body.model_dump(mode="json")
|
|
||||||
|
|
||||||
db.add(
|
|
||||||
DeviceStatus(
|
|
||||||
device_id=device.id,
|
|
||||||
reason=body.reason,
|
|
||||||
battery_mv=body.battery.mv,
|
|
||||||
battery_pct=body.battery.pct,
|
|
||||||
battery_valid=body.battery.valid,
|
|
||||||
awake_ms=body.power.awake_ms,
|
|
||||||
boot_count=body.power.boot_count,
|
|
||||||
wake_cause=body.power.wake_cause,
|
|
||||||
last_sleep_s=body.power.last_sleep_s,
|
|
||||||
total_sleep_s=body.power.total_sleep_s,
|
|
||||||
captured_today=body.counters.captured_today,
|
|
||||||
delivered_today=body.counters.delivered_today,
|
|
||||||
failed_today=body.counters.failed_today,
|
|
||||||
events_today=body.counters.events_today,
|
|
||||||
day_index=body.counters.day_index,
|
|
||||||
is_night=body.night.is_night,
|
|
||||||
nightlight_on=body.night.nightlight_on,
|
|
||||||
cam_profile=body.camera.profile,
|
|
||||||
radar_baud=body.radar.baud,
|
|
||||||
radar_uart_ok=body.radar.uart_ok,
|
|
||||||
stream_active=body.stream.active,
|
|
||||||
rssi=body.system.rssi,
|
|
||||||
ip=body.system.ip,
|
|
||||||
free_heap=body.system.free_heap,
|
|
||||||
free_psram=body.system.free_psram,
|
|
||||||
ring_depth=body.system.ring_depth,
|
|
||||||
time_synced=body.time_synced,
|
|
||||||
device_time=body.device_time,
|
|
||||||
fw_version=body.fw_version,
|
|
||||||
config_version=body.config_version,
|
|
||||||
# Everything as posted, including keys this server does not know
|
|
||||||
# about yet. The flat columns above are what is worth charting.
|
|
||||||
raw=raw,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
device.last_seen_at = datetime.now(UTC)
|
|
||||||
|
|
||||||
# Only overwrite a denormalised value when the device actually reported
|
|
||||||
# one. None means "not sent", which must not erase a good earlier reading.
|
|
||||||
if body.battery.mv is not None:
|
|
||||||
device.battery_mv = body.battery.mv
|
|
||||||
if body.battery.pct is not None:
|
|
||||||
device.battery_pct = body.battery.pct
|
|
||||||
if body.battery.valid is not None:
|
|
||||||
# false means NOT MEASURED, not empty. Stored as reported so the UI can
|
|
||||||
# render an em dash instead of inventing a low-battery alarm.
|
|
||||||
device.battery_valid = body.battery.valid
|
|
||||||
if body.system.rssi is not None:
|
|
||||||
device.rssi = body.system.rssi
|
|
||||||
if body.fw_version is not None:
|
|
||||||
device.fw_version = body.fw_version
|
|
||||||
|
|
||||||
# A device that has just announced it is going to sleep will not answer
|
|
||||||
# commands, and the UI should say so rather than show it as reachable.
|
|
||||||
device.awake = body.reason not in _GOING_QUIET
|
|
||||||
|
|
||||||
# device.config_version is the server's intent and is NOT touched here.
|
|
||||||
# body.config_version is what the device currently runs; the difference is
|
|
||||||
# exactly what tells it to GET /config.
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/heartbeat",
|
|
||||||
response_model=Envelope,
|
|
||||||
response_model_exclude_none=True,
|
|
||||||
summary="Device conditions; returns the command envelope",
|
|
||||||
tags=["devices"],
|
|
||||||
dependencies=[Depends(ratelimit.by_device("heartbeat", ratelimit.CONDITIONS))],
|
|
||||||
)
|
|
||||||
def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope:
|
|
||||||
_record(db, device, body)
|
|
||||||
envelope = build_envelope(db, device)
|
|
||||||
db.commit()
|
|
||||||
return envelope
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/status",
|
|
||||||
status_code=status.HTTP_204_NO_CONTENT,
|
|
||||||
response_class=Response,
|
|
||||||
summary="Device conditions; returns nothing actionable",
|
|
||||||
tags=["devices"],
|
|
||||||
dependencies=[Depends(ratelimit.by_device("status", ratelimit.CONDITIONS))],
|
|
||||||
)
|
|
||||||
def device_status(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Response:
|
|
||||||
_record(db, device, body)
|
|
||||||
db.commit()
|
|
||||||
# Deliberately no envelope: see the module docstring.
|
|
||||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
"""GET /api/v1/config -- the device's settings document.
|
|
||||||
|
|
||||||
Named device_config.py so it does not read as poorbird.config, which is the
|
|
||||||
server's own settings. The route is /config, as API.md specifies.
|
|
||||||
|
|
||||||
The response is a free-form JSON object by design. ``devices.config`` is one
|
|
||||||
JSONB document rather than forty columns because the firmware grows tunables
|
|
||||||
faster than a schema should change, and the device merges and clamps whatever
|
|
||||||
arrives: keys it does not know are ignored, keys that are absent leave its
|
|
||||||
current value alone, and dangerous values are clamped on the device itself
|
|
||||||
(app_config.cpp, configApplyJson). Partial documents are therefore not a
|
|
||||||
degraded case -- they are the normal one.
|
|
||||||
|
|
||||||
That is also why there is no response model. Validating this shape belongs on
|
|
||||||
the write path, when the admin UI saves a config, not on the way out to a
|
|
||||||
device that is going to re-validate it anyway.
|
|
||||||
|
|
||||||
This is a read. It deliberately does not touch last_seen_at: a GET should not
|
|
||||||
have side effects, and /heartbeat is what records liveness (API.md).
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
|
||||||
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import DeviceDep
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
# Settings that live in real columns on `devices` rather than in the JSONB,
|
|
||||||
# because the server queries and lists on them. They are still config keys as
|
|
||||||
# far as the firmware is concerned, so they have to be merged into the
|
|
||||||
# document on the way out or a change to the column would never reach the
|
|
||||||
# camera.
|
|
||||||
#
|
|
||||||
# device_name is the interesting one: enrollment deliberately does not let a
|
|
||||||
# device overwrite an operator's rename, and this is the path by which that
|
|
||||||
# rename actually reaches the device (app_config.cpp:307).
|
|
||||||
_COLUMN_BACKED = (
|
|
||||||
("device_name", "name"),
|
|
||||||
("heartbeat_interval_s", "heartbeat_interval_s"),
|
|
||||||
("status_interval_s", "status_interval_s"),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/config",
|
|
||||||
summary="The device's full settings document",
|
|
||||||
tags=["devices"],
|
|
||||||
dependencies=[Depends(ratelimit.by_device("config", ratelimit.CONFIG))],
|
|
||||||
)
|
|
||||||
def get_config(device: DeviceDep) -> dict[str, Any]:
|
|
||||||
# Start from the stored document, then let the column-backed keys win.
|
|
||||||
# The columns are the modelled source of truth; a stale copy of one of
|
|
||||||
# them inside the JSONB must not shadow it.
|
|
||||||
document: dict[str, Any] = dict(device.config or {})
|
|
||||||
|
|
||||||
for key, attr in _COLUMN_BACKED:
|
|
||||||
document[key] = getattr(device, attr)
|
|
||||||
|
|
||||||
# Last, mirroring configApplyJson, which applies config_version only after
|
|
||||||
# the rest of the payload has been processed. This is the only value the
|
|
||||||
# device compares, so it must describe the document it arrived with.
|
|
||||||
document["config_version"] = device.config_version
|
|
||||||
|
|
||||||
return document
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
"""POST /api/v1/enroll -- device enrollment and re-enrollment.
|
|
||||||
|
|
||||||
The only device endpoint not guarded by a bearer token, because it is where
|
|
||||||
the token comes from. It is guarded by ``X-Enroll-Secret`` instead: either the
|
|
||||||
shared bootstrap secret, or the device's own re-enrollment secret once it has
|
|
||||||
one (firmware/API.md, Authentication).
|
|
||||||
|
|
||||||
Re-enrollment is a normal, expected operation, not an error path. The firmware
|
|
||||||
re-enrolls on any 401, which is how a token rotated in the admin UI heals
|
|
||||||
itself without anyone climbing to the camera. API.md is explicit that a known
|
|
||||||
``device_uid`` must return the existing row with a fresh token rather than a
|
|
||||||
duplicate -- expect it on every rotation and after any database restore.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
|
||||||
from sqlalchemy import select
|
|
||||||
from sqlalchemy.exc import IntegrityError
|
|
||||||
|
|
||||||
from ...models.devices import Device
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import (
|
|
||||||
DbDep,
|
|
||||||
SettingsDep,
|
|
||||||
enroll_secret_accepted,
|
|
||||||
hash_credential,
|
|
||||||
new_credential,
|
|
||||||
require_enroll_secret_configured,
|
|
||||||
server_time_ms,
|
|
||||||
)
|
|
||||||
from ..schemas import EnrollRequest, EnrollResponse
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/enroll",
|
|
||||||
status_code=status.HTTP_201_CREATED,
|
|
||||||
response_model=EnrollResponse,
|
|
||||||
summary="Enroll a device, or re-issue its token",
|
|
||||||
tags=["devices"],
|
|
||||||
# Keyed by caller address: there is no device to key on yet, and this is
|
|
||||||
# the one endpoint where a shared secret could be ground at (SEC-004).
|
|
||||||
dependencies=[Depends(ratelimit.by_address("enroll", ratelimit.ENROLL))],
|
|
||||||
)
|
|
||||||
def enroll(
|
|
||||||
body: EnrollRequest,
|
|
||||||
db: DbDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
x_enroll_secret: str | None = Header(default=None),
|
|
||||||
) -> EnrollResponse:
|
|
||||||
# 503 before anything else: a server with no bootstrap secret is
|
|
||||||
# misconfigured, not rejecting this particular device. A 4xx here would
|
|
||||||
# make the firmware discard a token that is probably still good.
|
|
||||||
require_enroll_secret_configured(settings)
|
|
||||||
|
|
||||||
device = db.scalar(select(Device).where(Device.device_uid == body.device_uid))
|
|
||||||
|
|
||||||
# The lookup has to come first, because a returning device presents its own
|
|
||||||
# per-device secret rather than the shared one.
|
|
||||||
if not enroll_secret_accepted(x_enroll_secret, settings, device):
|
|
||||||
log.warning("enrollment refused", extra={"device_uid": body.device_uid})
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="invalid enrollment secret",
|
|
||||||
)
|
|
||||||
|
|
||||||
# A disabled device must not be able to re-enroll its way back in, or
|
|
||||||
# disabling it in the admin UI would mean nothing: it would simply collect
|
|
||||||
# a fresh token on its next 401.
|
|
||||||
if device is not None and not device.enabled:
|
|
||||||
log.warning("enrollment refused for disabled device", extra={"device_uid": body.device_uid})
|
|
||||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="device is disabled")
|
|
||||||
|
|
||||||
token = new_credential()
|
|
||||||
reenroll_secret = new_credential()
|
|
||||||
returning = device is not None
|
|
||||||
|
|
||||||
if device is None:
|
|
||||||
device = Device(device_uid=body.device_uid, name=body.device_name)
|
|
||||||
db.add(device)
|
|
||||||
|
|
||||||
# Hardware facts always follow the device: it is the authority on what it
|
|
||||||
# is running. The name deliberately does not -- it is set once at first
|
|
||||||
# enrollment and is an operator-facing label after that, so a re-enrollment
|
|
||||||
# must not silently undo a rename made in the admin UI.
|
|
||||||
device.mac = body.mac
|
|
||||||
device.hw_revision = body.hw_revision
|
|
||||||
device.fw_version = body.fw_version
|
|
||||||
|
|
||||||
device.token_hash = hash_credential(token)
|
|
||||||
device.reenroll_secret_hash = hash_credential(reenroll_secret)
|
|
||||||
|
|
||||||
try:
|
|
||||||
db.commit()
|
|
||||||
except IntegrityError:
|
|
||||||
# Two enrollments of the same device_uid racing each other. 503 rather
|
|
||||||
# than 409: it is transient and the firmware already retries, whereas a
|
|
||||||
# 4xx reads as "this device is not welcome".
|
|
||||||
db.rollback()
|
|
||||||
log.warning("enrollment raced", extra={"device_uid": body.device_uid})
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
||||||
detail="enrollment is busy, retry",
|
|
||||||
) from None
|
|
||||||
|
|
||||||
db.refresh(device)
|
|
||||||
log.info(
|
|
||||||
"device re-enrolled" if returning else "device enrolled",
|
|
||||||
extra={"device_uid": device.device_uid, "device_id": device.id},
|
|
||||||
)
|
|
||||||
|
|
||||||
# The plaintext token and secret exist here and nowhere else. Only their
|
|
||||||
# hashes were stored, so this response is the single opportunity to hand
|
|
||||||
# them to the device.
|
|
||||||
return EnrollResponse(
|
|
||||||
token=token,
|
|
||||||
device_id=device.id,
|
|
||||||
reenroll_secret=reenroll_secret,
|
|
||||||
server_time=server_time_ms(),
|
|
||||||
config_version=device.config_version,
|
|
||||||
)
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
"""GET /api/v1/firmware/{version}.bin -- the OTA image.
|
|
||||||
|
|
||||||
Bearer auth, like every other device endpoint. Three things the device
|
|
||||||
requires of this response, all checked before it erases a partition
|
|
||||||
(firmware/src/ota_mgr.cpp:110-128):
|
|
||||||
|
|
||||||
1. status exactly 200,
|
|
||||||
2. a ``Content-Length`` header -- it refuses a chunked response, because it
|
|
||||||
wants to size-check before committing to an erase,
|
|
||||||
3. that length equal to the ``size`` the envelope advertised.
|
|
||||||
|
|
||||||
So this must not be compressed or chunked on the way out. The camera talks to
|
|
||||||
the :8080 Caddy block, which has no ``encode`` directive, and FileResponse
|
|
||||||
sets an exact Content-Length from the file itself.
|
|
||||||
|
|
||||||
The admin-facing ``POST /api/v1/firmware`` from API.md is not here: it needs
|
|
||||||
user authentication and an admin role, neither of which exists yet
|
|
||||||
(REVIEW SEC-007). Rows are expected to arrive by other means until then.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, status
|
|
||||||
from fastapi.responses import FileResponse
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from ...config import Settings
|
|
||||||
from ...models.devices import Firmware
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import DbDep, DeviceDep, SettingsDep
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
|
|
||||||
def _resolve(file_path: str, settings: Settings) -> Path:
|
|
||||||
"""Where the image actually lives.
|
|
||||||
|
|
||||||
An absolute path is used as given; a relative one resolves under the
|
|
||||||
state directory. The value comes from the firmware row, which only an
|
|
||||||
administrator can write -- it is never built from anything in the
|
|
||||||
request, so there is no traversal to defend against here. The upload
|
|
||||||
endpoint that eventually writes it is where that check belongs.
|
|
||||||
"""
|
|
||||||
candidate = Path(file_path)
|
|
||||||
return candidate if candidate.is_absolute() else settings.state_dir / "firmware" / candidate
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/firmware/{version}.bin",
|
|
||||||
response_class=FileResponse,
|
|
||||||
summary="Download an OTA image",
|
|
||||||
tags=["firmware"],
|
|
||||||
dependencies=[Depends(ratelimit.by_device("firmware", ratelimit.FIRMWARE))],
|
|
||||||
)
|
|
||||||
def download_firmware(
|
|
||||||
version: str,
|
|
||||||
db: DbDep,
|
|
||||||
device: DeviceDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
) -> FileResponse:
|
|
||||||
row = db.scalar(select(Firmware).where(Firmware.version == version))
|
|
||||||
if row is None:
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such firmware")
|
|
||||||
|
|
||||||
path = _resolve(row.file_path, settings)
|
|
||||||
|
|
||||||
if not path.is_file():
|
|
||||||
# The row promises an image that is not there. 503 rather than 404:
|
|
||||||
# the firmware genuinely exists as far as the operator is concerned,
|
|
||||||
# and this is a server fault worth shouting about rather than a
|
|
||||||
# missing resource.
|
|
||||||
log.error(
|
|
||||||
"firmware row points at a missing file",
|
|
||||||
extra={"version": row.version, "path": str(path)},
|
|
||||||
)
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
||||||
detail="firmware image unavailable",
|
|
||||||
)
|
|
||||||
|
|
||||||
# The device compares Content-Length against the size the envelope gave
|
|
||||||
# it and aborts on a mismatch. Catching that here turns a confusing
|
|
||||||
# device-side abort into one clear line in the server log.
|
|
||||||
actual = path.stat().st_size
|
|
||||||
if actual != row.size_bytes:
|
|
||||||
log.error(
|
|
||||||
"firmware size does not match its row",
|
|
||||||
extra={"version": row.version, "recorded": row.size_bytes, "on_disk": actual},
|
|
||||||
)
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
||||||
detail="firmware image does not match its manifest",
|
|
||||||
)
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
"serving firmware",
|
|
||||||
extra={"version": row.version, "device_id": device.id, "bytes": actual},
|
|
||||||
)
|
|
||||||
|
|
||||||
return FileResponse(
|
|
||||||
path,
|
|
||||||
media_type="application/octet-stream",
|
|
||||||
filename=f"{row.version}.bin",
|
|
||||||
# The image is immutable for a given version, and the device verifies
|
|
||||||
# SHA-256 over the whole thing before activating the slot anyway.
|
|
||||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
|
||||||
)
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
"""Health.
|
|
||||||
|
|
||||||
Two endpoints on purpose:
|
|
||||||
|
|
||||||
* ``/api/v1/health`` always answers 200 with detail, because the WebUI banner
|
|
||||||
wants to *render* a degraded system, not fail to load.
|
|
||||||
* ``/healthz`` answers 503 when the database is unreachable, because that is
|
|
||||||
what a proxy or a monitor should act on.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import shutil
|
|
||||||
import time
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Response
|
|
||||||
from sqlalchemy import func, select, text
|
|
||||||
|
|
||||||
from ... import __version__
|
|
||||||
from ...config import get_settings
|
|
||||||
from ...db import SessionLocal
|
|
||||||
from ...models import BackupRun, Capture, Device
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
# Mounted at the root, not under /api/v1: proxies and monitors expect /healthz
|
|
||||||
# where it has always been.
|
|
||||||
root_router = APIRouter()
|
|
||||||
_STARTED = time.monotonic()
|
|
||||||
|
|
||||||
|
|
||||||
def _db_probe() -> tuple[bool, str | None, dict[str, Any]]:
|
|
||||||
facts: dict[str, Any] = {}
|
|
||||||
try:
|
|
||||||
with SessionLocal() as s:
|
|
||||||
s.execute(text("SELECT 1"))
|
|
||||||
facts["devices"] = s.scalar(select(func.count()).select_from(Device))
|
|
||||||
facts["captures"] = s.scalar(select(func.count()).select_from(Capture))
|
|
||||||
last_backup = s.scalar(select(func.max(BackupRun.finished_at)))
|
|
||||||
facts["last_backup_at"] = last_backup.isoformat() if last_backup else None
|
|
||||||
return True, None, facts
|
|
||||||
except Exception as exc: # noqa: BLE001 - the point is to report, not raise
|
|
||||||
return False, f"{type(exc).__name__}: {exc}", facts
|
|
||||||
|
|
||||||
|
|
||||||
def _disk() -> dict[str, Any]:
|
|
||||||
settings = get_settings()
|
|
||||||
try:
|
|
||||||
usage = shutil.disk_usage(settings.image_root)
|
|
||||||
except OSError:
|
|
||||||
# Not yet created, or not mounted. Both are real conditions to report.
|
|
||||||
return {"available": False, "path": str(settings.image_root)}
|
|
||||||
return {
|
|
||||||
"available": True,
|
|
||||||
"path": str(settings.image_root),
|
|
||||||
"total_bytes": usage.total,
|
|
||||||
"free_bytes": usage.free,
|
|
||||||
"used_pct": round(100 * usage.used / usage.total, 1) if usage.total else None,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/health", summary="System health, always 200")
|
|
||||||
def health() -> dict[str, Any]:
|
|
||||||
db_ok, db_error, facts = _db_probe()
|
|
||||||
settings = get_settings()
|
|
||||||
return {
|
|
||||||
"status": "ok" if db_ok else "degraded",
|
|
||||||
"version": __version__,
|
|
||||||
"uptime_s": round(time.monotonic() - _STARTED, 1),
|
|
||||||
"database": {"ok": db_ok, "error": db_error, **facts},
|
|
||||||
"disk": _disk(),
|
|
||||||
"enroll_secret_configured": settings.enroll_secret_is_set,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@root_router.get("/healthz", include_in_schema=False)
|
|
||||||
def healthz(response: Response) -> dict[str, str]:
|
|
||||||
db_ok, _, _ = _db_probe()
|
|
||||||
if not db_ok:
|
|
||||||
response.status_code = 503
|
|
||||||
return {"status": "unavailable"}
|
|
||||||
return {"status": "ok"}
|
|
||||||
@@ -1,220 +0,0 @@
|
|||||||
"""POST /api/v1/ingest -- a captured frame.
|
|
||||||
|
|
||||||
**Deviation from SPEC 4.1, and a deliberate one.** The spec says
|
|
||||||
multipart/form-data with the image and a JSON metadata part. The firmware
|
|
||||||
sends the raw JPEG as the body with the metadata in headers, because
|
|
||||||
multipart would make the device assemble a second buffer purely to add a
|
|
||||||
wrapper the server strips immediately; the raw body hands the framebuffer
|
|
||||||
pointer straight to the HTTP client (firmware/API.md). REVIEW.AI.md's
|
|
||||||
reference code implemented the multipart version and would not have matched
|
|
||||||
the firmware at all.
|
|
||||||
|
|
||||||
Returns the same envelope as /heartbeat, so a capture that was going to
|
|
||||||
happen anyway also delivers the command queue at no extra cost.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import hashlib
|
|
||||||
import logging
|
|
||||||
import uuid
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Header, HTTPException, status
|
|
||||||
from pydantic import ValidationError
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from ...images import (
|
|
||||||
MAX_IMAGE_BYTES,
|
|
||||||
jpeg_dimensions,
|
|
||||||
looks_like_jpeg,
|
|
||||||
relative_image_path,
|
|
||||||
write_atomically,
|
|
||||||
)
|
|
||||||
from ...models.captures import Capture
|
|
||||||
from ...worker.queue import enqueue
|
|
||||||
from .. import ratelimit
|
|
||||||
from ..deps import DbDep, DeviceDep, SettingsDep
|
|
||||||
from ..envelope import build_envelope
|
|
||||||
from ..schemas import Envelope, IngestMeta
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
|
|
||||||
def ingest_meta(
|
|
||||||
x_trigger: Annotated[str, Header()] = "radar",
|
|
||||||
x_burst_id: Annotated[str | None, Header()] = None,
|
|
||||||
x_burst_index: Annotated[int | None, Header()] = None,
|
|
||||||
x_burst_count: Annotated[int | None, Header()] = None,
|
|
||||||
x_pre_trigger: Annotated[int, Header()] = 0,
|
|
||||||
x_captured_at: Annotated[int, Header()] = 0,
|
|
||||||
x_frame_seq: Annotated[int | None, Header()] = None,
|
|
||||||
x_radar_state: Annotated[int | None, Header()] = None,
|
|
||||||
x_radar_distance_cm: Annotated[int | None, Header()] = None,
|
|
||||||
x_radar_energy: Annotated[int | None, Header()] = None,
|
|
||||||
x_rssi: Annotated[int | None, Header()] = None,
|
|
||||||
) -> IngestMeta:
|
|
||||||
"""Validate the header metadata into one model (REVIEW SEC-003)."""
|
|
||||||
try:
|
|
||||||
return IngestMeta(
|
|
||||||
trigger=x_trigger,
|
|
||||||
burst_id=x_burst_id or None,
|
|
||||||
burst_index=x_burst_index,
|
|
||||||
burst_count=x_burst_count,
|
|
||||||
pre_trigger=bool(x_pre_trigger),
|
|
||||||
# X-Captured-At: 0 means the device clock is unsynced. That is
|
|
||||||
# NULL, not 1970 -- storing an epoch date here would put the frame
|
|
||||||
# at the bottom of every chronological view forever (API.md).
|
|
||||||
captured_at=(
|
|
||||||
datetime.fromtimestamp(x_captured_at / 1000, UTC) if x_captured_at > 0 else None
|
|
||||||
),
|
|
||||||
frame_seq=x_frame_seq,
|
|
||||||
radar_state=x_radar_state,
|
|
||||||
radar_distance_cm=x_radar_distance_cm,
|
|
||||||
radar_energy=x_radar_energy,
|
|
||||||
rssi=x_rssi,
|
|
||||||
)
|
|
||||||
except ValidationError as exc:
|
|
||||||
# A dependency raising ValidationError would otherwise surface as a
|
|
||||||
# 500. The metadata is client input; it deserves a 422.
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
|
||||||
detail=exc.errors(include_url=False),
|
|
||||||
) from None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
|
||||||
"/ingest",
|
|
||||||
status_code=status.HTTP_201_CREATED,
|
|
||||||
response_model=Envelope,
|
|
||||||
response_model_exclude_none=True,
|
|
||||||
summary="Accept a captured frame; returns the command envelope",
|
|
||||||
tags=["captures"],
|
|
||||||
dependencies=[Depends(ratelimit.by_device("ingest", ratelimit.INGEST))],
|
|
||||||
)
|
|
||||||
def ingest(
|
|
||||||
db: DbDep,
|
|
||||||
device: DeviceDep,
|
|
||||||
settings: SettingsDep,
|
|
||||||
meta: Annotated[IngestMeta, Depends(ingest_meta)],
|
|
||||||
body: Annotated[bytes, Body(media_type="image/jpeg")] = b"",
|
|
||||||
) -> Envelope:
|
|
||||||
if not body:
|
|
||||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="empty body")
|
|
||||||
if len(body) > MAX_IMAGE_BYTES:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
|
|
||||||
detail=f"image exceeds {MAX_IMAGE_BYTES} bytes",
|
|
||||||
)
|
|
||||||
# Trust the bytes, not the Content-Type. 400 and not 401: the device must
|
|
||||||
# not read this as a credential problem and clear a perfectly good token.
|
|
||||||
if not looks_like_jpeg(body):
|
|
||||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="body is not a JPEG")
|
|
||||||
|
|
||||||
digest = hashlib.sha256(body).hexdigest()
|
|
||||||
|
|
||||||
# The device retries an upload whose response was lost, and it cannot tell
|
|
||||||
# that case from a genuine failure. Identical bytes from the same device
|
|
||||||
# are that retry -- two real frames never collide, since sensor noise
|
|
||||||
# alone makes every capture unique. Returning the original capture keeps
|
|
||||||
# ingest idempotent instead of filling the gallery with duplicates.
|
|
||||||
#
|
|
||||||
# Scoped to the device, and checked in the application rather than with a
|
|
||||||
# unique constraint: a genuine collision should lose a frame, not 500.
|
|
||||||
# Burst uploads are sequential (API.md), so there is no race to lose.
|
|
||||||
existing = db.scalar(
|
|
||||||
select(Capture).where(Capture.device_id == device.id, Capture.sha256 == digest)
|
|
||||||
)
|
|
||||||
if existing is not None:
|
|
||||||
log.info(
|
|
||||||
"ingest de-duplicated",
|
|
||||||
extra={"device_id": device.id, "capture_id": str(existing.id)},
|
|
||||||
)
|
|
||||||
envelope = build_envelope(db, device, capture_id=str(existing.id))
|
|
||||||
db.commit()
|
|
||||||
return envelope
|
|
||||||
|
|
||||||
capture_id = uuid.uuid4()
|
|
||||||
received_at = datetime.now(UTC)
|
|
||||||
relative = relative_image_path(capture_id, received_at)
|
|
||||||
destination = settings.image_root / relative
|
|
||||||
|
|
||||||
try:
|
|
||||||
write_atomically(destination, body)
|
|
||||||
except OSError as exc:
|
|
||||||
# Disk full, root not mounted, permissions. 503 rather than 500: it is
|
|
||||||
# transient from the device's point of view and it should retry.
|
|
||||||
log.error("cannot write capture", extra={"path": str(destination), "error": str(exc)})
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
||||||
detail="image storage unavailable",
|
|
||||||
) from None
|
|
||||||
|
|
||||||
dimensions = jpeg_dimensions(body)
|
|
||||||
|
|
||||||
capture = Capture(
|
|
||||||
id=capture_id,
|
|
||||||
device_id=device.id,
|
|
||||||
path=relative,
|
|
||||||
# Filled in by the thumbnail job below. NULL means "not yet", which
|
|
||||||
# the gallery has to handle regardless: a capture is visible the
|
|
||||||
# moment it lands, not once it has been processed.
|
|
||||||
thumb_path=None,
|
|
||||||
sha256=digest,
|
|
||||||
width=dimensions[0] if dimensions else None,
|
|
||||||
height=dimensions[1] if dimensions else None,
|
|
||||||
bytes=len(body),
|
|
||||||
captured_at_device=meta.captured_at,
|
|
||||||
received_at=received_at,
|
|
||||||
trigger=meta.trigger,
|
|
||||||
burst_id=meta.burst_id,
|
|
||||||
burst_index=meta.burst_index,
|
|
||||||
burst_count=meta.burst_count,
|
|
||||||
pre_trigger=meta.pre_trigger,
|
|
||||||
frame_seq=meta.frame_seq,
|
|
||||||
radar_state=meta.radar_state,
|
|
||||||
radar_distance_cm=meta.radar_distance_cm,
|
|
||||||
radar_energy=meta.radar_energy,
|
|
||||||
rssi=meta.rssi,
|
|
||||||
)
|
|
||||||
db.add(capture)
|
|
||||||
|
|
||||||
device.last_seen_at = received_at
|
|
||||||
if meta.rssi is not None:
|
|
||||||
device.rssi = meta.rssi
|
|
||||||
|
|
||||||
# Off the request path on purpose: decoding a frame to resize it is the
|
|
||||||
# one genuinely expensive thing about a capture, and the device is
|
|
||||||
# waiting on this response with a burst still to upload. Enqueued in the
|
|
||||||
# same transaction as the row, so the worker never sees a job for a
|
|
||||||
# capture that was rolled back.
|
|
||||||
enqueue(db, "thumbnail", {"capture_id": str(capture_id)})
|
|
||||||
|
|
||||||
envelope = build_envelope(db, device, capture_id=str(capture_id))
|
|
||||||
|
|
||||||
try:
|
|
||||||
db.commit()
|
|
||||||
except Exception:
|
|
||||||
# The file is already on disk. Remove it rather than leave an orphan
|
|
||||||
# that nothing references. The reverse order -- row first, file second
|
|
||||||
# -- would be worse: a row pointing at a missing image is a broken
|
|
||||||
# gallery entry, whereas a stray file is invisible and sweepable.
|
|
||||||
db.rollback()
|
|
||||||
destination.unlink(missing_ok=True)
|
|
||||||
raise
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
"capture ingested",
|
|
||||||
extra={
|
|
||||||
"device_id": device.id,
|
|
||||||
"capture_id": str(capture_id),
|
|
||||||
"bytes": len(body),
|
|
||||||
"trigger": meta.trigger,
|
|
||||||
"pre_trigger": meta.pre_trigger,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
return envelope
|
|
||||||
@@ -1,283 +0,0 @@
|
|||||||
"""Request and response shapes for the device API (REVIEW SEC-003).
|
|
||||||
|
|
||||||
The contract is ``firmware/API.md``, and where it disagrees with SPEC.md the
|
|
||||||
firmware wins, because the firmware is what is actually on the camera. Two
|
|
||||||
places where that matters are called out inline: ``/ingest`` carries a raw JPEG
|
|
||||||
body with metadata in headers, not multipart, and the enrollment body field is
|
|
||||||
``device_name``, not ``name``.
|
|
||||||
|
|
||||||
Nothing here talks to the database. These models exist so that a malformed or
|
|
||||||
hostile request is rejected at the edge with a 422, before any handler reaches
|
|
||||||
for a session.
|
|
||||||
|
|
||||||
One deliberate looseness: the conditions models accept unknown keys. The
|
|
||||||
firmware grows fields faster than the server learns about them, and
|
|
||||||
``device_status.raw`` exists precisely to keep the whole posted body. Rejecting
|
|
||||||
a camera because it reports something new would be the wrong failure.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import Annotated, Any, Literal
|
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
||||||
|
|
||||||
from ..models.captures import TRIGGERS
|
|
||||||
from ..models.devices import COMMAND_TYPES, STATUS_REASONS
|
|
||||||
|
|
||||||
Trigger = Literal[TRIGGERS] # type: ignore[valid-type]
|
|
||||||
StatusReason = Literal[STATUS_REASONS] # type: ignore[valid-type]
|
|
||||||
CommandType = Literal[COMMAND_TYPES] # type: ignore[valid-type]
|
|
||||||
|
|
||||||
# The firmware holds these in char[65], so 64 characters plus a NUL. Issue
|
|
||||||
# exactly 64 hex characters and a token can never be silently truncated on the
|
|
||||||
# device (firmware/include/app_config.h).
|
|
||||||
TOKEN_CHARS = 64
|
|
||||||
|
|
||||||
|
|
||||||
class _Loose(BaseModel):
|
|
||||||
"""Base for anything the firmware posts: keep unknown keys, do not 422."""
|
|
||||||
|
|
||||||
model_config = ConfigDict(extra="allow")
|
|
||||||
|
|
||||||
|
|
||||||
# --- enrollment -------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class EnrollRequest(BaseModel):
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
|
||||||
|
|
||||||
# eFuse MAC in hex. Survives reflashing, which is what makes it an identity
|
|
||||||
# rather than a name (API.md, Enrollment).
|
|
||||||
device_uid: Annotated[str, Field(min_length=6, max_length=32, pattern=r"^[0-9a-fA-F]+$")]
|
|
||||||
# API.md calls this device_name. REVIEW.AI.md calls it name; the firmware
|
|
||||||
# sends device_name, so that is what this is.
|
|
||||||
device_name: Annotated[str, Field(min_length=1, max_length=64)]
|
|
||||||
hw_revision: Annotated[str | None, Field(max_length=64)] = None
|
|
||||||
fw_version: Annotated[str | None, Field(max_length=32)] = None
|
|
||||||
mac: Annotated[str | None, Field(max_length=32)] = None
|
|
||||||
|
|
||||||
|
|
||||||
class EnrollResponse(BaseModel):
|
|
||||||
"""201. The token is returned in the clear exactly once, here.
|
|
||||||
|
|
||||||
Only its hash is stored. Returning the stored hash instead would hand the
|
|
||||||
device a credential the server cannot recognise, and every later request
|
|
||||||
would 401.
|
|
||||||
"""
|
|
||||||
|
|
||||||
token: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)]
|
|
||||||
device_id: int
|
|
||||||
reenroll_secret: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)]
|
|
||||||
server_time: int # epoch ms, UTC, authoritative (SPEC C7)
|
|
||||||
config_version: int
|
|
||||||
|
|
||||||
|
|
||||||
# --- the shared response envelope -------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class FirmwareTarget(BaseModel):
|
|
||||||
version: str
|
|
||||||
url: str
|
|
||||||
sha256: Annotated[str, Field(min_length=64, max_length=64)]
|
|
||||||
size: int
|
|
||||||
|
|
||||||
|
|
||||||
class Command(BaseModel):
|
|
||||||
id: int
|
|
||||||
type: CommandType
|
|
||||||
payload: dict[str, Any] | None = None
|
|
||||||
expires_at: int | None = None # epoch ms; the firmware ignores it, the server prunes on it
|
|
||||||
|
|
||||||
|
|
||||||
class Envelope(BaseModel):
|
|
||||||
"""Returned by /ingest and /heartbeat, identically (API.md, SPEC 4.1).
|
|
||||||
|
|
||||||
``capture_id`` is documented as an integer in API.md's example, but
|
|
||||||
``captures.id`` is a UUID and the firmware never reads the field back
|
|
||||||
(verified in firmware/src/api_client.cpp::parseEnvelope, which pulls only
|
|
||||||
server_time, config_version, firmware and commands). Sent as a UUID string.
|
|
||||||
"""
|
|
||||||
|
|
||||||
capture_id: str | None = None
|
|
||||||
server_time: int
|
|
||||||
config_version: int
|
|
||||||
# Omit the key entirely when the device is on target: present-and-different
|
|
||||||
# is itself the signal to flash (API.md). Omission is a serialisation
|
|
||||||
# concern, so the routes set response_model_exclude_none=True rather than
|
|
||||||
# anything here.
|
|
||||||
firmware: FirmwareTarget | None = None
|
|
||||||
commands: list[Command] = Field(default_factory=list)
|
|
||||||
|
|
||||||
|
|
||||||
# --- ingest -----------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class IngestMeta(BaseModel):
|
|
||||||
"""Metadata for POST /ingest, which arrives in headers, not a body.
|
|
||||||
|
|
||||||
Deviation from SPEC 4.1, and a deliberate one: the raw JPEG is the body, so
|
|
||||||
the device hands over its framebuffer pointer without assembling a second
|
|
||||||
multipart buffer (API.md). REVIEW.AI.md's reference code used multipart and
|
|
||||||
would not have matched the firmware.
|
|
||||||
"""
|
|
||||||
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
|
||||||
|
|
||||||
trigger: Trigger
|
|
||||||
burst_id: Annotated[str | None, Field(max_length=64)] = None
|
|
||||||
burst_index: int | None = None
|
|
||||||
burst_count: int | None = None
|
|
||||||
pre_trigger: bool = False
|
|
||||||
# epoch ms UTC. 0 means the device clock is unsynced: that is NULL, not
|
|
||||||
# 1970 (API.md). received_at stays authoritative either way (SPEC C7).
|
|
||||||
captured_at: datetime | None = None
|
|
||||||
frame_seq: int | None = None
|
|
||||||
radar_state: Annotated[int | None, Field(ge=0, le=3)] = None
|
|
||||||
radar_distance_cm: int | None = None
|
|
||||||
radar_energy: Annotated[int | None, Field(ge=0, le=100)] = None
|
|
||||||
# From X-Rssi, one of the common headers on every authenticated request
|
|
||||||
# rather than an ingest-specific one, but captures.rssi is the column it
|
|
||||||
# belongs in: signal strength at the moment this frame was uploaded.
|
|
||||||
rssi: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
# --- device conditions: one body, two endpoints -----------------------------
|
|
||||||
#
|
|
||||||
# POST /heartbeat -> 200 + Envelope, POST /status -> 204 and nothing.
|
|
||||||
# The split is not cosmetic: the device posts status immediately before deep
|
|
||||||
# sleep, and handing it commands at that moment would mark them delivered to a
|
|
||||||
# device that is about to be unable to run them (API.md).
|
|
||||||
|
|
||||||
|
|
||||||
class PowerBlock(_Loose):
|
|
||||||
uptime_ms: int | None = None
|
|
||||||
# Resets on every wake, unlike uptime_ms which resets only on reboot.
|
|
||||||
awake_ms: int | None = None
|
|
||||||
boot_count: int | None = None
|
|
||||||
wake_cause: Annotated[str | None, Field(max_length=16)] = None
|
|
||||||
last_sleep_s: int | None = None
|
|
||||||
total_sleep_s: int | None = None
|
|
||||||
sleep_enabled: bool | None = None
|
|
||||||
sleep_allowed: bool | None = None
|
|
||||||
inhibits: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class BatteryBlock(_Loose):
|
|
||||||
# false means NOT MEASURED, not empty: no divider is wired by default.
|
|
||||||
# Render as an em dash, never as a low-battery alarm (API.md).
|
|
||||||
valid: bool | None = None
|
|
||||||
mv: int | None = None
|
|
||||||
pct: Annotated[int | None, Field(ge=0, le=100)] = None
|
|
||||||
raw_mv: int | None = None
|
|
||||||
# 0 means pct is meaningless; show the voltage only.
|
|
||||||
chemistry: int | None = None
|
|
||||||
low: bool | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class CountersBlock(_Loose):
|
|
||||||
"""The device's opinion, not the truth: RTC memory, reset on power loss.
|
|
||||||
|
|
||||||
``captures`` is authoritative. What these are genuinely good for is the gap
|
|
||||||
between captured_today and delivered_today, which is an upload-health
|
|
||||||
signal you would otherwise only notice as a quiet camera.
|
|
||||||
"""
|
|
||||||
|
|
||||||
captured_today: int | None = None
|
|
||||||
delivered_today: int | None = None
|
|
||||||
failed_today: int | None = None
|
|
||||||
events_today: int | None = None
|
|
||||||
# Days since epoch in local time. Stays 0 until the clock syncs, so the
|
|
||||||
# pre-sync bucket is a phantom day that rolls over once. Do not chart it.
|
|
||||||
day_index: int | None = None
|
|
||||||
captured_boot: int | None = None
|
|
||||||
delivered_boot: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class CameraBlock(_Loose):
|
|
||||||
# Send names, not indices: entries have been inserted into the middle of
|
|
||||||
# framesize_t between driver releases, so a stored index silently means a
|
|
||||||
# different resolution after a firmware update (API.md).
|
|
||||||
frame_size: str | int | None = None
|
|
||||||
frame_size_id: int | None = None
|
|
||||||
width: int | None = None
|
|
||||||
height: int | None = None
|
|
||||||
# 0x2640 OV2640, 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have
|
|
||||||
# shipped with OV3660, so do not assume from the product listing.
|
|
||||||
sensor_pid: int | None = None
|
|
||||||
jpeg_quality: int | None = None
|
|
||||||
profile: Annotated[str | None, Field(max_length=16)] = None
|
|
||||||
ready: bool | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class NightBlock(_Loose):
|
|
||||||
is_night: bool | None = None
|
|
||||||
nightlight_on: bool | None = None
|
|
||||||
behaviour: int | None = None
|
|
||||||
capture_allowed: bool | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class StreamBlock(_Loose):
|
|
||||||
enabled: bool | None = None
|
|
||||||
active: bool | None = None
|
|
||||||
frames_sent: int | None = None
|
|
||||||
seconds_left: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class RadarBlock(_Loose):
|
|
||||||
# 0 here means no valid frame decoded at any rate: wiring or a dead module,
|
|
||||||
# and worth an alert (API.md).
|
|
||||||
baud: int | None = None
|
|
||||||
uart_ok: bool | None = None
|
|
||||||
out_pin: bool | None = None
|
|
||||||
state: Annotated[int | None, Field(ge=0, le=3)] = None
|
|
||||||
moving_cm: int | None = None
|
|
||||||
moving_energy: int | None = None
|
|
||||||
stationary_cm: int | None = None
|
|
||||||
stationary_energy: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class SystemBlock(_Loose):
|
|
||||||
rssi: int | None = None
|
|
||||||
ip: Annotated[str | None, Field(max_length=45)] = None
|
|
||||||
free_heap: int | None = None
|
|
||||||
free_psram: int | None = None
|
|
||||||
ring_depth: int | None = None
|
|
||||||
ring_bytes: int | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class DeviceConditions(_Loose):
|
|
||||||
"""The body of both POST /heartbeat and POST /status."""
|
|
||||||
|
|
||||||
reason: StatusReason
|
|
||||||
fw_version: Annotated[str | None, Field(max_length=32)] = None
|
|
||||||
hw_revision: Annotated[str | None, Field(max_length=64)] = None
|
|
||||||
config_version: int | None = None
|
|
||||||
|
|
||||||
power: PowerBlock = Field(default_factory=PowerBlock)
|
|
||||||
battery: BatteryBlock = Field(default_factory=BatteryBlock)
|
|
||||||
counters: CountersBlock = Field(default_factory=CountersBlock)
|
|
||||||
camera: CameraBlock = Field(default_factory=CameraBlock)
|
|
||||||
night: NightBlock = Field(default_factory=NightBlock)
|
|
||||||
stream: StreamBlock = Field(default_factory=StreamBlock)
|
|
||||||
radar: RadarBlock = Field(default_factory=RadarBlock)
|
|
||||||
system: SystemBlock = Field(default_factory=SystemBlock)
|
|
||||||
|
|
||||||
time_synced: bool | None = None
|
|
||||||
device_time: datetime | None = None
|
|
||||||
|
|
||||||
@field_validator("device_time", mode="before")
|
|
||||||
@classmethod
|
|
||||||
def _empty_is_none(cls, v: Any) -> Any:
|
|
||||||
return None if v in ("", 0) else v
|
|
||||||
|
|
||||||
|
|
||||||
# --- commands ---------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class CommandAck(BaseModel):
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
|
||||||
|
|
||||||
status: Literal["done", "failed", "rejected"]
|
|
||||||
detail: Annotated[str | None, Field(max_length=1000)] = None
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
"""Server-side sessions for the WebUI (SPEC 3.1, REVIEW SEC-007).
|
|
||||||
|
|
||||||
Cookies, not JWTs, and the session state lives in Postgres. The reason is
|
|
||||||
revocation: signing a user out, or ending every session when their password
|
|
||||||
changes, has to take effect immediately. A self-contained token cannot be
|
|
||||||
withdrawn before it expires without keeping a deny-list, which is the database
|
|
||||||
lookup it was supposed to avoid.
|
|
||||||
|
|
||||||
The cookie value is a 64-hex token; only its SHA-256 is stored. It reuses
|
|
||||||
``deps.new_credential``/``hash_credential`` rather than growing a second
|
|
||||||
implementation of the same idea -- device tokens and session tokens have the
|
|
||||||
same shape and the same reasoning behind a fast hash: both are CSPRNG output,
|
|
||||||
not passwords.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import UTC, datetime, timedelta
|
|
||||||
|
|
||||||
from fastapi import Response
|
|
||||||
from sqlalchemy import delete, select
|
|
||||||
from sqlalchemy.orm import Session as DbSession
|
|
||||||
|
|
||||||
from ..config import Settings
|
|
||||||
from ..models import Session as UserSession
|
|
||||||
from ..models import User
|
|
||||||
from .deps import hash_credential, new_credential
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
SESSION_COOKIE = "poorbird_session"
|
|
||||||
CSRF_COOKIE = "poorbird_csrf"
|
|
||||||
CSRF_HEADER = "x-csrf-token"
|
|
||||||
|
|
||||||
# Lax, not Strict. Strict would also suppress the cookie when someone follows
|
|
||||||
# an ordinary link into the app from anywhere else, so they arrive apparently
|
|
||||||
# signed out and sign in again for no reason. Lax still withholds the cookie
|
|
||||||
# from cross-site POST, which is the CSRF case that matters, and the per-session
|
|
||||||
# token below covers the rest.
|
|
||||||
SAMESITE = "lax"
|
|
||||||
|
|
||||||
|
|
||||||
def create_session(
|
|
||||||
db: DbSession,
|
|
||||||
user: User,
|
|
||||||
*,
|
|
||||||
settings: Settings,
|
|
||||||
ip: str | None = None,
|
|
||||||
user_agent: str | None = None,
|
|
||||||
) -> tuple[str, str]:
|
|
||||||
"""Open a session for ``user``. Returns ``(session_token, csrf_token)``.
|
|
||||||
|
|
||||||
Both are returned in plaintext exactly once, here, and only hashes or
|
|
||||||
per-session values are persisted. The caller is responsible for putting
|
|
||||||
them in cookies and for committing.
|
|
||||||
"""
|
|
||||||
token = new_credential()
|
|
||||||
csrf = new_credential()
|
|
||||||
|
|
||||||
db.add(
|
|
||||||
UserSession(
|
|
||||||
user_id=user.id,
|
|
||||||
token_hash=hash_credential(token),
|
|
||||||
csrf_token=csrf,
|
|
||||||
expires_at=datetime.now(UTC) + timedelta(hours=settings.session_lifetime_h),
|
|
||||||
# Truncated to the column width rather than allowed to raise: a
|
|
||||||
# long or hostile User-Agent must not be able to fail a login.
|
|
||||||
ip=ip[:45] if ip else None,
|
|
||||||
user_agent=user_agent[:255] if user_agent else None,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
db.flush()
|
|
||||||
return token, csrf
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_session(db: DbSession, token: str | None) -> tuple[UserSession, User] | None:
|
|
||||||
"""Look up a live session and its user, or None.
|
|
||||||
|
|
||||||
None covers every failure the caller should treat identically: no cookie, an
|
|
||||||
unknown token, an expired session, a deleted or deactivated user. They are
|
|
||||||
deliberately not distinguished in the return value -- the endpoint answers
|
|
||||||
401 for all of them, because telling a caller *which* one it was is telling
|
|
||||||
them whether a token was ever real.
|
|
||||||
"""
|
|
||||||
if not token:
|
|
||||||
return None
|
|
||||||
|
|
||||||
row = db.execute(
|
|
||||||
select(UserSession, User)
|
|
||||||
.join(User, User.id == UserSession.user_id)
|
|
||||||
.where(UserSession.token_hash == hash_credential(token))
|
|
||||||
).first()
|
|
||||||
if row is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
session, user = row
|
|
||||||
if session.expires_at <= datetime.now(UTC):
|
|
||||||
# Clear it out on the way past. Nothing else would, between the
|
|
||||||
# scheduled purge below and the row's own irrelevance.
|
|
||||||
db.delete(session)
|
|
||||||
db.commit()
|
|
||||||
return None
|
|
||||||
if not user.is_active:
|
|
||||||
return None
|
|
||||||
return session, user
|
|
||||||
|
|
||||||
|
|
||||||
def revoke_session(db: DbSession, token: str | None) -> None:
|
|
||||||
"""End one session. Idempotent: signing out twice is not an error."""
|
|
||||||
if not token:
|
|
||||||
return
|
|
||||||
db.execute(delete(UserSession).where(UserSession.token_hash == hash_credential(token)))
|
|
||||||
|
|
||||||
|
|
||||||
def revoke_all_for_user(db: DbSession, user_id: int) -> int:
|
|
||||||
"""End every session for one user, and return how many.
|
|
||||||
|
|
||||||
Used when a password changes: otherwise the old credential keeps working
|
|
||||||
through any browser that is already signed in, which is usually the reason
|
|
||||||
it was changed.
|
|
||||||
"""
|
|
||||||
result = db.execute(delete(UserSession).where(UserSession.user_id == user_id))
|
|
||||||
return result.rowcount or 0
|
|
||||||
|
|
||||||
|
|
||||||
# Deleting expired rows is deliberately *not* here. Expiry is enforced on read
|
|
||||||
# above, so a leftover row is inert, and the sweep is a scheduled job -- it
|
|
||||||
# lives with the worker's other housekeeping in worker/handlers.py. Putting it
|
|
||||||
# here would mean the worker importing from api/, which is the wrong way round
|
|
||||||
# for the same reason images.py sits at the package root.
|
|
||||||
|
|
||||||
|
|
||||||
# --- cookies ----------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def set_session_cookies(response: Response, token: str, csrf: str, *, settings: Settings) -> None:
|
|
||||||
"""Attach both cookies to a login response.
|
|
||||||
|
|
||||||
The session cookie is HttpOnly so script cannot read it. The CSRF cookie
|
|
||||||
deliberately is **not**: the whole mechanism depends on the app's own
|
|
||||||
JavaScript reading it and echoing it in a header, which an attacker on
|
|
||||||
another origin cannot do.
|
|
||||||
"""
|
|
||||||
max_age = settings.session_lifetime_h * 3600
|
|
||||||
|
|
||||||
response.set_cookie(
|
|
||||||
SESSION_COOKIE,
|
|
||||||
token,
|
|
||||||
max_age=max_age,
|
|
||||||
httponly=True,
|
|
||||||
secure=settings.session_cookie_secure,
|
|
||||||
samesite=SAMESITE,
|
|
||||||
path="/",
|
|
||||||
)
|
|
||||||
response.set_cookie(
|
|
||||||
CSRF_COOKIE,
|
|
||||||
csrf,
|
|
||||||
max_age=max_age,
|
|
||||||
httponly=False,
|
|
||||||
secure=settings.session_cookie_secure,
|
|
||||||
samesite=SAMESITE,
|
|
||||||
path="/",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def clear_session_cookies(response: Response, *, settings: Settings) -> None:
|
|
||||||
"""Remove both cookies.
|
|
||||||
|
|
||||||
The attributes have to match the ones they were set with or the browser
|
|
||||||
treats it as a different cookie and leaves the original in place -- a logout
|
|
||||||
that appears to work and does not.
|
|
||||||
"""
|
|
||||||
for name, httponly in ((SESSION_COOKIE, True), (CSRF_COOKIE, False)):
|
|
||||||
response.delete_cookie(
|
|
||||||
name,
|
|
||||||
httponly=httponly,
|
|
||||||
secure=settings.session_cookie_secure,
|
|
||||||
samesite=SAMESITE,
|
|
||||||
path="/",
|
|
||||||
)
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
"""Request and response shapes for the WebUI (Phase 3).
|
|
||||||
|
|
||||||
Separate from ``schemas.py``, which is the device contract in
|
|
||||||
``firmware/API.md`` and is not free to change. These are ours on both sides: the
|
|
||||||
server and ``web/`` are versioned together and ship together, so a field can be
|
|
||||||
renamed here in one commit.
|
|
||||||
|
|
||||||
The shapes are pinned to what ``web/src/auth/AuthProvider.tsx`` already expects,
|
|
||||||
because the scaffold was written first and there is no reason to make it move.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import uuid
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import Annotated, Literal
|
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
|
||||||
|
|
||||||
from ..models.captures import TRIGGERS
|
|
||||||
from ..models.users import ROLES, THEMES
|
|
||||||
|
|
||||||
Role = Literal[ROLES] # type: ignore[valid-type]
|
|
||||||
Theme = Literal[THEMES] # type: ignore[valid-type]
|
|
||||||
Trigger = Literal[TRIGGERS] # type: ignore[valid-type]
|
|
||||||
|
|
||||||
|
|
||||||
class LoginRequest(BaseModel):
|
|
||||||
model_config = ConfigDict(extra="ignore")
|
|
||||||
|
|
||||||
# Bounded, but not validated against a character set. Usernames are matched
|
|
||||||
# exactly against the database, so there is nothing to sanitise; a length cap
|
|
||||||
# is here only so an enormous body cannot reach Argon2.
|
|
||||||
username: Annotated[str, Field(min_length=1, max_length=64)]
|
|
||||||
# The password floor lives in passwords.validate_password_strength and is
|
|
||||||
# applied when a password is *set*. Applying it here too would refuse to
|
|
||||||
# even check a password that predates the rule, which is a lockout rather
|
|
||||||
# than a policy. Only an upper bound, matching MAX_PASSWORD_LENGTH.
|
|
||||||
password: Annotated[str, Field(min_length=1, max_length=1024)]
|
|
||||||
# Six digits when the account has TOTP. Absent, not empty, when it does not.
|
|
||||||
totp: Annotated[str | None, Field(max_length=16)] = None
|
|
||||||
|
|
||||||
|
|
||||||
class SessionUser(BaseModel):
|
|
||||||
"""What ``GET /auth/session`` and ``POST /auth/login`` both return.
|
|
||||||
|
|
||||||
Deliberately small. It is what the UI needs to render a shell and make role
|
|
||||||
decisions, and nothing else -- no email, no TOTP state, no password
|
|
||||||
metadata. A response shape is a place things accumulate, and the browser is
|
|
||||||
where they end up.
|
|
||||||
"""
|
|
||||||
|
|
||||||
id: int
|
|
||||||
username: str
|
|
||||||
role: Role
|
|
||||||
locale: str
|
|
||||||
theme: Theme
|
|
||||||
|
|
||||||
|
|
||||||
# --- gallery ----------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class CaptureSummary(BaseModel):
|
|
||||||
"""One tile in the grid.
|
|
||||||
|
|
||||||
Kept deliberately small, because a page of these is 50-200 rows and the
|
|
||||||
grid re-fetches on every filter change. Anything only the detail view
|
|
||||||
needs -- radar energy, battery, observations, tags -- is in
|
|
||||||
:class:`CaptureDetail` instead.
|
|
||||||
|
|
||||||
No image URLs. The client builds those from the id in lib/api.ts, which is
|
|
||||||
already the one place that knows the API prefix; putting them here would
|
|
||||||
duplicate that knowledge in every response.
|
|
||||||
"""
|
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
|
||||||
|
|
||||||
id: uuid.UUID
|
|
||||||
device_id: int
|
|
||||||
# SPEC C7: server time, always authoritative. captured_at_device is NULL
|
|
||||||
# when the camera's clock was unsynced, and the UI must not present it as
|
|
||||||
# 1970 -- see API.md on X-Captured-At: 0.
|
|
||||||
received_at: datetime
|
|
||||||
captured_at_device: datetime | None
|
|
||||||
width: int | None
|
|
||||||
height: int | None
|
|
||||||
bytes: int
|
|
||||||
trigger: Trigger
|
|
||||||
pre_trigger: bool
|
|
||||||
burst_id: str | None
|
|
||||||
burst_index: int | None
|
|
||||||
burst_count: int | None
|
|
||||||
reviewed: bool
|
|
||||||
kept: bool
|
|
||||||
# False while the thumbnail job is still queued, or permanently for a frame
|
|
||||||
# that could not be decoded. The grid shows a placeholder rather than a
|
|
||||||
# broken image, so it has to be able to tell.
|
|
||||||
has_thumb: bool
|
|
||||||
|
|
||||||
|
|
||||||
class CapturePage(BaseModel):
|
|
||||||
"""A keyset page, not an offset page.
|
|
||||||
|
|
||||||
At 5000 captures a day, OFFSET gets slower the further back you scroll,
|
|
||||||
which is precisely the direction a gallery scrolls. The cursor carries the
|
|
||||||
last row's ``(received_at, id)``; ``next_cursor`` is null at the end.
|
|
||||||
"""
|
|
||||||
|
|
||||||
items: list[CaptureSummary]
|
|
||||||
next_cursor: str | None
|
|
||||||
|
|
||||||
|
|
||||||
class TagOut(BaseModel):
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
|
||||||
|
|
||||||
id: int
|
|
||||||
label: str
|
|
||||||
colour: str | None
|
|
||||||
|
|
||||||
|
|
||||||
class TaxonOut(BaseModel):
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
|
||||||
|
|
||||||
id: int
|
|
||||||
scientific_name: str
|
|
||||||
name_de: str | None
|
|
||||||
name_en: str | None
|
|
||||||
|
|
||||||
|
|
||||||
class ObservationOut(BaseModel):
|
|
||||||
"""A label on a capture.
|
|
||||||
|
|
||||||
``source`` separates human labels from model predictions in one table
|
|
||||||
(SPEC 3.2), so the edit UI is already the training-data pipeline. The UI
|
|
||||||
must show which is which -- a prediction presented as a human label would
|
|
||||||
poison exactly that.
|
|
||||||
"""
|
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
|
||||||
|
|
||||||
id: int
|
|
||||||
taxon: TaxonOut | None
|
|
||||||
individuals: int
|
|
||||||
age: str
|
|
||||||
sex: str
|
|
||||||
behaviour: str | None
|
|
||||||
certainty: str
|
|
||||||
notes: str | None
|
|
||||||
source: Literal["human", "model"]
|
|
||||||
confidence: float | None
|
|
||||||
|
|
||||||
|
|
||||||
class CaptureDetail(CaptureSummary):
|
|
||||||
"""Everything about one capture, for the full-screen view."""
|
|
||||||
|
|
||||||
device_name: str
|
|
||||||
sha256: str
|
|
||||||
radar_state: int | None
|
|
||||||
radar_distance_cm: int | None
|
|
||||||
radar_energy: int | None
|
|
||||||
battery_mv: int | None
|
|
||||||
rssi: int | None
|
|
||||||
temp_c: float | None
|
|
||||||
frame_seq: int | None
|
|
||||||
observations: list[ObservationOut]
|
|
||||||
tags: list[TagOut]
|
|
||||||
@@ -1,153 +0,0 @@
|
|||||||
"""User authentication and authorization for the WebUI.
|
|
||||||
|
|
||||||
Separate from ``deps.py`` on purpose. That file is device auth: bearer tokens,
|
|
||||||
no cookies, no CSRF, and a 401 there means "clear your token and re-enroll".
|
|
||||||
This file is people: session cookies, CSRF, and roles. Mixing them is how a
|
|
||||||
device ends up able to read the gallery, which SPEC 3.1 forbids outright.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import secrets
|
|
||||||
from typing import Annotated
|
|
||||||
|
|
||||||
from fastapi import Depends, HTTPException, Request, status
|
|
||||||
|
|
||||||
from ..models import Session as UserSession
|
|
||||||
from ..models import User
|
|
||||||
from .deps import DbDep
|
|
||||||
from .ratelimit import client_address
|
|
||||||
from .sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE, resolve_session
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Methods that can change state. A GET must never need CSRF, and must never
|
|
||||||
# change anything -- if one did, no CSRF scheme would protect it.
|
|
||||||
UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
|
||||||
|
|
||||||
_UNAUTHENTICATED = HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="not signed in",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def current_session(request: Request, db: DbDep) -> tuple[UserSession, User]:
|
|
||||||
"""Resolve the session cookie to a live session and user, or 401."""
|
|
||||||
resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE))
|
|
||||||
if resolved is None:
|
|
||||||
raise _UNAUTHENTICATED
|
|
||||||
return resolved
|
|
||||||
|
|
||||||
|
|
||||||
def current_user(
|
|
||||||
resolved: Annotated[tuple[UserSession, User], Depends(current_session)],
|
|
||||||
) -> User:
|
|
||||||
return resolved[1]
|
|
||||||
|
|
||||||
|
|
||||||
SessionDep = Annotated[tuple[UserSession, User], Depends(current_session)]
|
|
||||||
CurrentUser = Annotated[User, Depends(current_user)]
|
|
||||||
|
|
||||||
|
|
||||||
def require_role(*roles: str):
|
|
||||||
"""Dependency factory: allow only these roles (SPEC 3.1).
|
|
||||||
|
|
||||||
``admin`` is not implicitly granted everything -- each route names the roles
|
|
||||||
it accepts, so widening one route cannot silently widen another. Where admin
|
|
||||||
should be included, it is listed.
|
|
||||||
|
|
||||||
403, not 404: the caller is authenticated, and pretending the route does not
|
|
||||||
exist would only make a permission problem look like a bug.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def guard(user: CurrentUser) -> User:
|
|
||||||
if user.role not in roles:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail=f"requires one of: {', '.join(sorted(roles))}",
|
|
||||||
)
|
|
||||||
return user
|
|
||||||
|
|
||||||
return guard
|
|
||||||
|
|
||||||
|
|
||||||
# --- CSRF -------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
async def csrf_middleware(request: Request, call_next):
|
|
||||||
"""Reject mutating cookie-authenticated requests without a valid CSRF token.
|
|
||||||
|
|
||||||
Applied as middleware rather than per-route so a new endpoint cannot forget
|
|
||||||
it. The condition is what keeps it correct:
|
|
||||||
|
|
||||||
* Only unsafe methods. A GET needing this would mean a GET that mutates.
|
|
||||||
* Only requests that **carry the session cookie**. Device endpoints
|
|
||||||
authenticate with a bearer token and never send cookies, so they are
|
|
||||||
untouched -- which matters, because a camera has no way to obtain a CSRF
|
|
||||||
token and blocking /ingest would take the whole system down.
|
|
||||||
* Logging in is therefore exempt without a special case: there is no session
|
|
||||||
cookie yet. Logging out is not exempt, and should not be -- an attacker
|
|
||||||
signing someone out is a nuisance worth preventing.
|
|
||||||
|
|
||||||
The header is compared against the token stored on the session row, not
|
|
||||||
merely against the cookie. Plain double-submit would let an attacker who can
|
|
||||||
write a cookie on the domain set both sides to a value they chose; the
|
|
||||||
victim's session token, which they cannot read, is what they would also
|
|
||||||
need.
|
|
||||||
"""
|
|
||||||
if request.method not in UNSAFE_METHODS or SESSION_COOKIE not in request.cookies:
|
|
||||||
return await call_next(request)
|
|
||||||
|
|
||||||
presented = request.headers.get(CSRF_HEADER)
|
|
||||||
if not presented:
|
|
||||||
return _csrf_failure(request, "missing")
|
|
||||||
|
|
||||||
# Middleware runs outside the dependency system, so it opens its own
|
|
||||||
# session. This is one indexed lookup, on mutating requests only.
|
|
||||||
from ..db import SessionLocal
|
|
||||||
|
|
||||||
with SessionLocal() as db:
|
|
||||||
resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE))
|
|
||||||
if resolved is None:
|
|
||||||
# Not signed in after all. Let the route's own dependency produce
|
|
||||||
# the 401, so the answer stays consistent with every other route.
|
|
||||||
return await call_next(request)
|
|
||||||
session, _user = resolved
|
|
||||||
if not secrets.compare_digest(presented, session.csrf_token):
|
|
||||||
return _csrf_failure(request, "mismatch")
|
|
||||||
|
|
||||||
return await call_next(request)
|
|
||||||
|
|
||||||
|
|
||||||
def _csrf_failure(request: Request, why: str):
|
|
||||||
from fastapi.responses import JSONResponse
|
|
||||||
|
|
||||||
log.warning(
|
|
||||||
"csrf check failed",
|
|
||||||
extra={
|
|
||||||
"reason": why,
|
|
||||||
"path": request.url.path,
|
|
||||||
"method": request.method,
|
|
||||||
"ip": client_address(request),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
return JSONResponse(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
content={
|
|
||||||
"detail": (
|
|
||||||
f"CSRF token {why}. Send the value of the {CSRF_COOKIE} cookie "
|
|
||||||
f"in the {CSRF_HEADER} header."
|
|
||||||
)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"CurrentUser",
|
|
||||||
"SessionDep",
|
|
||||||
"csrf_middleware",
|
|
||||||
"current_session",
|
|
||||||
"current_user",
|
|
||||||
"require_role",
|
|
||||||
]
|
|
||||||
@@ -1,410 +0,0 @@
|
|||||||
"""Entry points.
|
|
||||||
|
|
||||||
``poorbird check`` is the one to reach for first on a fresh machine: it
|
|
||||||
validates config, storage paths and database connectivity and prints what it
|
|
||||||
found, without starting anything.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from . import __version__
|
|
||||||
from .config import get_settings
|
|
||||||
from .logging_setup import configure_logging
|
|
||||||
|
|
||||||
|
|
||||||
def _alembic_config():
|
|
||||||
from alembic.config import Config
|
|
||||||
|
|
||||||
candidate = Path(os.environ.get("POORBIRD_ALEMBIC_INI", "alembic.ini"))
|
|
||||||
if not candidate.is_absolute():
|
|
||||||
candidate = Path.cwd() / candidate
|
|
||||||
if not candidate.exists():
|
|
||||||
raise SystemExit(
|
|
||||||
f"alembic.ini not found at {candidate}. Run from the server/ directory, "
|
|
||||||
"or set POORBIRD_ALEMBIC_INI."
|
|
||||||
)
|
|
||||||
cfg = Config(str(candidate))
|
|
||||||
cfg.set_main_option("script_location", str(candidate.parent / "migrations"))
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_serve(args: argparse.Namespace) -> int:
|
|
||||||
import uvicorn
|
|
||||||
|
|
||||||
settings = get_settings()
|
|
||||||
uvicorn.run(
|
|
||||||
"poorbird.api.app:app",
|
|
||||||
host=args.host or settings.api_host,
|
|
||||||
port=args.port or settings.api_port,
|
|
||||||
reload=args.reload,
|
|
||||||
log_config=None, # our own stdout logging, see logging_setup
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_worker(_args: argparse.Namespace) -> int:
|
|
||||||
from .worker import run
|
|
||||||
|
|
||||||
return run()
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_migrate(_args: argparse.Namespace) -> int:
|
|
||||||
from alembic import command
|
|
||||||
|
|
||||||
command.upgrade(_alembic_config(), "head")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_enqueue(args: argparse.Namespace) -> int:
|
|
||||||
from .db import SessionLocal
|
|
||||||
from .worker.queue import enqueue
|
|
||||||
|
|
||||||
payload = json.loads(args.payload) if args.payload else {}
|
|
||||||
with SessionLocal() as session:
|
|
||||||
job = enqueue(session, args.kind, payload)
|
|
||||||
session.commit()
|
|
||||||
print(f"queued job {job.id} ({args.kind})")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
# --- users ------------------------------------------------------------------
|
|
||||||
#
|
|
||||||
# Accounts are created here, not over HTTP. There is no public registration and
|
|
||||||
# no "first run" web form: both are bootstrap paths that stay reachable forever
|
|
||||||
# and have to be defended forever. A CLI command needs shell access on the
|
|
||||||
# server, which is already the trust boundary.
|
|
||||||
|
|
||||||
|
|
||||||
def _read_new_password(from_stdin: bool) -> str:
|
|
||||||
"""Prompt twice, or read one line from stdin.
|
|
||||||
|
|
||||||
Never a command-line argument: that lands in shell history, in the process
|
|
||||||
table, and in any log that records commands.
|
|
||||||
"""
|
|
||||||
import getpass
|
|
||||||
|
|
||||||
from .passwords import WeakPassword, validate_password_strength
|
|
||||||
|
|
||||||
if from_stdin:
|
|
||||||
# Two line-ending hazards, both silent, both only discoverable by
|
|
||||||
# failing to log in with a password you know is right:
|
|
||||||
#
|
|
||||||
# rstrip("\r\n") rather than rstrip("\n"), or a CRLF pipe leaves the
|
|
||||||
# carriage return inside the password.
|
|
||||||
#
|
|
||||||
# lstrip("") because Windows PowerShell prepends a UTF-8 BOM
|
|
||||||
# when it pipes to a native executable. A BOM is never part of an
|
|
||||||
# intended password, and this cost a debugging session to find.
|
|
||||||
password = sys.stdin.readline().rstrip("\r\n").lstrip("")
|
|
||||||
else:
|
|
||||||
password = getpass.getpass("password: ")
|
|
||||||
if password != getpass.getpass("repeat: "):
|
|
||||||
raise SystemExit("passwords did not match")
|
|
||||||
|
|
||||||
try:
|
|
||||||
validate_password_strength(password)
|
|
||||||
except WeakPassword as exc:
|
|
||||||
raise SystemExit(f"{exc}") from exc
|
|
||||||
return password
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_user_add(args: argparse.Namespace) -> int:
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from .db import SessionLocal
|
|
||||||
from .models import User
|
|
||||||
from .passwords import hash_password
|
|
||||||
from .totp import new_secret, provisioning_uri
|
|
||||||
|
|
||||||
password = _read_new_password(args.password_stdin)
|
|
||||||
|
|
||||||
# TODO 3.0: 2FA is enforced for admin. Enforcing that at login instead
|
|
||||||
# would mean the only admin could be locked out by their own account -- so
|
|
||||||
# it is enforced at creation, where the secret can still be handed over.
|
|
||||||
with_totp = args.totp
|
|
||||||
if with_totp is None:
|
|
||||||
with_totp = args.role == "admin"
|
|
||||||
if args.role == "admin" and not with_totp:
|
|
||||||
print("warning: creating an admin without TOTP, against the TODO 3.0 policy")
|
|
||||||
|
|
||||||
with SessionLocal() as session:
|
|
||||||
if session.scalar(select(User).where(User.username == args.username)) is not None:
|
|
||||||
raise SystemExit(f"user {args.username!r} already exists")
|
|
||||||
|
|
||||||
secret = new_secret() if with_totp else None
|
|
||||||
session.add(
|
|
||||||
User(
|
|
||||||
username=args.username,
|
|
||||||
email=args.email,
|
|
||||||
password_hash=hash_password(password),
|
|
||||||
role=args.role,
|
|
||||||
totp_secret=secret,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
session.commit()
|
|
||||||
|
|
||||||
print(f"created {args.role} {args.username!r}")
|
|
||||||
if secret is not None:
|
|
||||||
# Shown exactly once. It is stored so the server can verify codes, but
|
|
||||||
# printing it again later would turn a one-time handover into a
|
|
||||||
# standing way to mint a second authenticator.
|
|
||||||
print("\nScan this in an authenticator app now -- it is not shown again:")
|
|
||||||
print(f" {provisioning_uri(secret, args.username)}")
|
|
||||||
print(f"\n (manual entry key: {secret})")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_user_list(_args: argparse.Namespace) -> int:
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from .db import SessionLocal
|
|
||||||
from .models import User
|
|
||||||
|
|
||||||
with SessionLocal() as session:
|
|
||||||
users = session.scalars(select(User).order_by(User.id)).all()
|
|
||||||
|
|
||||||
if not users:
|
|
||||||
print("no users. Create one with: poorbird user add <name> --role admin")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
print(f"{'id':>4} {'username':<20} {'role':<8} {'2fa':<4} {'active':<7} last login")
|
|
||||||
for u in users:
|
|
||||||
last = u.last_login_at.strftime("%Y-%m-%d %H:%M") if u.last_login_at else "never"
|
|
||||||
print(
|
|
||||||
f"{u.id:>4} {u.username:<20} {u.role:<8} "
|
|
||||||
f"{'yes' if u.totp_secret else 'no':<4} "
|
|
||||||
f"{'yes' if u.is_active else 'NO':<7} {last}"
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_user_passwd(args: argparse.Namespace) -> int:
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from .db import SessionLocal
|
|
||||||
from .models import Session as UserSession
|
|
||||||
from .models import User
|
|
||||||
from .passwords import hash_password
|
|
||||||
|
|
||||||
password = _read_new_password(args.password_stdin)
|
|
||||||
|
|
||||||
with SessionLocal() as session:
|
|
||||||
user = session.scalar(select(User).where(User.username == args.username))
|
|
||||||
if user is None:
|
|
||||||
raise SystemExit(f"no such user: {args.username!r}")
|
|
||||||
user.password_hash = hash_password(password)
|
|
||||||
|
|
||||||
# A password change has to end existing sessions, or the old
|
|
||||||
# credential effectively still works through any browser that is
|
|
||||||
# already signed in -- which is the main reason people change it.
|
|
||||||
killed = (
|
|
||||||
session.query(UserSession)
|
|
||||||
.filter(UserSession.user_id == user.id)
|
|
||||||
.delete(synchronize_session=False)
|
|
||||||
)
|
|
||||||
session.commit()
|
|
||||||
|
|
||||||
print(f"password updated for {args.username!r}; {killed} session(s) signed out")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_seed(args: argparse.Namespace) -> int:
|
|
||||||
from .db import SessionLocal
|
|
||||||
from .seed import clear, generate
|
|
||||||
|
|
||||||
with SessionLocal() as session:
|
|
||||||
if args.clear:
|
|
||||||
captures, devices = clear(session)
|
|
||||||
print(f"removed {captures} seeded capture(s) and {devices} seed device(s)")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
print(f"generating {args.captures} capture(s) over {args.days} day(s)...")
|
|
||||||
made = generate(
|
|
||||||
session,
|
|
||||||
count=args.captures,
|
|
||||||
days=args.days,
|
|
||||||
device_name=args.device_name,
|
|
||||||
thumbnails=not args.no_thumbnails,
|
|
||||||
)
|
|
||||||
|
|
||||||
print(f"\ndone: {made} capture(s) on device {args.device_name!r}")
|
|
||||||
print("Remove them again with: poorbird seed --clear")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def cmd_check(_args: argparse.Namespace) -> int:
|
|
||||||
settings = get_settings()
|
|
||||||
problems: list[str] = []
|
|
||||||
|
|
||||||
print(f"poorbird {__version__}")
|
|
||||||
print(f" python {sys.version.split()[0]}")
|
|
||||||
|
|
||||||
# Never print the password.
|
|
||||||
if not settings.database_url_is_set:
|
|
||||||
print(" database_url NOT SET (POORBIRD_DATABASE_URL)")
|
|
||||||
problems.append("POORBIRD_DATABASE_URL not set")
|
|
||||||
else:
|
|
||||||
url = settings.database_url
|
|
||||||
if "@" in url:
|
|
||||||
scheme, _, rest = url.partition("://")
|
|
||||||
url = f"{scheme}://***@{rest.rpartition('@')[2]}"
|
|
||||||
print(f" database_url {url}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
from sqlalchemy import text
|
|
||||||
|
|
||||||
from .db import engine
|
|
||||||
|
|
||||||
with engine.connect() as conn:
|
|
||||||
version = conn.execute(text("SHOW server_version")).scalar()
|
|
||||||
print(f" database reachable (PostgreSQL {version})")
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
print(f" database UNREACHABLE: {type(exc).__name__}: {exc}")
|
|
||||||
problems.append("database unreachable")
|
|
||||||
|
|
||||||
try:
|
|
||||||
from alembic import command
|
|
||||||
|
|
||||||
print(" migrations ", end="")
|
|
||||||
command.current(_alembic_config())
|
|
||||||
except SystemExit as exc:
|
|
||||||
print(f"not checked ({exc})")
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
print(f"error: {type(exc).__name__}: {exc}")
|
|
||||||
|
|
||||||
for path in settings.storage_paths():
|
|
||||||
if not path.exists():
|
|
||||||
print(f" path {path} MISSING")
|
|
||||||
problems.append(f"{path} missing")
|
|
||||||
elif not os.access(path, os.W_OK):
|
|
||||||
print(f" path {path} NOT WRITABLE")
|
|
||||||
problems.append(f"{path} not writable")
|
|
||||||
else:
|
|
||||||
print(f" path {path} ok")
|
|
||||||
|
|
||||||
if not settings.enroll_secret_is_set:
|
|
||||||
print(" enroll_secret NOT SET (device enrollment will refuse requests)")
|
|
||||||
|
|
||||||
# The Caddy handoff (SPEC 3.3) needs the app and the proxy to agree on the
|
|
||||||
# layout: Caddy serves the PARENT of both roots and the app sends paths
|
|
||||||
# under /images and /thumbs. If the directories are not siblings with
|
|
||||||
# those names, every image 404s from Caddy with nothing in the app's log
|
|
||||||
# to explain it -- so it is worth saying here rather than discovering in a
|
|
||||||
# browser.
|
|
||||||
if settings.serve_images_directly:
|
|
||||||
print(" images served by the app (development only)")
|
|
||||||
else:
|
|
||||||
from .api.delivery import IMAGE_URL_PREFIX, THUMB_URL_PREFIX
|
|
||||||
|
|
||||||
image_root, thumb_root = settings.image_root, settings.thumb_root
|
|
||||||
expected_image = IMAGE_URL_PREFIX.lstrip("/")
|
|
||||||
expected_thumb = THUMB_URL_PREFIX.lstrip("/")
|
|
||||||
if (
|
|
||||||
image_root.parent != thumb_root.parent
|
|
||||||
or image_root.name != expected_image
|
|
||||||
or thumb_root.name != expected_thumb
|
|
||||||
):
|
|
||||||
print(
|
|
||||||
f" images LAYOUT MISMATCH: Caddy expects "
|
|
||||||
f"<root>/{expected_image} and <root>/{expected_thumb}, "
|
|
||||||
f"got {image_root} and {thumb_root}"
|
|
||||||
)
|
|
||||||
problems.append("image/thumb roots do not match the Caddy handoff layout")
|
|
||||||
else:
|
|
||||||
print(f" images handed off to Caddy from {image_root.parent}")
|
|
||||||
|
|
||||||
if problems:
|
|
||||||
print(f"\n{len(problems)} problem(s): " + "; ".join(problems))
|
|
||||||
return 1
|
|
||||||
print("\nall checks passed")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
|
||||||
parser = argparse.ArgumentParser(prog="poorbird", description="poorBird server")
|
|
||||||
parser.add_argument("--version", action="version", version=__version__)
|
|
||||||
sub = parser.add_subparsers(dest="command", required=True)
|
|
||||||
|
|
||||||
p = sub.add_parser("serve", help="run the HTTP API")
|
|
||||||
p.add_argument("--host")
|
|
||||||
p.add_argument("--port", type=int)
|
|
||||||
p.add_argument("--reload", action="store_true", help="development only")
|
|
||||||
p.set_defaults(func=cmd_serve)
|
|
||||||
|
|
||||||
p = sub.add_parser("worker", help="run the job queue worker and scheduler")
|
|
||||||
p.set_defaults(func=cmd_worker)
|
|
||||||
|
|
||||||
p = sub.add_parser("migrate", help="apply migrations (alembic upgrade head)")
|
|
||||||
p.set_defaults(func=cmd_migrate)
|
|
||||||
|
|
||||||
p = sub.add_parser("check", help="validate config, storage and database")
|
|
||||||
p.set_defaults(func=cmd_check)
|
|
||||||
|
|
||||||
p = sub.add_parser("enqueue", help="put a job on the queue (smoke test)")
|
|
||||||
p.add_argument("kind")
|
|
||||||
p.add_argument("payload", nargs="?", help="JSON object")
|
|
||||||
p.set_defaults(func=cmd_enqueue)
|
|
||||||
|
|
||||||
p = sub.add_parser(
|
|
||||||
"seed",
|
|
||||||
help="generate synthetic captures for gallery development",
|
|
||||||
description=(
|
|
||||||
"Creates captures on a dedicated seed device, with real JPEGs on disk. "
|
|
||||||
"--clear removes them again, and is scoped to seed devices only, so a "
|
|
||||||
"real camera's captures are never in scope."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
p.add_argument("--captures", type=int, default=500, help="how many frames (default 500)")
|
|
||||||
p.add_argument("--days", type=int, default=14, help="spread them over this many days")
|
|
||||||
p.add_argument("--device-name", default="seed-cam")
|
|
||||||
p.add_argument(
|
|
||||||
"--no-thumbnails",
|
|
||||||
action="store_true",
|
|
||||||
help="leave thumb_path NULL so the worker generates them, which is how to "
|
|
||||||
"exercise the queue at volume",
|
|
||||||
)
|
|
||||||
p.add_argument("--clear", action="store_true", help="delete all seeded data instead")
|
|
||||||
p.set_defaults(func=cmd_seed)
|
|
||||||
|
|
||||||
p = sub.add_parser("user", help="manage UI accounts (there is no web signup)")
|
|
||||||
usersub = p.add_subparsers(dest="user_command", required=True)
|
|
||||||
|
|
||||||
q = usersub.add_parser("add", help="create an account")
|
|
||||||
q.add_argument("username")
|
|
||||||
q.add_argument("--role", choices=["admin", "editor", "viewer"], default="viewer")
|
|
||||||
q.add_argument("--email")
|
|
||||||
q.add_argument(
|
|
||||||
"--totp",
|
|
||||||
dest="totp",
|
|
||||||
action="store_true",
|
|
||||||
default=None,
|
|
||||||
help="enable TOTP (the default for --role admin)",
|
|
||||||
)
|
|
||||||
q.add_argument("--no-totp", dest="totp", action="store_false", help="disable TOTP")
|
|
||||||
q.add_argument(
|
|
||||||
"--password-stdin", action="store_true", help="read the password from stdin, not a prompt"
|
|
||||||
)
|
|
||||||
q.set_defaults(func=cmd_user_add)
|
|
||||||
|
|
||||||
q = usersub.add_parser("list", help="list accounts")
|
|
||||||
q.set_defaults(func=cmd_user_list)
|
|
||||||
|
|
||||||
q = usersub.add_parser("passwd", help="set a password and sign out that user's sessions")
|
|
||||||
q.add_argument("username")
|
|
||||||
q.add_argument("--password-stdin", action="store_true")
|
|
||||||
q.set_defaults(func=cmd_user_passwd)
|
|
||||||
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
settings = get_settings()
|
|
||||||
configure_logging(settings.log_level, settings.log_format)
|
|
||||||
return args.func(args)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
"""Configuration.
|
|
||||||
|
|
||||||
Every value comes from the environment (TODO.md Phase 1.2). Nothing is read
|
|
||||||
from a committed config file, and no path, host or secret is baked into code.
|
|
||||||
systemd supplies these via ``EnvironmentFile=/etc/poorbird/poorbird.env``; for
|
|
||||||
local development a ``.env`` in the working directory is picked up as well.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from functools import lru_cache
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Literal
|
|
||||||
|
|
||||||
from pydantic import SecretStr, field_validator
|
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
||||||
|
|
||||||
# Values that mean "nobody filled this in". The .example files ship with these,
|
|
||||||
# and a copied-but-unedited example must not boot as if it were configured.
|
|
||||||
_PLACEHOLDERS = frozenset({"change_me", "changeme", "todo", "xxx", "secret"})
|
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
|
||||||
model_config = SettingsConfigDict(
|
|
||||||
env_prefix="POORBIRD_",
|
|
||||||
env_file=".env",
|
|
||||||
env_file_encoding="utf-8",
|
|
||||||
extra="ignore",
|
|
||||||
)
|
|
||||||
|
|
||||||
# --- database ---------------------------------------------------------
|
|
||||||
# Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket
|
|
||||||
# is the one genuinely container-hostile choice (TODO.md Phase 1.2).
|
|
||||||
#
|
|
||||||
# No default. A working URL in code means real credentials in code, and the
|
|
||||||
# module docstring above already promises none (REVIEW SEC-006). Absence is
|
|
||||||
# reported by ``poorbird check`` and raised with a readable message by db.py,
|
|
||||||
# rather than silently connecting to whatever happens to be on localhost.
|
|
||||||
database_url: str = ""
|
|
||||||
# FastAPI runs this app's ``def`` handlers in anyio's threadpool (40 threads
|
|
||||||
# by default), and each one holds a session for the whole request. A pool of
|
|
||||||
# 5 meant the 6th concurrent request waited on ``pool_timeout`` before it
|
|
||||||
# even reached the database (REVIEW §7). The real ceiling is
|
|
||||||
# pool_size + db_max_overflow, so both are named here rather than left to
|
|
||||||
# SQLAlchemy's invisible default of 10.
|
|
||||||
db_pool_size: int = 15
|
|
||||||
db_max_overflow: int = 10
|
|
||||||
db_echo: bool = False
|
|
||||||
|
|
||||||
# --- http -------------------------------------------------------------
|
|
||||||
api_host: str = "127.0.0.1"
|
|
||||||
api_port: int = 8080
|
|
||||||
|
|
||||||
# --- storage ----------------------------------------------------------
|
|
||||||
# A small number of explicit top-level directories, never scattered under
|
|
||||||
# the app dir: these are the future volume mounts.
|
|
||||||
#
|
|
||||||
# image_root is the single source of truth for the image path. Caddy reads
|
|
||||||
# the same value, because the auth-checked handoff (SPEC 3.3) needs the app
|
|
||||||
# and the proxy to agree on where the bytes live.
|
|
||||||
image_root: Path = Path("/srv/poorbird/images")
|
|
||||||
thumb_root: Path = Path("/srv/poorbird/thumbs")
|
|
||||||
state_dir: Path = Path("/var/lib/poorbird")
|
|
||||||
|
|
||||||
# Who copies the image bytes (SPEC 3.3, api/delivery.py).
|
|
||||||
#
|
|
||||||
# False in production: the app authorises and answers with
|
|
||||||
# X-Accel-Redirect, and Caddy reads the file. Python never handles the
|
|
||||||
# payload. True for local development, where there is no Caddy to honour
|
|
||||||
# that header and every image would otherwise arrive empty.
|
|
||||||
#
|
|
||||||
# This does NOT relax the authorisation -- the same check runs either way.
|
|
||||||
# It only changes how an already-authorised response is finished.
|
|
||||||
serve_images_directly: bool = False
|
|
||||||
|
|
||||||
# --- devices ----------------------------------------------------------
|
|
||||||
# Shared bootstrap secret presented by a device in X-Enroll-Secret.
|
|
||||||
# See firmware/API.md: do NOT rotate this without shipping new firmware,
|
|
||||||
# or you remove the last-resort recovery path for a mounted camera.
|
|
||||||
#
|
|
||||||
# Environment only, never a literal here (REVIEW SEC-001). Empty is allowed
|
|
||||||
# so the Phase 1 commands still run on a fresh clone; the device endpoints
|
|
||||||
# refuse to serve without it.
|
|
||||||
enroll_secret: SecretStr = SecretStr("")
|
|
||||||
|
|
||||||
# --- user sessions (Phase 3) ------------------------------------------
|
|
||||||
# SPEC 3.4 lists session lifetime as a UI-editable server setting. It lives
|
|
||||||
# here until the settings UI exists; promoting it to the settings table then
|
|
||||||
# is a read, not a redesign.
|
|
||||||
session_lifetime_h: int = 24 * 14
|
|
||||||
|
|
||||||
# Secure cookies require HTTPS, which Caddy always terminates in production.
|
|
||||||
# It must be false for local development, because the Vite dev server is
|
|
||||||
# plain http on localhost and a Secure cookie is silently dropped there --
|
|
||||||
# which presents as "login succeeds but I am never signed in", with nothing
|
|
||||||
# in any log. Hence a setting rather than a hardcoded True.
|
|
||||||
session_cookie_secure: bool = True
|
|
||||||
|
|
||||||
# --- rate limiting ----------------------------------------------------
|
|
||||||
# In-process token buckets (api/ratelimit.py), sized for one uvicorn
|
|
||||||
# process. Off by default in tests, which would otherwise exhaust a
|
|
||||||
# bucket and start asserting against 429s.
|
|
||||||
rate_limit_enabled: bool = True
|
|
||||||
|
|
||||||
# --- worker -----------------------------------------------------------
|
|
||||||
# Idle polling only: the loop drains a non-empty queue back to back without
|
|
||||||
# sleeping, so this is the delay before a *newly* enqueued job is noticed,
|
|
||||||
# not a per-job cost. 5s trades latency nobody can perceive on a bird camera
|
|
||||||
# for 12 idle queries a minute instead of 30.
|
|
||||||
worker_poll_interval_s: float = 5.0
|
|
||||||
job_max_attempts: int = 3
|
|
||||||
|
|
||||||
# --- logging ----------------------------------------------------------
|
|
||||||
# Always to stdout/stderr. journald catches it now; a log driver would
|
|
||||||
# catch it later. Never app-managed log files.
|
|
||||||
log_level: str = "INFO"
|
|
||||||
log_format: Literal["text", "json"] = "text"
|
|
||||||
|
|
||||||
@field_validator("database_url")
|
|
||||||
@classmethod
|
|
||||||
def _reject_unedited_example(cls, v: str) -> str:
|
|
||||||
if any(p in v.lower() for p in _PLACEHOLDERS):
|
|
||||||
raise ValueError(
|
|
||||||
"POORBIRD_DATABASE_URL still contains a placeholder from the "
|
|
||||||
"example file. Put the real password in, or leave the variable "
|
|
||||||
"unset."
|
|
||||||
)
|
|
||||||
return v
|
|
||||||
|
|
||||||
@field_validator("enroll_secret")
|
|
||||||
@classmethod
|
|
||||||
def _reject_placeholder_secret(cls, v: SecretStr) -> SecretStr:
|
|
||||||
if v.get_secret_value().strip().lower() in _PLACEHOLDERS:
|
|
||||||
raise ValueError(
|
|
||||||
"POORBIRD_ENROLL_SECRET is a placeholder. Generate one with "
|
|
||||||
"'openssl rand -hex 32', or leave it unset until Phase 2."
|
|
||||||
)
|
|
||||||
return v
|
|
||||||
|
|
||||||
@property
|
|
||||||
def database_url_is_set(self) -> bool:
|
|
||||||
return bool(self.database_url.strip())
|
|
||||||
|
|
||||||
@property
|
|
||||||
def enroll_secret_is_set(self) -> bool:
|
|
||||||
return bool(self.enroll_secret.get_secret_value())
|
|
||||||
|
|
||||||
def storage_paths(self) -> list[Path]:
|
|
||||||
return [self.image_root, self.thumb_root, self.state_dir]
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache
|
|
||||||
def get_settings() -> Settings:
|
|
||||||
return Settings()
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
"""Engine and session factory.
|
|
||||||
|
|
||||||
Synchronous SQLAlchemy, deliberately. At one camera and a few thousand frames a
|
|
||||||
day the async machinery buys nothing and costs clarity, and the worker's
|
|
||||||
``FOR UPDATE SKIP LOCKED`` loop is far easier to reason about synchronously.
|
|
||||||
FastAPI runs ``def`` handlers in a threadpool, so this does not block the loop.
|
|
||||||
Revisit only if the MJPEG relay (Phase 6) turns out to want it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from collections.abc import Iterator
|
|
||||||
|
|
||||||
from sqlalchemy import create_engine
|
|
||||||
from sqlalchemy.orm import Session, sessionmaker
|
|
||||||
|
|
||||||
from .config import get_settings
|
|
||||||
|
|
||||||
_settings = get_settings()
|
|
||||||
|
|
||||||
if not _settings.database_url_is_set:
|
|
||||||
# create_engine("") raises "Could not parse SQLAlchemy URL from string ''",
|
|
||||||
# which sends people looking in the wrong place. Say what to actually do.
|
|
||||||
raise RuntimeError(
|
|
||||||
"POORBIRD_DATABASE_URL is not set. Export it, or put it in server/.env:\n"
|
|
||||||
" POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:<password>"
|
|
||||||
"@127.0.0.1:5432/poorbird\n"
|
|
||||||
"See server/deploy/poorbird.env.example. Run 'poorbird check' to verify."
|
|
||||||
)
|
|
||||||
|
|
||||||
engine = create_engine(
|
|
||||||
_settings.database_url,
|
|
||||||
pool_size=_settings.db_pool_size,
|
|
||||||
max_overflow=_settings.db_max_overflow,
|
|
||||||
# Past pool_size + max_overflow a caller waits rather than failing. It has
|
|
||||||
# to be finite: without a timeout a pool leak presents as requests hanging
|
|
||||||
# forever instead of as an error naming the pool.
|
|
||||||
pool_timeout=30,
|
|
||||||
pool_pre_ping=True,
|
|
||||||
echo=_settings.db_echo,
|
|
||||||
future=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False, future=True)
|
|
||||||
|
|
||||||
|
|
||||||
def session_scope() -> Iterator[Session]:
|
|
||||||
"""Context-managed session for scripts and the worker."""
|
|
||||||
with SessionLocal() as session:
|
|
||||||
yield session
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
"""Where capture bytes go, and what can be read back out of them.
|
|
||||||
|
|
||||||
Lives at package level rather than under ``api`` because both sides use it:
|
|
||||||
the ingest route writes frames, and the worker reads them back to build
|
|
||||||
thumbnails. A worker importing from ``api`` would be the wrong way round.
|
|
||||||
|
|
||||||
Split by cost, deliberately. Everything above the thumbnail section runs on
|
|
||||||
the ingest path, once per frame, and must never be the reason a burst is
|
|
||||||
slow -- so it reads nine bytes of JPEG header rather than decoding an image.
|
|
||||||
Pillow appears only below, in the worker, where the frame has to be decoded
|
|
||||||
anyway.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import uuid
|
|
||||||
from datetime import datetime
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
# Matches `request_body max_size 12MB` in deploy/Caddyfile. Enforced here too,
|
|
||||||
# because Caddy is not in front of the app in development and a limit that
|
|
||||||
# only exists in the proxy is not a limit.
|
|
||||||
MAX_IMAGE_BYTES = 12 * 1024 * 1024
|
|
||||||
|
|
||||||
# SOI. A JPEG always starts FF D8 FF; anything else is not one, whatever the
|
|
||||||
# Content-Type header claims.
|
|
||||||
_JPEG_MAGIC = b"\xff\xd8\xff"
|
|
||||||
|
|
||||||
# Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG) and
|
|
||||||
# CC (DAC) share the range but are not SOF.
|
|
||||||
_SOF_MARKERS = frozenset(
|
|
||||||
{0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def looks_like_jpeg(data: bytes) -> bool:
|
|
||||||
return data.startswith(_JPEG_MAGIC)
|
|
||||||
|
|
||||||
|
|
||||||
def jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
|
|
||||||
"""(width, height) from the JPEG header, or None if it cannot be read.
|
|
||||||
|
|
||||||
Walks the segment chain to the first SOF. None is not an error: a frame
|
|
||||||
whose dimensions we cannot parse is still a frame worth keeping, and the
|
|
||||||
columns are nullable for exactly that reason.
|
|
||||||
"""
|
|
||||||
i, n = 2, len(data)
|
|
||||||
|
|
||||||
while i + 3 < n:
|
|
||||||
if data[i] != 0xFF:
|
|
||||||
i += 1
|
|
||||||
continue
|
|
||||||
|
|
||||||
marker = data[i + 1]
|
|
||||||
|
|
||||||
# Standalone markers: no length field follows.
|
|
||||||
if marker == 0x01 or 0xD0 <= marker <= 0xD8:
|
|
||||||
i += 2
|
|
||||||
continue
|
|
||||||
if marker == 0xD9: # EOI
|
|
||||||
break
|
|
||||||
|
|
||||||
segment_length = int.from_bytes(data[i + 2 : i + 4], "big")
|
|
||||||
if segment_length < 2:
|
|
||||||
break # malformed; a shorter length would not advance
|
|
||||||
|
|
||||||
if marker in _SOF_MARKERS:
|
|
||||||
if i + 9 > n:
|
|
||||||
break
|
|
||||||
height = int.from_bytes(data[i + 5 : i + 7], "big")
|
|
||||||
width = int.from_bytes(data[i + 7 : i + 9], "big")
|
|
||||||
return (width, height) if width and height else None
|
|
||||||
|
|
||||||
i += 2 + segment_length
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def relative_image_path(capture_id: uuid.UUID, received_at: datetime) -> str:
|
|
||||||
"""``YYYY/MM/DD/<uuid>.jpg`` (SPEC 3.3).
|
|
||||||
|
|
||||||
Dated by ``received_at``, never by the device clock: the device may be
|
|
||||||
unsynced and report nothing at all, and SPEC C7 makes server time
|
|
||||||
authoritative. Stored relative to POORBIRD_IMAGE_ROOT so the root stays a
|
|
||||||
deployment concern -- Caddy resolves the same relative path against the
|
|
||||||
same configured root when it serves the bytes.
|
|
||||||
"""
|
|
||||||
return f"{received_at:%Y/%m/%d}/{capture_id}.jpg"
|
|
||||||
|
|
||||||
|
|
||||||
def write_atomically(destination: Path, data: bytes) -> None:
|
|
||||||
"""Write via a temporary file in the same directory, then rename.
|
|
||||||
|
|
||||||
A half-written JPEG is indistinguishable from a whole one until something
|
|
||||||
tries to decode it, so the file must never be visible at its final path
|
|
||||||
until it is complete. Same directory keeps the rename on one filesystem,
|
|
||||||
which is what makes it atomic.
|
|
||||||
"""
|
|
||||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
temporary = destination.with_name(f".{destination.name}.part")
|
|
||||||
|
|
||||||
try:
|
|
||||||
temporary.write_bytes(data)
|
|
||||||
os.replace(temporary, destination)
|
|
||||||
except BaseException:
|
|
||||||
temporary.unlink(missing_ok=True)
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
# --- thumbnails -------------------------------------------------------------
|
|
||||||
#
|
|
||||||
# Worker only. Nothing above this line imports Pillow, so the ingest path
|
|
||||||
# never pays for it.
|
|
||||||
|
|
||||||
# 400px on the long edge, WebP, matching the /thumbs/<uuid>_400.webp pattern
|
|
||||||
# in SPEC 3.3. The number is in the filename, so changing it means writing to
|
|
||||||
# a new name rather than silently serving a differently-sized image from the
|
|
||||||
# old one.
|
|
||||||
THUMB_EDGE = 400
|
|
||||||
THUMB_QUALITY = 80
|
|
||||||
|
|
||||||
|
|
||||||
class UndecodableImage(Exception):
|
|
||||||
"""The bytes are not an image this build of Pillow can read.
|
|
||||||
|
|
||||||
Distinct from an I/O error on purpose: a frame that cannot be decoded
|
|
||||||
will never decode, so retrying is pointless and the worker should record
|
|
||||||
the fact rather than burn its attempts.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def relative_thumb_path(capture_id: uuid.UUID) -> str:
|
|
||||||
"""``<uuid>_400.webp`` (SPEC 3.3), flat rather than dated.
|
|
||||||
|
|
||||||
Thumbnails are addressed by capture id alone and there are far fewer of
|
|
||||||
them per byte, so the dated tree that keeps the image directories to a
|
|
||||||
sane size buys nothing here.
|
|
||||||
"""
|
|
||||||
return f"{capture_id}_{THUMB_EDGE}.webp"
|
|
||||||
|
|
||||||
|
|
||||||
def make_thumbnail(source: Path) -> tuple[bytes, tuple[int, int]]:
|
|
||||||
"""Encode a WebP thumbnail. Returns the bytes and the SOURCE dimensions.
|
|
||||||
|
|
||||||
The source size is returned because the worker is the first place that
|
|
||||||
truly decodes the frame: ingest reads the JPEG header, which can be
|
|
||||||
absent or unparseable, and this is the chance to fill in what it missed.
|
|
||||||
"""
|
|
||||||
import io
|
|
||||||
|
|
||||||
from PIL import Image, UnidentifiedImageError
|
|
||||||
|
|
||||||
try:
|
|
||||||
with Image.open(source) as img:
|
|
||||||
img.load()
|
|
||||||
original = (img.width, img.height)
|
|
||||||
|
|
||||||
# Never upscale. A frame smaller than the thumbnail box should
|
|
||||||
# stay its own size rather than be blown up into a blurry one.
|
|
||||||
thumb = img.convert("RGB")
|
|
||||||
thumb.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS)
|
|
||||||
|
|
||||||
buffer = io.BytesIO()
|
|
||||||
thumb.save(buffer, format="WEBP", quality=THUMB_QUALITY, method=4)
|
|
||||||
return buffer.getvalue(), original
|
|
||||||
except (UnidentifiedImageError, OSError, ValueError) as exc:
|
|
||||||
# Pillow raises OSError for a truncated file as well as for a real
|
|
||||||
# I/O fault, and the two are not worth separating here: either way
|
|
||||||
# this frame is not going to produce a thumbnail.
|
|
||||||
raise UndecodableImage(f"{type(exc).__name__}: {exc}") from exc
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
"""Logging to stdout only.
|
|
||||||
|
|
||||||
journald captures stdout for the systemd units today; a container log driver
|
|
||||||
would capture the same stream unchanged. Nothing writes log files.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import sys
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
|
|
||||||
_RESERVED = set(logging.LogRecord("", 0, "", 0, "", None, None).__dict__) | {
|
|
||||||
"message",
|
|
||||||
"asctime",
|
|
||||||
"taskName",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class JsonFormatter(logging.Formatter):
|
|
||||||
def format(self, record: logging.LogRecord) -> str:
|
|
||||||
payload = {
|
|
||||||
"ts": datetime.fromtimestamp(record.created, UTC).isoformat(),
|
|
||||||
"level": record.levelname,
|
|
||||||
"logger": record.name,
|
|
||||||
"msg": record.getMessage(),
|
|
||||||
}
|
|
||||||
for key, value in record.__dict__.items():
|
|
||||||
if key not in _RESERVED and not key.startswith("_"):
|
|
||||||
payload[key] = value
|
|
||||||
if record.exc_info:
|
|
||||||
payload["exc"] = self.formatException(record.exc_info)
|
|
||||||
return json.dumps(payload, default=str)
|
|
||||||
|
|
||||||
|
|
||||||
def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
|
|
||||||
handler = logging.StreamHandler(sys.stdout)
|
|
||||||
if fmt == "json":
|
|
||||||
handler.setFormatter(JsonFormatter())
|
|
||||||
else:
|
|
||||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s"))
|
|
||||||
|
|
||||||
root = logging.getLogger()
|
|
||||||
root.handlers.clear()
|
|
||||||
root.addHandler(handler)
|
|
||||||
root.setLevel(level.upper())
|
|
||||||
|
|
||||||
# uvicorn installs its own handlers; make them use ours instead.
|
|
||||||
for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
|
|
||||||
lg = logging.getLogger(name)
|
|
||||||
lg.handlers.clear()
|
|
||||||
lg.propagate = True
|
|
||||||
|
|
||||||
logging.getLogger("apscheduler").setLevel("WARNING")
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
"""All models, imported here so ``Base.metadata`` is complete.
|
|
||||||
|
|
||||||
Alembic's env.py and the drift test both rely on importing this one module.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from .base import Base
|
|
||||||
from .captures import Capture, Observation, Tag, Taxon, capture_tags
|
|
||||||
from .devices import Device, DeviceCommand, DeviceStatus, Firmware
|
|
||||||
from .ops import AuditLog, BackupRun, Job, Setting
|
|
||||||
from .users import Session, User
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"AuditLog",
|
|
||||||
"BackupRun",
|
|
||||||
"Base",
|
|
||||||
"Capture",
|
|
||||||
"Device",
|
|
||||||
"DeviceCommand",
|
|
||||||
"DeviceStatus",
|
|
||||||
"Firmware",
|
|
||||||
"Job",
|
|
||||||
"Observation",
|
|
||||||
"Session",
|
|
||||||
"Setting",
|
|
||||||
"Tag",
|
|
||||||
"Taxon",
|
|
||||||
"User",
|
|
||||||
"capture_tags",
|
|
||||||
]
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from sqlalchemy import MetaData
|
|
||||||
from sqlalchemy.orm import DeclarativeBase
|
|
||||||
|
|
||||||
# Explicit names for every constraint. Without this, Alembic autogenerate
|
|
||||||
# cannot drop or alter constraints Postgres named for itself, and migrations
|
|
||||||
# start needing hand-written DDL.
|
|
||||||
NAMING_CONVENTION = {
|
|
||||||
"ix": "ix_%(table_name)s_%(column_0_N_name)s",
|
|
||||||
"uq": "uq_%(table_name)s_%(column_0_N_name)s",
|
|
||||||
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
|
||||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
|
||||||
"pk": "pk_%(table_name)s",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class Base(DeclarativeBase):
|
|
||||||
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
"""Captures, observations, taxonomy and tags.
|
|
||||||
|
|
||||||
Two structural decisions from SPEC 3, both load-bearing:
|
|
||||||
|
|
||||||
1. ``captures`` 1--n ``observations``. One photo can hold two species, and can
|
|
||||||
legitimately hold none (a false trigger, an empty frame). A single
|
|
||||||
``species`` column on the image would have to be undone later.
|
|
||||||
2. Human labels and model predictions share one table, separated by
|
|
||||||
``source``. The edit UI is therefore already the training-data pipeline for
|
|
||||||
any future detection model, with no migration when that day comes.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import uuid
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from sqlalchemy import (
|
|
||||||
BigInteger,
|
|
||||||
Boolean,
|
|
||||||
CheckConstraint,
|
|
||||||
Column,
|
|
||||||
DateTime,
|
|
||||||
Float,
|
|
||||||
ForeignKey,
|
|
||||||
Index,
|
|
||||||
Integer,
|
|
||||||
String,
|
|
||||||
Table,
|
|
||||||
Text,
|
|
||||||
Uuid,
|
|
||||||
func,
|
|
||||||
)
|
|
||||||
from sqlalchemy.dialects.postgresql import JSONB
|
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
||||||
|
|
||||||
from .base import Base
|
|
||||||
|
|
||||||
# API.md sends 'radar'; SPEC 3 predates the LD2410 decision and says 'pir'.
|
|
||||||
TRIGGERS = ("radar", "manual", "timer", "stream_grab")
|
|
||||||
|
|
||||||
|
|
||||||
class Capture(Base):
|
|
||||||
__tablename__ = "captures"
|
|
||||||
__table_args__ = (
|
|
||||||
CheckConstraint("trigger IN " + str(TRIGGERS), name="trigger_valid"),
|
|
||||||
Index("ix_captures_device_received", "device_id", "received_at"),
|
|
||||||
Index("ix_captures_burst", "burst_id", "burst_index"),
|
|
||||||
Index("ix_captures_triage", "kept", "reviewed", "received_at"),
|
|
||||||
)
|
|
||||||
|
|
||||||
# UUID rather than a serial, because it is also the filename:
|
|
||||||
# /srv/poorbird/images/2026/09/08/<uuid>.jpg (SPEC 3.3).
|
|
||||||
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
|
||||||
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
|
|
||||||
|
|
||||||
path: Mapped[str] = mapped_column(Text)
|
|
||||||
thumb_path: Mapped[str | None] = mapped_column(Text)
|
|
||||||
sha256: Mapped[str] = mapped_column(String(64), index=True)
|
|
||||||
width: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
height: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
bytes: Mapped[int] = mapped_column(BigInteger)
|
|
||||||
|
|
||||||
# NULL when the device clock was unsynced. X-Captured-At: 0 means unsynced,
|
|
||||||
# NOT 1970 -- never store an epoch date for it (API.md).
|
|
||||||
captured_at_device: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
# SPEC C7: authoritative, always.
|
|
||||||
received_at: Mapped[datetime] = mapped_column(
|
|
||||||
DateTime(timezone=True), server_default=func.now()
|
|
||||||
)
|
|
||||||
|
|
||||||
trigger: Mapped[str] = mapped_column(String(16))
|
|
||||||
burst_id: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
burst_index: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
burst_count: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
# SPEC 0 / API.md: this frame was captured BEFORE the trigger fired, out of
|
|
||||||
# the PSRAM ring. Usually the good ones -- the bird is still arriving.
|
|
||||||
pre_trigger: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
||||||
frame_seq: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
|
|
||||||
radar_state: Mapped[int | None] = mapped_column(Integer) # 0 none 1 moving 2 stationary 3 both
|
|
||||||
radar_distance_cm: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
radar_energy: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
|
|
||||||
battery_mv: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
rssi: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
temp_c: Mapped[float | None] = mapped_column(Float)
|
|
||||||
|
|
||||||
reviewed: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
||||||
# Soft reject. Drives retention -- see TODO Phase 5 and open question 8.
|
|
||||||
kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
|
|
||||||
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
|
|
||||||
observations: Mapped[list[Observation]] = relationship(
|
|
||||||
back_populates="capture", cascade="all, delete-orphan"
|
|
||||||
)
|
|
||||||
tags: Mapped[list[Tag]] = relationship(secondary="capture_tags", back_populates="captures")
|
|
||||||
|
|
||||||
|
|
||||||
class Observation(Base):
|
|
||||||
__tablename__ = "observations"
|
|
||||||
__table_args__ = (
|
|
||||||
CheckConstraint("age IN ('adult', 'juvenile', 'unknown')", name="age_valid"),
|
|
||||||
CheckConstraint("sex IN ('male', 'female', 'unknown')", name="sex_valid"),
|
|
||||||
CheckConstraint(
|
|
||||||
"behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')",
|
|
||||||
name="behaviour_valid",
|
|
||||||
),
|
|
||||||
CheckConstraint(
|
|
||||||
"certainty IN ('certain', 'probable', 'uncertain')", name="certainty_valid"
|
|
||||||
),
|
|
||||||
CheckConstraint("source IN ('human', 'model')", name="source_valid"),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
||||||
capture_id: Mapped[uuid.UUID] = mapped_column(
|
|
||||||
ForeignKey("captures.id", ondelete="CASCADE"), index=True
|
|
||||||
)
|
|
||||||
taxon_id: Mapped[int | None] = mapped_column(ForeignKey("taxa.id", ondelete="RESTRICT"))
|
|
||||||
|
|
||||||
individuals: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
|
|
||||||
age: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
|
|
||||||
sex: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
|
|
||||||
behaviour: Mapped[str | None] = mapped_column(String(16))
|
|
||||||
certainty: Mapped[str] = mapped_column(
|
|
||||||
String(16), default="certain", server_default="'certain'"
|
|
||||||
)
|
|
||||||
notes: Mapped[str | None] = mapped_column(Text)
|
|
||||||
|
|
||||||
source: Mapped[str] = mapped_column(String(8), default="human", server_default="'human'")
|
|
||||||
# Populated only when source = 'model'. Schema is ready; the pipeline is
|
|
||||||
# explicitly not built (SPEC Option C).
|
|
||||||
model_version: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
confidence: Mapped[float | None] = mapped_column(Float)
|
|
||||||
bbox: Mapped[dict | None] = mapped_column(JSONB)
|
|
||||||
|
|
||||||
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
updated_at: Mapped[datetime] = mapped_column(
|
|
||||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
|
||||||
)
|
|
||||||
|
|
||||||
capture: Mapped[Capture] = relationship(back_populates="observations")
|
|
||||||
taxon: Mapped[Taxon | None] = relationship()
|
|
||||||
|
|
||||||
|
|
||||||
class Taxon(Base):
|
|
||||||
"""Seeded, never free text.
|
|
||||||
|
|
||||||
This is what makes "species, biologically" real rather than a string
|
|
||||||
column that accumulates Kohlmeise, kohlmeise, Parus major and Kohlmeise?
|
|
||||||
as four distinct species (SPEC 3.2).
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "taxa"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
gbif_key: Mapped[int | None] = mapped_column(BigInteger, unique=True)
|
|
||||||
scientific_name: Mapped[str] = mapped_column(String(128), unique=True)
|
|
||||||
name_de: Mapped[str | None] = mapped_column(String(128), index=True)
|
|
||||||
name_en: Mapped[str | None] = mapped_column(String(128), index=True)
|
|
||||||
family: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
# "order" is reserved in SQL; SQLAlchemy quotes it.
|
|
||||||
order: Mapped[str | None] = mapped_column("order", String(64))
|
|
||||||
iucn_status: Mapped[str | None] = mapped_column(String(8))
|
|
||||||
# Ranks the autocomplete. The local garden list comes first.
|
|
||||||
is_local_common: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
||||||
|
|
||||||
|
|
||||||
class Tag(Base):
|
|
||||||
__tablename__ = "tags"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
label: Mapped[str] = mapped_column(String(64), unique=True)
|
|
||||||
colour: Mapped[str | None] = mapped_column(String(16))
|
|
||||||
|
|
||||||
captures: Mapped[list[Capture]] = relationship(secondary="capture_tags", back_populates="tags")
|
|
||||||
|
|
||||||
|
|
||||||
capture_tags = Table(
|
|
||||||
"capture_tags",
|
|
||||||
Base.metadata,
|
|
||||||
Column("capture_id", ForeignKey("captures.id", ondelete="CASCADE"), primary_key=True),
|
|
||||||
Column("tag_id", ForeignKey("tags.id", ondelete="CASCADE"), primary_key=True),
|
|
||||||
)
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
"""Devices, their command queue, their telemetry and the firmware images.
|
|
||||||
|
|
||||||
Field names follow firmware/API.md, which is the contract the firmware
|
|
||||||
actually implements. Where SPEC.md 3 and API.md disagree, API.md wins and the
|
|
||||||
difference is noted inline.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from sqlalchemy import (
|
|
||||||
BigInteger,
|
|
||||||
Boolean,
|
|
||||||
CheckConstraint,
|
|
||||||
DateTime,
|
|
||||||
Float,
|
|
||||||
ForeignKey,
|
|
||||||
Index,
|
|
||||||
Integer,
|
|
||||||
String,
|
|
||||||
Text,
|
|
||||||
func,
|
|
||||||
)
|
|
||||||
from sqlalchemy.dialects.postgresql import JSONB
|
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
||||||
|
|
||||||
from .base import Base
|
|
||||||
|
|
||||||
COMMAND_TYPES = (
|
|
||||||
"apply_config",
|
|
||||||
"capture_now",
|
|
||||||
"report_status",
|
|
||||||
"wake_and_hold",
|
|
||||||
"sleep_now",
|
|
||||||
"stream_start",
|
|
||||||
"stream_stop",
|
|
||||||
"ota_update",
|
|
||||||
"reboot",
|
|
||||||
)
|
|
||||||
|
|
||||||
STATUS_REASONS = (
|
|
||||||
"heartbeat",
|
|
||||||
"periodic",
|
|
||||||
"after_event",
|
|
||||||
"before_sleep",
|
|
||||||
"before_night_sleep",
|
|
||||||
"on_request",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class Device(Base):
|
|
||||||
__tablename__ = "devices"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
|
|
||||||
# eFuse MAC in hex. Survives reflashing, which is what makes it an
|
|
||||||
# identity rather than a name (API.md, Enrollment).
|
|
||||||
device_uid: Mapped[str] = mapped_column(String(32), unique=True, index=True)
|
|
||||||
name: Mapped[str] = mapped_column(String(64))
|
|
||||||
mac: Mapped[str | None] = mapped_column(String(32))
|
|
||||||
hw_revision: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
fw_version: Mapped[str | None] = mapped_column(String(32))
|
|
||||||
|
|
||||||
# Only the hash is stored. The token is high-entropy, so a fast hash is
|
|
||||||
# defensible here (API.md).
|
|
||||||
#
|
|
||||||
# Indexed because every authenticated device request resolves a bearer
|
|
||||||
# token by this column: it is the hottest lookup in the device API.
|
|
||||||
#
|
|
||||||
# Unique so that two devices can never end up sharing a token. NULLs stay
|
|
||||||
# distinct in Postgres, so any number of devices may sit here un-enrolled
|
|
||||||
# or revoked.
|
|
||||||
token_hash: Mapped[str | None] = mapped_column(String(128), unique=True, index=True)
|
|
||||||
# Per-device re-enrollment credential, so a rotated token cannot strand a
|
|
||||||
# camera that has no USB access once mounted (SPEC 0).
|
|
||||||
reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128))
|
|
||||||
|
|
||||||
# --- last-known conditions, denormalised from device_status for the list view
|
|
||||||
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
battery_mv: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
battery_pct: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
# false means NOT MEASURED, not empty. No divider is wired by default.
|
|
||||||
# Render as an em dash, never as a low-battery alarm (API.md, SPEC 0).
|
|
||||||
battery_valid: Mapped[bool] = mapped_column(Boolean, default=False)
|
|
||||||
rssi: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
temp_c: Mapped[float | None] = mapped_column(Float)
|
|
||||||
# Reported every heartbeat so the UI can show command latency honestly (SPEC 0).
|
|
||||||
awake: Mapped[bool] = mapped_column(Boolean, default=True)
|
|
||||||
|
|
||||||
# --- settings surface
|
|
||||||
# One JSONB document rather than forty columns. This mirrors GET /config
|
|
||||||
# exactly: every key is optional and the device merges and clamps partial
|
|
||||||
# documents, so a strict column-per-key schema would be a migration every
|
|
||||||
# time the firmware gains a tunable. The UI edits it as a form; validation
|
|
||||||
# lives in a Pydantic model, not in the DDL.
|
|
||||||
config: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
|
||||||
# The only thing the device compares. Bump on every config change.
|
|
||||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
|
|
||||||
|
|
||||||
heartbeat_interval_s: Mapped[int] = mapped_column(Integer, default=300, server_default="300")
|
|
||||||
status_interval_s: Mapped[int] = mapped_column(Integer, default=900, server_default="900")
|
|
||||||
responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
||||||
|
|
||||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
|
|
||||||
commands: Mapped[list[DeviceCommand]] = relationship(
|
|
||||||
back_populates="device", cascade="all, delete-orphan"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class DeviceCommand(Base):
|
|
||||||
"""SPEC C1: the device is never pushed to, it drains this queue.
|
|
||||||
|
|
||||||
Commands ride along on the /ingest and /heartbeat response, so a capture
|
|
||||||
that was going to happen anyway also delivers the queue at no extra cost.
|
|
||||||
/status deliberately returns nothing actionable (API.md).
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "device_commands"
|
|
||||||
__table_args__ = (
|
|
||||||
CheckConstraint(
|
|
||||||
"type IN " + str(COMMAND_TYPES),
|
|
||||||
name="type_valid",
|
|
||||||
),
|
|
||||||
CheckConstraint(
|
|
||||||
"ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')",
|
|
||||||
name="ack_status_valid",
|
|
||||||
),
|
|
||||||
Index("ix_device_commands_pending", "device_id", "created_at"),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
|
|
||||||
type: Mapped[str] = mapped_column(String(32))
|
|
||||||
payload: Mapped[dict | None] = mapped_column(JSONB)
|
|
||||||
|
|
||||||
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
ack_status: Mapped[str | None] = mapped_column(String(16))
|
|
||||||
result: Mapped[str | None] = mapped_column(Text)
|
|
||||||
expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
|
|
||||||
device: Mapped[Device] = relationship(back_populates="commands")
|
|
||||||
|
|
||||||
|
|
||||||
class Firmware(Base):
|
|
||||||
__tablename__ = "firmware"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
||||||
version: Mapped[str] = mapped_column(String(32), unique=True)
|
|
||||||
semver: Mapped[str | None] = mapped_column(String(32))
|
|
||||||
file_path: Mapped[str] = mapped_column(Text)
|
|
||||||
sha256: Mapped[str] = mapped_column(String(64))
|
|
||||||
size_bytes: Mapped[int] = mapped_column(BigInteger)
|
|
||||||
release_notes: Mapped[str | None] = mapped_column(Text)
|
|
||||||
# SPEC C6 / API.md: the device refuses to flash below this.
|
|
||||||
min_battery_pct: Mapped[int] = mapped_column(Integer, default=50, server_default="50")
|
|
||||||
uploaded_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
||||||
uploaded_at: Mapped[datetime] = mapped_column(
|
|
||||||
DateTime(timezone=True), server_default=func.now()
|
|
||||||
)
|
|
||||||
is_target: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
|
|
||||||
|
|
||||||
|
|
||||||
class DeviceStatus(Base):
|
|
||||||
"""Time series, one row per conditions report (SPEC 0).
|
|
||||||
|
|
||||||
The flat columns are the ones worth querying and charting. ``raw`` keeps
|
|
||||||
the whole posted body so nothing is lost when the firmware grows a field
|
|
||||||
before the server learns about it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "device_status"
|
|
||||||
__table_args__ = (
|
|
||||||
CheckConstraint("reason IN " + str(STATUS_REASONS), name="reason_valid"),
|
|
||||||
Index("ix_device_status_device_at", "device_id", "at"),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
||||||
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
|
|
||||||
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
reason: Mapped[str] = mapped_column(String(32))
|
|
||||||
|
|
||||||
battery_mv: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
battery_pct: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
battery_valid: Mapped[bool | None] = mapped_column(Boolean)
|
|
||||||
|
|
||||||
awake_ms: Mapped[int | None] = mapped_column(BigInteger)
|
|
||||||
boot_count: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
wake_cause: Mapped[str | None] = mapped_column(String(16))
|
|
||||||
last_sleep_s: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
total_sleep_s: Mapped[int | None] = mapped_column(BigInteger)
|
|
||||||
|
|
||||||
# The device's opinion, not the truth: these live in RTC memory and reset
|
|
||||||
# on power loss. `captures` is authoritative. Their real value is the GAP
|
|
||||||
# between captured and delivered, which is an upload-health signal.
|
|
||||||
captured_today: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
delivered_today: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
failed_today: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
events_today: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
# Days since epoch, local time; stays 0 until the clock syncs, so the
|
|
||||||
# pre-sync bucket is a phantom day. Do not chart it (API.md).
|
|
||||||
day_index: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
|
|
||||||
is_night: Mapped[bool | None] = mapped_column(Boolean)
|
|
||||||
nightlight_on: Mapped[bool | None] = mapped_column(Boolean)
|
|
||||||
cam_profile: Mapped[str | None] = mapped_column(String(16))
|
|
||||||
|
|
||||||
# 0 here means no valid frame was decoded at any rate: wiring or a dead
|
|
||||||
# module, and worth an alert (API.md).
|
|
||||||
radar_baud: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
radar_uart_ok: Mapped[bool | None] = mapped_column(Boolean)
|
|
||||||
stream_active: Mapped[bool | None] = mapped_column(Boolean)
|
|
||||||
|
|
||||||
rssi: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
ip: Mapped[str | None] = mapped_column(String(45))
|
|
||||||
free_heap: Mapped[int | None] = mapped_column(BigInteger)
|
|
||||||
free_psram: Mapped[int | None] = mapped_column(BigInteger)
|
|
||||||
ring_depth: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
|
|
||||||
time_synced: Mapped[bool | None] = mapped_column(Boolean)
|
|
||||||
device_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
fw_version: Mapped[str | None] = mapped_column(String(32))
|
|
||||||
config_version: Mapped[int | None] = mapped_column(Integer)
|
|
||||||
|
|
||||||
raw: Mapped[dict | None] = mapped_column(JSONB)
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
"""Operational tables: settings, audit log, backup runs, and the job queue."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from sqlalchemy import (
|
|
||||||
BigInteger,
|
|
||||||
CheckConstraint,
|
|
||||||
DateTime,
|
|
||||||
ForeignKey,
|
|
||||||
Index,
|
|
||||||
Integer,
|
|
||||||
String,
|
|
||||||
Text,
|
|
||||||
func,
|
|
||||||
)
|
|
||||||
from sqlalchemy.dialects.postgresql import JSONB
|
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
|
||||||
|
|
||||||
from .base import Base
|
|
||||||
|
|
||||||
JOB_STATUSES = ("queued", "running", "done", "failed")
|
|
||||||
|
|
||||||
|
|
||||||
class Setting(Base):
|
|
||||||
"""SPEC 3.4. "Fully configurable" needs a boundary or it never finishes.
|
|
||||||
|
|
||||||
Server scope: retention policy, thumbnail size, backup schedule + target,
|
|
||||||
alarm thresholds and channels, default theme, default locale, session
|
|
||||||
lifetime. Anything not on that list is a code change, deliberately.
|
|
||||||
|
|
||||||
Backup schedule lives here rather than in a systemd timer, which is why
|
|
||||||
scheduling runs in the worker (TODO Phase 1.2).
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "settings"
|
|
||||||
__table_args__ = (CheckConstraint("scope IN ('server', 'device')", name="scope_valid"),)
|
|
||||||
|
|
||||||
key: Mapped[str] = mapped_column(String(64), primary_key=True)
|
|
||||||
value: Mapped[str | None] = mapped_column(Text)
|
|
||||||
value_type: Mapped[str] = mapped_column(String(16), default="str", server_default="'str'")
|
|
||||||
scope: Mapped[str] = mapped_column(String(16), default="server", server_default="'server'")
|
|
||||||
updated_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
||||||
updated_at: Mapped[datetime] = mapped_column(
|
|
||||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class AuditLog(Base):
|
|
||||||
__tablename__ = "audit_log"
|
|
||||||
__table_args__ = (Index("ix_audit_log_entity", "entity", "entity_id", "at"),)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
||||||
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
||||||
action: Mapped[str] = mapped_column(String(64))
|
|
||||||
entity: Mapped[str] = mapped_column(String(64))
|
|
||||||
entity_id: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
before: Mapped[dict | None] = mapped_column(JSONB)
|
|
||||||
after: Mapped[dict | None] = mapped_column(JSONB)
|
|
||||||
ip: Mapped[str | None] = mapped_column(String(45))
|
|
||||||
|
|
||||||
|
|
||||||
class BackupRun(Base):
|
|
||||||
__tablename__ = "backup_runs"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
||||||
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
status: Mapped[str] = mapped_column(String(16), default="running")
|
|
||||||
bytes: Mapped[int | None] = mapped_column(BigInteger)
|
|
||||||
snapshot_id: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
# A backup you have never restored is a hypothesis: set by the monthly
|
|
||||||
# restore test (TODO Phase 5).
|
|
||||||
restore_tested_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
error: Mapped[str | None] = mapped_column(Text)
|
|
||||||
|
|
||||||
|
|
||||||
class Job(Base):
|
|
||||||
"""Postgres-backed queue, claimed with FOR UPDATE SKIP LOCKED. No Redis.
|
|
||||||
|
|
||||||
This second writer is the concrete reason SPEC C8 pushed past SQLite.
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "jobs"
|
|
||||||
__table_args__ = (
|
|
||||||
CheckConstraint("status IN " + str(JOB_STATUSES), name="status_valid"),
|
|
||||||
# The claim query's covering index.
|
|
||||||
Index("ix_jobs_claimable", "status", "run_at", "priority"),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
||||||
kind: Mapped[str] = mapped_column(String(64))
|
|
||||||
payload: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
|
||||||
status: Mapped[str] = mapped_column(String(16), default="queued", server_default="'queued'")
|
|
||||||
priority: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
|
||||||
|
|
||||||
run_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
|
||||||
max_attempts: Mapped[int] = mapped_column(Integer, default=3, server_default="3")
|
|
||||||
|
|
||||||
locked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
locked_by: Mapped[str | None] = mapped_column(String(128))
|
|
||||||
last_error: Mapped[str | None] = mapped_column(Text)
|
|
||||||
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
"""Users and sessions.
|
|
||||||
|
|
||||||
Devices are NOT users (SPEC 3.1). A device authenticates with a bearer token
|
|
||||||
scoped to /ingest, /heartbeat, /status, /config, /commands/*/ack, /firmware/*
|
|
||||||
and /stream/*. It can never read the gallery.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import uuid
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from sqlalchemy import (
|
|
||||||
Boolean,
|
|
||||||
CheckConstraint,
|
|
||||||
DateTime,
|
|
||||||
ForeignKey,
|
|
||||||
String,
|
|
||||||
Uuid,
|
|
||||||
func,
|
|
||||||
)
|
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
|
||||||
|
|
||||||
from .base import Base
|
|
||||||
|
|
||||||
ROLES = ("admin", "editor", "viewer")
|
|
||||||
THEMES = ("light", "dark", "blue")
|
|
||||||
|
|
||||||
|
|
||||||
class User(Base):
|
|
||||||
__tablename__ = "users"
|
|
||||||
__table_args__ = (
|
|
||||||
CheckConstraint("role IN " + str(ROLES), name="role_valid"),
|
|
||||||
CheckConstraint("theme IN " + str(THEMES), name="theme_valid"),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
|
||||||
username: Mapped[str] = mapped_column(String(64), unique=True)
|
|
||||||
email: Mapped[str | None] = mapped_column(String(255))
|
|
||||||
# Argon2id. Populated in Phase 3; nothing writes it yet.
|
|
||||||
password_hash: Mapped[str | None] = mapped_column(String(255))
|
|
||||||
role: Mapped[str] = mapped_column(String(16), default="viewer", server_default="'viewer'")
|
|
||||||
totp_secret: Mapped[str | None] = mapped_column(String(64))
|
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
|
|
||||||
|
|
||||||
theme: Mapped[str] = mapped_column(String(16), default="light", server_default="'light'")
|
|
||||||
locale: Mapped[str] = mapped_column(String(8), default="de", server_default="'de'")
|
|
||||||
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
||||||
|
|
||||||
|
|
||||||
class Session(Base):
|
|
||||||
"""A signed-in browser.
|
|
||||||
|
|
||||||
``id`` is internal and never leaves the server. The cookie carries a
|
|
||||||
separate high-entropy token of which only the SHA-256 is stored, exactly as
|
|
||||||
device tokens work (api/deps.py). Using ``id`` as the cookie value would be
|
|
||||||
simpler and would mean a database dump handed over every live session.
|
|
||||||
|
|
||||||
``csrf_token`` is per session rather than global, so the double-submit check
|
|
||||||
cannot be satisfied by an attacker who can merely set a cookie on the
|
|
||||||
domain -- they would also need this session's token, which is what they do
|
|
||||||
not have.
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "sessions"
|
|
||||||
|
|
||||||
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
|
||||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
|
||||||
# SHA-256 hex of the cookie value. Unique so a collision is a constraint
|
|
||||||
# error rather than two users sharing a session, and indexed because this
|
|
||||||
# is the lookup on every authenticated request.
|
|
||||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
|
||||||
csrf_token: Mapped[str] = mapped_column(String(64))
|
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
||||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
|
|
||||||
ip: Mapped[str | None] = mapped_column(String(45))
|
|
||||||
user_agent: Mapped[str | None] = mapped_column(String(255))
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
"""User password hashing (SPEC 3.1, REVIEW SEC-009).
|
|
||||||
|
|
||||||
Argon2id, via ``argon2-cffi``. Lives at the package root rather than under
|
|
||||||
``api/`` because the CLI creates the first user before any HTTP request exists,
|
|
||||||
and a CLI importing from ``api`` would be the wrong way round -- the same reason
|
|
||||||
``images.py`` sits here.
|
|
||||||
|
|
||||||
**Why not the SHA-256 in api/deps.py.** That one hashes device tokens, which are
|
|
||||||
256 bits of CSPRNG output: there is no dictionary to attack, and a per-request
|
|
||||||
Argon2 would cost every heartbeat. A password is a human-chosen secret from a
|
|
||||||
very small space, so the hash has to be deliberately slow. Same word, opposite
|
|
||||||
requirements.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from argon2 import PasswordHasher
|
|
||||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# argon2-cffi's defaults track the RFC 9106 guidance and move with the library,
|
|
||||||
# which is the point of not pinning our own numbers here. At the time of writing
|
|
||||||
# that is time_cost=3, memory_cost=64 MiB, parallelism=4 -- tens of milliseconds
|
|
||||||
# on this hardware, which is the intended cost.
|
|
||||||
_hasher = PasswordHasher()
|
|
||||||
|
|
||||||
# A floor, not a policy engine. Length is the only property that reliably
|
|
||||||
# correlates with strength; composition rules mostly produce "Passw0rd!".
|
|
||||||
MIN_PASSWORD_LENGTH = 12
|
|
||||||
|
|
||||||
# Argon2 reads at most this much, and a huge body should not become a CPU cost.
|
|
||||||
# 1 KiB is far past any real passphrase.
|
|
||||||
MAX_PASSWORD_LENGTH = 1024
|
|
||||||
|
|
||||||
|
|
||||||
class WeakPassword(ValueError):
|
|
||||||
"""Raised by :func:`validate_password_strength`."""
|
|
||||||
|
|
||||||
|
|
||||||
def validate_password_strength(password: str) -> None:
|
|
||||||
"""Raise :class:`WeakPassword` if the password is unusable.
|
|
||||||
|
|
||||||
Deliberately minimal: a length floor and a check that it is not entirely
|
|
||||||
whitespace. Anything more opinionated belongs in the UI, where it can give
|
|
||||||
feedback as the user types instead of rejecting after the fact.
|
|
||||||
"""
|
|
||||||
if len(password) < MIN_PASSWORD_LENGTH:
|
|
||||||
raise WeakPassword(f"password must be at least {MIN_PASSWORD_LENGTH} characters")
|
|
||||||
if len(password) > MAX_PASSWORD_LENGTH:
|
|
||||||
raise WeakPassword(f"password must be at most {MAX_PASSWORD_LENGTH} characters")
|
|
||||||
if not password.strip():
|
|
||||||
raise WeakPassword("password must not be only whitespace")
|
|
||||||
|
|
||||||
|
|
||||||
def hash_password(password: str) -> str:
|
|
||||||
"""Hash a password for storage in ``users.password_hash``.
|
|
||||||
|
|
||||||
The result carries its own parameters, so raising the cost later does not
|
|
||||||
invalidate existing hashes -- see :func:`needs_rehash`.
|
|
||||||
"""
|
|
||||||
return _hasher.hash(password)
|
|
||||||
|
|
||||||
|
|
||||||
def verify_password(password: str, stored_hash: str | None) -> bool:
|
|
||||||
"""True if ``password`` matches ``stored_hash``.
|
|
||||||
|
|
||||||
Never raises for an ordinary wrong password, a NULL hash or a corrupt one:
|
|
||||||
all three are simply "no". A user row with ``password_hash IS NULL`` is one
|
|
||||||
that has never had a password set, and it must not be loggable-in rather
|
|
||||||
than crashing the login route.
|
|
||||||
"""
|
|
||||||
if not stored_hash:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
return _hasher.verify(stored_hash, password)
|
|
||||||
except (VerifyMismatchError, VerificationError):
|
|
||||||
return False
|
|
||||||
except InvalidHashError:
|
|
||||||
# The stored value is not an Argon2 hash at all. Worth saying out loud,
|
|
||||||
# because it means something wrote that column by hand.
|
|
||||||
log.error("stored password hash is not a valid Argon2 hash")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def needs_rehash(stored_hash: str) -> bool:
|
|
||||||
"""True if this hash was made with weaker parameters than current defaults.
|
|
||||||
|
|
||||||
Login is the only moment the plaintext is available, so it is the only
|
|
||||||
moment a hash can be upgraded. Call this after a successful verify.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return _hasher.check_needs_rehash(stored_hash)
|
|
||||||
except InvalidHashError:
|
|
||||||
return False
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
"""Shared Alembic comparison options.
|
|
||||||
|
|
||||||
Used by both ``migrations/env.py`` and the schema-drift test, so autogenerate
|
|
||||||
and the test can never disagree about what counts as a difference.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
|
|
||||||
def _normalise_default(value: Any) -> str:
|
|
||||||
"""Strip a Postgres type cast and the SQL quoting from a default.
|
|
||||||
|
|
||||||
Postgres reflects a varchar default as ``'viewer'::character varying``
|
|
||||||
while the model's metadata renders it as ``'viewer'``. Compared literally,
|
|
||||||
every string default in the schema looks like drift, forever -- which
|
|
||||||
trains you to ignore the one time it isn't.
|
|
||||||
"""
|
|
||||||
text = str(value).strip()
|
|
||||||
if "::" in text:
|
|
||||||
text = text.split("::", 1)[0]
|
|
||||||
return text.strip().strip("'").strip().lower()
|
|
||||||
|
|
||||||
|
|
||||||
def compare_server_default(
|
|
||||||
context: Any,
|
|
||||||
inspected_column: Any,
|
|
||||||
metadata_column: Any,
|
|
||||||
inspected_default: Any,
|
|
||||||
metadata_default: Any,
|
|
||||||
rendered_metadata_default: Any,
|
|
||||||
) -> bool | None:
|
|
||||||
"""Return True when the defaults genuinely differ.
|
|
||||||
|
|
||||||
Returning None hands the decision back to Alembic, which is what we want
|
|
||||||
whenever one side has no default at all -- that IS a real difference and
|
|
||||||
Alembic's own logic reports it correctly.
|
|
||||||
"""
|
|
||||||
if inspected_default is None or rendered_metadata_default is None:
|
|
||||||
return None
|
|
||||||
return _normalise_default(inspected_default) != _normalise_default(rendered_metadata_default)
|
|
||||||
|
|
||||||
|
|
||||||
# One place to define what "compare the schema" means.
|
|
||||||
COMPARE_OPTS: dict[str, Any] = {
|
|
||||||
"compare_type": True,
|
|
||||||
"compare_server_default": compare_server_default,
|
|
||||||
}
|
|
||||||
@@ -1,257 +0,0 @@
|
|||||||
"""Synthetic captures for developing the gallery (TODO 3.0).
|
|
||||||
|
|
||||||
Generated, not downloaded. Three reasons, from the recorded decision:
|
|
||||||
|
|
||||||
* no image licensing question at all, and no binary blobs in git;
|
|
||||||
* it can produce the *volume* a virtualised grid has to be tested against,
|
|
||||||
which no set of real photos on hand would; and
|
|
||||||
* a real photo proves nothing about a gallery that a generated one does not.
|
|
||||||
|
|
||||||
**Seeded data is confined to its own device**, whose ``device_uid`` starts with
|
|
||||||
``SEED_UID_PREFIX``. That is what makes ``--clear`` safe: it deletes captures
|
|
||||||
belonging to seed devices and nothing else, so a real camera's frames are never
|
|
||||||
in scope. Without that boundary a convenience command sits next to real data
|
|
||||||
holding a delete, which is not a risk worth carrying for test rows.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import random
|
|
||||||
import secrets
|
|
||||||
import uuid
|
|
||||||
from datetime import UTC, datetime, timedelta
|
|
||||||
|
|
||||||
from sqlalchemy import delete, select
|
|
||||||
from sqlalchemy.orm import Session
|
|
||||||
|
|
||||||
from .config import get_settings
|
|
||||||
from .images import (
|
|
||||||
make_thumbnail,
|
|
||||||
relative_image_path,
|
|
||||||
relative_thumb_path,
|
|
||||||
write_atomically,
|
|
||||||
)
|
|
||||||
from .models import Capture, Device, Job
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Deliberately hex-looking, so it is a plausible device_uid, while still being
|
|
||||||
# unmistakable in a listing. "5eed".
|
|
||||||
SEED_UID_PREFIX = "5eed"
|
|
||||||
|
|
||||||
# A burst is what the firmware actually sends: a handful of frames around one
|
|
||||||
# radar trigger, the first of them pulled from the PSRAM pre-trigger ring.
|
|
||||||
BURST_MIN, BURST_MAX = 3, 5
|
|
||||||
|
|
||||||
# Realistic per API.md/SPEC: UXGA frames of a few hundred KB.
|
|
||||||
FRAME_WIDTH, FRAME_HEIGHT = 1600, 1200
|
|
||||||
|
|
||||||
# Birds are diurnal, and a gallery grouped by day looks wrong if captures are
|
|
||||||
# spread evenly around the clock. Weight toward daylight.
|
|
||||||
_DAY_HOURS = list(range(5, 21))
|
|
||||||
|
|
||||||
|
|
||||||
def _synthetic_jpeg(width: int, height: int, seed: int) -> bytes:
|
|
||||||
"""A distinct, cheap JPEG per capture.
|
|
||||||
|
|
||||||
Distinct matters more than pretty: identical tiles make it impossible to
|
|
||||||
see whether the grid is actually scrolling, and a flat colour compresses to
|
|
||||||
a few hundred bytes, which would not exercise the thumbnail path at a
|
|
||||||
realistic size. A coarse gradient plus noise blocks gives both.
|
|
||||||
"""
|
|
||||||
import io
|
|
||||||
|
|
||||||
from PIL import Image, ImageDraw
|
|
||||||
|
|
||||||
rng = random.Random(seed)
|
|
||||||
image = Image.new("RGB", (width, height))
|
|
||||||
draw = ImageDraw.Draw(image)
|
|
||||||
|
|
||||||
base = (rng.randint(40, 140), rng.randint(70, 170), rng.randint(40, 120))
|
|
||||||
# Coarse bands rather than per-pixel work: 500 frames at 1600x1200 is
|
|
||||||
# enough to notice, and the point is bytes on disk, not art.
|
|
||||||
band = max(8, height // 48)
|
|
||||||
for y in range(0, height, band):
|
|
||||||
shade = y / height
|
|
||||||
draw.rectangle(
|
|
||||||
[0, y, width, y + band],
|
|
||||||
fill=(
|
|
||||||
min(255, int(base[0] * (0.6 + shade))),
|
|
||||||
min(255, int(base[1] * (0.6 + shade))),
|
|
||||||
min(255, int(base[2] * (0.6 + shade))),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
for _ in range(60):
|
|
||||||
x, y = rng.randint(0, width), rng.randint(0, height)
|
|
||||||
size = rng.randint(20, 90)
|
|
||||||
draw.ellipse(
|
|
||||||
[x, y, x + size, y + size],
|
|
||||||
fill=(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)),
|
|
||||||
)
|
|
||||||
|
|
||||||
buffer = io.BytesIO()
|
|
||||||
image.save(buffer, format="JPEG", quality=78)
|
|
||||||
return buffer.getvalue()
|
|
||||||
|
|
||||||
|
|
||||||
def seed_device(db: Session, name: str) -> Device:
|
|
||||||
"""The device seeded captures hang off. Reused if it already exists."""
|
|
||||||
device = db.scalar(
|
|
||||||
select(Device).where(Device.name == name, Device.device_uid.startswith(SEED_UID_PREFIX))
|
|
||||||
)
|
|
||||||
if device is not None:
|
|
||||||
return device
|
|
||||||
|
|
||||||
device = Device(
|
|
||||||
device_uid=f"{SEED_UID_PREFIX}{secrets.token_hex(6)}",
|
|
||||||
name=name,
|
|
||||||
# No token. A seed device is a row for the gallery to point at, not a
|
|
||||||
# camera that can authenticate -- issuing it a working credential
|
|
||||||
# would be creating a real way in for the sake of test data.
|
|
||||||
token_hash=None,
|
|
||||||
enabled=True,
|
|
||||||
battery_valid=False,
|
|
||||||
)
|
|
||||||
db.add(device)
|
|
||||||
db.commit()
|
|
||||||
db.refresh(device)
|
|
||||||
return device
|
|
||||||
|
|
||||||
|
|
||||||
def generate(
|
|
||||||
db: Session,
|
|
||||||
*,
|
|
||||||
count: int,
|
|
||||||
days: int,
|
|
||||||
device_name: str,
|
|
||||||
thumbnails: bool,
|
|
||||||
progress: bool = True,
|
|
||||||
) -> int:
|
|
||||||
"""Create ``count`` captures spread over the last ``days``. Returns how many.
|
|
||||||
|
|
||||||
Frames are written to disk for real, because a gallery whose rows point at
|
|
||||||
files that do not exist tests nothing about the delivery path -- which is
|
|
||||||
the half most likely to be wrong.
|
|
||||||
"""
|
|
||||||
settings = get_settings()
|
|
||||||
device = seed_device(db, device_name)
|
|
||||||
rng = random.Random()
|
|
||||||
|
|
||||||
made = 0
|
|
||||||
while made < count:
|
|
||||||
remaining = count - made
|
|
||||||
burst_size = min(rng.randint(BURST_MIN, BURST_MAX), remaining)
|
|
||||||
# Absorb a tail too short to be a burst. Plain truncation leaves a
|
|
||||||
# final burst of one or two frames with burst_count=1, which no camera
|
|
||||||
# sends -- and a one-frame burst is entirely pre-trigger, so it also
|
|
||||||
# makes that flag meaningless. Bursts here are 3-7 rather than 3-5,
|
|
||||||
# which is a better trade than inventing data the firmware cannot
|
|
||||||
# produce. (This was a flaky test before it was a comment: whether it
|
|
||||||
# happened depended on the random sizes.)
|
|
||||||
if 0 < remaining - burst_size < BURST_MIN:
|
|
||||||
burst_size = remaining
|
|
||||||
burst_id = str(uuid.uuid4())
|
|
||||||
|
|
||||||
# One trigger event, somewhere in the window, at a plausible hour.
|
|
||||||
moment = datetime.now(UTC) - timedelta(
|
|
||||||
days=rng.uniform(0, days),
|
|
||||||
)
|
|
||||||
moment = moment.replace(hour=rng.choice(_DAY_HOURS), minute=rng.randint(0, 59))
|
|
||||||
|
|
||||||
for index in range(burst_size):
|
|
||||||
capture_id = uuid.uuid4()
|
|
||||||
# Frames within a burst are milliseconds apart, which is exactly
|
|
||||||
# the received_at tie the gallery cursor has to survive.
|
|
||||||
captured = moment + timedelta(milliseconds=index * 120)
|
|
||||||
received = captured + timedelta(milliseconds=rng.randint(200, 1500))
|
|
||||||
|
|
||||||
data = _synthetic_jpeg(FRAME_WIDTH, FRAME_HEIGHT, seed=capture_id.int % (2**31))
|
|
||||||
relative = relative_image_path(capture_id, received)
|
|
||||||
write_atomically(settings.image_root / relative, data)
|
|
||||||
|
|
||||||
capture = Capture(
|
|
||||||
id=capture_id,
|
|
||||||
device_id=device.id,
|
|
||||||
path=relative,
|
|
||||||
sha256=secrets.token_hex(32),
|
|
||||||
width=FRAME_WIDTH,
|
|
||||||
height=FRAME_HEIGHT,
|
|
||||||
bytes=len(data),
|
|
||||||
captured_at_device=captured,
|
|
||||||
received_at=received,
|
|
||||||
trigger="radar" if rng.random() < 0.9 else "manual",
|
|
||||||
burst_id=burst_id,
|
|
||||||
burst_index=index,
|
|
||||||
burst_count=burst_size,
|
|
||||||
# The first frame or two come out of the pre-trigger ring, and
|
|
||||||
# are usually the good ones -- the bird is still arriving.
|
|
||||||
pre_trigger=index < (1 if burst_size < 4 else 2),
|
|
||||||
frame_seq=made + index,
|
|
||||||
radar_state=rng.choice([1, 2, 3]),
|
|
||||||
radar_distance_cm=rng.randint(60, 320),
|
|
||||||
radar_energy=rng.randint(20, 100),
|
|
||||||
battery_mv=None,
|
|
||||||
rssi=rng.randint(-82, -45),
|
|
||||||
temp_c=round(rng.uniform(2.0, 26.0), 1),
|
|
||||||
reviewed=rng.random() < 0.2,
|
|
||||||
kept=rng.random() > 0.1,
|
|
||||||
)
|
|
||||||
|
|
||||||
if thumbnails:
|
|
||||||
thumb_relative = relative_thumb_path(capture_id)
|
|
||||||
thumb_bytes, _ = make_thumbnail(settings.image_root / relative)
|
|
||||||
write_atomically(settings.thumb_root / thumb_relative, thumb_bytes)
|
|
||||||
capture.thumb_path = thumb_relative
|
|
||||||
|
|
||||||
db.add(capture)
|
|
||||||
|
|
||||||
made += burst_size
|
|
||||||
# Commit per burst, so interrupting a long run leaves whole bursts
|
|
||||||
# rather than a half-written one, and so 500 rows are not one
|
|
||||||
# transaction held open across 500 image encodes.
|
|
||||||
db.commit()
|
|
||||||
if progress and made % 50 < burst_size:
|
|
||||||
print(f" {made}/{count}")
|
|
||||||
|
|
||||||
return made
|
|
||||||
|
|
||||||
|
|
||||||
def clear(db: Session) -> tuple[int, int]:
|
|
||||||
"""Delete every seeded capture and device. Returns (captures, devices).
|
|
||||||
|
|
||||||
Scoped to seed devices by ``device_uid`` prefix, which is the whole reason
|
|
||||||
that prefix exists. A real camera's captures are never in scope, and this
|
|
||||||
command therefore cannot be the thing that loses them.
|
|
||||||
"""
|
|
||||||
devices = db.scalars(select(Device).where(Device.device_uid.startswith(SEED_UID_PREFIX))).all()
|
|
||||||
if not devices:
|
|
||||||
return 0, 0
|
|
||||||
|
|
||||||
settings = get_settings()
|
|
||||||
device_ids = [d.id for d in devices]
|
|
||||||
captures = db.scalars(select(Capture).where(Capture.device_id.in_(device_ids))).all()
|
|
||||||
|
|
||||||
for capture in captures:
|
|
||||||
(settings.image_root / capture.path).unlink(missing_ok=True)
|
|
||||||
if capture.thumb_path:
|
|
||||||
(settings.thumb_root / capture.thumb_path).unlink(missing_ok=True)
|
|
||||||
|
|
||||||
# Thumbnail jobs reference captures that are about to stop existing. The
|
|
||||||
# handler already tolerates a missing capture -- retention will do this
|
|
||||||
# routinely in Phase 5 -- but leaving them means the worker waking up to do
|
|
||||||
# pointless work and logging about it, which looks like a fault later.
|
|
||||||
capture_ids = [str(c.id) for c in captures]
|
|
||||||
if capture_ids:
|
|
||||||
db.execute(
|
|
||||||
delete(Job).where(
|
|
||||||
Job.kind == "thumbnail",
|
|
||||||
Job.payload["capture_id"].astext.in_(capture_ids),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
db.execute(delete(Capture).where(Capture.device_id.in_(device_ids)))
|
|
||||||
db.execute(delete(Device).where(Device.id.in_(device_ids)))
|
|
||||||
db.commit()
|
|
||||||
return len(captures), len(devices)
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
"""TOTP second factor (TODO 3.0, SPEC Q14).
|
|
||||||
|
|
||||||
Built now rather than later, on purpose. Retrofitting 2FA means reopening the
|
|
||||||
login flow, the session model, the user model and the audit log at once, and
|
|
||||||
``users.totp_secret`` was in the schema from Phase 1 for exactly this.
|
|
||||||
|
|
||||||
Policy, from TODO 3.0: **enforced for ``admin``, opt-in for everyone else.**
|
|
||||||
Over Tailscale the network layer already demands an enrolled device, so UI 2FA
|
|
||||||
is belt-and-braces; the day this is served from a public domain it stops being
|
|
||||||
optional. A ``require_2fa`` server setting flips the whole thing.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import pyotp
|
|
||||||
|
|
||||||
# RFC 6238 defaults, which is also what every authenticator app assumes.
|
|
||||||
DIGITS = 6
|
|
||||||
PERIOD_S = 30
|
|
||||||
|
|
||||||
# Accept the adjacent 30-second steps as well as the current one, so a phone
|
|
||||||
# clock a few seconds out still works. One step either side is the usual
|
|
||||||
# compromise: three windows is 90 seconds of exposure rather than 30, and
|
|
||||||
# anything wider starts to matter.
|
|
||||||
VALID_WINDOW = 1
|
|
||||||
|
|
||||||
ISSUER = "poorBird"
|
|
||||||
|
|
||||||
|
|
||||||
def new_secret() -> str:
|
|
||||||
"""A fresh base32 secret for ``users.totp_secret``."""
|
|
||||||
return pyotp.random_base32()
|
|
||||||
|
|
||||||
|
|
||||||
def provisioning_uri(secret: str, username: str) -> str:
|
|
||||||
"""The ``otpauth://`` URI an authenticator app scans as a QR code."""
|
|
||||||
return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).provisioning_uri(
|
|
||||||
name=username, issuer_name=ISSUER
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def verify(secret: str | None, code: str | None) -> bool:
|
|
||||||
"""True if ``code`` is currently valid for ``secret``.
|
|
||||||
|
|
||||||
Returns False rather than raising for a missing secret, a missing code or a
|
|
||||||
malformed one. pyotp compares with ``hmac.compare_digest`` internally, so a
|
|
||||||
wrong code does not leak its position through timing.
|
|
||||||
|
|
||||||
**Known limitation:** a code stays valid for its whole window, so it can be
|
|
||||||
replayed within ~90 seconds by someone who observed it. Preventing that
|
|
||||||
needs the last-accepted counter persisted per user, which is a column this
|
|
||||||
schema does not have yet. Worth adding if this is ever exposed publicly;
|
|
||||||
on a Tailscale-only LAN the observer has already had to get onto the
|
|
||||||
network. Not silently ignored -- just not paid for yet.
|
|
||||||
"""
|
|
||||||
if not secret or not code:
|
|
||||||
return False
|
|
||||||
|
|
||||||
code = code.strip().replace(" ", "")
|
|
||||||
if not code.isdigit() or len(code) != DIGITS:
|
|
||||||
return False
|
|
||||||
|
|
||||||
return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).verify(
|
|
||||||
code, valid_window=VALID_WINDOW
|
|
||||||
)
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
from .main import run
|
|
||||||
|
|
||||||
__all__ = ["run"]
|
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
"""Job handlers.
|
|
||||||
|
|
||||||
A handler takes a session and a payload, and either returns (success) or
|
|
||||||
raises (retry, then park). Register with ``@handler("kind")``.
|
|
||||||
|
|
||||||
Phase 2 adds ``thumbnail``. Phase 5 adds ``backup``, ``retention`` and
|
|
||||||
``restore_test``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import uuid
|
|
||||||
from collections.abc import Callable
|
|
||||||
from datetime import UTC, datetime
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from pydantic import BaseModel, ValidationError
|
|
||||||
from sqlalchemy import delete, text
|
|
||||||
from sqlalchemy.orm import Session
|
|
||||||
|
|
||||||
from ..config import get_settings
|
|
||||||
from ..images import UndecodableImage, make_thumbnail, relative_thumb_path, write_atomically
|
|
||||||
from ..models import Capture
|
|
||||||
from ..models import Session as UserSession
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
Handler = Callable[[Session, dict[str, Any]], None]
|
|
||||||
HANDLERS: dict[str, Handler] = {}
|
|
||||||
|
|
||||||
|
|
||||||
def handler(kind: str) -> Callable[[Handler], Handler]:
|
|
||||||
def register(fn: Handler) -> Handler:
|
|
||||||
if kind in HANDLERS:
|
|
||||||
raise RuntimeError(f"duplicate handler for {kind!r}")
|
|
||||||
HANDLERS[kind] = fn
|
|
||||||
return fn
|
|
||||||
|
|
||||||
return register
|
|
||||||
|
|
||||||
|
|
||||||
@handler("noop")
|
|
||||||
def _noop(session: Session, payload: dict[str, Any]) -> None:
|
|
||||||
"""Smoke test for the queue. `poorbird enqueue noop` exercises the path."""
|
|
||||||
log.info("noop job ran", extra={"payload": payload})
|
|
||||||
|
|
||||||
|
|
||||||
class ThumbnailPayload(BaseModel):
|
|
||||||
"""Validated job payload (REVIEW SEC-003).
|
|
||||||
|
|
||||||
Job payloads are JSONB and nothing stops a malformed one being enqueued,
|
|
||||||
so a handler that indexes straight into the dict fails with a KeyError
|
|
||||||
three retries later instead of saying what was wrong.
|
|
||||||
"""
|
|
||||||
|
|
||||||
capture_id: uuid.UUID
|
|
||||||
|
|
||||||
|
|
||||||
@handler("thumbnail")
|
|
||||||
def _thumbnail(session: Session, payload: dict[str, Any]) -> None:
|
|
||||||
"""Build the WebP thumbnail for one capture.
|
|
||||||
|
|
||||||
Enqueued by /ingest after the frame is on disk and in the same
|
|
||||||
transaction as the capture row, so by the time this runs both exist.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
job = ThumbnailPayload.model_validate(payload)
|
|
||||||
except ValidationError as exc:
|
|
||||||
# Permanently wrong, not transient. Raising would spend three
|
|
||||||
# attempts rediscovering that the payload is still malformed.
|
|
||||||
log.error("thumbnail job payload is invalid", extra={"payload": payload, "error": str(exc)})
|
|
||||||
return
|
|
||||||
|
|
||||||
capture = session.get(Capture, job.capture_id)
|
|
||||||
if capture is None:
|
|
||||||
# Deleted between enqueue and now. Retention will do this routinely
|
|
||||||
# once Phase 5 exists, and it is not a failure.
|
|
||||||
log.info("thumbnail skipped, capture is gone", extra={"capture_id": str(job.capture_id)})
|
|
||||||
return
|
|
||||||
|
|
||||||
settings = get_settings()
|
|
||||||
source = settings.image_root / capture.path
|
|
||||||
|
|
||||||
if not source.is_file():
|
|
||||||
# The file should be there: ingest writes it before committing the
|
|
||||||
# row. Its absence is a real fault, and transient causes (a mount
|
|
||||||
# that has not come back yet) are worth retrying for.
|
|
||||||
raise FileNotFoundError(f"capture file missing: {source}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
data, (width, height) = make_thumbnail(source)
|
|
||||||
except UndecodableImage as exc:
|
|
||||||
# A frame that cannot be decoded will never decode. Record it and
|
|
||||||
# finish, rather than retrying twice more to learn the same thing.
|
|
||||||
log.warning(
|
|
||||||
"capture could not be decoded, leaving it without a thumbnail",
|
|
||||||
extra={"capture_id": str(capture.id), "path": capture.path, "error": str(exc)},
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
relative = relative_thumb_path(capture.id)
|
|
||||||
write_atomically(settings.thumb_root / relative, data)
|
|
||||||
|
|
||||||
capture.thumb_path = relative
|
|
||||||
# Ingest reads dimensions from the JPEG header, which can be missing or
|
|
||||||
# unparseable. This is the first full decode, so fill in what it missed.
|
|
||||||
if capture.width is None or capture.height is None:
|
|
||||||
capture.width, capture.height = width, height
|
|
||||||
|
|
||||||
session.commit()
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
"thumbnail written",
|
|
||||||
extra={"capture_id": str(capture.id), "path": relative, "bytes": len(data)},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@handler("purge_expired_sessions")
|
|
||||||
def _purge_expired_sessions(session: Session, payload: dict[str, Any]) -> None:
|
|
||||||
"""Delete expired WebUI sessions.
|
|
||||||
|
|
||||||
Housekeeping, not security: expiry is already enforced on every read
|
|
||||||
(api/sessions.resolve_session), so a row left here is inert and cannot
|
|
||||||
authenticate anything. This only stops the table growing for as long as the
|
|
||||||
server runs.
|
|
||||||
"""
|
|
||||||
result = session.execute(delete(UserSession).where(UserSession.expires_at <= datetime.now(UTC)))
|
|
||||||
session.commit()
|
|
||||||
if result.rowcount:
|
|
||||||
log.info("purged expired sessions", extra={"count": result.rowcount})
|
|
||||||
|
|
||||||
|
|
||||||
@handler("prune_expired_commands")
|
|
||||||
def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None:
|
|
||||||
"""Expire commands the device never came back for.
|
|
||||||
|
|
||||||
A queued wake_and_hold from three days ago should not fire the moment a
|
|
||||||
camera reconnects after an outage.
|
|
||||||
"""
|
|
||||||
result = session.execute(
|
|
||||||
text(
|
|
||||||
"""
|
|
||||||
UPDATE device_commands
|
|
||||||
SET ack_status = 'failed',
|
|
||||||
acked_at = now(),
|
|
||||||
result = 'expired before delivery'
|
|
||||||
WHERE expires_at IS NOT NULL
|
|
||||||
AND expires_at < now()
|
|
||||||
AND acked_at IS NULL
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
)
|
|
||||||
session.commit()
|
|
||||||
if result.rowcount:
|
|
||||||
log.info("expired stale device commands", extra={"count": result.rowcount})
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
"""Worker process: job queue consumer plus the scheduler.
|
|
||||||
|
|
||||||
Scheduling lives here rather than in systemd timers. SPEC 3.4 makes the backup
|
|
||||||
schedule and the retention policy UI-editable server settings, and a
|
|
||||||
UI-editable timer would mean the app writing unit files and calling
|
|
||||||
``daemon-reload`` behind a polkit rule. In-app, a schedule is a settings row.
|
|
||||||
(TODO Phase 1.2.)
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import signal
|
|
||||||
import threading
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from apscheduler.schedulers.background import BackgroundScheduler
|
|
||||||
|
|
||||||
from ..config import get_settings
|
|
||||||
from ..db import SessionLocal
|
|
||||||
from ..logging_setup import configure_logging
|
|
||||||
from . import queue
|
|
||||||
from .handlers import HANDLERS
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
_stop = threading.Event()
|
|
||||||
|
|
||||||
|
|
||||||
def _run_one(job: dict[str, Any]) -> None:
|
|
||||||
kind = job["kind"]
|
|
||||||
fn = HANDLERS.get(kind)
|
|
||||||
with SessionLocal() as session:
|
|
||||||
if fn is None:
|
|
||||||
queue.fail(session, job["id"], f"no handler registered for {kind!r}")
|
|
||||||
log.error("unknown job kind", extra={"kind": kind, "job_id": job["id"]})
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
fn(session, job["payload"] or {})
|
|
||||||
except Exception as exc: # noqa: BLE001 - a handler must not kill the worker
|
|
||||||
session.rollback()
|
|
||||||
log.exception("job failed", extra={"kind": kind, "job_id": job["id"]})
|
|
||||||
queue.fail(session, job["id"], f"{type(exc).__name__}: {exc}")
|
|
||||||
else:
|
|
||||||
queue.complete(session, job["id"])
|
|
||||||
log.info("job done", extra={"kind": kind, "job_id": job["id"]})
|
|
||||||
|
|
||||||
|
|
||||||
def _build_scheduler() -> BackgroundScheduler:
|
|
||||||
"""Periodic work, enqueued rather than executed inline.
|
|
||||||
|
|
||||||
The scheduler only ever *enqueues*. That keeps every unit of work in one
|
|
||||||
place -- the queue -- where it is visible, retried and auditable, instead
|
|
||||||
of some jobs running inside a timer callback where a failure disappears.
|
|
||||||
"""
|
|
||||||
scheduler = BackgroundScheduler(timezone="UTC")
|
|
||||||
|
|
||||||
def _enqueue(kind: str) -> None:
|
|
||||||
with SessionLocal() as session:
|
|
||||||
queue.enqueue(session, kind)
|
|
||||||
session.commit()
|
|
||||||
|
|
||||||
scheduler.add_job(
|
|
||||||
lambda: _enqueue("prune_expired_commands"),
|
|
||||||
"interval",
|
|
||||||
minutes=15,
|
|
||||||
id="prune_expired_commands",
|
|
||||||
max_instances=1,
|
|
||||||
coalesce=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Hourly is plenty: expired sessions are already refused on read, so this
|
|
||||||
# is only stopping the table from growing.
|
|
||||||
scheduler.add_job(
|
|
||||||
lambda: _enqueue("purge_expired_sessions"),
|
|
||||||
"interval",
|
|
||||||
hours=1,
|
|
||||||
id="purge_expired_sessions",
|
|
||||||
max_instances=1,
|
|
||||||
coalesce=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _reclaim() -> None:
|
|
||||||
with SessionLocal() as session:
|
|
||||||
queue.requeue_stale(session)
|
|
||||||
|
|
||||||
scheduler.add_job(
|
|
||||||
_reclaim, "interval", minutes=5, id="requeue_stale", max_instances=1, coalesce=True
|
|
||||||
)
|
|
||||||
|
|
||||||
# Phase 5 adds: backup (schedule from the settings table), retention,
|
|
||||||
# restore_test (monthly).
|
|
||||||
return scheduler
|
|
||||||
|
|
||||||
|
|
||||||
def run() -> int:
|
|
||||||
settings = get_settings()
|
|
||||||
configure_logging(settings.log_level, settings.log_format)
|
|
||||||
|
|
||||||
def _handle_signal(signum: int, _frame: Any) -> None:
|
|
||||||
log.info("shutdown requested", extra={"signal": signum})
|
|
||||||
_stop.set()
|
|
||||||
|
|
||||||
signal.signal(signal.SIGTERM, _handle_signal)
|
|
||||||
signal.signal(signal.SIGINT, _handle_signal)
|
|
||||||
|
|
||||||
scheduler = _build_scheduler()
|
|
||||||
scheduler.start()
|
|
||||||
log.info(
|
|
||||||
"poorbird worker started",
|
|
||||||
extra={"worker": queue.WORKER_ID, "handlers": sorted(HANDLERS)},
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
# One job per claim, deliberately. The review suggested claiming in
|
|
||||||
# batches of 5, but this loop already runs jobs back to back without
|
|
||||||
# sleeping while the queue has work, so a batch would only save claim
|
|
||||||
# round-trips -- and it would cost crash safety. Claiming 5 marks all 5
|
|
||||||
# 'running'; dying after the first leaves four locked by a process that
|
|
||||||
# no longer exists, invisible until requeue_stale gets to them up to 15
|
|
||||||
# minutes later. Single claims keep exactly one job at risk.
|
|
||||||
while not _stop.is_set():
|
|
||||||
try:
|
|
||||||
with SessionLocal() as session:
|
|
||||||
job = queue.claim(session)
|
|
||||||
except Exception: # noqa: BLE001 - a DB blip must not end the worker
|
|
||||||
log.exception("could not reach the database; backing off")
|
|
||||||
_stop.wait(5.0)
|
|
||||||
continue
|
|
||||||
|
|
||||||
if job is None:
|
|
||||||
_stop.wait(settings.worker_poll_interval_s)
|
|
||||||
continue
|
|
||||||
|
|
||||||
_run_one(job)
|
|
||||||
finally:
|
|
||||||
scheduler.shutdown(wait=False)
|
|
||||||
log.info("poorbird worker stopped")
|
|
||||||
|
|
||||||
return 0
|
|
||||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user