Merge branch 'mega' into feature/ESP32_IDF_5_1

This commit is contained in:
TD-er
2023-11-27 17:07:02 +01:00
committed by GitHub
48 changed files with 4824 additions and 4 deletions
+182
View File
@@ -0,0 +1,182 @@
.. include:: ../Plugin/_plugin_substitutions_p15x.repl
.. _P159_page:
|P159_typename|
==================================================
|P159_shortinfo|
Plugin details
--------------
Type: |P159_type|
Name: |P159_name|
Status: |P159_status|
GitHub: |P159_github|_
Maintainer: |P159_maintainer|
Used libraries: |P159_usedlibraries|
Description
-----------
Detecting (human) presence can be achieved in several ways, like via IR detection sensors, or a light-beam that's interrupted by someone passing. But these sensors have quite some limitations, like limited sensitivity, no information about the distance, or weather a person is there but not moving.
The limitations of these existing sensors are not applicable when using radar-based presence detection, and since some time, rather affordable radar human-presence detectors are available. These are available with 5 GHz, 10 GHz, 24 GHz and 60 GHz radar frequency transmitter/receiver chips. Because of the accuracy and range, achievable with 24 GHz sensors, these are quite popular, so support has been added to ESPEasy.
Some examples of these sensors:
.. image:: P159_ld2410b.png
:width: 250px
:alt: LD2410b with bluetooth support, 35 x 7 mm in size
LD2410b with bluetooth support, 35 x 7 mm in size
.. image:: P159_ld2410c.png
:width: 250px
:alt: LD2410c, 22 x 15 mm in size
LD2410c, 22 x 15 mm in size
(Images are sourced from AliExpress vendors)
Configuration
-------------
.. image:: P159_DeviceConfiguration.png
* **Name**: Required by ESPEasy, must be unique among the list of available devices/tasks.
* **Enabled**: The device can be disabled or enabled. When not enabled the device should not use any resources.
Sensor
^^^^^^
See: :ref:`SerialHelper_page`
For this sensor, only the **Serial port**, and for ESP32 or Software Serial, the GPIO selection options are available.
.. warning:: The ``SWSerial`` option should better not be used, because of the high speed (256000 baud) that is used for the serial connection!
Device Settings
^^^^^^^^^^^^^^^
* **Engineering mode**: With this option set ``Yes``, when changed the settings will be saved and the page reloaded, several extra Values are made available for selection. When not using the extra values available, **Engineering mode** should best be set to ``No`` to lower the system-load.
.. image:: P159_EngineeringMode.png
* *Available options*: **Yes** or **No** (the default).
* **Generate Events only when changed**: Checking this option prevents sending an event if none of the values has changed on the next **Interval**.
Output Configuration
^^^^^^^^^^^^^^^^^^^^
* **Number Output Values**: Select the number of values that should be available. Default set to ``Quad`` (4).
.. image:: P159_NumberOutputValues.png
* Select from **Single** (1) to **Quad** (4).
After submitting the page, the number of Values will be changed to the selected number.
* **Value 1** .. **Value 4**: For each Value the desired data can be configured, depending on the setting for **Engineering mode**, the available options are adjusted.
* Engineering mode = **No**:
.. image:: P159_ValueOptionsStandard.png
* Engineering mode = **Yes**:
.. image:: P159_ValueOptionsEngineering1.png
.. image:: P159_ValueOptionsEngineering2.png
Available options:
* *Presence*: 0 = No presence, 1 = Presence detected
* *Stationairy presence*: 0 = No stationary presence, 1 = Stationary presence detected (Stationairy = non-moving person)
* *Moving presence*: 0 = No moving presence, 1 = Moving presence detected
* *Object distance*: Distance of the detected presence, in cm.
* *Stationary Object distance*: Distance of the detected stationary presence, in cm.
* *Moving Object distance*: Distance of the detected moving presence, in cm.
* *Stationary Object energy*: Energy level of the detected stationary presence, undefined unit, range 0..100.
* *Moving Object energy*: Energy level of the detected moving presence, undefined unit, range 0..100.
Engineering mode enabled:
* *Ambient light sensor*: If the unit includes an ambient light sensor, and many do, then this will hold the light level, undefined unit, range 0..255. This is an undocumented setting from the device, only usable on boards that have this sensor installed.
* *Output pin state*: This reflects the **Out** pin, available on most boards. This is an undocumented setting from the device.
* *Stationary Object energy gate 0..8*: 9 selections of the Stationary Object energy level for each 'gate' (the concept of gates is explained below)
* *Moving Object energy gate 0..8*: 9 selections of the Moving Object energy level for each 'gate'
.. * *Stationary sensitivity gate 0..8*: 9 selections of the configured Stationary sensitivity level for each 'gate'
.. * *Moving sensitivity gate 0..8*: 9 selections of the configured Moving sensitivity level for each 'gate'
Sensitivity settings
^^^^^^^^^^^^^^^^^^^^
Once the task is enabled, and a sensor is connected, extra configuration settings are available, that are disabled by default, and show the current configuration, as read from the sensor. To change any of these settings, the **Modify sensor settings** checkbox must be enabled, and the input fields will be enabled. The settings available are for configuring the idle time, number of active gates and sensitivity per gate.
A **gate** is an area in view of the sensor. Each gate is aproximately 75 cm distance (sequentially) from the sensor, and the highest active gate-number, default set to the max. value, is 8 (number starts at 0, so there are 9 gates). These active gates can be configured separately for detecting Moving and Stationary objects/persons. The lowest gate-number that can be selected is 2.
.. image:: P159_SensitivitySettings.png
By default, the **Modify sensor settings** checkbox is unchecked.
After checking the checkbox to enabled state, the settings will be available immediately:
.. image:: P159_SensitivitySettingsEnabled.png
* **Firmware version**: The version of the firmware installed on the sensor. The version shown in the screenshots is only shown as informational, and not a required value. For the Bluetooth enabled LD2410b sensor, updates for the firmware, when available, can be installed by using the LD2410 Mobile phone app. This firmware update feature is not available from ESPEasy.
* **Modify sensor settings**: Enable the checkbox to change the sensitivity settings, and store these in the sensor when the page is Submitted.
* **Idle seconds**: The number of seconds the *Presence* stays active after presence is removed, can be set here. Default value 5 sec. max. value is 65535 sec.
* **Max. Moving gates**: The number of active gates for detecting Moving presence. Range 2 .. 8.
* **Max. Stationary gates**: The number of active gates for detecting Stationary presence. Range 2 .. 8.
* **Sensitivity, Gate 0 .. 8**: For each type of detection, the sensitivity treshold can be set, range 0 .. 100, where 0 is the most sensitive, and 100 means it won't trigger, as that's the max. value that will be reported.
For each gate the distance range in meters is also shown. When the highest enabled Gate is less that the default 8, then only up to that gate-number is shown and configurable.
If the **Modify sensor settings** checkbox is checked when submitting the page, the settings are sent to the sensor, and the sensor will be restarted to activate them. The configured values are persistently stored in the LD2410 sensor.
Might the configuration not be set correctly, and changing them again doesn't seem to work, then resetting the sensor, by issuing the ``ld2410,factoryreset`` command while the task is enabled and the sensor connected, the factory defaults will be restored. (See the list of supported commands, below.)
Data Acquisition
^^^^^^^^^^^^^^^^
This group of settings, **Single event with all values** and **Send to Controller** settings are standard available configuration items. Send to Controller is only visible when one or more Controllers are configured.
* **Interval** By default, Interval will be set to 0 sec. as this is optional for this device. The data will be collected and optionally sent to any configured controllers using this interval. For sending the values to the enabled controller(s), the command ``TaskRun,<taskName|taskNr>`` can be used.
Values
^^^^^^
The plugin provides user configurable values, where the names will be changed according to the selected sensor value. A formula can be set to recalculate. The number of decimals can be set as desired, and defaults to 0.
In selected builds, per Value is a **Stats** checkbox available, that when checked, gathers the data and presents recent data in a graph, as described here: :ref:`Task Value Statistics: <Task Value Statistics>`
Commands available
^^^^^^^^^^^^^^^^^^
.. include:: P159_commands.repl
Get Config Values
^^^^^^^^^^^^^^^^^
Get Config Values retrieves values or settings from the sensor or plugin, and can be used in Rules, Display plugins, Formula's etc. The square brackets **are** part of the variable. Replace ``<taskname>`` by the **Name** of the task.
.. include:: P159_config_values.repl
Change log
----------
.. versionchanged:: 2.0
...
|added|
2023-11-13 Initial release version.
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+14
View File
@@ -0,0 +1,14 @@
.. csv-table::
:header: "Command Syntax", "Extra information"
:widths: 20, 30
"
``ld2410,factoryreset``
","
Sending this command to the task and a sensor is connected, then the sensor will be reset to the factory default settings, and restarted. There are no questions asked or extra arguments to provide. Use with caution of you have carefully configured, f.e. the sensitivity settings.
"
"
``ld2410,logall``
","
This command will send all available sensor values (see below) to the log at INFO level. This can be viewed via an USB serial connection, when the Serial console is enabled, or via another log view, like the Tools/Log page. The minimum log level has to be set to INFO for the values to be shown.
"
@@ -0,0 +1,74 @@
.. csv-table::
:header: "Config value", "Information"
:widths: 20, 30
"
``[<taskname>#Presence]``
","
Returns the currently reported Presence state, 0 (no presence) or 1 (presence detected)
"
"
``[<taskname>#StatPres]``
","
Returns the currently reported Stationary Presence state, 0 (no presence) or 1 (presence detected)
"
"
``[<taskname>#MovPres]``
","
Returns the currently reported Moving Presence state, 0 (no presence) or 1 (presence detected)
"
"
``[<taskname>#Distance]``
","
Returns the distance of the detected object from the sensor, in cm.
"
"
``[<taskname>#StatDist]``
","
Returns the distance of the detected Stationary object from the sensor, in cm.
"
"
``[<taskname>#MovDist]``
","
Returns the distance of the detected Moving object from the sensor, in cm.
"
"
``[<taskname>#StatEnergy]``
","
Returns the energy level of the detected Stationary object from the sensor, unknown unit, range 0..100.
"
"
``[<taskname>#MovEnergy]``
","
Returns the energy level of the detected Moving object from the sensor, unknown unit, range 0..100.
"
"
``[<taskname>#AmbLight]``
","
Returns the level of the ambient light, when available, unknown unit, range 0..255.
"
"
``[<taskname>#OutputPin]``
","
Returns the currently reported Output pin state, 0 (no presence) or 1 (presence detected)
"
"
``[<taskname>#StatEnergyGate0..8]``
","
Returns the energy level of the Stationary object per gate 0..8, unknown unit, value range 0..100.
"
"
``[<taskname>#MovEnergyGate0..8]``
","
Returns the energy level of the Moving object per gate 0..8, unknown unit, value range 0..100.
"
"
``[<taskname>#StatSensGate0..8]``
","
Returns the configured sensitivity level of the Stationary object per gate 0..8, unknown unit, value range 0..100.
"
"
``[<taskname>#MovSensGate0..8]``
","
Returns the configured sensitivity level of the Moving object per gate 0..8, unknown unit, value range 0..100.
"
Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

+6
View File
@@ -385,6 +385,7 @@ There are different released versions of ESP Easy:
":ref:`P152_page`","|P152_status|","P152"
":ref:`P153_page`","|P153_status|","P153"
":ref:`P154_page`","|P154_status|","P154"
":ref:`P159_page`","|P159_status|","P159"
Internal GPIO handling
@@ -541,6 +542,11 @@ Power management
Plugins: |Plugin_PowerMgt|
Presence
---------
Plugins: |Plugin_Presence|
Regulator
---------
@@ -25,6 +25,7 @@
.. |Plugin_Output| replace:: :ref:`P029_page`, :ref:`P038_page`, :ref:`P041_page`, :ref:`P042_page`, :ref:`P043_page`, :ref:`P070_page`, :ref:`P124_page`, :ref:`P126_page`, :ref:`P128_page`, :ref:`P152_page`
.. |Plugin_Position| replace:: :ref:`P082_page`, :ref:`P121_page`
.. |Plugin_PowerMgt| replace:: :ref:`P137_page`, :ref:`P138_page`
.. |Plugin_Presence| replace:: :ref:`P159_page`
.. |Plugin_Regulator| replace:: :ref:`P021_page`
.. |Plugin_RFID| replace:: :ref:`P008_page`, :ref:`P017_page`, :ref:`P040_page`, :ref:`P111_page`
.. |Plugin_Switch_input| replace:: :ref:`P001_page`, :ref:`P009_page`, :ref:`P019_page`, :ref:`P059_page`, :ref:`P080_page`, :ref:`P091_page`, :ref:`P097_page`, :ref:`P143_page`
@@ -62,3 +62,16 @@
.. |P154_maintainer| replace:: `TD-er`
.. |P154_compileinfo| replace:: `.`
.. |P154_usedlibraries| replace:: `Adafruit BMP3XX Library`
.. |P159_name| replace:: :cyan:`LD2410`
.. |P159_type| replace:: :cyan:`Presence`
.. |P159_typename| replace:: :cyan:`Presence - LD2410`
.. |P159_porttype| replace:: `.`
.. |P159_status| replace:: :yellow:`COLLECTION G`
.. |P159_github| replace:: P159_LD2410.ino
.. _P159_github: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P159_LD2410.ino
.. |P159_usedby| replace:: `.`
.. |P159_shortinfo| replace:: `LD2410 24 GHz Radar human presence detection sensor`
.. |P159_maintainer| replace:: `tonhuisman`
.. |P159_compileinfo| replace:: `.`
.. |P159_usedlibraries| replace:: `ncmreynolds/ld2410, with 'skoona' and ESPEasy specific enhancements`
+504
View File
@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+89
View File
@@ -0,0 +1,89 @@
# LD2410
## Introduction
An Arduino library for the Hi-Link LD2410 24Ghz FMCW radar sensor. This sensor is a Frequency Modulated Continuous Wave radar, which makes it good for presence detection and its sensitivity at different ranges to both static and moving targets can be configured.
![](ld2410andbreakout.jpg)
The code in this library is based heavily off this [piece of work for ESPHome](https://github.com/rain931215/ESPHome-LD2410) and the manufacturer datasheet.
The LD2410, as sold for configuration with the common breakout boards shown above communicates over serial at 256000 baud by default. This library allows you to configure and use the sensor over this serial connection. As the LD2410 is a device that uses a high baud rate, a microcontroller with a spare hardware UART for this communication is preferable to bit-banged software serial.
The modules also provide an 'active high' output on the 'OUT' pin which can be used to signal presence, based off the settings configured. Once the modules are configured it is not necessary to use their UART, but it provides much more information.
## Connections
The module must be powered by 5V or higher, but does 3.3v I/O, please consider this when working with the module.
![](ld2410pinout.jpg)
The default header pitch is 1.27mm, half the size of the usual 0.1" hobbyist pin headers so you may need to buy some, or carefully de-solder the existing pins to use the module.
![](ld2410pcb.jpg)
If you have the breakout board, you can use the VCC, GND, TX and RX pins to work with the module.
## Reading distances
The LD2410 has a number of 'gates', each of which correspond to a distance of about 0.75m and many of the settings/measurements are calculated from this.
You set the sensitivity at each 'gate' on a scale 0-100, any object that doesn't register above this scale is not reported on. The defaults do a good job of spotting an adult person and estimating distance.
Both moving and stationary targets are detected separately, with a value for each in centimetres. The accuracy of this distance isn't amazing but given this sensor is targeted as a replacement for something like a passive infrared sensor it's a very big improvement.
The minimal sketch to read distances is in the example 'basicSensor.ino'.
## Configuring the sensor
Each 'gate' has a sensitivity value for stationary and moving targets. You can also set a maximum gate that ignores readings beyond a certain gate for both stationary and moving targets and an 'idle timeout' for how long it reports on something after moving away.
A sketch to configure the sensor is in the example 'setupSensor.ino' it's an interactive sketch that will take commands sent over the Serial monitor. It should demonstrate all the various bits of the configuration you can change.
## Methods/variables
Many of the configuration methods return a boolean value. This is because the protocol between the LD2410 and the microcontroller involves requesting the change and the LD2410 acknowledges this with success or failure. This means these methods are synchronous, they will block until the LD2410 responds with succeed/fail or the transaction times out after 100ms.
The presence/distance readings report the most recent values as the LD2410 continuously streams data, which is processed by calling *read()* as often as is practical.
```
bool ld2410::begin(Stream &radarStream, bool waitForRadar = true) - You must supply a Stream for the UART (eg. Serial1 that the LD2410 is connected to) and by default it waits for the radar to respond so it feeds back if it is connected
void debug(Stream &debugStream) - Enables debugging output of the library on a Stream you pass it (eg. Serial)
void read() - You must call this frequently in your main loop to process incoming frames from the LD2410
bool isConnected() - Is the LD2410 connected and sending data regularly
bool presenceDetected() - Is a presence detected. Nice and simple
bool stationaryTargetDetected() - Is a stationary target detected.
uint16_t stationaryTargetDistance() - Distance to the stationary target in centimetres.
uint8_t stationaryTargetEnergy() - The 'energy'of the target on a scale 0-100, which also a kind of confidence value.
bool movingTargetDetected() - Is a moving target detected.
uint16_t movingTargetDistance() - Distance to the moving target in centimetres.
uint8_t movingTargetEnergy() - The 'energy'of the target on a scale 0-100, which also a kind of confidence value.
bool requestFirmwareVersion() - Request the firmware version, which is then available on the values below.
uint8_t firmware_major_version
uint8_t firmware_minor_version
uint32_t firmware_bugfix_version - This is coded as HEX
bool requestCurrentConfiguration() - Request the full current configuration, which you can then read with the variable & methods below.
uint8_t max_gate - The max gate ID reported by the sensor
uint8_t max_moving_gate - The highest gate ID that will report moving targets
uint8_t max_stationary_gate - The highers gate ID that will report stationary targets
uint8_t motion_sensitivity[max_gate + 1] - One value 0-100 per gate
uint8_t stationary_sensitivity[max_gate + 1] - One value 0-100 per gate
bool setMaxValues(uint8_t moving, uint8_t stationary, uint16_t inactivityTimer) - Set furthest gates and inactivitity timer for targets
bool setGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary) - Set gate sensitivites 0-100
bool requestRestart() - Request a restart of the LD2410. Which is needed to apply some settings.
bool requestFactoryReset() - Request a factory reset of the LD2410. You need to restart afterwards to take effect.
bool requestStartEngineeringMode() - Request engineering mode, which sends more data on targets.
bool requestEndEngineeringMode() - Request the end of engineering mode.
```
## Changelog
- v0.1.1 - Readings for stationary and moving targets were transposed, now fixed. Fixes #1 - stationaryTargetDetected() always true. Many improvements to parsing of commands/acks from the LD2410 and better debug logging.
- v0.1.0 - Initial release
## Known issues/to-do list
The code is somewhat verbose/inefficient.
No support for engineering mode data yet.
Feel free to contact me with PRs, suggestions and improvements.
@@ -0,0 +1,411 @@
{
"frameEnd": "*/",
"frameParser": "/* \n * @brief Frame parsing function, you can modify this to suit your needs.\n * \n * By customizing this code, you can use a single JSON project file to \n * process different kinds of frames that are sent by the microcontroller \n * or any data source that is connected to Serial Studio. Frame parsing code\n * is specific to every JSON project that you create.\n *\n * @param frame string with the latest received frame.\n * @param separator data separator sequence defined by the JSON project.\n *\n * @note. only data that is *inside* the data delimiters will\n * be processed by the frame parser.\n *\n * @note you can safely declare global variables outside the\n * @c parse() function.\n */\nfunction parse(frame, separator) {\n return frame.split(separator);\n}",
"frameStart": "/*",
"groups": [
{
"datasets": [
{
"alarm": 0,
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 0,
"min": 0,
"title": "Moving",
"units": "cm",
"value": "%2",
"widget": ""
},
{
"alarm": 0,
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 0,
"min": 0,
"title": "Detection",
"units": "cm",
"value": "%3",
"widget": ""
},
{
"alarm": 50,
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Energy",
"units": "dBZ",
"value": "%4",
"widget": ""
}
],
"title": "Moving Target",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": 0,
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 0,
"min": 0,
"title": "Stationary",
"units": "cm",
"value": "%5",
"widget": ""
},
{
"alarm": 0,
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 0,
"min": 0,
"title": "Detection",
"units": "cm",
"value": "%6",
"widget": ""
},
{
"alarm": 50,
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 0,
"min": 0,
"title": "Energy",
"units": "dBZ",
"value": "%7",
"widget": ""
}
],
"title": "Stationary Target",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%8",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%9",
"widget": "gauge"
},
{
"alarm": "%10",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%11",
"widget": "gauge"
}
],
"title": "Gate 0",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%12",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%13",
"widget": "gauge"
},
{
"alarm": "%14",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%15",
"widget": "gauge"
}
],
"title": "Gate 1",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%16",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%17",
"widget": "gauge"
},
{
"alarm": "%18",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%19",
"widget": "gauge"
}
],
"title": "Gate 2",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%20",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%21",
"widget": "gauge"
},
{
"alarm": "%22",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%23",
"widget": "gauge"
}
],
"title": "Gate 3",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%24",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%25",
"widget": "gauge"
},
{
"alarm": "%26",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%27",
"widget": "gauge"
}
],
"title": "Gate 4",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%28",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%29",
"widget": "gauge"
},
{
"alarm": "%30",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%31",
"widget": "gauge"
}
],
"title": "Gate 5",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%32",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%33",
"widget": "gauge"
},
{
"alarm": "%34",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%35",
"widget": "gauge"
}
],
"title": "Gate 6",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%36",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%37",
"widget": "gauge"
},
{
"alarm": "%38",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%39",
"widget": "gauge"
}
],
"title": "Gate 7",
"widget": "multiplot"
},
{
"datasets": [
{
"alarm": "%40",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Movement Energy",
"units": "dBZ",
"value": "%41",
"widget": "gauge"
},
{
"alarm": "%42",
"fft": false,
"fftSamples": 1024,
"graph": true,
"led": false,
"log": false,
"max": 100,
"min": 0,
"title": "Static Energy",
"units": "dBZ",
"value": "%43",
"widget": "gauge"
}
],
"title": "Gate 8",
"widget": "multiplot"
}
],
"separator": ",",
"title": "%1"
}
+12
View File
@@ -0,0 +1,12 @@
Advanced udpToSerialStudio.cpp
SerialStudio reads the UDP output of the ESP and plots the various
data points. The ESP also has a command console on both Serial
and UDP port 8091, which allow configuration of LD2410 device.
You will need the JSON project file in this folder and the app "SerialStudio" at this link:
- https://github.com/Serial-Studio/Serial-Studio/releases
### This file maps to csv data: use via SerialStudio Setup option
ld2410-alarm-final.json buildWithAlarmSerialStudioCSV()
@@ -0,0 +1,488 @@
/*
* Example sketch for reporting on readings from the LD2410 using
* whatever settings are currently configured.
*
* The sketch assumes an ESP32 board with the LD2410 connected as Serial2
* on pins 16 & 17, the serial configuration for other boards may vary.
*
* Program broadcasts [reporting data] on port 8090, and listens on
* port 8091 for commands or configuration requests,
* responses are sent to callers ip/port as discovered.
*
* Where [reporting data], can be CSV-like, JSON with Short or Long attributes as
* documented in [SerialStudio's page](https://github.com/Serial-Studio/Serial-Studio/wiki/Communication-Protocol)
*
* WIFI_SSID and WIFI_PASS are double-quoted environment variables with related values,
* -- example: export PLATFORMIO_BUILD_FLAGS=-DWIFI_PASS='"ssid-password"' -DWIFI_SSID='"ssid-value"'
* or
* -- example: export WIFI_PASS='"ssid-password"'
* -- export WIFI_SSID='"ssid-value"'
*
* Gates:
* - each gate is 0.75m or 30 inches
* 0 to 9 gates = 6.75m or 22 feet ish
*
*
*/
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncUDP.h>
#include <ld2410.h>
#define RXD2 16 // 8
#define TXD2 17 // 9
#define MAX_COMMAND_TOKENS 32
#define SNAME "LD2410 Sensor 01"
#define SERIAL_STUDIO 1
#ifdef SERIAL_STUDIO
AsyncUDP udp;
#endif
const char* ssid = WIFI_SSID;
const char* ssidPassword = WIFI_PASS;
const uint16_t sendPort = 8090;
const uint16_t listenPort = 8091;
IPAddress ipSerialStudio(10,100,1,5);
uint16_t remotePort = 8090; // default value, will be overridden on reciept of udp request
IPAddress ipRemote(10,100,1,5); // default value, will be overridden on reciept of udp request
ld2410 radar;
volatile bool udpFlag = false; // send for callback
uint32_t lastReading = 0;
uint32_t pos = 0;
uint32_t pos1 = 0;
uint32_t pos2 = 0;
bool sending_enabled = true;
char buffer1[128];
char serialBuffer[256];
String command = "";
String output = "";
/*
* Available Commands */
String availableCommands() {
String sCmd = "";
sCmd += "\nSupported commands:";
sCmd += "\n\t( 1) help: this text.";
sCmd += "\n\t( 2) streamstart: start sending udp data to SerialStudio.";
sCmd += "\n\t( 3) streamstop: stop sending to SerialStream.";
sCmd += "\n\t( 4) read: read current values from the sensor";
sCmd += "\n\t( 5) readconfig: read the configuration from the sensor";
sCmd += "\n\t( 6) setmaxvalues <motion gate> <stationary gate> <inactivitytimer> (2-8) (0-65535)seconds";
sCmd += "\n\t( 7) setsensitivity <gate> <motionsensitivity> <stationarysensitivity> (2-8|255) (0-100)";
sCmd += "\n\t( 8) restart: restart the sensor";
sCmd += "\n\t( 9) readversion: read firmware version";
sCmd += "\n\t(10) factoryreset: factory reset the sensor";
sCmd += "\n\t(11) deviceinfo: LD2410 device info";
sCmd += "\n\t(12) reboot: reboot hosting micro-controller\n";
return sCmd;
}
/*
* Command Processor
* - there are two ommands not implemented
* - requestConfigurationModeBegin()
* - requestConfigurationModeEnd()
* Otherwise all commands are available as options
*/
String commandProcessor(String &cmdStr) {
String sBuf = "\n";
int iCmd = cmdStr.toInt();
cmdStr.trim();
if(cmdStr.equals("help") || iCmd == 1)
{
sBuf += availableCommands();
}
else if(cmdStr.equals("streamstart") || iCmd == 2)
{
sending_enabled = true;
sBuf += "\nSerialStudio UDP Stream Enabled. \n";
}
else if(cmdStr.equals("streamstop") || iCmd == 3)
{
sending_enabled = false;
sBuf += "\nSerialStudio UDP Stream Disabled.\n";
}
else if(cmdStr.equals("read") || iCmd == 4)
{
sBuf += "\nReading from sensor: ";
if(radar.isConnected())
{
sBuf += "OK\n";
if(radar.presenceDetected())
{
if(radar.stationaryTargetDetected())
{
sBuf += "Stationary target: ";
sBuf += radar.stationaryTargetDistance();
sBuf += " cm energy: ";
sBuf += radar.stationaryTargetEnergy();
sBuf += " dBZ\n";
}
if(radar.movingTargetDetected())
{
sBuf += "Moving target: ";
sBuf += radar.movingTargetDistance();
sBuf += " cm energy: ";
sBuf += radar.movingTargetEnergy();
sBuf += " dBZ\n";
}
if(!radar.stationaryTargetDetected() && !radar.movingTargetDetected()) {
sBuf += "No Detection, in Idle Hold window of: ";
sBuf += radar.cfgSensorIdleTimeInSeconds();
sBuf += " seconds\n";
}
}
else
{
sBuf += "\nnothing detected\n";
}
}
else
{
sBuf += "failed to read\n";
}
}
else if(cmdStr.equals("readconfig") || iCmd == 5)
{
sBuf += "\nReading configuration from sensor: ";
if(radar.requestCurrentConfiguration())
{
sBuf += "OK\n";
sBuf += "Maximum gate ID: ";
sBuf += radar.cfgMaxGate();
sBuf += "\n";
sBuf += "Maximum gate for moving targets: ";
sBuf += radar.cfgMaxMovingGate();
sBuf += "\n";
sBuf += "Maximum gate for stationary targets: ";
sBuf += radar.cfgMaxStationaryGate();
sBuf += "\n";
sBuf += "Idle time for targets: ";
sBuf += radar.cfgSensorIdleTimeInSeconds() ;
sBuf += "s\n";
sBuf += "Gate sensitivity\n";
for(uint8_t gate = 0; gate < LD2410_MAX_GATES; gate++)
{
sBuf += "Gate ";
sBuf += gate;
sBuf += " moving targets: ";
sBuf += radar.cfgMovingGateSensitivity(gate);
sBuf += " dBZ stationary targets: ";
sBuf += radar.cfgStationaryGateSensitivity(gate);
sBuf += " dBZ\n";
}
}
else
{
sBuf += "Failed\n";
}
}
else if(cmdStr.startsWith("setmaxvalues") || iCmd == 6)
{
uint8_t firstSpace = cmdStr.indexOf(' ');
uint8_t secondSpace = cmdStr.indexOf(' ',firstSpace + 1);
uint8_t thirdSpace = cmdStr.indexOf(' ',secondSpace + 1);
uint8_t newMovingMaxDistance = (cmdStr.substring(firstSpace,secondSpace)).toInt();
uint8_t newStationaryMaxDistance = (cmdStr.substring(secondSpace,thirdSpace)).toInt();
uint16_t inactivityTimer = (cmdStr.substring(thirdSpace,cmdStr.length())).toInt();
if(newMovingMaxDistance > 0 && newStationaryMaxDistance > 0 && newMovingMaxDistance <= 8 && newStationaryMaxDistance <= 8)
{
sBuf += "\nSetting max values to gate ";
sBuf += newMovingMaxDistance;
sBuf += " moving targets, gate ";
sBuf += newStationaryMaxDistance;
sBuf += " stationary targets, ";
sBuf += inactivityTimer;
sBuf += "s inactivity timer: ";
if(radar.setMaxValues(newMovingMaxDistance, newStationaryMaxDistance, inactivityTimer))
{
sBuf += "OK, now restart to apply settings\n";
}
else
{
sBuf += "failed\n";
}
}
else
{
sBuf += "Can't set distances to ";
sBuf += newMovingMaxDistance;
sBuf += " moving ";
sBuf += newStationaryMaxDistance;
sBuf += " stationary, try again\n";
}
}
else if(cmdStr.startsWith("setsensitivity") || iCmd == 7)
{
uint8_t firstSpace = cmdStr.indexOf(' ');
uint8_t secondSpace = cmdStr.indexOf(' ',firstSpace + 1);
uint8_t thirdSpace = cmdStr.indexOf(' ',secondSpace + 1);
uint8_t gate = (cmdStr.substring(firstSpace,secondSpace)).toInt();
uint8_t motionSensitivity = (cmdStr.substring(secondSpace,thirdSpace)).toInt();
uint8_t stationarySensitivity = (cmdStr.substring(thirdSpace,cmdStr.length())).toInt();
// Command method 1 -- limit gate to 0-8 -- set one gate set
// Command method 2 -- limit gate to 255 -- set all gates to same sensitivity value
if(motionSensitivity >= 0 && stationarySensitivity >= 0 && motionSensitivity <= 100 && stationarySensitivity <= 100)
{
sBuf += "\nSetting gate ";
sBuf += gate;
sBuf += " motion sensitivity to ";
sBuf += motionSensitivity;
sBuf += " dBZ & stationary sensitivity to ";
sBuf += stationarySensitivity;
sBuf += " dBZ: \n";
if(radar.setGateSensitivityThreshold(gate, motionSensitivity, stationarySensitivity))
{
sBuf += "OK, now restart to apply settings\n";
}
else
{
sBuf += "failed\n";
}
}
else
{
sBuf += "Can't set gate ";
sBuf += gate;
sBuf += " motion sensitivity to ";
sBuf += motionSensitivity;
sBuf += " dBZ & stationary sensitivity to ";
sBuf += stationarySensitivity;
sBuf += " dBZ, try again\n";
}
}
else if(cmdStr.equals("restart") || iCmd ==8)
{
if(radar.requestRestart())
{
delay(1500);
if(radar.requestStartEngineeringMode()) {
sBuf += "\nRestarting sensor: OK\n";
}
}
else
{
sBuf += "\nRestarting sensor: failed\n";
}
}
else if(cmdStr.equals("readversion") || iCmd == 9)
{
sBuf += "\nRequesting firmware version: ";
if(radar.requestFirmwareVersion())
{
sBuf += radar.cmdFirmwareVersion();
}
else
{
sBuf += "Failed\n";
}
}
else if(cmdStr.equals("factoryreset") || iCmd == 10)
{
sBuf += "\nFactory resetting sensor: ";
if(radar.requestFactoryReset())
{
sBuf += "OK, now restart sensor to take effect\n";
}
else
{
sBuf += "failed\n";
}
}
else if(cmdStr.equals("deviceinfo") || iCmd == 11)
{
sBuf += "\nLD2410 Device Information: \n";
sBuf += "Data reporting mode: ";
sBuf += (radar.isEngineeringMode() ? "Engineering Mode" : "Target Mode");
sBuf += "\nCommunication protocol version: v";
sBuf += radar.cmdProtocolVersion();
sBuf += ".0\nCommunications Buffer Size: ";
sBuf += radar.cmdCommunicationBufferSize();
sBuf += " bytes\nDevice firmare version: ";
sBuf += radar.cmdFirmwareVersion();
sBuf += "\tEngineering retain data value: ";
sBuf += radar.engRetainDataValue();
sBuf += "\n";
}
else if(cmdStr.equals("reboot") || iCmd == 12)
{
ESP.restart();
}
else
{
sBuf += "\nUnknown command: ";
sBuf += cmdStr;
sBuf += "\n";
}
cmdStr.clear();
sBuf += "\n choose:> ";
return sBuf;
}
/*
* Accepts Serial chars and process chars as a command
* when the newline char is received
*/
void commandHandler() {
if(Serial.available())
{
char typedCharacter = Serial.read();
if(typedCharacter == '\n') {
Serial.print( commandProcessor(command) );
} else {
Serial.print(typedCharacter);
if(typedCharacter != '\r') { // effectively ignore CRs
command += typedCharacter;
}
}
}
}
#ifdef SERIAL_STUDIO
/*
* Send data via UDP */
void sendToRequestor(String str, bool requestor = false) {
if(requestor) {
udp.connect(ipRemote,remotePort);
} else {
udp.connect(ipSerialStudio,sendPort);
}
// Serial.printf("DEBUG: SizeOf(serialBuffer)=%d Length(str)=%d Contents:%s", sizeof(serialBuffer), str.length(), str.c_str());
udp.print(str);
return udp.close();
}
#endif
/*
* CSV like Values for SerialStudio App - see test folder */
// %1,2,3, 4, 5,6,7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43
/*LD2410 Sensor 01,0,0,62,43,0,0,50,15, 0, 0,50,15, 0, 0,40, 5,40,62,30, 9,40,45,20, 3,30,25,15, 6,30,18,15, 1,20,10,15, 2,20, 8,15, 7,20, 6*/
String buildWithAlarmSerialStudioCSV() {
pos = snprintf(serialBuffer,sizeof(serialBuffer),"/*%s,%d,%d,%d,%d,%d,%d,",SNAME,radar.stationaryTargetDistance(),radar.detectionDistance(), radar.stationaryTargetEnergy(),radar.movingTargetDistance(), radar.detectionDistance(), radar.movingTargetEnergy());
for(int x = 0; x < LD2410_MAX_GATES; ++x) {
pos1 = snprintf(buffer1,sizeof(buffer1),"%d,%d,%d,%d,", radar.cfgMovingGateSensitivity(x), radar.engMovingDistanceGateEnergy(x), radar.cfgStationaryGateSensitivity(x), radar.engStaticDistanceGateEnergy(x));
strcat(serialBuffer, buffer1);
pos += pos1;
}
serialBuffer[--pos] = 0;
strcat(serialBuffer, "*/\n");
return String(serialBuffer);
}
void setup(void)
{
delay(1000);
// start console path
Serial.begin(115200);
delay(250);
// start path to LD2410
// radar.debug(Serial);
Serial2.begin (256000, SERIAL_8N1, RXD2, TXD2); //UART for monitoring the radar rx, tx
#ifdef SERIAL_STUDIO
// Start WiFi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, ssidPassword);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("WiFi connected with IP: ");
Serial.println(WiFi.localIP());
// 10.100.1.186
if(udp.listen(listenPort)) {
Serial.print(F("Client Listening on port: "));
Serial.println(listenPort);
udp.onPacket([](AsyncUDPPacket packet) {
Serial.print("UDP Packet Type: ");
Serial.print(packet.isBroadcast() ? "Broadcast" : packet.isMulticast() ? "Multicast" : "Unicast");
Serial.print(", From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.print(packet.remotePort());
Serial.print(", To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.print(packet.localPort());
Serial.print(", Length: ");
Serial.print(packet.length());
Serial.print(", Data: ");
Serial.write(packet.data(), packet.length());
Serial.println();
// save path for response when using udp
ipRemote = packet.remoteIP();
remotePort = packet.remotePort();
// Parse Commands -- executing inside a callback can be problematic
// Using udpFlag to have loop handle it
command = (const char*)packet.data();
udpFlag=true;
});
}
Serial.println(F("Client Initialized..."));
#endif
// Start LD2410 Sensor
if(radar.begin(Serial2))
{
Serial.println(F("Sensor Initialized..."));
delay(500);
radar.requestStartEngineeringMode();
}
else
{
Serial.println(F(" Sensor was not connected"));
}
Serial.println(F("setup() Complete..."));
Serial.println( availableCommands() );
Serial.print("\n choose> ");
}
void loop()
{
radar.ld2410_loop();
if(sending_enabled) {
if(radar.isConnected() && millis() - lastReading > 1000) //Report every 1000ms
{
lastReading = millis();
#ifdef SERIAL_STUDIO
sendToRequestor( buildWithAlarmSerialStudioCSV(), false );
#else
if(Serial.available()) {
Serial.print( buildWithAlarmSerialStudioCSV() );
}
#endif
}
}
#ifdef SERIAL_STUDIO
if(udpFlag && (command.length() > 1)) { // handle cb request
sendToRequestor(commandProcessor(command), true);
udpFlag=false;
command.clear();
}
#endif
commandHandler();
}
@@ -0,0 +1,120 @@
/*
* Example sketch for reporting on readings from the LD2410 using whatever settings are currently configured.
*
* This has been tested on the following platforms...
*
* On ESP32, connect the LD2410 to GPIO pins 32&33
* On ESP32S2, connect the LD2410 to GPIO pins 8&9
* On ESP32C3, connect the LD2410 to GPIO pins 4&5
* On Arduino Leonardo or other ATmega32u4 board connect the LD2410 to GPIO pins TX & RX hardware serial
*
* The serial configuration for other boards will vary and you'll need to assign them yourself
*
* There is no example for ESP8266 as it only has one usable UART and will not boot if the alternate UART pins are used for the radar.
*
* For this sketch and other examples to be useful the board needs to have two usable UARTs.
*
*/
#if defined(ESP32)
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 32
#define RADAR_TX_PIN 33
#elif CONFIG_IDF_TARGET_ESP32S2
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 9
#define RADAR_TX_PIN 8
#elif CONFIG_IDF_TARGET_ESP32C3
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 4
#define RADAR_TX_PIN 5
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 32
#define RADAR_TX_PIN 33
#endif
#elif defined(__AVR_ATmega32U4__)
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 0
#define RADAR_TX_PIN 1
#endif
#include <ld2410.h>
ld2410 radar;
uint32_t lastReading = 0;
bool radarConnected = false;
void setup(void)
{
MONITOR_SERIAL.begin(115200); //Feedback over Serial Monitor
//radar.debug(MONITOR_SERIAL); //Uncomment to show debug information from the library on the Serial Monitor. By default this does not show sensor reads as they are very frequent.
#if defined(ESP32)
RADAR_SERIAL.begin(256000, SERIAL_8N1, RADAR_RX_PIN, RADAR_TX_PIN); //UART for monitoring the radar
#elif defined(__AVR_ATmega32U4__)
RADAR_SERIAL.begin(256000); //UART for monitoring the radar
#endif
delay(500);
MONITOR_SERIAL.print(F("\nConnect LD2410 radar TX to GPIO:"));
MONITOR_SERIAL.println(RADAR_RX_PIN);
MONITOR_SERIAL.print(F("Connect LD2410 radar RX to GPIO:"));
MONITOR_SERIAL.println(RADAR_TX_PIN);
MONITOR_SERIAL.print(F("LD2410 radar sensor initialising: "));
if(radar.begin(RADAR_SERIAL))
{
MONITOR_SERIAL.println(F("OK"));
MONITOR_SERIAL.print(F("LD2410 firmware version: "));
MONITOR_SERIAL.print(radar.firmware_major_version);
MONITOR_SERIAL.print('.');
MONITOR_SERIAL.print(radar.firmware_minor_version);
MONITOR_SERIAL.print('.');
MONITOR_SERIAL.println(radar.firmware_bugfix_version, HEX);
}
else
{
MONITOR_SERIAL.println(F("not connected"));
}
}
void loop()
{
radar.read();
if(radar.isConnected() && millis() - lastReading > 1000) //Report every 1000ms
{
lastReading = millis();
if(radar.presenceDetected())
{
if(radar.stationaryTargetDetected())
{
Serial.print(F("Stationary target: "));
Serial.print(radar.stationaryTargetDistance());
Serial.print(F("cm energy:"));
Serial.print(radar.stationaryTargetEnergy());
Serial.print(' ');
}
if(radar.movingTargetDetected())
{
Serial.print(F("Moving target: "));
Serial.print(radar.movingTargetDistance());
Serial.print(F("cm energy:"));
Serial.print(radar.movingTargetEnergy());
}
Serial.println();
}
else
{
Serial.println(F("No target"));
}
}
}
@@ -0,0 +1,330 @@
/*
* Example sketch to show using configuration commands on the LD2410.
*
* This has been tested on the following platforms...
*
* On ESP32, connect the LD2410 to GPIO pins 32&33
* On ESP32S2, connect the LD2410 to GPIO pins 8&9
* On ESP32C3, connect the LD2410 to GPIO pins 4&5
* On Arduino Leonardo or other ATmega32u4 board connect the LD2410 to GPIO pins TX & RX hardware serial
*
* The serial configuration for other boards will vary and you'll need to assign them yourself
*
* There is no example for ESP8266 as it only has one usable UART and will not boot if the alternate UART pins are used for the radar.
*
* For this sketch and other examples to be useful the board needs to have two usable UARTs.
*
*/
#if defined(ESP32)
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 32
#define RADAR_TX_PIN 33
#elif CONFIG_IDF_TARGET_ESP32S2
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 9
#define RADAR_TX_PIN 8
#elif CONFIG_IDF_TARGET_ESP32C3
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 4
#define RADAR_TX_PIN 5
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 32
#define RADAR_TX_PIN 33
#endif
#elif defined(__AVR_ATmega32U4__)
#define MONITOR_SERIAL Serial
#define RADAR_SERIAL Serial1
#define RADAR_RX_PIN 0
#define RADAR_TX_PIN 1
#endif
#include <ld2410.h>
ld2410 radar;
bool engineeringMode = false;
String command;
void setup(void)
{
MONITOR_SERIAL.begin(115200); //Feedback over Serial Monitor
delay(500); //Give a while for Serial Monitor to wake up
//radar.debug(Serial); //Uncomment to show debug information from the library on the Serial Monitor. By default this does not show sensor reads as they are very frequent.
#if defined(ESP32)
RADAR_SERIAL.begin(256000, SERIAL_8N1, RADAR_RX_PIN, RADAR_TX_PIN); //UART for monitoring the radar
#elif defined(__AVR_ATmega32U4__)
RADAR_SERIAL.begin(256000); //UART for monitoring the radar
#endif
delay(500);
MONITOR_SERIAL.print(F("\nConnect LD2410 radar TX to GPIO:"));
MONITOR_SERIAL.println(RADAR_RX_PIN);
MONITOR_SERIAL.print(F("Connect LD2410 radar RX to GPIO:"));
MONITOR_SERIAL.println(RADAR_TX_PIN);
MONITOR_SERIAL.print(F("LD2410 radar sensor initialising: "));
if(radar.begin(RADAR_SERIAL))
{
MONITOR_SERIAL.println(F("OK"));
MONITOR_SERIAL.print(F("LD2410 firmware version: "));
MONITOR_SERIAL.print(radar.firmware_major_version);
MONITOR_SERIAL.print('.');
MONITOR_SERIAL.print(radar.firmware_minor_version);
MONITOR_SERIAL.print('.');
MONITOR_SERIAL.println(radar.firmware_bugfix_version, HEX);
}
else
{
MONITOR_SERIAL.println(F("not connected"));
}
MONITOR_SERIAL.println(F("Supported commands\nread: read current values from the sensor\nreadconfig: read the configuration from the sensor\nsetmaxvalues <motion gate> <stationary gate> <inactivitytimer>\nsetsensitivity <gate> <motionsensitivity> <stationarysensitivity>\nenableengineeringmode: enable engineering mode\ndisableengineeringmode: disable engineering mode\nrestart: restart the sensor\nreadversion: read firmware version\nfactoryreset: factory reset the sensor\n"));
}
void loop()
{
radar.read(); //Always read frames from the sensor
if(MONITOR_SERIAL.available())
{
char typedCharacter = MONITOR_SERIAL.read();
if(typedCharacter == '\r' || typedCharacter == '\n')
{
command.trim();
if(command.equals("read"))
{
command = "";
MONITOR_SERIAL.print(F("Reading from sensor: "));
if(radar.isConnected())
{
MONITOR_SERIAL.println(F("OK"));
if(radar.presenceDetected())
{
if(radar.stationaryTargetDetected())
{
MONITOR_SERIAL.print(F("Stationary target: "));
MONITOR_SERIAL.print(radar.stationaryTargetDistance());
MONITOR_SERIAL.print(F("cm energy: "));
MONITOR_SERIAL.println(radar.stationaryTargetEnergy());
}
if(radar.movingTargetDetected())
{
MONITOR_SERIAL.print(F("Moving target: "));
MONITOR_SERIAL.print(radar.movingTargetDistance());
MONITOR_SERIAL.print(F("cm energy: "));
MONITOR_SERIAL.println(radar.movingTargetEnergy());
}
}
else
{
MONITOR_SERIAL.println(F("nothing detected"));
}
}
else
{
MONITOR_SERIAL.println(F("failed to read"));
}
}
else if(command.equals("readconfig"))
{
command = "";
MONITOR_SERIAL.print(F("Reading configuration from sensor: "));
if(radar.requestCurrentConfiguration())
{
MONITOR_SERIAL.println(F("OK"));
MONITOR_SERIAL.print(F("Maximum gate ID: "));
MONITOR_SERIAL.println(radar.max_gate);
MONITOR_SERIAL.print(F("Maximum gate for moving targets: "));
MONITOR_SERIAL.println(radar.max_moving_gate);
MONITOR_SERIAL.print(F("Maximum gate for stationary targets: "));
MONITOR_SERIAL.println(radar.max_stationary_gate);
MONITOR_SERIAL.print(F("Idle time for targets: "));
MONITOR_SERIAL.println(radar.sensor_idle_time);
MONITOR_SERIAL.println(F("Gate sensitivity"));
for(uint8_t gate = 0; gate <= radar.max_gate; gate++)
{
MONITOR_SERIAL.print(F("Gate "));
MONITOR_SERIAL.print(gate);
MONITOR_SERIAL.print(F(" moving targets: "));
MONITOR_SERIAL.print(radar.motion_sensitivity[gate]);
MONITOR_SERIAL.print(F(" stationary targets: "));
MONITOR_SERIAL.println(radar.stationary_sensitivity[gate]);
}
}
else
{
MONITOR_SERIAL.println(F("Failed"));
}
}
else if(command.startsWith("setmaxvalues"))
{
uint8_t firstSpace = command.indexOf(' ');
uint8_t secondSpace = command.indexOf(' ',firstSpace + 1);
uint8_t thirdSpace = command.indexOf(' ',secondSpace + 1);
uint8_t newMovingMaxDistance = (command.substring(firstSpace,secondSpace)).toInt();
uint8_t newStationaryMaxDistance = (command.substring(secondSpace,thirdSpace)).toInt();
uint16_t inactivityTimer = (command.substring(thirdSpace,command.length())).toInt();
if(newMovingMaxDistance > 0 && newStationaryMaxDistance > 0 && newMovingMaxDistance <= 8 && newStationaryMaxDistance <= 8)
{
MONITOR_SERIAL.print(F("Setting max values to gate "));
MONITOR_SERIAL.print(newMovingMaxDistance);
MONITOR_SERIAL.print(F(" moving targets, gate "));
MONITOR_SERIAL.print(newStationaryMaxDistance);
MONITOR_SERIAL.print(F(" stationary targets, "));
MONITOR_SERIAL.print(inactivityTimer);
MONITOR_SERIAL.print(F("s inactivity timer: "));
command = "";
if(radar.setMaxValues(newMovingMaxDistance, newStationaryMaxDistance, inactivityTimer))
{
MONITOR_SERIAL.println(F("OK, now restart to apply settings"));
}
else
{
MONITOR_SERIAL.println(F("failed"));
}
}
else
{
MONITOR_SERIAL.print(F("Can't set distances to "));
MONITOR_SERIAL.print(newMovingMaxDistance);
MONITOR_SERIAL.print(F(" moving "));
MONITOR_SERIAL.print(newStationaryMaxDistance);
MONITOR_SERIAL.println(F(" stationary, try again"));
command = "";
}
}
else if(command.startsWith("setsensitivity"))
{
uint8_t firstSpace = command.indexOf(' ');
uint8_t secondSpace = command.indexOf(' ',firstSpace + 1);
uint8_t thirdSpace = command.indexOf(' ',secondSpace + 1);
uint8_t gate = (command.substring(firstSpace,secondSpace)).toInt();
uint8_t motionSensitivity = (command.substring(secondSpace,thirdSpace)).toInt();
uint8_t stationarySensitivity = (command.substring(thirdSpace,command.length())).toInt();
if(motionSensitivity >= 0 && stationarySensitivity >= 0 && motionSensitivity <= 100 && stationarySensitivity <= 100)
{
MONITOR_SERIAL.print(F("Setting gate "));
MONITOR_SERIAL.print(gate);
MONITOR_SERIAL.print(F(" motion sensitivity to "));
MONITOR_SERIAL.print(motionSensitivity);
MONITOR_SERIAL.print(F(" & stationary sensitivity to "));
MONITOR_SERIAL.print(stationarySensitivity);
MONITOR_SERIAL.println(F(": "));
command = "";
if(radar.setGateSensitivityThreshold(gate, motionSensitivity, stationarySensitivity))
{
MONITOR_SERIAL.println(F("OK, now restart to apply settings"));
}
else
{
MONITOR_SERIAL.println(F("failed"));
}
}
else
{
MONITOR_SERIAL.print(F("Can't set gate "));
MONITOR_SERIAL.print(gate);
MONITOR_SERIAL.print(F(" motion sensitivity to "));
MONITOR_SERIAL.print(motionSensitivity);
MONITOR_SERIAL.print(F(" & stationary sensitivity to "));
MONITOR_SERIAL.print(stationarySensitivity);
MONITOR_SERIAL.println(F(", try again"));
command = "";
}
}
else if(command.equals("enableengineeringmode"))
{
command = "";
MONITOR_SERIAL.print(F("Enabling engineering mode: "));
if(radar.requestStartEngineeringMode())
{
MONITOR_SERIAL.println(F("OK"));
}
else
{
MONITOR_SERIAL.println(F("failed"));
}
}
else if(command.equals("disableengineeringmode"))
{
command = "";
MONITOR_SERIAL.print(F("Disabling engineering mode: "));
if(radar.requestEndEngineeringMode())
{
MONITOR_SERIAL.println(F("OK"));
}
else
{
MONITOR_SERIAL.println(F("failed"));
}
}
else if(command.equals("restart"))
{
command = "";
MONITOR_SERIAL.print(F("Restarting sensor: "));
if(radar.requestRestart())
{
MONITOR_SERIAL.println(F("OK"));
}
else
{
MONITOR_SERIAL.println(F("failed"));
}
}
else if(command.equals("readversion"))
{
command = "";
MONITOR_SERIAL.print(F("Requesting firmware version: "));
if(radar.requestFirmwareVersion())
{
Serial.print(radar.cmdFirmwareVersion());
}
else
{
MONITOR_SERIAL.println(F("Failed"));
}
}
else if(command.equals("factoryreset"))
{
command = "";
MONITOR_SERIAL.print(F("Factory resetting sensor: "));
if(radar.requestFactoryReset())
{
MONITOR_SERIAL.println(F("OK, now restart sensor to take effect"));
}
else
{
MONITOR_SERIAL.println(F("failed"));
}
}
else
{
MONITOR_SERIAL.print(F("Unknown command: "));
MONITOR_SERIAL.println(command);
command = "";
}
}
else
{
command += typedCharacter;
}
}
/*
if() //Some data has been received from the radar
{
if(radar.presenceDetected())
{
MONITOR_SERIAL.print(F("Stationary target: "));
MONITOR_SERIAL.println(radar.stationaryTargetDistance());
MONITOR_SERIAL.print(F("Moving target: "));
MONITOR_SERIAL.println(radar.movingTargetDistance());
}
}
*/
}
+39
View File
@@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
+50
View File
@@ -0,0 +1,50 @@
ld2410 KEYWORD1
begin KEYWORD2
debug KEYWORD2
isConnected KEYWORD2
read KEYWORD2
presenceDetected KEYWORD2
ld2410_loop KEYWORD2
isStationary KEYWORD2
isMoving KEYWORD2
isEngineeringMode KEYWORD2
reportingDataComposition KEYWORD2
detectionDistance KEYWORD2
stationaryTargetDetected KEYWORD2
stationaryTargetDistance KEYWORD2
stationaryTargetEnergy KEYWORD2
movingTargetDetected KEYWORD2
movingTargetDistance KEYWORD2
movingTargetEnergy KEYWORD2
engMovingDistanceGateEnergy KEYWORD2
engStaticDistanceGateEnergy KEYWORD2
engMaxMovingDistanceGate KEYWORD2
engMaxStaticDistanceGate KEYWORD2
engRetainDataValue KEYWORD2
requestRestart KEYWORD2
requestFactoryReset KEYWORD2
requestFirmwareVersion
requestCurrentConfiguration
requestStartEngineeringMode KEYWORD2
requestEndEngineeringMode KEYWORD2
setSerialBaudRate KEYWORD2
setMaxValues KEYWORD2
setGateSensitivityThreshold KEYWORD2
requestConfigurationModeOpen KEYWORD2
requestConfigurationModeClose KEYWORD2
cmdProtocolVersion KEYWORD2
cmdFirmwareVersion KEYWORD2
cfgMaxGate KEYWORD2
cfgMaxMovingGate KEYWORD2
cfgMaxStationaryGate KEYWORD2
cfgSensorIdleTimeInSeconds KEYWORD2
cfgMovingGateSensitivity KEYWORD2
cfgStationaryGateSensitivity KEYWORD2
Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+46
View File
@@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
+11
View File
@@ -0,0 +1,11 @@
name=ld2410
version=0.1.3
author=Nick Reynolds
maintainer=Nick Reynolds <ncmreynolds+ld2410@googlemail.com>
sentence=An Arduino library for the Hi-Link LD2410 24Ghz FMCW radar sensor.
paragraph= This sensor is a Frequency Modulated Continuous Wave radar, which makes it good for presence detection and its sensitivity at different ranges to both static and moving targets can be configured.
category=Sensors
url=https://github.com/ncmreynolds/ld2410
depends=
includes=ld2410.h
architectures=*
+32
View File
@@ -0,0 +1,32 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
src_dir = examples/
lib_dir = .
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
board_build.mcu = esp32
board_build.f_cpu = 240000000L
upload_speed = 921600
monitor_speed = 256000
monitor_encoding = hexlify
monitor_filters = log2file,time,esp32_exception_decoder
build_flags =
-D PLATFORMIO_BUILD_FLAGS
-D PIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY
; -D PIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH
-DWIFI_PASS='"BeveilgdMetWpa"'
-DWIFI_SSID='"Kantoor3"'
File diff suppressed because it is too large Load Diff
+324
View File
@@ -0,0 +1,324 @@
/*
* An Arduino library for the Hi-Link LD2410 24Ghz FMCW radar sensor.
*
* This sensor is a Frequency Modulated Continuous Wave radar, which makes it good for presence detection and its sensitivity at different
*ranges to both static and moving targets can be configured.
*
* The code in this library is based off the manufacturer datasheet and reading of this initial piece of work for ESPHome
*https://github.com/rain931215/ESPHome-LD2410.
*
* https://github.com/ncmreynolds/ld2410
*
* Released under LGPL-2.1 see https://github.com/ncmreynolds/ld2410/LICENSE for full license
*
*/
#pragma once
#include <Arduino.h>
#if __cplusplus >= 202002L
# include <atomic>
typedef std::atomic<bool> atomic_bool;
#else // if __cplusplus >= 202002L
typedef volatile bool atomic_bool;
#endif // if __cplusplus >= 202002L
// #define LD2410_DEBUG // Send any debug to serial?
// #define LD2410_DEBUG_DATA //Debug all Data Frames
// #define LD2410_DEBUG_COMMANDS //Debug Command Acks
// #define LD2410_DEBUG_PARSE //Debug Reporting Frames
// Exclude DEBUG logging when requested externally
#if defined(LIBRARIES_NO_LOG) && LIBRARIES_NO_LOG
# ifdef LD2410_DEBUG
# undef LD2410_DEBUG
# endif // ifdef LD2410_DEBUG
#endif // if defined(LIBRARIES_NO_LOG) && LIBRARIES_NO_LOG
/*
* Protocol Command Words
*/
#define LD2410_MAX_FRAME_LENGTH 0x40 // or 64 bytes
#define LD2410_MAX_GATES 9 // 0 - 8 gates
#define CMD_CONFIGURATION_ENABLE 0xFF
#define CMD_CONFIGURATION_END 0xFE
#define CMD_MAX_DISTANCE_AND_UNMANNED_DURATION 0x60
#define CMD_READ_PARAMETER 0x61
#define CMD_ENGINEERING_ENABLE 0x62
#define CMD_ENGINEERING_END 0x63
#define CMD_RANGE_GATE_SENSITIVITY 0x64
#define CMD_READ_FIRMWARE_VERSION 0xA0
#define CMD_SET_SERIAL_PORT_BAUD 0xA1
#define CMD_FACTORY_RESET 0xA2
#define CMD_RESTART 0xA3
/*
* Data Frame Formats
*/
#define FRAME_TYPE_REPORTING 0x01
#define FRAME_TYPE_TARGET 0x02
#define FRAME_PREFIX_PROTOCOL 0xFD
#define FRAME_PREFIX_REPORTING 0xF4
#define FRAME_TYPE_FLAG 0xAA
#define FRAME_TYPE_MARKER 0x55
/*
* Target State Constants
*/
#define TARGET_NONE 0x00
#define TARGET_MOVING 0x01
#define TARGET_STATIONARY 0x02
#define TARGET_MOVING_AND_STATIONARY 0x03
#define SERIAL_RECEIVE_MAX_MS 5 // Read for max. N milliseconds, we'd need (64*(8+2))*(1/256000)=2.5msec to read an entire buffer
#define SERIAL_RECEIVE_GRACE_MS 2 // Read more if still this amount of milliseconds available
class ld2410 {
public:
ld2410(); // Constructor function
~ld2410(); // Destructor function
/*
* Primary APIs */
bool begin(Stream&,
bool waitForRadar = true); // Start the ld2410
#ifdef LD2410_DEBUG
void debug(Stream&); // Start debugging on a stream
#endif // ifdef LD2410_DEBUG
bool ld2410_loop() {
return read_frame_();
} // Sensor loop service
bool presenceDetected() {
return target_type_ != 0;
} // last report data had a type
bool isConnected();
bool isStationary() {
return stationaryTargetDetected();
}
bool isMoving() {
return movingTargetDetected();
}
uint16_t detectionDistance() {
return detection_distance_;
} // Target Reporting Data
bool dataReady() {
return data_ready_;
}
/*
* Utilities -- depreciation candidates */
uint8_t reportingDataComposition() {
return target_type_;
} // Target data state 0-3
bool isEngineeringMode() {
return engineering_mode_;
} // Reporting Data
bool movingTargetDetected();
bool stationaryTargetDetected();
bool read() {
return read_frame_();
}
/*
* primary sensor responses */
uint16_t stationaryTargetDistance() {
return stationary_target_distance_;
} // Target Reporting Data
uint8_t stationaryTargetEnergy() {
return stationary_target_energy_;
} // Target Reporting Data
uint16_t movingTargetDistance() {
return moving_target_distance_;
} // Target Reporting Data
uint8_t movingTargetEnergy() {
return moving_target_energy_;
} // Target Reporting Data
/*
* available if engineering mode is active */
uint8_t engMovingDistanceGateEnergy(uint8_t gate) {
return (gate < LD2410_MAX_GATES) ? movement_distance_gate_energy[gate] : 255;
} // Engineering Reporting Data
uint8_t engStaticDistanceGateEnergy(uint8_t gate) {
return (gate < LD2410_MAX_GATES) ? static_distance_gate_engergy[gate] : 255;
} // Engineering Reporting Data
uint16_t engMaxMovingDistanceGate() {
return max_moving_distance_gate;
} // Engineering Reporting Data
uint16_t engMaxStaticDistanceGate() {
return max_static_distance_gate;
} // Engineering Reporting Data
uint16_t engRetainDataValue() {
return engineering_retain_data_;
} // Engineering Reporting Data, last value
uint8_t engLightSensorValue() {
return light_sensor_data_;
} // Engineering Reporting Data, light sensor (undocumented)
uint8_t engOutputPinState() {
return output_pin_data_;
} // Engineering Reporting Data, output pin state (undocumented)
/*
* Commands */
bool requestRestart();
bool requestFactoryReset();
bool requestFirmwareVersion();
bool requestCurrentConfiguration();
bool requestStartEngineeringMode();
bool requestEndEngineeringMode();
bool setSerialBaudRate(uint8_t cSpeed);
bool setMaxValues(uint16_t moving,
uint16_t stationary,
uint16_t inactivityTimer); // Realistically gate values are 0-8 but sent as uint16_t
bool setGateSensitivityThreshold(uint8_t gate,
uint8_t moving,
uint8_t stationary);
bool requestConfigurationModeBegin(); // support multi command executions BEGIN
bool requestConfigurationModeEnd(); // support multi command executions END
/*
* available after related command has been executed */
uint16_t cmdProtocolVersion() {
return configuration_protocol_version_;
} // Configuration mode response
uint16_t cmdCommunicationBufferSize() {
return configuration_buffer_size_;
} // Configuration mode response
String cmdFirmwareVersion(); // Returns value from command
/*
* available after Read Parameter command has been executed */
uint8_t cfgMaxGate() {
return max_gate;
} // Read Parameters command response
uint8_t cfgMaxMovingGate() {
return max_moving_gate;
} // Read Parameters command response
uint8_t cfgMaxStationaryGate() {
return max_stationary_gate;
} // Read Parameters command response
uint16_t cfgSensorIdleTimeInSeconds() {
return sensor_idle_time;
} // Read Parameters command response
uint8_t cfgMovingGateSensitivity(uint8_t gate) {
return (gate < LD2410_MAX_GATES) ? motion_sensitivity[gate] : 255;
} // Read Parameters command response
uint8_t cfgStationaryGateSensitivity(uint8_t gate) {
return (gate < LD2410_MAX_GATES) ? stationary_sensitivity[gate] : 255;
} // Read Parameters command response
uint16_t getErrorCountAndReset();
protected:
/*
* Request Firmware Version command responses */
char firmwareBuffer[LD2410_MAX_FRAME_LENGTH]; // 64 byte buffer
uint8_t firmware_major_version = 0; // Reported major version
uint8_t firmware_minor_version = 0; // Reported minor version
uint32_t firmware_bugfix_version = 0; // Reported bugfix version (coded as hex)
/*
* Read Parameter command response data */
uint8_t max_gate = 0; // Read parameter data
uint8_t max_moving_gate = 0; // Read parameter data
uint8_t max_stationary_gate = 0; // Read parameter data
uint16_t sensor_idle_time = 0; // Read parameter data
uint8_t motion_sensitivity[LD2410_MAX_GATES] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Read parameter data
uint8_t stationary_sensitivity[LD2410_MAX_GATES] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Read parameter data
/*
* Protocol & Engineering Frame Data */
uint16_t moving_target_distance_ = 0; // protocol mode info
uint8_t moving_target_energy_ = 0; // protocol mode info
uint16_t stationary_target_distance_ = 0; // protocol mode info
uint8_t stationary_target_energy_ = 0; // protocol mode info
uint16_t detection_distance_ = 0; // protocol & engineering mode info
uint8_t max_moving_distance_gate = 0; // engineering mode info
uint8_t max_static_distance_gate = 0; // engineering mode info
uint8_t movement_distance_gate_energy[LD2410_MAX_GATES] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Engineering mode info
uint8_t static_distance_gate_engergy[LD2410_MAX_GATES] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Engineering mode info
uint16_t engineering_retain_data_ = 0; // last value in engineering data frame, extra
// retain ??
uint8_t light_sensor_data_ = 0; // engineering mode, light sensor (undocumented)
uint8_t output_pin_data_ = 0; // engineering mode, output pin state
// (undocumented)
/*
* Configuration mode response info */
uint16_t configuration_protocol_version_ = 0; // From Enter Configuration Mode Response
uint16_t configuration_buffer_size_ = LD2410_MAX_FRAME_LENGTH; // From Enter Configuration Mode Response
private:
/*
* feature control variables */
Stream *radar_uart_ = nullptr;
#ifdef LD2410_DEBUG
Stream *debug_uart_ = nullptr; // The stream used for the debugging
#endif // ifdef LD2410_DEBUG
uint32_t radar_uart_timeout = 250; // How long to give up on receiving some useful data from the LD2410
uint32_t radar_uart_last_packet_ = 0; // Time of the last packet from the radar
uint32_t radar_uart_last_command_ = 0; // Time of the last command sent to the radar
uint32_t radar_uart_command_timeout_ = 250; // Timeout for sending commands
uint16_t _errorCount = 0; // Internal errorcounter, managed via getErrorCountAndReset()
uint8_t latest_ack_ = 0;
uint8_t target_type_ = 0;
uint8_t radar_data_frame_position_ = 0; // Where in the frame we are currently writing
uint8_t radar_data_frame_[LD2410_MAX_FRAME_LENGTH]; // Store the incoming data from the radar, to check it's in a valid format
bool frame_started_ = false; // Whether a frame is currently being read
bool ack_frame_ = false; // Whether the incoming frame is LIKELY an ACK frame
bool waiting_for_ack_ = false; // Whether a command has just been sent
bool engineering_mode_ = false; // Wheter engineering mode is active
bool latest_command_success_ = false;
bool configuration_mode_active = false; // Configuration state (multi-mode)
atomic_bool data_ready_ = false; // Can we read the current data?
/*
* feature management functions */
uint16_t serial_to_int_(uint8_t index); // Unpack bytes
bool debug_command_results_(const char *title);
bool wait_for_command_ack_(uint8_t command);
bool isProtocolDataFrame_(); // Command -Determine type of Frame
bool isReportingDataFrame_(); // Data - Determine type of Frame
bool read_frame_(); // Try to read a frame from the UART
bool parse_data_frame_(); // Is the current data frame valid?
bool parse_command_frame_(); // Is the current command frame valid?
void print_frame_(); // Print the frame for debugging
void send_command_preamble_(); // Commands have the same preamble
void send_command_postamble_(); // Commands have the same postamble
bool enter_configuration_mode_(); // Necessary before sending any command
bool leave_configuration_mode_(); // Will not read values without leaving command mode
};
+23
View File
@@ -0,0 +1,23 @@
This directory is intended for PlatformIO Test Runner and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html
SerialStudio reads the serial port output of the ESP and plot the various
data points. You will need the JSON project file in this folder and the
app "SerialStudio" at this link:
- https://github.com/Serial-Studio/Serial-Studio/releases
- https://www.dobitaobyte.com.br/laboratorio-maker-05-serial-studio-monitor-serial-de-tempo-real/
### Both are maps to process csv data: use via SerialStudio Setup option
ld2410-alarm.json buildWithAlarmSerialStudioCSV()
ld2410-json.json buildSerialStudioCSV()
+2
View File
@@ -527,6 +527,8 @@ static const char DATA_ESPEASY_DEFAULT_MIN_CSS[] PROGMEM = {
// #define USES_P153 // SHT4x
// #define USES_P154 // BMP3xx
// #define USES_P159 // Presence - LD2410 Radar detection
/*
#######################################################################################################
########### Controllers
+2
View File
@@ -6,6 +6,7 @@
// #######################################################################################################
/** Changelog:
* 2023-11-24 tonhuisman: Add Device flag for I2CMax100kHz as this sensor won't work at 400 kHz
* 2022-05-08 tonhuisman: Use ESPEasy core I2C functions where possible
* Add support for use of the Analog output pin and 'analogout,<value>' command
* Add configuration of all possible analog input modes
@@ -47,6 +48,7 @@ boolean Plugin_007(uint8_t function, struct EventStruct *event, String& string)
Device[deviceCount].TimerOption = true;
Device[deviceCount].GlobalSyncOption = true;
Device[deviceCount].OutputDataType = Output_Data_type_t::Simple;
Device[deviceCount].I2CMax100kHz = true; // Max 100 kHz allowed/supported
break;
}
+5
View File
@@ -5,6 +5,10 @@
// #################################### Plugin 024: MLX90614 IR temperature I2C 0x5A) ###############################################
// #######################################################################################################
/** Changelog:
* 2023-11-23 tonhuisman: Add Device flag for I2CMax100kHz as this sensor won't work at 400 kHz
* 2023-11-23 tonhuisman: Add Changelog
*/
# include "src/PluginStructs/P024_data_struct.h"
@@ -36,6 +40,7 @@ boolean Plugin_024(uint8_t function, struct EventStruct *event, String& string)
Device[deviceCount].TimerOption = true;
Device[deviceCount].GlobalSyncOption = true;
Device[deviceCount].PluginStats = true;
Device[deviceCount].I2CMax100kHz = true; // Max 100 kHz allowed/supported
break;
}
+2
View File
@@ -11,6 +11,7 @@
// Changelog:
//
// 2023-11-24 tonhuisman: Add Device flag for I2CMax100kHz as this sensor won't work at 400 kHz
// 2022-02-26 tonhuisman: Implement commands for get/set measurement interval, and a setting too. Bugfix.
// 2022-02-26 tonhuisman: Implement commands for auto/manual CO2 calibration, and setting for auto calibration
// 2021-11-20 tonhuisman: Implement multi-instance support (using PluginStruct)
@@ -56,6 +57,7 @@ boolean Plugin_117(uint8_t function, struct EventStruct *event, String& string)
Device[deviceCount].TimerOption = true;
Device[deviceCount].GlobalSyncOption = true;
Device[deviceCount].PluginStats = true;
Device[deviceCount].I2CMax100kHz = true; // Max 100 kHz allowed/supported
break;
}
+2
View File
@@ -6,6 +6,7 @@
// #######################################################################################################
/**
* 2023-11-23 tonhuisman: Add Device flag for I2CMax100kHz as this sensor won't work at 400 kHz
* 2022-08-28 tonhuisman: Include 'CO2' in plugin name, to be in line with other CO2 plugins
* 2022-08-24 tonhuisman: Removed [TESTING] tag
* 2022-08-04 tonhuisman: Add forced recalibration subcommand scd4x,setfrc,<frcvalue>
@@ -49,6 +50,7 @@ boolean Plugin_135(uint8_t function, struct EventStruct *event, String& string)
Device[deviceCount].TimerOption = true;
Device[deviceCount].GlobalSyncOption = true;
Device[deviceCount].PluginStats = true;
Device[deviceCount].I2CMax100kHz = true; // Max 100 kHz allowed/supported
break;
}
+332
View File
@@ -0,0 +1,332 @@
#include "_Plugin_Helper.h"
// #######################################################################################################
// ########################### Plugin 159: Radar Presence detection LD2410(/LD2420) ####################
// #######################################################################################################
/** Changelog:
* 2023-10-29 tonhuisman: Rework processing, allow Interval = 0, as now the events will be generated when a value changes,
* but at most once per 100 msec, to not overload the ESP. Fixed the LD2410 library to work correctly
* with the event-driven scheduler model of ESPEasy, instead of the continuous loop() run of Arduino
* Add getconfig values for configured sensitivity level per gate, see below
* 2023-10-28 tonhuisman: !! Breaking change (again): Insert Gate 0 value before Gate 1 value, both for Static and Moving
* energy, as that was missing until now. This is because of poor documentation, talking about 8 values
* where there are in fact 9 values, 0..8 !
* Add support for getting all values (function PLUGIN_GET_CONFIG_VALUE), also when not configured
* like [<TaskName>#<ValueName>]. Available valuenames: see below.
* Add command ld2410,logall that writes all available values to the log (depending on Engineering mode)
* 2023-10-23 tonhuisman: !! Breaking change: Insert OutputPinState (undocumented) value after AmbientLight value
* shifting all Sensitivity value offsets by 1 !!
* 2023-10-22 tonhuisman: Add command handling: ld2410,factoryreset
* 2023-10-21 tonhuisman: Read data at 50/sec instead of 10/sec to catch up with the high speed of output
* Add/update settings for Sensitivity and nr. of active gates, idle seconds
* Shorten default value names, (breaking) change setting for Engineering mode
* Add setting for generating events only when a value has changed
* 2023-10-14 tonhuisman: Using ld2410 library from https://github.com/ncmreynolds/ld2410, but with PR #3 applied
* including a fix for index/index + 1, mentioned in the comments of that PR and timeout
* extended to 2500 msec
* 2023-10-14 tonhuisman: Initial plugin setup
*/
/** Info:
* This plugin reads the presence and distance of stationary and moving objects detected by the HiLink LD2410 and LD2420 24 GHz Radar
* human presence detectors
*/
/** Commands:
* ld2410,factoryreset : Reset sensor to factory defaults, also restarts the sensor like the task is just started.
* ld2410,logall : Send all available values to the log (INFO level) like: "LD2410: <Display name>: <value>"
*/
/** ValueNames: (for PLUGIN_GET_CONFIG_VALUE support)
* Presence : Presence (0/1)
* StatPres : Stationary presence (0/1)
* MovPres : Moving presence (0/1)
* Distance : Distance in cm
* StatDist : Stationary distance in cm
* MovDist : Moving distance in cm
* StatEnergy : Stationary object energy level
* MovEnergy : Moving object energy level
* AmbLight : Ambient light level (0..255) (unknown unit)
* OutputPin : State of the output pin (0/1)
* StatEnergyGate0..StatEnergyGate8 : Stationary object energy level for gate 0..8, 75 cm/gate
* MovEnergyGate0..MovEnergyGate8 : Moving object energy for gate 0..8, 75 cm/gate
* StatSensGate0..StatSensGate8 : Stationary sensitivity setting gate 0..8
* MovSensGate0..MovSensGate8 : Moving sensitivity setting gate 0..8
*/
#ifdef USES_P159
# include "src/PluginStructs/P159_data_struct.h" // Sensor abstraction for P159
// Standard plugin defines
# define PLUGIN_159
# define PLUGIN_ID_159 159
# define PLUGIN_NAME_159 "Presence - LD2410"
boolean Plugin_159(uint8_t function, struct EventStruct *event, String& string)
{
boolean success = false;
switch (function)
{
case PLUGIN_DEVICE_ADD:
{
// This case defines the device characteristics
Device[++deviceCount].Number = PLUGIN_ID_159;
Device[deviceCount].Type = DEVICE_TYPE_SERIAL;
Device[deviceCount].VType = Sensor_VType::SENSOR_TYPE_SINGLE;
Device[deviceCount].ValueCount = 4;
Device[deviceCount].OutputDataType = Output_Data_type_t::Simple;
Device[deviceCount].FormulaOption = true;
Device[deviceCount].SendDataOption = true;
Device[deviceCount].GlobalSyncOption = true;
Device[deviceCount].TimerOption = true;
Device[deviceCount].TimerOptional = true;
Device[deviceCount].PluginStats = true;
Device[deviceCount].ExitTaskBeforeSave = false; // Enable calling PLUGIN_WEBFORM_SAVE on the instantiated object
break;
}
case PLUGIN_GET_DEVICENAME:
{
string = F(PLUGIN_NAME_159);
break;
}
case PLUGIN_GET_DEVICEVALUENAMES:
{
const int valueCount = P159_NR_OUTPUT_VALUES;
for (uint8_t i = 0; i < VARS_PER_TASK; ++i) {
if (i < valueCount) {
const uint8_t pconfigIndex = i + P159_QUERY1_CONFIG_POS;
const uint8_t option = PCONFIG(pconfigIndex);
if ((option >= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0) && (option <= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE8)) {
ExtraTaskSettings.setTaskDeviceValueName(i, concat(Plugin_159_valuename(P159_OUTPUT_STATIC_DISTANCE_GATE_index, false),
option - P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0));
} else
if ((option >= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0) && (option <= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE8)) {
ExtraTaskSettings.setTaskDeviceValueName(i, concat(Plugin_159_valuename(P159_OUTPUT_MOVING_DISTANCE_GATE_index, false),
option - P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0));
} else {
ExtraTaskSettings.setTaskDeviceValueName(i, Plugin_159_valuename(option, false));
}
ExtraTaskSettings.TaskDeviceValueDecimals[i] = 0; // No values have decimals
} else {
ExtraTaskSettings.clearTaskDeviceValueName(i);
}
}
break;
}
case PLUGIN_GET_DEVICEGPIONAMES:
{
serialHelper_getGpioNames(event);
break;
}
case PLUGIN_WEBFORM_SHOW_CONFIG:
{
string += serialHelper_getSerialTypeLabel(event);
success = true;
break;
}
case PLUGIN_GET_DEVICEVALUECOUNT:
{
event->Par1 = P159_NR_OUTPUT_VALUES;
success = true;
break;
}
case PLUGIN_GET_DEVICEVTYPE:
{
event->sensorType = static_cast<Sensor_VType>(PCONFIG(P159_SENSOR_TYPE_INDEX));
event->idx = P159_SENSOR_TYPE_INDEX;
success = true;
break;
}
case PLUGIN_SET_DEFAULTS:
{
PCONFIG(0) = P159_OUTPUT_PRESENCE;
PCONFIG(1) = P159_OUTPUT_DISTANCE;
PCONFIG(2) = P159_OUTPUT_STATIONARY_ENERGY;
PCONFIG(3) = P159_OUTPUT_MOVING_ENERGY;
PCONFIG(P159_SENSOR_TYPE_INDEX) = static_cast<uint8_t>(Sensor_VType::SENSOR_TYPE_QUAD);
success = true;
break;
}
case PLUGIN_WEBFORM_LOAD_OUTPUT_SELECTOR:
{
const uint8_t optionCount = P159_GET_ENGINEERING_MODE == 1 ? P159_NR_ENGINEERING_OUTPUT_OPTIONS : P159_NR_OUTPUT_OPTIONS;
String options[optionCount];
for (uint8_t option = 0; option < optionCount; ++option) {
if ((option >= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0) && (option <= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE8)) {
options[option] = concat(Plugin_159_valuename(P159_OUTPUT_STATIC_DISTANCE_GATE_index, true),
option - P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0);
} else
if ((option >= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0) && (option <= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE8)) {
options[option] = concat(Plugin_159_valuename(P159_OUTPUT_MOVING_DISTANCE_GATE_index, true),
option - P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0);
} else {
options[option] = Plugin_159_valuename(option, true);
}
}
const int valueCount = P159_NR_OUTPUT_VALUES;
for (uint8_t i = 0; i < valueCount; ++i) {
const uint8_t pconfigIndex = i + P159_QUERY1_CONFIG_POS;
sensorTypeHelper_loadOutputSelector(event, pconfigIndex, i, optionCount, options);
}
success = true;
break;
}
case PLUGIN_WEBFORM_LOAD:
{
addFormSelector_YesNo(F("Engineering mode"), F("eng"), P159_GET_ENGINEERING_MODE, true);
addFormNote(F("When changing this setting the page will be reloaded"));
addFormCheckBox(F("Generate Events only when changed"), F("diff"), P159_GET_UPDATE_DIFF_ONLY);
success = true;
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if (nullptr != P159_data) {
addFormSubHeader(F("Sensitivity settings"));
success = P159_data->plugin_webform_load(event);
}
break;
}
case PLUGIN_WEBFORM_SAVE:
{
P159_SET_ENGINEERING_MODE(getFormItemInt(F("eng")));
P159_SET_UPDATE_DIFF_ONLY(isFormItemChecked(F("diff")) ? 1 : 0);
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if (nullptr != P159_data) {
P159_data->plugin_webform_save(event);
}
success = true;
break;
}
case PLUGIN_INIT:
{
int8_t rxPin = serialHelper_getRxPin(event);
int8_t txPin = serialHelper_getTxPin(event);
ESPEasySerialPort portType = serialHelper_getSerialType(event);
// Create the P159_data_struct object that will do all the sensor interaction
initPluginTaskData(event->TaskIndex, new (std::nothrow) P159_data_struct(portType,
rxPin,
txPin,
P159_GET_ENGINEERING_MODE == 1));
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
success = nullptr != P159_data;
addLog(LOG_LEVEL_INFO, concat(F("P159 : INIT, success: "), success ? 1 : 0));
break;
}
case PLUGIN_READ:
{
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if (nullptr != P159_data) {
success = P159_data->plugin_read(event);
}
break;
}
case PLUGIN_WRITE:
{
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if (nullptr != P159_data) {
success = P159_data->plugin_write(event, string);
}
break;
}
case PLUGIN_GET_CONFIG_VALUE:
{
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if (nullptr != P159_data) {
success = P159_data->plugin_get_config_value(event, string);
}
break;
}
case PLUGIN_EXIT:
{
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if (nullptr != P159_data) {
P159_data->disconnectSerial();
}
success = true;
break;
}
case PLUGIN_TEN_PER_SECOND:
{
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if ((nullptr != P159_data) && !P159_data->isRunning()) {
success = P159_data->processSensor(event); // Not Running can have 50 msec delays included, so NOT in PLUGIN_FIFTY_PER_SECOND !
}
break;
}
case PLUGIN_FIFTY_PER_SECOND:
{
P159_data_struct *P159_data = static_cast<P159_data_struct *>(getPluginTaskData(event->TaskIndex));
if ((nullptr != P159_data) && P159_data->isRunning()) {
success = P159_data->processSensor(event); // When running no delays are inserted, so can go in PLUGIN_FIFTY_PER_SECOND
}
break;
}
} // switch
return success;
} // function
#endif // ifdef USES_P159
+6
View File
@@ -1615,6 +1615,9 @@ To create/register a plugin, you have to :
#ifndef USES_P154
#define USES_P154 // Environment - BMP3xx
#endif
#ifndef USES_P159
#define USES_P159 // Presence - LD2410 Radar detection
#endif
#endif
@@ -2285,6 +2288,9 @@ To create/register a plugin, you have to :
#ifndef USES_P154
#define USES_P154 // Environment - BMP3xx
#endif
#ifndef USES_P159
#define USES_P159 // Presence - LD2410 Radar detection
#endif
// Controllers
#ifndef USES_C015
+1
View File
@@ -93,6 +93,7 @@ struct __attribute__((__packed__)) DeviceStruct
// (F.e.: M5Stack Core/Core2 needs to power the TFT before SPI can be started)
bool TaskLogsOwnPeaks : 1; // When PluginStats is enabled, a call to PLUGIN_READ will also check for peaks. With this enabled, the plugin must call to check for peaks itself.
bool I2CNoDeviceCheck : 1; // When enabled, NO I2C check will be done on the I2C address returned from PLUGIN_I2C_GET_ADDRESS function call
bool I2CMax100kHz : 1; // When enabled, the device is only able to handle 100 kHz bus-clock speed, shows warning and enables "Force Slow I2C speed" by default
};
+427
View File
@@ -0,0 +1,427 @@
#include "../PluginStructs/P159_data_struct.h"
#ifdef USES_P159
const __FlashStringHelper* Plugin_159_valuename(uint8_t value_nr,
bool displayString) {
const __FlashStringHelper *strings[] { /*** ATTENTION: Don't change order of values as these are stored as user-selected!!! ***/
F("Presence"), F("Presence"),
F("Stationary Presence"), F("StatPres"),
F("Moving Presence"), F("MovPres"),
F("Object distance"), F("Distance"),
F("Stationary Object distance"), F("StatDist"),
F("Moving Object distance"), F("MovDist"),
F("Stationary Object energy"), F("StatEnergy"),
F("Moving Object energy"), F("MovEnergy"),
F("Ambient light sensor"), F("AmbLight"),
F("Output pin state"), F("OutputPin"),
F("Stationary Object energy gate "), F("StatEnergyGate"),
F("Moving Object energy gate "), F("MovEnergyGate"),
F("Stationary sensitivity gate "), F("StatSensGate"),
F("Moving sensitivity gate "), F("MovSensGate"),
};
const size_t index = (2 * value_nr) + (displayString ? 0 : 1);
constexpr size_t nrStrings = NR_ELEMENTS(strings);
if (index < nrStrings) {
return strings[index];
}
return F("");
}
P159_data_struct::P159_data_struct(ESPEasySerialPort portType,
int8_t rxPin,
int8_t txPin,
bool engineeringMode) {
_engineeringMode = engineeringMode;
// Try to open the associated serial port
easySerial = new (std::nothrow) ESPeasySerial(portType, rxPin, txPin);
if (nullptr != easySerial) {
easySerial->begin(256000);
radar = new (std::nothrow) ld2410();
if (nullptr != radar) {
if (radar->begin(*easySerial, false)) {
bool rst = radar->requestRestart();
// start initiated, now wait, next step: request configuration
milestone = millis();
state = P159_state_e::Restarting;
addLog(LOG_LEVEL_INFO, concat(F("LD2410: Restart sensor: "), rst ? 1 : 0));
} else {
delete radar;
radar = nullptr;
}
}
}
addLog(LOG_LEVEL_INFO, concat(F("LD2410: Initialized: "), isValid() ? 1 : 0));
} // constructor
void P159_data_struct::disconnectSerial() {
if (nullptr != easySerial) {
delete easySerial;
easySerial = nullptr;
}
if (nullptr != radar) {
delete radar;
radar = nullptr;
}
} // disconnectSerial()
bool P159_data_struct::processSensor(struct EventStruct *event) {
bool new_data = false;
if (isValid()) {
uint32_t iStart = millis(); // FIXME Remove log
P159_state_e sState = state;
switch (state) {
case P159_state_e::Initializing:
addLog(LOG_LEVEL_INFO, F("LD2410: Initializing..."));
break;
case P159_state_e::Restarting:
if ((milestone > 0) && (timePassedSince(milestone) > P159_DELAY_RESTART)) {
state = P159_state_e::GetVersion;
milestone = 0;
radar->requestFirmwareVersion();
}
break;
case P159_state_e::GetVersion:
state = P159_state_e::GetConfiguration;
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLog(LOG_LEVEL_INFO, concat(F("LD2410: Firmware version: "), radar->cmdFirmwareVersion()));
}
_configurationRead = radar->requestCurrentConfiguration();
break;
case P159_state_e::GetConfiguration:
state = P159_state_e::Engineering;
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLog(LOG_LEVEL_INFO, concat(F("LD2410: Fetch configuration: "), _configurationRead ? 1 : 0));
if (_configurationRead) {
const uint8_t mGate = radar->cfgMaxGate();
const uint8_t mMvGate = radar->cfgMaxMovingGate();
const uint8_t mStGate = radar->cfgMaxStationaryGate();
const uint8_t mMax = std::max(mGate, std::max(mMvGate, mStGate));
addLog(LOG_LEVEL_INFO, strformat(F("LD2410: Sensor idle time: %d sec."), radar->cfgSensorIdleTimeInSeconds()));
addLog(LOG_LEVEL_INFO, strformat(F("LD2410: Max. gate: %d, max. moving gate: %d, max. stationary gate: %d"),
mGate, mMvGate, mStGate));
for (uint8_t i = 0; i <= mMax; ++i) {
addLog(LOG_LEVEL_INFO, strformat(F("LD2410: Sensitivity, gate %d (%.2f - %.2f mtr): moving:%3d, stationary:%3d"),
i, i * 0.75f, (i + 1) * 0.75f,
i <= mMvGate ? radar->cfgMovingGateSensitivity(i) : 0,
i <= mStGate ? radar->cfgStationaryGateSensitivity(i) : 0));
}
}
}
break;
case P159_state_e::Engineering:
state = P159_state_e::Running;
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
if (_engineeringMode) {
addLog(LOG_LEVEL_INFO, concat(F("LD2410: Engineering mode: "), radar->requestStartEngineeringMode() ? 1 : 0));
}
addLog(LOG_LEVEL_INFO, F("LD2410: Enter Running state."));
}
break;
case P159_state_e::Running:
new_data = radar->ld2410_loop();
if (new_data && radar->dataReady()) {
const int8_t valueCount = P159_NR_OUTPUT_VALUES;
bool result = false;
for (int8_t i = 0; i < valueCount; ++i) {
const uint8_t pconfigIndex = i + P159_QUERY1_CONFIG_POS;
bool isChanged = false;
UserVar[event->BaseVarIndex + i] = getRadarValue(PCONFIG(pconfigIndex), UserVar[event->BaseVarIndex + i], isChanged);
result |= isChanged;
}
if (result && (timePassedSince(lastSent) >= P159_DELAY_SENDOUT)) {
lastSent = millis(); // Sending data incorporated in timing, just like PLUGIN_READ
sendData(event);
const uint16_t err = radar->getErrorCountAndReset();
if ((err != 0) && loglevelActiveFor(LOG_LEVEL_ERROR)) {
addLog(LOG_LEVEL_ERROR, concat(F("LD2410: Frame Errorcounter: "), err));
}
}
}
break;
}
if (P159_state_e::Running != sState) { // FIXME Remove log
addLog(LOG_LEVEL_INFO, strformat(F("LD2410: Starting state: %d duration: %d msec."),
static_cast<uint8_t>(sState), timePassedSince(iStart)));
}
} // isValid()
return new_data;
} // processSensor()
bool P159_data_struct::plugin_read(struct EventStruct *event) {
bool result = false;
if (isValid() && radar->isConnected()) {
const int8_t valueCount = P159_NR_OUTPUT_VALUES;
result = !P159_GET_UPDATE_DIFF_ONLY;
for (int8_t i = 0; i < valueCount; ++i) {
const uint8_t pconfigIndex = i + P159_QUERY1_CONFIG_POS;
bool isChanged = false;
UserVar[event->BaseVarIndex + i] = getRadarValue(PCONFIG(pconfigIndex), UserVar[event->BaseVarIndex + i], isChanged);
result |= isChanged;
}
if (result && (timePassedSince(lastSent) < P159_DELAY_SENDOUT)) { // Avoid duplicate sendouts
result = false;
} else if (result) {
lastSent = millis();
}
}
return result;
} // plugin_read()
int P159_data_struct::getRadarValue(int16_t valueIndex,
int previousValue,
bool & isChanged) {
int result = previousValue;
if (isValid()) {
switch (valueIndex) {
case P159_OUTPUT_PRESENCE: result = radar->presenceDetected() ? 1 : 0; break;
case P159_OUTPUT_STATIONARY_PRESENCE: result = radar->isStationary() ? 1 : 0; break;
case P159_OUTPUT_MOVING_PRESENCE: result = radar->isMoving() ? 1 : 0; break;
case P159_OUTPUT_DISTANCE: result = radar->detectionDistance(); break;
case P159_OUTPUT_STATIONARY_DISTANCE: result = radar->stationaryTargetDistance(); break;
case P159_OUTPUT_MOVING_DISTANCE: result = radar->movingTargetDistance(); break;
case P159_OUTPUT_STATIONARY_ENERGY: result = radar->stationaryTargetEnergy(); break;
case P159_OUTPUT_MOVING_ENERGY: result = radar->movingTargetEnergy(); break;
}
if ((valueIndex >= P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE0) && (valueIndex <= P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE8)) {
result = radar->cfgStationaryGateSensitivity(valueIndex - P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE0);
}
else
if ((valueIndex >= P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE0) && (valueIndex <= P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE8)) {
result = radar->cfgMovingGateSensitivity(valueIndex - P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE0);
}
if (_engineeringMode) {
if ((valueIndex >= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0) && (valueIndex <= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE8)) {
result = radar->engStaticDistanceGateEnergy(valueIndex - P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0);
}
else
if ((valueIndex >= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0) && (valueIndex <= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE8)) {
result = radar->engMovingDistanceGateEnergy(valueIndex - P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0);
}
else
if (P159_OUTPUT_LIGHT_SENSOR == valueIndex) {
result = radar->engLightSensorValue();
}
else
if (P159_OUTPUT_PIN_STATE == valueIndex) {
result = radar->engOutputPinState();
}
}
isChanged = result != previousValue;
} // isValid()
return result;
} // getRadarValue()
void P159_data_struct::addJavascript() {
addHtml(F("<script type='text/javascript'>"
"function chDis(s,m) {"
"for(i=1;i<=m;i++){" // "console.log('pc_arg'+i);" // For debugging the js code
"document.getElementById('pc_arg'+i).disabled=!s"
"}"
"};</script>"
));
}
bool P159_data_struct::plugin_webform_load(struct EventStruct *event) {
bool result = false;
if (isValid()) {
if (!_configurationRead) {
_configurationRead = radar->requestCurrentConfiguration();
}
if (_configurationRead) {
addRowLabel(F("Firmware version: "));
addHtml(radar->cmdFirmwareVersion());
const uint8_t mGate = radar->cfgMaxGate();
const uint8_t mMvGate = radar->cfgMaxMovingGate();
const uint8_t mStGate = radar->cfgMaxStationaryGate();
const uint8_t mMax = std::max(mGate, std::max(mMvGate, mStGate));
const uint16_t idleTime = radar->cfgSensorIdleTimeInSeconds();
addJavascript();
addFormCheckBox(F("Modify sensor settings"), F("saveSens"), false);
int idx = 0;
addFormNumericBox(F("Idle seconds"), getPluginCustomArgName(idx++), idleTime, 0, 65535,
# if FEATURE_TOOLTIPS
EMPTY_STRING,
# endif // if FEATURE_TOOLTIPS
true);
addUnit(F("0..65535 sec."));
addFormNumericBox(F("Max. Moving gates"), getPluginCustomArgName(idx++), mMvGate, 2, 8,
# if FEATURE_TOOLTIPS
EMPTY_STRING,
# endif // if FEATURE_TOOLTIPS
true);
addUnit(F("2..8"));
addFormNumericBox(F("Max. Stationary gates"), getPluginCustomArgName(idx++), mStGate, 2, 8,
# if FEATURE_TOOLTIPS
EMPTY_STRING,
# endif // if FEATURE_TOOLTIPS
true);
addUnit(F("2..8"));
addRowLabel(F("Sensitivity"));
html_table(EMPTY_STRING, false); // Sub-table
html_table_header(F("Gate"), 200);
html_table_header(F("Moving"), 100);
html_table_header(F("Stationary"), 100);
for (uint8_t i = 0; i <= mMax; ++i) {
html_TR_TD();
addHtml(strformat(F("Gate %d (%.2f - %.2f mtr)"), i, i * 0.75f, (i + 1) * 0.75f));
html_TD();
addNumericBox(getPluginCustomArgName(idx++), radar->cfgMovingGateSensitivity(i), 0, 100, true);
html_TD();
addNumericBox(getPluginCustomArgName(idx++), radar->cfgStationaryGateSensitivity(i), 0, 100, true);
}
html_end_table();
addHtml(strformat(F("\n<script type='text/javascript'>document.getElementById('saveSens')."
"onclick=function(){chDis(this.checked,%d)};</script>"),
idx));
result = true;
}
}
return result;
}
bool P159_data_struct::plugin_webform_save(struct EventStruct *event) {
bool result = false;
const bool doSave = isFormItemChecked(F("saveSens"));
if (isValid() && doSave) {
int idx = 0;
const uint16_t idle = getFormItemInt(getPluginCustomArgName(idx++));
const uint8_t gMove = getFormItemInt(getPluginCustomArgName(idx++));
const uint8_t gStat = getFormItemInt(getPluginCustomArgName(idx++));
addLog(LOG_LEVEL_INFO, F("LD2410: Save sensitivity settings to sensor, start..."));
radar->requestConfigurationModeBegin();
radar->setMaxValues(gMove, gStat, idle);
const uint16_t maxGate = radar->cfgMaxGate();
for (uint16_t gate = 0; gate <= maxGate; ++gate) {
const uint16_t sMove = getFormItemInt(getPluginCustomArgName(idx++));
const uint16_t sStat = getFormItemInt(getPluginCustomArgName(idx++));
// Set sensitivity (level) to 100 to effectively disable sensitivity
radar->setGateSensitivityThreshold(gate, gate <= gMove ? sMove : 100, gate <= gStat ? sStat : 100);
}
radar->requestConfigurationModeEnd();
addLog(LOG_LEVEL_INFO, F("LD2410: Save sensitivity settings to sensor, done."));
}
return result;
}
bool P159_data_struct::plugin_write(struct EventStruct *event,
String & string) {
bool result = false;
const String cmd = parseString(string, 1);
if (isValid() && equals(cmd, F("ld2410"))) {
const String subcmd = parseString(string, 2);
if (equals(subcmd, F("factoryreset"))) {
addLog(LOG_LEVEL_ERROR, F("LD2410: Performing unconditional sensor factory reset!"));
result = radar->requestFactoryReset();
radar->requestRestart();
// start initiated, now wait, next step: request configuration
milestone = millis();
state = P159_state_e::Restarting;
} else if (equals(subcmd, F("logall"))) {
result = plugin_get_config_value(event, string, true);
}
}
return result;
}
bool P159_data_struct::plugin_get_config_value(struct EventStruct *event,
String & string,
bool logAll) {
bool result = false;
if (isValid()) {
const String cmd = parseString(string, 1);
const int16_t count = P159_NR_MAX_OUTPUT_OPTIONS;
for (int16_t option = 0; option < count; ++option) {
int16_t idx = option;
int16_t gate = -1;
if ((option >= P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE0) && (option <= P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE8)) {
idx = P159_OUTPUT_STATIC_SENSOR_GATE_index;
gate = option - P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE0;
} else
if ((option >= P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE0) && (option <= P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE8)) {
idx = P159_OUTPUT_MOVING_SENSOR_GATE_index;
gate = option - P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE0;
} else
if ((option >= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0) && (option <= P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE8)) {
if (_engineeringMode) {
idx = P159_OUTPUT_STATIC_DISTANCE_GATE_index;
gate = option - P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0;
} else {
idx = -1;
}
} else
if ((option >= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0) && (option <= P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE8)) {
if (_engineeringMode) {
idx = P159_OUTPUT_MOVING_DISTANCE_GATE_index;
gate = option - P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0;
} else {
idx = -1;
}
}
if ((idx > -1) && (logAll ||
cmd.equalsIgnoreCase(concat(Plugin_159_valuename(idx, false), (gate > -1) ? String(gate) : EMPTY_STRING)))) {
bool dummy;
string = getRadarValue(option, -1, dummy);
result = true;
if (!logAll) {
break;
} else if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLog(LOG_LEVEL_INFO, strformat(F("LD2410: %s: %s"),
concat(Plugin_159_valuename(idx, true), (gate > -1) ? String(gate) : EMPTY_STRING).c_str(),
string.c_str()));
}
}
}
}
return result;
}
#endif // USES_P159
+120
View File
@@ -0,0 +1,120 @@
#ifndef PLUGINSTRUCTS_P159_DATA_STRUCT_H
#define PLUGINSTRUCTS_P159_DATA_STRUCT_H
#include "../../_Plugin_Helper.h"
#ifdef USES_P159
# define PLUGIN_159_DEBUG false // set to true for extra log info
# include <ESPeasySerial.h>
# include <ld2410.h>
// place sensor type selector right after the output value settings
# define P159_QUERY1_CONFIG_POS 0
# define P159_SENSOR_TYPE_INDEX (P159_QUERY1_CONFIG_POS + VARS_PER_TASK)
# define P159_NR_OUTPUT_VALUES getValueCountFromSensorType(static_cast<Sensor_VType>(PCONFIG(P159_SENSOR_TYPE_INDEX)))
# define P159_CONFIG_FLAGS PCONFIG_ULONG(0)
# define P159_FLAG_ENGINEERING_MODE 0
# define P159_FLAG_UPDATE_DIFF_ONLY 1
# define P159_GET_ENGINEERING_MODE bitRead(P159_CONFIG_FLAGS, P159_FLAG_ENGINEERING_MODE)
# define P159_SET_ENGINEERING_MODE(x) bitWrite(P159_CONFIG_FLAGS, P159_FLAG_ENGINEERING_MODE, x)
# define P159_GET_UPDATE_DIFF_ONLY bitRead(P159_CONFIG_FLAGS, P159_FLAG_UPDATE_DIFF_ONLY)
# define P159_SET_UPDATE_DIFF_ONLY(x) bitWrite(P159_CONFIG_FLAGS, P159_FLAG_UPDATE_DIFF_ONLY, x)
# define P159_OUTPUT_PRESENCE 0
# define P159_OUTPUT_STATIONARY_PRESENCE 1
# define P159_OUTPUT_MOVING_PRESENCE 2
# define P159_OUTPUT_DISTANCE 3
# define P159_OUTPUT_STATIONARY_DISTANCE 4
# define P159_OUTPUT_MOVING_DISTANCE 5
# define P159_OUTPUT_STATIONARY_ENERGY 6
# define P159_OUTPUT_MOVING_ENERGY 7
// Engineering mode:
# define P159_OUTPUT_LIGHT_SENSOR 8
# define P159_OUTPUT_PIN_STATE 9
# define P159_OUTPUT_STATIC_DISTANCE_GATE_index 10
# define P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE0 10
# define P159_OUTPUT_STATIC_DISTANCE_ENERGY_GATE8 18
# define P159_OUTPUT_MOVING_DISTANCE_GATE_index 11
# define P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE0 19
# define P159_OUTPUT_MOVING_DISTANCE_ENERGY_GATE8 27
# define P159_OUTPUT_STATIC_SENSOR_GATE_index 12
# define P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE0 28
# define P159_OUTPUT_STATIC_SENSOR_ENERGY_GATE8 36
# define P159_OUTPUT_MOVING_SENSOR_GATE_index 13
# define P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE0 37
# define P159_OUTPUT_MOVING_SENSOR_ENERGY_GATE8 45
# define P159_NR_OUTPUT_OPTIONS 8 // Last P159_OUTPUT_*_DISTANCE value + 1 (count)
# define P159_NR_ENGINEERING_OUTPUT_OPTIONS 28 // Last P159_OUTPUT_*_DISTANCE value + 1 (count) ENGINEERING
# define P159_NR_MAX_OUTPUT_OPTIONS 46 // Last P159_OUTPUT_*_SENSOR value + 1 (count)
# define P159_DELAY_RESTART 2500 // milliseconds to 'wait' (ignore) after a device-restart
# define P159_DELAY_SENDOUT 100 // Minimal milliseconds between sending data/events
enum class P159_state_e : uint8_t {
Initializing = 0u,
Restarting = 1u,
GetVersion = 2u,
GetConfiguration = 3u,
Engineering = 4u,
Running = 5u,
};
const __FlashStringHelper* Plugin_159_valuename(uint8_t value_nr,
bool displayString);
struct P159_data_struct : public PluginTaskData_base {
P159_data_struct(ESPEasySerialPort portType,
int8_t rxPin,
int8_t txPin,
bool engineeringMode);
virtual ~P159_data_struct() = default;
void disconnectSerial(); // Disconnect the serial port connected to the sensor
bool processSensor(struct EventStruct *event); // Process sensor, must be called regularly
bool plugin_read(struct EventStruct *event);
bool plugin_webform_load(struct EventStruct *event);
bool plugin_webform_save(struct EventStruct *event);
bool plugin_write(struct EventStruct *event,
String & string);
bool plugin_get_config_value(struct EventStruct *event,
String & string,
bool logAll = false);
bool isValid() const {
return nullptr != easySerial && nullptr != radar;
}
P159_state_e getCurrentState() const {
return state;
}
bool isRunning() const {
return isValid() && P159_state_e::Running == state;
}
private:
int getRadarValue(int16_t valueIndex,
int previousValue,
bool & isChanged);
void addJavascript();
ESPeasySerial *easySerial = nullptr; // Serial port object
ld2410 *radar = nullptr; // Sensor object
uint32_t milestone = 0; // When can we do the next phase when not in Running state?
uint32_t lastSent = 0; // Last time we sent out data
P159_state_e state = P159_state_e::Initializing;
bool _engineeringMode = false;
bool _configurationRead = false;
};
#endif // USES_P159
#endif // PLUGINSTRUCTS_P159_DATA_STRUCT_H
+13 -2
View File
@@ -150,6 +150,14 @@ void handle_devices() {
{
// change of device: cleanup old device and reset default settings
setTaskDevice_to_TaskIndex(taskdevicenumber, taskIndex);
const deviceIndex_t DeviceIndex = getDeviceIndex(taskdevicenumber);
if (validDeviceIndex(DeviceIndex)) {
const DeviceStruct& device = Device[DeviceIndex];
if ((device.Type == DEVICE_TYPE_I2C) && device.I2CMax100kHz) { // 100 kHz-only I2C device?
bitWrite(Settings.I2C_Flags[taskIndex], I2C_FLAGS_SLOW_SPEED, 1); // Then: Enable Force Slow I2C speed checkbox by default
}
}
}
else if (taskdevicenumber != INVALID_PLUGIN_ID) // save settings
{
@@ -951,7 +959,7 @@ void handle_devices_TaskSettingsPage(taskIndex_t taskIndex, uint8_t page)
addPinConfig = false;
if (Settings.TaskDeviceDataFeed[taskIndex] == 0) {
devicePage_show_I2C_config(taskIndex);
devicePage_show_I2C_config(taskIndex, DeviceIndex);
}
}
@@ -1145,7 +1153,7 @@ void devicePage_show_serial_config(taskIndex_t taskIndex)
}
#endif
void devicePage_show_I2C_config(taskIndex_t taskIndex)
void devicePage_show_I2C_config(taskIndex_t taskIndex, deviceIndex_t DeviceIndex)
{
struct EventStruct TempEvent(taskIndex);
@@ -1159,6 +1167,9 @@ void devicePage_show_I2C_config(taskIndex_t taskIndex)
PluginCall(PLUGIN_WEBFORM_SHOW_I2C_PARAMS, &TempEvent, dummy);
addFormCheckBox(F("Force Slow I2C speed"), F("taskdeviceflags0"), bitRead(Settings.I2C_Flags[taskIndex], I2C_FLAGS_SLOW_SPEED));
if (Device[DeviceIndex].I2CMax100kHz) {
addFormNote(F("This device is specified for max. 100 kHz operation!"));
}
# if FEATURE_I2CMULTIPLEXER
+1 -1
View File
@@ -56,7 +56,7 @@ void devicePage_show_pin_config(taskIndex_t taskIndex, deviceIndex_t DeviceIndex
void devicePage_show_serial_config(taskIndex_t taskIndex);
#endif
void devicePage_show_I2C_config(taskIndex_t taskIndex);
void devicePage_show_I2C_config(taskIndex_t taskIndex, deviceIndex_t DeviceIndex);
void devicePage_show_output_data_type(taskIndex_t taskIndex, deviceIndex_t DeviceIndex);
+2
View File
@@ -104,6 +104,8 @@ var commonPlugins = [
"dac", "dac,1", "dac,2",
//P153
"sht4x", "sht4x,startup",
//P159
"ld2410", "ld2410,factoryreset", "ld2410,logall",
];
var pluginDispKind = [
//P095
+1 -1
View File
File diff suppressed because one or more lines are too long