Compare commits
64 Commits
34b20b1f8f
...
containeri
Author | SHA1 | Date | |
---|---|---|---|
50a052df9a
|
|||
c4820e8035
|
|||
31b6f8633c
|
|||
e20b474dfd | |||
5b009f50e5 | |||
d010c5d12a | |||
b594a02870 | |||
1f3349c348 | |||
5b0e2b6797 | |||
1791f463b7 | |||
c94f5bdb45 | |||
584d6df2d0 | |||
cd63e76469 | |||
4c54edbcea | |||
8b938e7687 | |||
1c84cd00da | |||
1397f5d775 | |||
65f6670ca4 | |||
049a9d027c | |||
4aa25c687b | |||
b3cc313139 | |||
be3c4a5095 | |||
4160202cdc | |||
9de85b6e37 | |||
79087c9353 | |||
0d495d0f56
|
|||
242e748ca0
|
|||
f853b6f2b2
|
|||
5bc20d312a
|
|||
4faae86a6b
|
|||
4fa1a05fc3
|
|||
3a24dcec53
|
|||
e7895577ca
|
|||
be9a076b33
|
|||
47ad4c70de | |||
c4aa3a1450 | |||
f0d89417b6 | |||
a8e17cda3b | |||
a38d704498 | |||
50b2e994ca | |||
7a7f000743 | |||
d650358bab | |||
9f113adf7e | |||
735f836458 | |||
f02d935f40 | |||
cc4e9efffd | |||
5d91daf23d | |||
577c38d026 | |||
6b711e29fc | |||
5fb8705d9a | |||
e57e87af3f | |||
450197c7cd | |||
736925f7de | |||
1fb9d2ab1b | |||
ea60d804b3 | |||
d059b7b1db | |||
e7b6bda747 | |||
04849162cd | |||
5621f17e61
|
|||
d0e5627815
|
|||
7115809f2b
|
|||
c1d0ce542c
|
|||
b7b08d8747
|
|||
8d68f0ef14
|
10
bin/build-esp-plant-dev-tools.sh
Executable file
10
bin/build-esp-plant-dev-tools.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_NAME="localhost/esp-plant-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
|
||||
pushd "$CONTAINER_TOOLS_BASEDIR"
|
||||
podman build -t "$CONTAINER_NAME" -f "esp-plant-dev-tools.Containerfile" .
|
||||
popd
|
16
bin/esp-plant-dev-tools.Containerfile
Normal file
16
bin/esp-plant-dev-tools.Containerfile
Normal file
@@ -0,0 +1,16 @@
|
||||
FROM debian:latest
|
||||
|
||||
RUN apt update -y && apt upgrade -y && apt install unzip curl xz-utils nodejs -y
|
||||
|
||||
RUN cd /root && \
|
||||
curl -L -o xpack-riscv-toolchain.tar.gz "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v14.2.0-3/xpack-riscv-none-elf-gcc-14.2.0-3-linux-x64.tar.gz" && \
|
||||
mkdir xpack-toolchain && \
|
||||
tar -xvf xpack-riscv-toolchain.tar.gz -C xpack-toolchain --strip-components=1 && \
|
||||
mv xpack-toolchain/bin/* /usr/local/bin && \
|
||||
mv xpack-toolchain/lib/ /usr/local && \
|
||||
mv xpack-toolchain/lib64/ /usr/local && \
|
||||
mv xpack-toolchain/libexec /usr/local && \
|
||||
mv xpack-toolchain/riscv-none-elf /usr/local && \
|
||||
rm -rf xpack-toolchain xpack-riscv-toolchain.tar.gz
|
||||
|
||||
RUN apt install npm -y
|
29
bin/npm
Executable file
29
bin/npm
Executable file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_IMAGE="localhost/esp-plant-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
PLANTCTL_PROJECT_DIR="$(readlink -f "$CONTAINER_TOOLS_BASEDIR/..")"
|
||||
|
||||
function _fatal {
|
||||
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
declare -a PODMAN_ARGS=(
|
||||
"--rm" "-i" "--log-driver=none"
|
||||
"-v" "$PLANTCTL_PROJECT_DIR:$PLANTCTL_PROJECT_DIR:rw"
|
||||
"-v" "$PWD:$PWD:rw"
|
||||
"-w" "$PWD"
|
||||
)
|
||||
|
||||
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
|
||||
|
||||
if ! podman image exists "$CONTAINER_IMAGE"; then
|
||||
#attempt to build container
|
||||
"$CONTAINER_TOOLS_BASEDIR/build-esp-plant-dev-tools.sh" 1>&2 ||
|
||||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
|
||||
fi
|
||||
|
||||
podman run "${PODMAN_ARGS[@]}" --entrypoint npm "$CONTAINER_IMAGE" "$@"
|
29
bin/npx
Executable file
29
bin/npx
Executable file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_IMAGE="localhost/esp-plant-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
PLANTCTL_PROJECT_DIR="$(readlink -f "$CONTAINER_TOOLS_BASEDIR/..")"
|
||||
|
||||
function _fatal {
|
||||
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
declare -a PODMAN_ARGS=(
|
||||
"--rm" "-i" "--log-driver=none"
|
||||
"-v" "$PLANTCTL_PROJECT_DIR:$PLANTCTL_PROJECT_DIR:rw"
|
||||
"-v" "$PWD:$PWD:rw"
|
||||
"-w" "$PWD"
|
||||
)
|
||||
|
||||
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
|
||||
|
||||
if ! podman image exists "$CONTAINER_IMAGE"; then
|
||||
#attempt to build container
|
||||
"$CONTAINER_TOOLS_BASEDIR/build-esp-plant-dev-tools.sh" 1>&2 ||
|
||||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
|
||||
fi
|
||||
|
||||
podman run "${PODMAN_ARGS[@]}" --entrypoint npx "$CONTAINER_IMAGE" "$@"
|
29
bin/riscv32-unknown-elf-gcc
Executable file
29
bin/riscv32-unknown-elf-gcc
Executable file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_IMAGE="localhost/esp-plant-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
PLANTCTL_PROJECT_DIR="$(readlink -f "$CONTAINER_TOOLS_BASEDIR/..")"
|
||||
|
||||
function _fatal {
|
||||
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
declare -a PODMAN_ARGS=(
|
||||
"--rm" "-i" "--log-driver=none"
|
||||
"-v" "$PLANTCTL_PROJECT_DIR:$PLANTCTL_PROJECT_DIR:rw"
|
||||
"-v" "$PWD:$PWD:rw"
|
||||
"-w" "$PWD"
|
||||
)
|
||||
|
||||
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
|
||||
|
||||
if ! podman image exists "$CONTAINER_IMAGE"; then
|
||||
#attempt to build container
|
||||
"$CONTAINER_TOOLS_BASEDIR/build-esp-plant-dev-tools.sh" 1>&2 ||
|
||||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
|
||||
fi
|
||||
|
||||
podman run "${PODMAN_ARGS[@]}" --entrypoint riscv-none-elf-gcc "$CONTAINER_IMAGE" "$@"
|
BIN
board/Body1.3mf
Normal file
BIN
board/Body1.3mf
Normal file
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -462,8 +462,8 @@
|
||||
"no_connect_dangling": "warning",
|
||||
"pin_not_connected": "error",
|
||||
"pin_not_driven": "error",
|
||||
"pin_to_pin": "error",
|
||||
"power_pin_not_driven": "error",
|
||||
"pin_to_pin": "ignore",
|
||||
"power_pin_not_driven": "ignore",
|
||||
"same_local_global_label": "warning",
|
||||
"similar_label_and_power": "warning",
|
||||
"similar_labels": "warning",
|
||||
@@ -472,6 +472,7 @@
|
||||
"single_global_label": "ignore",
|
||||
"unannotated": "error",
|
||||
"unconnected_wire_endpoint": "warning",
|
||||
"undefined_netclass": "error",
|
||||
"unit_value_mismatch": "error",
|
||||
"unresolved_variable": "error",
|
||||
"wire_dangling": "error"
|
||||
|
File diff suppressed because it is too large
Load Diff
BIN
board/modules/MPPT/battery-charging.png
Normal file
BIN
board/modules/MPPT/battery-charging.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 2.1 KiB |
6
board/modules/MPPT/battery-charging.svg
Normal file
6
board/modules/MPPT/battery-charging.svg
Normal file
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-battery-charging" viewBox="0 0 16 16">
|
||||
<path d="M9.585 2.568a.5.5 0 0 1 .226.58L8.677 6.832h1.99a.5.5 0 0 1 .364.843l-5.334 5.667a.5.5 0 0 1-.842-.49L5.99 9.167H4a.5.5 0 0 1-.364-.843l5.333-5.667a.5.5 0 0 1 .616-.09z"/>
|
||||
<path d="M2 4h4.332l-.94 1H2a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h2.38l-.308 1H2a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2"/>
|
||||
<path d="M2 6h2.45L2.908 7.639A1.5 1.5 0 0 0 3.313 10H2zm8.595-2-.308 1H12a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H9.276l-.942 1H12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"/>
|
||||
<path d="M12 10h-1.783l1.542-1.639q.146-.156.241-.34zm0-3.354V6h-.646a1.5 1.5 0 0 1 .646.646M16 8a1.5 1.5 0 0 1-1.5 1.5v-3A1.5 1.5 0 0 1 16 8"/>
|
||||
</svg>
|
After Width: | Height: | Size: 738 B |
@@ -428,7 +428,7 @@
|
||||
(symbol "Sensor_1_1"
|
||||
(rectangle
|
||||
(start -5.08 -1.27)
|
||||
(end 5.08 -29.21)
|
||||
(end 5.08 -34.29)
|
||||
(stroke
|
||||
(width 0)
|
||||
(type solid)
|
||||
@@ -455,7 +455,7 @@
|
||||
)
|
||||
)
|
||||
)
|
||||
(pin no_connect line
|
||||
(pin power_in line
|
||||
(at 7.62 -5.08 180)
|
||||
(length 2.54)
|
||||
(name "VBAT"
|
||||
@@ -527,10 +527,10 @@
|
||||
)
|
||||
)
|
||||
)
|
||||
(pin output line
|
||||
(pin input line
|
||||
(at 7.62 -15.24 180)
|
||||
(length 2.54)
|
||||
(name "GND"
|
||||
(name "CAN_H"
|
||||
(effects
|
||||
(font
|
||||
(size 1.27 1.27)
|
||||
@@ -545,10 +545,10 @@
|
||||
)
|
||||
)
|
||||
)
|
||||
(pin output line
|
||||
(pin input line
|
||||
(at 7.62 -17.78 180)
|
||||
(length 2.54)
|
||||
(name "GND"
|
||||
(name "CAN_L"
|
||||
(effects
|
||||
(font
|
||||
(size 1.27 1.27)
|
||||
@@ -635,6 +635,42 @@
|
||||
)
|
||||
)
|
||||
)
|
||||
(pin output line
|
||||
(at 7.62 -30.48 180)
|
||||
(length 2.54)
|
||||
(name "GND"
|
||||
(effects
|
||||
(font
|
||||
(size 1.27 1.27)
|
||||
)
|
||||
)
|
||||
)
|
||||
(number "12"
|
||||
(effects
|
||||
(font
|
||||
(size 1.27 1.27)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
(pin output line
|
||||
(at 7.62 -33.02 180)
|
||||
(length 2.54)
|
||||
(name "GND"
|
||||
(effects
|
||||
(font
|
||||
(size 1.27 1.27)
|
||||
)
|
||||
)
|
||||
)
|
||||
(number "13"
|
||||
(effects
|
||||
(font
|
||||
(size 1.27 1.27)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
(embedded_fonts no)
|
||||
)
|
||||
|
@@ -164,45 +164,61 @@
|
||||
(remove_unused_layers no)
|
||||
(uuid "eee06414-e977-45a8-a5e0-618644284d45")
|
||||
)
|
||||
(pad "7" thru_hole rect
|
||||
(at -0.5 -12)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(pad "7" thru_hole circle
|
||||
(at -42.4 -0.06)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "536f0038-06c5-45e5-b1c8-898a364f6ec4")
|
||||
(uuid "a794ee5a-cb4c-4bc2-9f30-7f38ae9862fc")
|
||||
)
|
||||
(pad "8" thru_hole rect
|
||||
(at 39.5 -16)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(pad "8" thru_hole circle
|
||||
(at -42.4 2.48)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "3e0cdbaa-8219-48c4-bb0a-fd4f0e78a390")
|
||||
(uuid "f9ed5486-c56c-4c91-b707-d09fae18d351")
|
||||
)
|
||||
(pad "9" thru_hole rect
|
||||
(at 39.5 22.5)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "f01565c2-eadd-4451-9dea-2ebe28d872f0")
|
||||
)
|
||||
(pad "10" thru_hole rect
|
||||
(at -0.5 15)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "56ec7c50-069f-4f46-9b83-ac18e4928930")
|
||||
)
|
||||
(pad "11" thru_hole rect
|
||||
(at -43 22.5)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "f423be21-13b8-46de-8e19-e48325411a29")
|
||||
)
|
||||
(pad "12" thru_hole rect
|
||||
(at -0.5 -12)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "536f0038-06c5-45e5-b1c8-898a364f6ec4")
|
||||
)
|
||||
(pad "13" thru_hole rect
|
||||
(at 39.5 -16)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "3e0cdbaa-8219-48c4-bb0a-fd4f0e78a390")
|
||||
)
|
||||
(embedded_fonts no)
|
||||
)
|
||||
|
208
board/modules/Sensors_can/Sensors/Sensor.pretty/Sensor.kicad_mod
Normal file
208
board/modules/Sensors_can/Sensors/Sensor.pretty/Sensor.kicad_mod
Normal file
@@ -0,0 +1,208 @@
|
||||
(footprint "Sensor"
|
||||
(version 20241229)
|
||||
(generator "pcbnew")
|
||||
(generator_version "9.0")
|
||||
(layer "F.Cu")
|
||||
(property "Reference" "REF**"
|
||||
(at 0 -0.5 0)
|
||||
(unlocked yes)
|
||||
(layer "F.SilkS")
|
||||
(uuid "f71e9c26-7923-4e5c-828e-153927862740")
|
||||
(effects
|
||||
(font
|
||||
(size 1 1)
|
||||
(thickness 0.1)
|
||||
)
|
||||
)
|
||||
)
|
||||
(property "Value" "Sensor"
|
||||
(at 0 1 0)
|
||||
(unlocked yes)
|
||||
(layer "F.Fab")
|
||||
(uuid "d40c7203-0c06-49e1-8672-dbd216694fc8")
|
||||
(effects
|
||||
(font
|
||||
(size 1 1)
|
||||
(thickness 0.15)
|
||||
)
|
||||
)
|
||||
)
|
||||
(property "Datasheet" ""
|
||||
(at 0 0 0)
|
||||
(unlocked yes)
|
||||
(layer "F.Fab")
|
||||
(hide yes)
|
||||
(uuid "6720cb18-0687-4d55-a6ad-3ccf0819eac2")
|
||||
(effects
|
||||
(font
|
||||
(size 1 1)
|
||||
(thickness 0.15)
|
||||
)
|
||||
)
|
||||
)
|
||||
(property "Description" ""
|
||||
(at 0 0 0)
|
||||
(unlocked yes)
|
||||
(layer "F.Fab")
|
||||
(hide yes)
|
||||
(uuid "43905e6e-773d-4d5e-8d72-57c092c3495a")
|
||||
(effects
|
||||
(font
|
||||
(size 1 1)
|
||||
(thickness 0.15)
|
||||
)
|
||||
)
|
||||
)
|
||||
(attr smd)
|
||||
(fp_line
|
||||
(start -45 -18)
|
||||
(end 41 -18)
|
||||
(stroke
|
||||
(width 0.1)
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "e63ec799-95c4-407e-acc9-9c7e6d3e330c")
|
||||
)
|
||||
(fp_line
|
||||
(start -45 24)
|
||||
(end -45 -18)
|
||||
(stroke
|
||||
(width 0.1)
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "a66c286b-432b-493d-9619-2dd4fbfdb21c")
|
||||
)
|
||||
(fp_line
|
||||
(start -44 24)
|
||||
(end -45 24)
|
||||
(stroke
|
||||
(width 0.1)
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "71526e68-71d4-4b13-ab74-482657a06849")
|
||||
)
|
||||
(fp_line
|
||||
(start 41 -18)
|
||||
(end 41 24)
|
||||
(stroke
|
||||
(width 0.1)
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "55554342-bbff-4d1b-b931-67fb7eaa5895")
|
||||
)
|
||||
(fp_line
|
||||
(start 41 24)
|
||||
(end -44 24)
|
||||
(stroke
|
||||
(width 0.1)
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "2dc0ee59-36f6-407e-821a-c6acfe3ea887")
|
||||
)
|
||||
(fp_text user "${REFERENCE}"
|
||||
(at 0 2.5 0)
|
||||
(unlocked yes)
|
||||
(layer "F.Fab")
|
||||
(uuid "befc0725-b201-4f81-b0dc-b327becad9ba")
|
||||
(effects
|
||||
(font
|
||||
(size 1 1)
|
||||
(thickness 0.15)
|
||||
)
|
||||
)
|
||||
)
|
||||
(pad "1" thru_hole rect
|
||||
(at -42.4 -15.3)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "5538ac99-6e48-4111-a3df-8ff33be72ff3")
|
||||
)
|
||||
(pad "2" thru_hole circle
|
||||
(at -42.4 -12.76)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "0c1d4a6c-7871-46ae-a262-a8223571975e")
|
||||
)
|
||||
(pad "3" thru_hole circle
|
||||
(at -42.4 -10.22)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "70df4148-0415-45a2-8365-0977fcda45a1")
|
||||
)
|
||||
(pad "4" thru_hole circle
|
||||
(at -42.4 -7.68)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "179dd332-2ab2-4917-91ec-35f232b45ce3")
|
||||
)
|
||||
(pad "5" thru_hole circle
|
||||
(at -42.4 -5.14)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "17bc8f3a-4727-4e31-90f4-8252dff5ad1c")
|
||||
)
|
||||
(pad "6" thru_hole circle
|
||||
(at -42.4 -2.6)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "eee06414-e977-45a8-a5e0-618644284d45")
|
||||
)
|
||||
(pad "7" thru_hole rect
|
||||
(at -0.5 -12)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "536f0038-06c5-45e5-b1c8-898a364f6ec4")
|
||||
)
|
||||
(pad "8" thru_hole rect
|
||||
(at 39.5 -16)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "3e0cdbaa-8219-48c4-bb0a-fd4f0e78a390")
|
||||
)
|
||||
(pad "9" thru_hole rect
|
||||
(at 39.5 22.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "f01565c2-eadd-4451-9dea-2ebe28d872f0")
|
||||
)
|
||||
(pad "10" thru_hole rect
|
||||
(at -0.5 15)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "56ec7c50-069f-4f46-9b83-ac18e4928930")
|
||||
)
|
||||
(pad "11" thru_hole rect
|
||||
(at -43 22.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "f423be21-13b8-46de-8e19-e48325411a29")
|
||||
)
|
||||
(embedded_fonts no)
|
||||
)
|
5377
board/modules/Sensors_can/Sensors/Sensors.kicad_pcb
Normal file
5377
board/modules/Sensors_can/Sensors/Sensors.kicad_pcb
Normal file
File diff suppressed because it is too large
Load Diff
136
board/modules/Sensors_can/Sensors/Sensors.kicad_prl
Normal file
136
board/modules/Sensors_can/Sensors/Sensors.kicad_prl
Normal file
@@ -0,0 +1,136 @@
|
||||
{
|
||||
"board": {
|
||||
"active_layer": 6,
|
||||
"active_layer_preset": "All Layers",
|
||||
"auto_track_width": false,
|
||||
"hidden_netclasses": [],
|
||||
"hidden_nets": [],
|
||||
"high_contrast_mode": 0,
|
||||
"net_color_mode": 1,
|
||||
"opacity": {
|
||||
"images": 0.6,
|
||||
"pads": 1.0,
|
||||
"shapes": 1.0,
|
||||
"tracks": 1.0,
|
||||
"vias": 1.0,
|
||||
"zones": 0.6
|
||||
},
|
||||
"selection_filter": {
|
||||
"dimensions": true,
|
||||
"footprints": true,
|
||||
"graphics": true,
|
||||
"keepouts": true,
|
||||
"lockedItems": false,
|
||||
"otherItems": true,
|
||||
"pads": true,
|
||||
"text": true,
|
||||
"tracks": true,
|
||||
"vias": true,
|
||||
"zones": true
|
||||
},
|
||||
"visible_items": [
|
||||
"vias",
|
||||
"footprint_text",
|
||||
"footprint_anchors",
|
||||
"ratsnest",
|
||||
"grid",
|
||||
"footprints_front",
|
||||
"footprints_back",
|
||||
"footprint_values",
|
||||
"footprint_references",
|
||||
"tracks",
|
||||
"drc_errors",
|
||||
"drawing_sheet",
|
||||
"bitmaps",
|
||||
"pads",
|
||||
"zones",
|
||||
"drc_warnings",
|
||||
"locked_item_shadows",
|
||||
"conflict_shadows",
|
||||
"shapes"
|
||||
],
|
||||
"visible_layers": "ffffffff_ffffffff_ffffffff_ffffffff",
|
||||
"zone_display_mode": 1
|
||||
},
|
||||
"git": {
|
||||
"repo_type": "",
|
||||
"repo_username": "",
|
||||
"ssh_key": ""
|
||||
},
|
||||
"meta": {
|
||||
"filename": "Sensors.kicad_prl",
|
||||
"version": 5
|
||||
},
|
||||
"net_inspector_panel": {
|
||||
"col_hidden": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
],
|
||||
"col_order": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
10,
|
||||
11
|
||||
],
|
||||
"col_widths": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"custom_group_rules": [],
|
||||
"expanded_rows": [],
|
||||
"filter_by_net_name": true,
|
||||
"filter_by_netclass": true,
|
||||
"filter_text": "",
|
||||
"group_by_constraint": false,
|
||||
"group_by_netclass": false,
|
||||
"show_unconnected_nets": false,
|
||||
"show_zero_pad_nets": false,
|
||||
"sort_ascending": true,
|
||||
"sorting_column": 0
|
||||
},
|
||||
"open_jobsets": [],
|
||||
"project": {
|
||||
"files": []
|
||||
},
|
||||
"schematic": {
|
||||
"selection_filter": {
|
||||
"graphics": true,
|
||||
"images": true,
|
||||
"labels": true,
|
||||
"lockedItems": false,
|
||||
"otherItems": true,
|
||||
"pins": true,
|
||||
"symbols": true,
|
||||
"text": true,
|
||||
"wires": true
|
||||
}
|
||||
}
|
||||
}
|
674
board/modules/Sensors_can/Sensors/Sensors.kicad_pro
Normal file
674
board/modules/Sensors_can/Sensors/Sensors.kicad_pro
Normal file
@@ -0,0 +1,674 @@
|
||||
{
|
||||
"board": {
|
||||
"3dviewports": [],
|
||||
"design_settings": {
|
||||
"defaults": {
|
||||
"apply_defaults_to_fp_fields": false,
|
||||
"apply_defaults_to_fp_shapes": false,
|
||||
"apply_defaults_to_fp_text": false,
|
||||
"board_outline_line_width": 0.05,
|
||||
"copper_line_width": 0.2,
|
||||
"copper_text_italic": false,
|
||||
"copper_text_size_h": 1.5,
|
||||
"copper_text_size_v": 1.5,
|
||||
"copper_text_thickness": 0.3,
|
||||
"copper_text_upright": false,
|
||||
"courtyard_line_width": 0.05,
|
||||
"dimension_precision": 4,
|
||||
"dimension_units": 3,
|
||||
"dimensions": {
|
||||
"arrow_length": 1270000,
|
||||
"extension_offset": 500000,
|
||||
"keep_text_aligned": true,
|
||||
"suppress_zeroes": true,
|
||||
"text_position": 0,
|
||||
"units_format": 0
|
||||
},
|
||||
"fab_line_width": 0.1,
|
||||
"fab_text_italic": false,
|
||||
"fab_text_size_h": 1.0,
|
||||
"fab_text_size_v": 1.0,
|
||||
"fab_text_thickness": 0.15,
|
||||
"fab_text_upright": false,
|
||||
"other_line_width": 0.1,
|
||||
"other_text_italic": false,
|
||||
"other_text_size_h": 1.0,
|
||||
"other_text_size_v": 1.0,
|
||||
"other_text_thickness": 0.15,
|
||||
"other_text_upright": false,
|
||||
"pads": {
|
||||
"drill": 0.8,
|
||||
"height": 1.27,
|
||||
"width": 2.54
|
||||
},
|
||||
"silk_line_width": 0.1,
|
||||
"silk_text_italic": false,
|
||||
"silk_text_size_h": 1.0,
|
||||
"silk_text_size_v": 1.0,
|
||||
"silk_text_thickness": 0.1,
|
||||
"silk_text_upright": false,
|
||||
"zones": {
|
||||
"min_clearance": 0.5
|
||||
}
|
||||
},
|
||||
"diff_pair_dimensions": [
|
||||
{
|
||||
"gap": 0.0,
|
||||
"via_gap": 0.0,
|
||||
"width": 0.0
|
||||
}
|
||||
],
|
||||
"drc_exclusions": [],
|
||||
"meta": {
|
||||
"version": 2
|
||||
},
|
||||
"rule_severities": {
|
||||
"annular_width": "error",
|
||||
"clearance": "error",
|
||||
"connection_width": "warning",
|
||||
"copper_edge_clearance": "error",
|
||||
"copper_sliver": "warning",
|
||||
"courtyards_overlap": "error",
|
||||
"creepage": "error",
|
||||
"diff_pair_gap_out_of_range": "error",
|
||||
"diff_pair_uncoupled_length_too_long": "error",
|
||||
"drill_out_of_range": "error",
|
||||
"duplicate_footprints": "warning",
|
||||
"extra_footprint": "warning",
|
||||
"footprint": "error",
|
||||
"footprint_filters_mismatch": "ignore",
|
||||
"footprint_symbol_mismatch": "warning",
|
||||
"footprint_type_mismatch": "ignore",
|
||||
"hole_clearance": "error",
|
||||
"hole_to_hole": "warning",
|
||||
"holes_co_located": "warning",
|
||||
"invalid_outline": "error",
|
||||
"isolated_copper": "warning",
|
||||
"item_on_disabled_layer": "error",
|
||||
"items_not_allowed": "error",
|
||||
"length_out_of_range": "error",
|
||||
"lib_footprint_issues": "warning",
|
||||
"lib_footprint_mismatch": "warning",
|
||||
"malformed_courtyard": "ignore",
|
||||
"microvia_drill_out_of_range": "error",
|
||||
"mirrored_text_on_front_layer": "warning",
|
||||
"missing_courtyard": "ignore",
|
||||
"missing_footprint": "warning",
|
||||
"net_conflict": "warning",
|
||||
"nonmirrored_text_on_back_layer": "warning",
|
||||
"npth_inside_courtyard": "ignore",
|
||||
"padstack": "warning",
|
||||
"pth_inside_courtyard": "ignore",
|
||||
"shorting_items": "error",
|
||||
"silk_edge_clearance": "ignore",
|
||||
"silk_over_copper": "warning",
|
||||
"silk_overlap": "warning",
|
||||
"skew_out_of_range": "error",
|
||||
"solder_mask_bridge": "error",
|
||||
"starved_thermal": "warning",
|
||||
"text_height": "warning",
|
||||
"text_on_edge_cuts": "error",
|
||||
"text_thickness": "warning",
|
||||
"through_hole_pad_without_hole": "error",
|
||||
"too_many_vias": "error",
|
||||
"track_angle": "error",
|
||||
"track_dangling": "warning",
|
||||
"track_segment_length": "error",
|
||||
"track_width": "error",
|
||||
"tracks_crossing": "error",
|
||||
"unconnected_items": "error",
|
||||
"unresolved_variable": "error",
|
||||
"via_dangling": "warning",
|
||||
"zones_intersect": "error"
|
||||
},
|
||||
"rules": {
|
||||
"max_error": 0.005,
|
||||
"min_clearance": 0.0,
|
||||
"min_connection": 0.0,
|
||||
"min_copper_edge_clearance": 0.5,
|
||||
"min_groove_width": 0.0,
|
||||
"min_hole_clearance": 0.15,
|
||||
"min_hole_to_hole": 0.25,
|
||||
"min_microvia_diameter": 0.2,
|
||||
"min_microvia_drill": 0.1,
|
||||
"min_resolved_spokes": 2,
|
||||
"min_silk_clearance": 0.0,
|
||||
"min_text_height": 0.8,
|
||||
"min_text_thickness": 0.08,
|
||||
"min_through_hole_diameter": 0.25,
|
||||
"min_track_width": 0.0,
|
||||
"min_via_annular_width": 0.05,
|
||||
"min_via_diameter": 0.25,
|
||||
"solder_mask_to_copper_clearance": 0.005,
|
||||
"use_height_for_length_calcs": true
|
||||
},
|
||||
"teardrop_options": [
|
||||
{
|
||||
"td_onpthpad": true,
|
||||
"td_onroundshapesonly": false,
|
||||
"td_onsmdpad": true,
|
||||
"td_ontrackend": false,
|
||||
"td_onvia": true
|
||||
}
|
||||
],
|
||||
"teardrop_parameters": [
|
||||
{
|
||||
"td_allow_use_two_tracks": true,
|
||||
"td_curve_segcount": 0,
|
||||
"td_height_ratio": 1.0,
|
||||
"td_length_ratio": 0.5,
|
||||
"td_maxheight": 2.0,
|
||||
"td_maxlen": 1.0,
|
||||
"td_on_pad_in_zone": false,
|
||||
"td_target_name": "td_round_shape",
|
||||
"td_width_to_size_filter_ratio": 0.9
|
||||
},
|
||||
{
|
||||
"td_allow_use_two_tracks": true,
|
||||
"td_curve_segcount": 0,
|
||||
"td_height_ratio": 1.0,
|
||||
"td_length_ratio": 0.5,
|
||||
"td_maxheight": 2.0,
|
||||
"td_maxlen": 1.0,
|
||||
"td_on_pad_in_zone": false,
|
||||
"td_target_name": "td_rect_shape",
|
||||
"td_width_to_size_filter_ratio": 0.9
|
||||
},
|
||||
{
|
||||
"td_allow_use_two_tracks": true,
|
||||
"td_curve_segcount": 0,
|
||||
"td_height_ratio": 1.0,
|
||||
"td_length_ratio": 0.5,
|
||||
"td_maxheight": 2.0,
|
||||
"td_maxlen": 1.0,
|
||||
"td_on_pad_in_zone": false,
|
||||
"td_target_name": "td_track_end",
|
||||
"td_width_to_size_filter_ratio": 0.9
|
||||
}
|
||||
],
|
||||
"track_widths": [
|
||||
0.0,
|
||||
0.1,
|
||||
0.2,
|
||||
0.5
|
||||
],
|
||||
"tuning_pattern_settings": {
|
||||
"diff_pair_defaults": {
|
||||
"corner_radius_percentage": 80,
|
||||
"corner_style": 1,
|
||||
"max_amplitude": 1.0,
|
||||
"min_amplitude": 0.2,
|
||||
"single_sided": false,
|
||||
"spacing": 1.0
|
||||
},
|
||||
"diff_pair_skew_defaults": {
|
||||
"corner_radius_percentage": 80,
|
||||
"corner_style": 1,
|
||||
"max_amplitude": 1.0,
|
||||
"min_amplitude": 0.2,
|
||||
"single_sided": false,
|
||||
"spacing": 0.6
|
||||
},
|
||||
"single_track_defaults": {
|
||||
"corner_radius_percentage": 80,
|
||||
"corner_style": 1,
|
||||
"max_amplitude": 1.0,
|
||||
"min_amplitude": 0.2,
|
||||
"single_sided": false,
|
||||
"spacing": 0.6
|
||||
}
|
||||
},
|
||||
"via_dimensions": [
|
||||
{
|
||||
"diameter": 0.0,
|
||||
"drill": 0.0
|
||||
},
|
||||
{
|
||||
"diameter": 0.3,
|
||||
"drill": 0.25
|
||||
}
|
||||
],
|
||||
"zones_allow_external_fillets": false
|
||||
},
|
||||
"ipc2581": {
|
||||
"dist": "",
|
||||
"distpn": "",
|
||||
"internal_id": "",
|
||||
"mfg": "",
|
||||
"mpn": ""
|
||||
},
|
||||
"layer_pairs": [],
|
||||
"layer_presets": [],
|
||||
"viewports": []
|
||||
},
|
||||
"boards": [],
|
||||
"cvpcb": {
|
||||
"equivalence_files": []
|
||||
},
|
||||
"erc": {
|
||||
"erc_exclusions": [],
|
||||
"meta": {
|
||||
"version": 0
|
||||
},
|
||||
"pin_map": [
|
||||
[
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
2,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
2,
|
||||
1,
|
||||
1,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
2,
|
||||
1,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
2,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
0,
|
||||
2,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
2,
|
||||
0,
|
||||
0,
|
||||
2
|
||||
],
|
||||
[
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2,
|
||||
2
|
||||
]
|
||||
],
|
||||
"rule_severities": {
|
||||
"bus_definition_conflict": "error",
|
||||
"bus_entry_needed": "error",
|
||||
"bus_to_bus_conflict": "error",
|
||||
"bus_to_net_conflict": "error",
|
||||
"different_unit_footprint": "error",
|
||||
"different_unit_net": "error",
|
||||
"duplicate_reference": "error",
|
||||
"duplicate_sheet_names": "error",
|
||||
"endpoint_off_grid": "warning",
|
||||
"extra_units": "error",
|
||||
"footprint_filter": "ignore",
|
||||
"footprint_link_issues": "warning",
|
||||
"four_way_junction": "ignore",
|
||||
"global_label_dangling": "warning",
|
||||
"hier_label_mismatch": "error",
|
||||
"label_dangling": "error",
|
||||
"label_multiple_wires": "warning",
|
||||
"lib_symbol_issues": "warning",
|
||||
"lib_symbol_mismatch": "warning",
|
||||
"missing_bidi_pin": "warning",
|
||||
"missing_input_pin": "warning",
|
||||
"missing_power_pin": "error",
|
||||
"missing_unit": "warning",
|
||||
"multiple_net_names": "warning",
|
||||
"net_not_bus_member": "warning",
|
||||
"no_connect_connected": "warning",
|
||||
"no_connect_dangling": "warning",
|
||||
"pin_not_connected": "error",
|
||||
"pin_not_driven": "error",
|
||||
"pin_to_pin": "ignore",
|
||||
"power_pin_not_driven": "ignore",
|
||||
"same_local_global_label": "warning",
|
||||
"similar_label_and_power": "warning",
|
||||
"similar_labels": "warning",
|
||||
"similar_power": "warning",
|
||||
"simulation_model_issue": "ignore",
|
||||
"single_global_label": "ignore",
|
||||
"unannotated": "error",
|
||||
"unconnected_wire_endpoint": "warning",
|
||||
"unit_value_mismatch": "error",
|
||||
"unresolved_variable": "error",
|
||||
"wire_dangling": "error"
|
||||
}
|
||||
},
|
||||
"libraries": {
|
||||
"pinned_footprint_libs": [],
|
||||
"pinned_symbol_libs": []
|
||||
},
|
||||
"meta": {
|
||||
"filename": "Sensors.kicad_pro",
|
||||
"version": 3
|
||||
},
|
||||
"net_settings": {
|
||||
"classes": [
|
||||
{
|
||||
"bus_width": 12,
|
||||
"clearance": 0.15,
|
||||
"diff_pair_gap": 0.25,
|
||||
"diff_pair_via_gap": 0.25,
|
||||
"diff_pair_width": 0.2,
|
||||
"line_style": 0,
|
||||
"microvia_diameter": 0.3,
|
||||
"microvia_drill": 0.1,
|
||||
"name": "Default",
|
||||
"pcb_color": "rgba(0, 0, 0, 0.000)",
|
||||
"priority": 2147483647,
|
||||
"schematic_color": "rgba(0, 0, 0, 0.000)",
|
||||
"track_width": 0.2,
|
||||
"via_diameter": 0.6,
|
||||
"via_drill": 0.3,
|
||||
"wire_width": 6
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"version": 4
|
||||
},
|
||||
"net_colors": null,
|
||||
"netclass_assignments": null,
|
||||
"netclass_patterns": []
|
||||
},
|
||||
"pcbnew": {
|
||||
"last_paths": {
|
||||
"gencad": "",
|
||||
"idf": "",
|
||||
"netlist": "",
|
||||
"plot": "",
|
||||
"pos_files": "",
|
||||
"specctra_dsn": "",
|
||||
"step": "Sensors.step",
|
||||
"svg": "",
|
||||
"vrml": ""
|
||||
},
|
||||
"page_layout_descr_file": ""
|
||||
},
|
||||
"schematic": {
|
||||
"annotate_start_num": 0,
|
||||
"bom_export_filename": "${PROJECTNAME}.csv",
|
||||
"bom_fmt_presets": [],
|
||||
"bom_fmt_settings": {
|
||||
"field_delimiter": ",",
|
||||
"keep_line_breaks": false,
|
||||
"keep_tabs": false,
|
||||
"name": "CSV",
|
||||
"ref_delimiter": ",",
|
||||
"ref_range_delimiter": "",
|
||||
"string_delimiter": "\""
|
||||
},
|
||||
"bom_presets": [],
|
||||
"bom_settings": {
|
||||
"exclude_dnp": false,
|
||||
"fields_ordered": [
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Reference",
|
||||
"name": "Reference",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": true,
|
||||
"label": "Value",
|
||||
"name": "Value",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": true,
|
||||
"label": "Footprint",
|
||||
"name": "Footprint",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Datasheet",
|
||||
"name": "Datasheet",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Description",
|
||||
"name": "Description",
|
||||
"show": false
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Qty",
|
||||
"name": "${QUANTITY}",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "#",
|
||||
"name": "${ITEM_NUMBER}",
|
||||
"show": false
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "LCSC_PART_NUMBER",
|
||||
"name": "LCSC_PART_NUMBER",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Sim.Device",
|
||||
"name": "Sim.Device",
|
||||
"show": false
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Sim.Pins",
|
||||
"name": "Sim.Pins",
|
||||
"show": false
|
||||
},
|
||||
{
|
||||
"group_by": false,
|
||||
"label": "Sim.Type",
|
||||
"name": "Sim.Type",
|
||||
"show": false
|
||||
},
|
||||
{
|
||||
"group_by": true,
|
||||
"label": "DNP",
|
||||
"name": "${DNP}",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": true,
|
||||
"label": "Exclude from BOM",
|
||||
"name": "${EXCLUDE_FROM_BOM}",
|
||||
"show": true
|
||||
},
|
||||
{
|
||||
"group_by": true,
|
||||
"label": "Exclude from Board",
|
||||
"name": "${EXCLUDE_FROM_BOARD}",
|
||||
"show": true
|
||||
}
|
||||
],
|
||||
"filter_string": "",
|
||||
"group_symbols": true,
|
||||
"include_excluded_from_bom": true,
|
||||
"name": "",
|
||||
"sort_asc": true,
|
||||
"sort_field": "Reference"
|
||||
},
|
||||
"connection_grid_size": 50.0,
|
||||
"drawing": {
|
||||
"dashed_lines_dash_length_ratio": 12.0,
|
||||
"dashed_lines_gap_length_ratio": 3.0,
|
||||
"default_line_thickness": 6.0,
|
||||
"default_text_size": 50.0,
|
||||
"field_names": [],
|
||||
"intersheets_ref_own_page": false,
|
||||
"intersheets_ref_prefix": "",
|
||||
"intersheets_ref_short": false,
|
||||
"intersheets_ref_show": false,
|
||||
"intersheets_ref_suffix": "",
|
||||
"junction_size_choice": 3,
|
||||
"label_size_ratio": 0.375,
|
||||
"operating_point_overlay_i_precision": 3,
|
||||
"operating_point_overlay_i_range": "~A",
|
||||
"operating_point_overlay_v_precision": 3,
|
||||
"operating_point_overlay_v_range": "~V",
|
||||
"overbar_offset_ratio": 1.23,
|
||||
"pin_symbol_size": 25.0,
|
||||
"text_offset_ratio": 0.15
|
||||
},
|
||||
"legacy_lib_dir": "",
|
||||
"legacy_lib_list": [],
|
||||
"meta": {
|
||||
"version": 1
|
||||
},
|
||||
"net_format_name": "",
|
||||
"page_layout_descr_file": "",
|
||||
"plot_directory": "",
|
||||
"space_save_all_events": true,
|
||||
"spice_current_sheet_as_root": false,
|
||||
"spice_external_command": "spice \"%I\"",
|
||||
"spice_model_current_sheet_as_root": true,
|
||||
"spice_save_all_currents": false,
|
||||
"spice_save_all_dissipations": false,
|
||||
"spice_save_all_voltages": false,
|
||||
"subpart_first_id": 65,
|
||||
"subpart_id_separator": 0
|
||||
},
|
||||
"sheets": [
|
||||
[
|
||||
"46346c04-8bed-48b4-837b-9342dd403232",
|
||||
"Root"
|
||||
]
|
||||
],
|
||||
"text_variables": {}
|
||||
}
|
3405
board/modules/Sensors_can/Sensors/Sensors.kicad_sch
Normal file
3405
board/modules/Sensors_can/Sensors/Sensors.kicad_sch
Normal file
File diff suppressed because it is too large
Load Diff
35338
board/modules/Sensors_can/Sensors/Sensors.step
Normal file
35338
board/modules/Sensors_can/Sensors/Sensors.step
Normal file
File diff suppressed because it is too large
Load Diff
4
board/modules/Sensors_can/Sensors/sym-lib-table
Normal file
4
board/modules/Sensors_can/Sensors/sym-lib-table
Normal file
@@ -0,0 +1,4 @@
|
||||
(sym_lib_table
|
||||
(version 7)
|
||||
(lib (name "Modules")(type "KiCad")(uri "/home/empire/workspace/PlantCtrl/board/modules/Modules.kicad_sym")(options "")(descr ""))
|
||||
)
|
14
board/modules/Sensors_can/ch32-sensor/.cargo/config.toml
Normal file
14
board/modules/Sensors_can/ch32-sensor/.cargo/config.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[build]
|
||||
target = "riscv32imc-unknown-none-elf"
|
||||
|
||||
[target."riscv32imc-unknown-none-elf"]
|
||||
rustflags = [
|
||||
# "-C", "link-arg=-Tlink.x",
|
||||
]
|
||||
# runner = "riscv64-unknown-elf-gdb -q -x openocd.gdb"
|
||||
# runner = "riscv-none-embed-gdb -q -x openocd.gdb"
|
||||
# runner = "gdb -q -x openocd.gdb"
|
||||
# runner = "wlink -v flash"
|
||||
|
||||
runner = "wlink -v flash --enable-sdi-print --watch-serial --erase"
|
||||
# runner = "wlink -v flash"
|
7
board/modules/Sensors_can/ch32-sensor/.gdbinit
Normal file
7
board/modules/Sensors_can/ch32-sensor/.gdbinit
Normal file
@@ -0,0 +1,7 @@
|
||||
target extended-remote :3333
|
||||
set remotetimeout 2000
|
||||
|
||||
#symbol-file target/riscv32imc-unknown-none-elf/release/ch32v203-examples
|
||||
file target/riscv32imc-unknown-none-elf/release/bms
|
||||
|
||||
monitor reset halt
|
1
board/modules/Sensors_can/ch32-sensor/.gitignore
vendored
Normal file
1
board/modules/Sensors_can/ch32-sensor/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
target
|
43
board/modules/Sensors_can/ch32-sensor/Cargo.toml
Normal file
43
board/modules/Sensors_can/ch32-sensor/Cargo.toml
Normal file
@@ -0,0 +1,43 @@
|
||||
[package]
|
||||
name = "bms"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
ch32-hal = { git = "https://github.com/ch32-rs/ch32-hal", features = [
|
||||
"ch32v203c8t6",
|
||||
"memory-x",
|
||||
"embassy",
|
||||
"rt",
|
||||
"time-driver-tim2",
|
||||
], default-features = false }
|
||||
|
||||
embassy-executor = { version = "0.7.0", features = [
|
||||
"arch-riscv32",
|
||||
"executor-thread",
|
||||
] }
|
||||
|
||||
embassy-time = { version = "0.4.0" }
|
||||
embassy-usb = { version = "0.3.0" }
|
||||
embassy-futures = { version = "0.1.0" }
|
||||
|
||||
# This is okay because we should automatically use whatever ch32-hal uses
|
||||
qingke-rt = "*"
|
||||
qingke = "*"
|
||||
|
||||
panic-halt = "1.0"
|
||||
|
||||
embedded-hal = "1.0.0"
|
||||
heapless = "0.8.0"
|
||||
micromath = { version = "2.1.0", features = ["num-traits"] }
|
||||
embedded-can = "0.4.1"
|
||||
|
||||
[profile.dev]
|
||||
#lto = true
|
||||
opt-level = 1
|
||||
|
||||
[profile.release]
|
||||
strip = false # symbols are not flashed to the microcontroller, so don't strip them.
|
||||
#lto = true
|
||||
debug = true
|
||||
opt-level = "z" # Optimize for size.
|
72
board/modules/Sensors_can/ch32-sensor/README.md
Normal file
72
board/modules/Sensors_can/ch32-sensor/README.md
Normal file
@@ -0,0 +1,72 @@
|
||||
|
||||
# ch32v203-bms
|
||||
|
||||
A simple battery management controller software.
|
||||
|
||||
## CAN bus and hardware address
|
||||
|
||||
This firmware exposes a CAN interface on the CH32V203 and uses 4 hardware address pins to allow up to 16 sensors on the same bus.
|
||||
|
||||
- CAN pins (default mapping):
|
||||
- CAN RX: PA11
|
||||
- CAN TX: PA12
|
||||
- Address select pins (with internal pull-ups):
|
||||
- A0: PA0
|
||||
- A1: PA1
|
||||
- A2: PA2
|
||||
- A3: PA3
|
||||
|
||||
Wire each address pin to GND to set its corresponding bit to 1. The 4-bit address range is 0..15. The node’s CAN Standard ID is `0x100 | addr`, i.e. 0x100..0x10F. The CAN acceptance filter is configured to only accept frames with the node’s own ID.
|
||||
|
||||
Adjust the pins above if your PCB routes CAN or address lines to different pads.
|
||||
|
||||
## 555 timer (software) emulation mode
|
||||
|
||||
To save the BOM cost of a classic NE555 in simple oscillator applications, this firmware implements a minimal 555-like Schmitt trigger using the MCU’s ADC and a GPIO, approximating the behavior when the capacitor is charged/discharged via Q through a resistor, and the combined Trigger/Threshold senses the capacitor node.
|
||||
|
||||
- Pins used:
|
||||
- Q output: PB2
|
||||
- Combined Trigger/Threshold (ADC input): PA0
|
||||
- Wiring:
|
||||
- PB2 (Q) -> series resistor R -> capacitor node
|
||||
- Capacitor node -> capacitor to GND
|
||||
- Capacitor node -> PA0 (ADC input)
|
||||
- Behavior:
|
||||
- When ADC(PA0) <= ~1/3 Vref, PB2 is driven High.
|
||||
- When ADC(PA0) >= ~2/3 Vref, PB2 is driven Low.
|
||||
- Hysteresis avoids chatter; the actual charge/discharge dynamics follow your chosen R and C.
|
||||
- Notes:
|
||||
- Use an appropriate resistor from PB2 to the capacitor to set oscillation frequency. Start with 10k..100k and adjust with C.
|
||||
- Ensure PA0 is routed to the capacitor node and left high impedance (no strong pull-ups/downs) so the ADC can sense the analog voltage.
|
||||
- PB2 drives the on-board LED (if present), so the LED might blink at the oscillation frequency.
|
||||
|
||||
This mode is implemented in `src/main.rs` using `hal::adc::Adc::convert(&mut pin, SampleTime::...)` to take periodic samples and a simple state machine to toggle the Q output based on ~1/3 and ~2/3 Vref thresholds.
|
||||
|
||||
## Building
|
||||
|
||||
``` sh
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
## Flash
|
||||
|
||||
``` sh
|
||||
wchisp config reset
|
||||
wchip wchisp flash target/riscv32imc-unknown-none-elf/release/bms
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
For debugging purposes a container file is provided together with wrapper scripts to start the containerized `openocd` and `riscv-gdb` transparently. The wrapper scripts assume that `podman` is setup.
|
||||
|
||||
Starting Debug server
|
||||
|
||||
```
|
||||
./bin/openocd
|
||||
```
|
||||
|
||||
Connecting with gdb for interactive debugging
|
||||
|
||||
```
|
||||
./bin/gdb -f target/riscv32imc-unknown-none-elf/release/bms
|
||||
```
|
10
board/modules/Sensors_can/ch32-sensor/bin/build-wch-tools-container.sh
Executable file
10
board/modules/Sensors_can/ch32-sensor/bin/build-wch-tools-container.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_NAME="localhost/wch-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
|
||||
pushd "$CONTAINER_TOOLS_BASEDIR"
|
||||
podman build -t "$CONTAINER_NAME" -f "../wch-tools.Containerfile" .
|
||||
popd
|
29
board/modules/Sensors_can/ch32-sensor/bin/gdb
Executable file
29
board/modules/Sensors_can/ch32-sensor/bin/gdb
Executable file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_IMAGE="localhost/wch-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
|
||||
function _fatal {
|
||||
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
declare -a PODMAN_ARGS=(
|
||||
"--rm" "-i" "--log-driver=none"
|
||||
"--network=host"
|
||||
"--pid=host"
|
||||
"-v" "$PWD:$PWD:rw"
|
||||
"-w" "$PWD"
|
||||
)
|
||||
|
||||
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
|
||||
|
||||
if ! podman image exists "$CONTAINER_IMAGE"; then
|
||||
#attempt to build container
|
||||
"$CONTAINER_TOOLS_BASEDIR/build-wch-tools-container.sh" 1>&2 ||
|
||||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
|
||||
fi
|
||||
|
||||
podman run "${PODMAN_ARGS[@]}" --entrypoint riscv-none-elf-gdb-py3 "$CONTAINER_IMAGE" "$@"
|
44
board/modules/Sensors_can/ch32-sensor/bin/openocd
Executable file
44
board/modules/Sensors_can/ch32-sensor/bin/openocd
Executable file
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CONTAINER_IMAGE="localhost/wch-dev-tools:latest"
|
||||
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
|
||||
|
||||
function _fatal {
|
||||
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
declare -a PODMAN_ARGS=(
|
||||
"--rm" "-i" "--log-driver=none"
|
||||
"--network=host"
|
||||
"-v" "$PWD:$PWD:rw"
|
||||
"-w" "$PWD"
|
||||
)
|
||||
|
||||
for device in /dev/bus/usb/*/*; do
|
||||
if udevadm info "$device" | grep -q "ID_VENDOR=wch.cn" && \
|
||||
udevadm info "$device" | grep -q "ID_MODEL=WCH-Link"; then
|
||||
DEBUGGER_DEV_PATH="$device"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ -z "${DEBUGGER_DEV_PATH:-}" ]]; then
|
||||
echo "Could not find hardware debugger … Exiting!" 1>&2
|
||||
exit 1
|
||||
else
|
||||
# add jlink to podman device
|
||||
PODMAN_ARGS+=("--device=$DEBUGGER_DEV_PATH")
|
||||
fi
|
||||
|
||||
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
|
||||
|
||||
if ! podman image exists "$CONTAINER_IMAGE"; then
|
||||
#attempt to build container
|
||||
"$CONTAINER_TOOLS_BASEDIR/build-wch-tools-container.sh" 1>&2 ||
|
||||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
|
||||
fi
|
||||
|
||||
podman run "${PODMAN_ARGS[@]}" --entrypoint openocd "$CONTAINER_IMAGE" "$@"
|
11
board/modules/Sensors_can/ch32-sensor/build.rs
Normal file
11
board/modules/Sensors_can/ch32-sensor/build.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
fn main() {
|
||||
// println!("cargo:rustc-link-arg-bins=--nmagic");
|
||||
println!("cargo:rustc-link-arg-bins=-Tlink.x");
|
||||
// println!("cargo:rustc-link-arg-bins=-Tdefmt.x");
|
||||
|
||||
let out_dir = std::env::var("OUT_DIR").unwrap();
|
||||
let out_dir = std::path::PathBuf::from(out_dir);
|
||||
std::fs::write(out_dir.join("memory.x"), include_bytes!("memory.x")).unwrap();
|
||||
println!("cargo:rustc-link-search={}", out_dir.display());
|
||||
println!("cargo:rerun-if-changed=memory.x");
|
||||
}
|
125
board/modules/Sensors_can/ch32-sensor/memory.x
Normal file
125
board/modules/Sensors_can/ch32-sensor/memory.x
Normal file
@@ -0,0 +1,125 @@
|
||||
/* CH32V203c8t6 */
|
||||
MEMORY
|
||||
{
|
||||
FLASH : ORIGIN = 0x00000000, LENGTH = 64K /* BANK_1 */
|
||||
RAM : ORIGIN = 0x20000000, LENGTH = 20K
|
||||
}
|
||||
REGION_ALIAS("REGION_TEXT", FLASH);
|
||||
REGION_ALIAS("REGION_RODATA", FLASH);
|
||||
REGION_ALIAS("REGION_DATA", RAM);
|
||||
REGION_ALIAS("REGION_BSS", RAM);
|
||||
REGION_ALIAS("REGION_HEAP", RAM);
|
||||
REGION_ALIAS("REGION_STACK", RAM);
|
||||
|
||||
/* fault handlers */
|
||||
|
||||
PROVIDE(InstructionMisaligned = ExceptionHandler);
|
||||
PROVIDE(InstructionFault = ExceptionHandler);
|
||||
PROVIDE(IllegalInstruction = ExceptionHandler);
|
||||
PROVIDE(Breakpoint = ExceptionHandler);
|
||||
PROVIDE(LoadMisaligned = ExceptionHandler);
|
||||
PROVIDE(LoadFault = ExceptionHandler);
|
||||
PROVIDE(StoreMisaligned = ExceptionHandler);
|
||||
PROVIDE(StoreFault = ExceptionHandler);;
|
||||
PROVIDE(UserEnvCall = ExceptionHandler);
|
||||
PROVIDE(SupervisorEnvCall = ExceptionHandler);
|
||||
PROVIDE(MachineEnvCall = ExceptionHandler);
|
||||
PROVIDE(InstructionPageFault = ExceptionHandler);
|
||||
PROVIDE(LoadPageFault = ExceptionHandler);
|
||||
PROVIDE(StorePageFault = ExceptionHandler);
|
||||
|
||||
/* core interrupt handlers */
|
||||
|
||||
PROVIDE(NonMaskableInt = DefaultHandler);
|
||||
PROVIDE(Software = DefaultHandler);
|
||||
|
||||
/* external interrupt handlers */
|
||||
|
||||
PROVIDE(WWDG = DefaultHandler);
|
||||
PROVIDE(PVD = DefaultHandler);
|
||||
PROVIDE(TAMPER = DefaultHandler);
|
||||
PROVIDE(RTC = DefaultHandler);
|
||||
PROVIDE(FLASH = DefaultHandler);
|
||||
PROVIDE(RCC = DefaultHandler);
|
||||
PROVIDE(EXTI0 = DefaultHandler);
|
||||
PROVIDE(EXTI1 = DefaultHandler);
|
||||
PROVIDE(EXTI2 = DefaultHandler);
|
||||
PROVIDE(EXTI3 = DefaultHandler);
|
||||
PROVIDE(EXTI4 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL1 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL2 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL3 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL4 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL5 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL6 = DefaultHandler);
|
||||
PROVIDE(DMA1_CHANNEL7 = DefaultHandler);
|
||||
PROVIDE(ADC = DefaultHandler);
|
||||
PROVIDE(USB_HP_CAN1_TX = DefaultHandler);
|
||||
/*PROVIDE(USB_LP_CAN1_RX0 = DefaultHandler);*/
|
||||
PROVIDE(CAN1_RX1 = DefaultHandler);
|
||||
PROVIDE(CAN1_SCE = DefaultHandler);
|
||||
PROVIDE(EXTI9_5 = DefaultHandler);
|
||||
PROVIDE(TIM1_BRK = DefaultHandler);
|
||||
PROVIDE(TIM1_UP_ = DefaultHandler);
|
||||
PROVIDE(TIM1_TRG_COM = DefaultHandler);
|
||||
PROVIDE(TIM1_CC = DefaultHandler);
|
||||
PROVIDE(TIM2 = DefaultHandler);
|
||||
PROVIDE(TIM3 = DefaultHandler);
|
||||
PROVIDE(TIM4 = DefaultHandler);
|
||||
PROVIDE(I2C1_EV = DefaultHandler);
|
||||
PROVIDE(I2C1_ER = DefaultHandler);
|
||||
PROVIDE(I2C2_EV = DefaultHandler);
|
||||
PROVIDE(I2C2_ER = DefaultHandler);
|
||||
PROVIDE(SPI1 = DefaultHandler);
|
||||
PROVIDE(SPI2 = DefaultHandler);
|
||||
PROVIDE(USART1 = DefaultHandler);
|
||||
PROVIDE(USART2 = DefaultHandler);
|
||||
PROVIDE(USART3 = DefaultHandler);
|
||||
PROVIDE(EXTI15_10 = DefaultHandler);
|
||||
PROVIDE(RTCALARM = DefaultHandler);
|
||||
PROVIDE(USBWAKE_UP = DefaultHandler);
|
||||
PROVIDE(TIM8_BRK = DefaultHandler);
|
||||
PROVIDE(TIM8_UP_ = DefaultHandler);
|
||||
PROVIDE(TIM8_TRG_COM = DefaultHandler);
|
||||
PROVIDE(TIM8_CC = DefaultHandler);
|
||||
PROVIDE(RNG = DefaultHandler);
|
||||
PROVIDE(FSMC = DefaultHandler);
|
||||
PROVIDE(SDIO = DefaultHandler);
|
||||
PROVIDE(TIM5 = DefaultHandler);
|
||||
PROVIDE(SPI3 = DefaultHandler);
|
||||
PROVIDE(UART4 = DefaultHandler);
|
||||
PROVIDE(UART5 = DefaultHandler);
|
||||
PROVIDE(TIM6 = DefaultHandler);
|
||||
PROVIDE(TIM7 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL1 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL2 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL3 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL4 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL5 = DefaultHandler);
|
||||
PROVIDE(ETH = DefaultHandler);
|
||||
PROVIDE(ETH_WKUP = DefaultHandler);
|
||||
PROVIDE(CAN2_TX = DefaultHandler);
|
||||
PROVIDE(CAN2_RX0 = DefaultHandler);
|
||||
PROVIDE(CAN2_RX1 = DefaultHandler);
|
||||
PROVIDE(CAN2_SCE = DefaultHandler);
|
||||
PROVIDE(OTG_FS = DefaultHandler);
|
||||
PROVIDE(USBHSWAKEUP = DefaultHandler);
|
||||
PROVIDE(USBHS = DefaultHandler);
|
||||
PROVIDE(DVP = DefaultHandler);
|
||||
PROVIDE(UART6 = DefaultHandler);
|
||||
PROVIDE(UART7 = DefaultHandler);
|
||||
PROVIDE(UART8 = DefaultHandler);
|
||||
PROVIDE(TIM9_BRK = DefaultHandler);
|
||||
PROVIDE(TIM9_UP_ = DefaultHandler);
|
||||
PROVIDE(TIM9_TRG_COM = DefaultHandler);
|
||||
PROVIDE(TIM9_CC = DefaultHandler);
|
||||
PROVIDE(TIM10_BRK = DefaultHandler);
|
||||
PROVIDE(TIM10_UP_ = DefaultHandler);
|
||||
PROVIDE(TIM10_TRG_COM = DefaultHandler);
|
||||
PROVIDE(TIM10_CC = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL6 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL7 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL8 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL9 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL10 = DefaultHandler);
|
||||
PROVIDE(DMA2_CHANNEL11 = DefaultHandler);
|
17
board/modules/Sensors_can/ch32-sensor/openocd.cfg
Normal file
17
board/modules/Sensors_can/ch32-sensor/openocd.cfg
Normal file
@@ -0,0 +1,17 @@
|
||||
set _CHIPNAME ch32v203
|
||||
set _TARGETNAME $_CHIPNAME.cpu
|
||||
|
||||
#bindto 0.0.0.0
|
||||
|
||||
adapter driver wlinke
|
||||
adapter speed 6000
|
||||
transport select sdi
|
||||
|
||||
sdi newtap $_CHIPNAME cpu -irlen 5 --expected-id 0x00001
|
||||
target create $_TARGETNAME.0 wch_riscv -chain-position $_TARGETNAME
|
||||
$_TARGETNAME.0 configure -work-area-phys 0x20000000 -work-area-size 10000 -work-area-backup 1
|
||||
set _FLASHNAME $_CHIPNAME.flash
|
||||
|
||||
flash bank $_FLASHNAME wch_rsicv 0x00000000 0 0 0 $_TARGETNAME.0
|
||||
|
||||
init
|
@@ -0,0 +1,2 @@
|
||||
[toolchain]
|
||||
channel = "nightly"
|
61
board/modules/Sensors_can/ch32-sensor/src/main.rs
Normal file
61
board/modules/Sensors_can/ch32-sensor/src/main.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
#![feature(type_alias_impl_trait)]
|
||||
#![feature(impl_trait_in_assoc_type)]
|
||||
|
||||
// Simple 555-like oscillator implemented in firmware.
|
||||
// - Q output: PB2 (also drives the on-board LED if present)
|
||||
// - Combined Trigger/Threshold analog input: PA0 (capacitor node)
|
||||
// Wiring suggestion:
|
||||
// Q (PB2) --[R]--+-- C -- GND
|
||||
// |
|
||||
// PA0 (ADC input)
|
||||
// The firmware toggles Q high when PA0 <= 1/3 Vref and low when PA0 >= 2/3 Vref.
|
||||
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_time::Timer;
|
||||
use hal::gpio::{Level, Output};
|
||||
use {ch32_hal as hal, panic_halt as _};
|
||||
|
||||
use hal::adc::{Adc, SampleTime};
|
||||
|
||||
#[embassy_executor::main(entry = "qingke_rt::entry")]
|
||||
async fn main(_spawner: Spawner) -> ! {
|
||||
let p = hal::init(Default::default());
|
||||
|
||||
// Q output on PB2
|
||||
let mut q = Output::new(p.PB2, Level::Low, Default::default());
|
||||
|
||||
// ADC on PA0 for combined Trigger/Threshold input
|
||||
let mut adc = Adc::new(p.ADC1, Default::default());
|
||||
let mut trig_thres = p.PA0; // analog-capable pin used as ADC channel
|
||||
|
||||
// ADC characteristics: assume 12-bit if HAL doesn't expose it.
|
||||
// If the HAL provides a method to query resolution, prefer that.
|
||||
let full_scale: u16 = 4095; // 12-bit default
|
||||
let thr_low: u16 = (full_scale as u32 / 3) as u16; // ~1/3 Vref
|
||||
let thr_high: u16 = ((full_scale as u32 * 2) / 3) as u16; // ~2/3 Vref
|
||||
|
||||
// Start with Q low. State variable to avoid redundant toggles.
|
||||
let mut q_high = false;
|
||||
q.set_low();
|
||||
|
||||
loop {
|
||||
// Read capacitor node voltage via ADC
|
||||
let sample: u16 = adc.convert(&mut trig_thres, SampleTime::CYCLES239_5);
|
||||
|
||||
// Implement Schmitt trigger behavior like NE555 using thresholds
|
||||
if !q_high && sample <= thr_low {
|
||||
// Trigger: voltage fell below 1/3 Vref -> set output high
|
||||
q.set_high();
|
||||
q_high = true;
|
||||
} else if q_high && sample >= thr_high {
|
||||
// Threshold: voltage rose above 2/3 Vref -> set output low
|
||||
q.set_low();
|
||||
q_high = false;
|
||||
}
|
||||
|
||||
// Small delay to reduce CPU usage; adjust for responsiveness/noise
|
||||
Timer::after_micros(200).await;
|
||||
}
|
||||
}
|
@@ -0,0 +1,27 @@
|
||||
FROM debian:bookworm
|
||||
|
||||
RUN apt update -y && apt upgrade -y && apt install git libjaylink-dev libusb-1.0-0 unzip curl libhidapi-hidraw0 xz-utils -y
|
||||
|
||||
RUN cd /root && \
|
||||
curl -L -o mrs-toolchain.tar.xz "https://github.com/ch32-riscv-ug/MounRiver_Studio_Community_miror/releases/download/1.92-toolchain/MRS_Toolchain_Linux_x64_V1.92.tar.xz" && \
|
||||
mkdir mrs-toolchain && \
|
||||
tar -xvf mrs-toolchain.tar.xz -C mrs-toolchain --strip-components=1 && \
|
||||
mv mrs-toolchain/OpenOCD/bin/openocd /usr/local/bin && \
|
||||
mv mrs-toolchain/OpenOCD/share/openocd /usr/local/share && \
|
||||
# mv mrs-toolchain/RISC-V_Embedded_GCC12/bin/riscv-none-elf-gdb /usr/local/bin && \ # both toolchains in MRS are to old to work with emacs dape
|
||||
# mv mrs-toolchain/RISC-V_Embedded_GCC12/libexec /usr/local && \ # both toolchains in MRS are to old to work with emacs dape
|
||||
rm -rf mrs-toolchain mrs-toolchain.tar.xz && \
|
||||
# Use up to date xpack toolchains for gdb
|
||||
curl -L -o xpack-riscv-toolchain.tar.gz "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v14.2.0-3/xpack-riscv-none-elf-gcc-14.2.0-3-linux-x64.tar.gz" && \
|
||||
mkdir xpack-toolchain && \
|
||||
tar -xvf xpack-riscv-toolchain.tar.gz -C xpack-toolchain --strip-components=1 && \
|
||||
mv xpack-toolchain/bin/* /usr/local/bin && \
|
||||
mv xpack-toolchain/lib/ /usr/local && \
|
||||
mv xpack-toolchain/lib64/ /usr/local && \
|
||||
mv xpack-toolchain/libexec /usr/local && \
|
||||
mv xpack-toolchain/riscv-none-elf /usr/local && \
|
||||
rm -rf xpack-toolchain xpack-riscv-toolchain.tar.gz
|
||||
|
||||
RUN mkdir -p /root/.config/gdb && echo "set auto-load safe-path /" >> /root/.config/gdb/gdbinit
|
||||
|
||||
ENTRYPOINT [ "/usr/bin/bash" ]
|
@@ -166,40 +166,40 @@
|
||||
)
|
||||
(pad "7" thru_hole rect
|
||||
(at -0.5 -12)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "536f0038-06c5-45e5-b1c8-898a364f6ec4")
|
||||
)
|
||||
(pad "8" thru_hole rect
|
||||
(at 39.5 -16)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "3e0cdbaa-8219-48c4-bb0a-fd4f0e78a390")
|
||||
)
|
||||
(pad "9" thru_hole rect
|
||||
(at 39.5 22.5)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "f01565c2-eadd-4451-9dea-2ebe28d872f0")
|
||||
)
|
||||
(pad "10" thru_hole rect
|
||||
(at -0.5 15)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "56ec7c50-069f-4f46-9b83-ac18e4928930")
|
||||
)
|
||||
(pad "11" thru_hole rect
|
||||
(at -43 22.5)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(uuid "f423be21-13b8-46de-8e19-e48325411a29")
|
||||
|
@@ -738,7 +738,7 @@
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "87f61a83-c9a2-45b6-a235-fe6e83f3dbe3")
|
||||
(uuid "23d58535-2840-4798-8fe6-a41e5dd82cfc")
|
||||
)
|
||||
(fp_line
|
||||
(start -45 24)
|
||||
@@ -748,7 +748,7 @@
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "f24175c8-21e2-4899-af70-89e48457e9ba")
|
||||
(uuid "ed3c0755-343c-4d19-9481-c2c33348ef82")
|
||||
)
|
||||
(fp_line
|
||||
(start -44 24)
|
||||
@@ -758,7 +758,7 @@
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "a884c661-0353-48a0-9bc6-995e02652e36")
|
||||
(uuid "cd2e639b-4e20-40a4-8976-6223f2753aeb")
|
||||
)
|
||||
(fp_line
|
||||
(start 41 -18)
|
||||
@@ -768,7 +768,7 @@
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "675d135e-52c1-4dd1-b434-983f40a2b544")
|
||||
(uuid "f34b006e-828a-45d3-b0f5-daad16782ed8")
|
||||
)
|
||||
(fp_line
|
||||
(start 41 24)
|
||||
@@ -778,7 +778,7 @@
|
||||
(type default)
|
||||
)
|
||||
(layer "F.SilkS")
|
||||
(uuid "fbfb2621-73ae-4c15-8403-abdec5cc45cd")
|
||||
(uuid "03fcb85f-a42f-4eab-bf16-6ff7087e0441")
|
||||
)
|
||||
(fp_text user "${REFERENCE}"
|
||||
(at 0 2.5 0)
|
||||
@@ -860,8 +860,8 @@
|
||||
)
|
||||
(pad "7" thru_hole rect
|
||||
(at -0.5 -12)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(net 1 "GND")
|
||||
@@ -871,8 +871,8 @@
|
||||
)
|
||||
(pad "8" thru_hole rect
|
||||
(at 39.5 -16)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(net 1 "GND")
|
||||
@@ -882,8 +882,8 @@
|
||||
)
|
||||
(pad "9" thru_hole rect
|
||||
(at 39.5 22.5)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(net 1 "GND")
|
||||
@@ -893,8 +893,8 @@
|
||||
)
|
||||
(pad "10" thru_hole rect
|
||||
(at -0.5 15)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(net 1 "GND")
|
||||
@@ -904,8 +904,8 @@
|
||||
)
|
||||
(pad "11" thru_hole rect
|
||||
(at -43 22.5)
|
||||
(size 0.85 0.85)
|
||||
(drill 0.5)
|
||||
(size 1.7 1.7)
|
||||
(drill 1)
|
||||
(layers "*.Cu" "*.Mask")
|
||||
(remove_unused_layers no)
|
||||
(net 1 "GND")
|
||||
|
@@ -460,6 +460,7 @@
|
||||
"single_global_label": "ignore",
|
||||
"unannotated": "error",
|
||||
"unconnected_wire_endpoint": "warning",
|
||||
"undefined_netclass": "error",
|
||||
"unit_value_mismatch": "error",
|
||||
"unresolved_variable": "error",
|
||||
"wire_dangling": "error"
|
||||
|
4
board/modules/Sensors_simplified/Sensors/fp-lib-table
Normal file
4
board/modules/Sensors_simplified/Sensors/fp-lib-table
Normal file
@@ -0,0 +1,4 @@
|
||||
(fp_lib_table
|
||||
(version 7)
|
||||
(lib (name "Sensor")(type "KiCad")(uri "${KIPRJMOD}/Sensor.pretty")(options "")(descr ""))
|
||||
)
|
Binary file not shown.
@@ -1,154 +1,177 @@
|
||||
P CODE 00
|
||||
P UNITS CUST 0
|
||||
P arrayDim N
|
||||
317CAN- VIA MD0157PA00X+070354Y-006220X0315Y0000R000S3
|
||||
317CAN+ VIA MD0157PA00X+064606Y-009213X0315Y0000R000S3
|
||||
317FLOW VIA MD0157PA00X+048543Y-021063X0315Y0000R000S3
|
||||
317TEMP VIA MD0157PA00X+048898Y-023268X0315Y0000R000S3
|
||||
317EN VIA MD0157PA00X+062697Y-009154X0315Y0000R000S3
|
||||
317EN VIA MD0157PA00X+062500Y-010827X0315Y0000R000S3
|
||||
317VBAT VIA MD0157PA00X+043130Y-036024X0315Y0000R000S3
|
||||
317VBAT VIA MD0157PA00X+043130Y-035039X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+077500Y-007000X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+062402Y-010433X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054134Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+062205Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058169Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+051772Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+041500Y-042900X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059685Y-012402X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054429Y-011909X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+053346Y-010925X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+062205Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+040945Y-035630X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+077500Y-042900X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059055Y-012402X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056594Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+061122Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054626Y-010827X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056693Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045669Y-007087X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054724Y-012205X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+063386Y-011220X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059685Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045699Y-017156X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048091Y-016535X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+053740Y-011220X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048917Y-031102X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056299Y-005591X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055709Y-011220X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058169Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+061654Y-008071X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054035Y-010138X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054331Y-010531X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055217Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056102Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055315Y-011516X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055709Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054921Y-011220X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059843Y-005591X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050787Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+049016Y-034154X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+051772Y-008858X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046555Y-030512X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+061122Y-012303X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055709Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059055Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+041575Y-007087X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+040945Y-034646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+063386Y-012598X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048031Y-014567X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+057185Y-011516X0315Y0000R000S3
|
||||
3173_3V VIA MD0157PA00X+064646Y-014567X0315Y0000R000S3
|
||||
3173_3V VIA MD0157PA00X+075906Y-014331X0315Y0000R000S3
|
||||
3173_3V VIA MD0157PA00X+074094Y-014331X0315Y0000R000S3
|
||||
3173_3V VIA MD0157PA00X+067874Y-014567X0315Y0000R000S3
|
||||
317TEMP VIA MD0157PA00X+072343Y-012303X0315Y0000R000S3
|
||||
317TEMP VIA MD0157PA00X+049099Y-026344X0315Y0000R000S3
|
||||
317TANK_SENSOR VIA MD0157PA00X+063091Y-007776X0315Y0000R000S3
|
||||
317TANK_SENSOR VIA MD0157PA00X+047244Y-017421X0315Y0000R000S3
|
||||
317CHARGE VIA MD0157PA00X+071949Y-006693X0315Y0000R000S3
|
||||
317ESP_RX VIA MD0157PA00X+071949Y-007776X0315Y0000R000S3
|
||||
317ESP_TX VIA MD0157PA00X+071949Y-007283X0315Y0000R000S3
|
||||
317SDA VIA MD0157PA00X+048031Y-014094X0315Y0000R000S3
|
||||
317CHARGE VIA MD0157PA00X+071575Y-006732X0315Y0000R000S3
|
||||
317SDA VIA MD0157PA00X+072441Y-010630X0315Y0000R000S3
|
||||
317SCL VIA MD0157PA00X+048819Y-013780X0315Y0000R000S3
|
||||
317SDA VIA MD0157PA00X+050134Y-014937X0315Y0000R000S3
|
||||
317SCL VIA MD0157PA00X+072441Y-011417X0315Y0000R000S3
|
||||
317SCL VIA MD0157PA00X+051535Y-013898X0315Y0000R000S3
|
||||
317NET-(CD1-A) VIA MD0157PA00X+058661Y-009843X0315Y0000R000S3
|
||||
317NET-(CD1-A) VIA MD0157PA00X+045866Y-005906X0315Y0000R000S3
|
||||
317CD_PROBE VIA MD0157PA00X+072638Y-009744X0315Y0000R000S3
|
||||
317ISDAY VIA MD0157PA00X+066929Y-011024X0315Y0000R000S3
|
||||
317LED_ENABLE VIA MD0157PA00X+064764Y-010728X0315Y0000R000S3
|
||||
317WORKING VIA MD0157PA00X+058661Y-011417X0315Y0000R000S3
|
||||
317WORKING VIA MD0157PA00X+071949Y-008169X0315Y0000R000S3
|
||||
317WORKING VIA MD0157PA00X+069843Y-008858X0315Y0000R000S3
|
||||
317ENABLE_TANK VIA MD0157PA00X+062894Y-011516X0315Y0000R000S3
|
||||
317ENABLE_TANK VIA MD0157PA00X+050525Y-015584X0315Y0000R000S3
|
||||
317USB_D- VIA MD0157PA00X+045276Y-010305X0315Y0000R000S3
|
||||
317USB_D- VIA MD0157PA00X+063377Y-011752X0315Y0000R000S3
|
||||
317USB_D- VIA MD0157PA00X+052902Y-009500X0315Y0000R000S3
|
||||
317FLOW VIA MD0157PA00X+048543Y-023228X0315Y0000R000S3
|
||||
317FLOW VIA MD0157PA00X+063484Y-007382X0315Y0000R000S3
|
||||
317USB_D+ VIA MD0157PA00X+045276Y-010719X0315Y0000R000S3
|
||||
317USB_D+ VIA MD0157PA00X+063377Y-012165X0315Y0000R000S3
|
||||
317USB_D+ VIA MD0157PA00X+052610Y-009792X0315Y0000R000S3
|
||||
317BOOT_SEL VIA MD0157PA00X+064764Y-009744X0315Y0000R000S3
|
||||
317BOOT_SEL VIA MD0157PA00X+070374Y-012205X0315Y0000R000S3
|
||||
317WARN_LED VIA MD0157PA00X+069803Y-008465X0315Y0000R000S3
|
||||
317WARN_LED VIA MD0157PA00X+044390Y-005807X0315Y0000R000S3
|
||||
317WARN_LED VIA MD0157PA00X+063386Y-008268X0315Y0000R000S3
|
||||
327GND U2 -1 A01X+064094Y-005709X0591Y0354R000S2
|
||||
3273_3V U2 -2 A01X+064094Y-006209X0591Y0354R000S2
|
||||
327EN U2 -3 A01X+064094Y-006709X0591Y0354R000S2
|
||||
327FLOW U2 -4 A01X+064094Y-007209X0591Y0354R000S2
|
||||
327TANK_SENSOR U2 -5 A01X+064094Y-007709X0591Y0354R000S2
|
||||
327WARN_LED U2 -6 A01X+064094Y-008209X0591Y0354R000S2
|
||||
327ISDAY U2 -7 A01X+064094Y-008709X0591Y0354R000S2
|
||||
327-(U2-IO0-PAD8) U2 -8 A01X+064094Y-009209X0591Y0354R000S2
|
||||
327BOOT_SEL U2 -9 A01X+064094Y-009709X0591Y0354R000S2
|
||||
327(U2-IO8-PAD10) U2 -10 A01X+064094Y-010209X0591Y0354R000S2
|
||||
327LED_ENABLE U2 -11 A01X+064094Y-010709X0591Y0354R000S2
|
||||
327ENABLE_TANK U2 -12 A01X+064094Y-011209X0591Y0354R000S2
|
||||
327USB_D- U2 -13 A01X+064094Y-011709X0591Y0354R000S2
|
||||
327USB_D+ U2 -14 A01X+064094Y-012209X0591Y0354R000S2
|
||||
327BOOT_SEL U2 -15 A01X+070984Y-012209X0591Y0354R000S2
|
||||
327TEMP U2 -16 A01X+070984Y-011709X0591Y0354R000S2
|
||||
327SCL U2 -17 A01X+070984Y-011209X0591Y0354R000S2
|
||||
327SDA U2 -18 A01X+070984Y-010709X0591Y0354R000S2
|
||||
327EXTRA_2 U2 -19 A01X+070984Y-010209X0591Y0354R000S2
|
||||
327CD_PROBE U2 -20 A01X+070984Y-009709X0591Y0354R000S2
|
||||
327EXTRA_1 U2 -21 A01X+070984Y-009209X0591Y0354R000S2
|
||||
327-(U2-NC-PAD22) U2 -22 A01X+070984Y-008709X0591Y0354R000S2
|
||||
327WORKING U2 -23 A01X+070984Y-008209X0591Y0354R000S2
|
||||
327ESP_RX U2 -24 A01X+070984Y-007709X0591Y0354R000S2
|
||||
327ESP_TX U2 -25 A01X+070984Y-007209X0591Y0354R000S2
|
||||
327CHARGE U2 -26 A01X+070984Y-006709X0591Y0354R000S2
|
||||
327PUMP_ENABLE U2 -27 A01X+070984Y-006209X0591Y0354R000S2
|
||||
327GND U2 -28 A01X+070984Y-005709X0591Y0354R000S2
|
||||
327GND U2 -29_5 A01X+066947Y-007961X0315Y0315R000S2
|
||||
327GND U2 -29_1 A01X+066455Y-007469X0315Y0315R000S2
|
||||
327GND U2 -29_2 A01X+066947Y-007469X0315Y0315R000S2
|
||||
327GND U2 -29_3 A01X+067439Y-007469X0315Y0315R000S2
|
||||
327GND U2 -29_4 A01X+066455Y-007961X0315Y0315R000S2
|
||||
327GND U2 -29_6 A01X+067439Y-007961X0315Y0315R000S2
|
||||
327GND U2 -29_7 A01X+066455Y-008453X0315Y0315R000S2
|
||||
327GND U2 -29_8 A01X+066947Y-008453X0315Y0315R000S2
|
||||
327GND U2 -29_9 A01X+067439Y-008453X0315Y0315R000S2
|
||||
317GND U2 -30_1 D0098PA00X+066701Y-007469X0138Y0000R000S3
|
||||
317GND U2 -30_2 D0098PA00X+067193Y-007469X0138Y0000R000S3
|
||||
317GND U2 -30_3 D0098PA00X+066455Y-007715X0138Y0000R000S3
|
||||
317GND U2 -30_4 D0098PA00X+066947Y-007715X0138Y0000R000S3
|
||||
317GND U2 -30_5 D0098PA00X+067439Y-007715X0138Y0000R000S3
|
||||
317GND U2 -30_6 D0098PA00X+066701Y-007961X0138Y0000R000S3
|
||||
317GND U2 -30_7 D0098PA00X+067193Y-007961X0138Y0000R000S3
|
||||
317GND U2 -30_8 D0098PA00X+066455Y-008207X0138Y0000R000S3
|
||||
317GND U2 -30_9 D0098PA00X+066947Y-008207X0138Y0000R000S3
|
||||
317GND U2 -30_1 D0098PA00X+067439Y-008207X0138Y0000R000S3
|
||||
317GND U2 -30_1 D0098PA00X+066701Y-008453X0138Y0000R000S3
|
||||
317GND U2 -30_1 D0098PA00X+067193Y-008453X0138Y0000R000S3
|
||||
317CONFIG2 VIA MD0157PA00X+060394Y-009724X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+077500Y-007000X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+062402Y-010433X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054449Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+044606Y-010551X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054921Y-011417X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050787Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042126Y-008976X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+062205Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059291Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058150Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054843Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+043228Y-012480X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050827Y-007402X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+047244Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+060374Y-011594X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+041500Y-042900X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+047165Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042717Y-013031X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+057008Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+062205Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058917Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+040945Y-035630X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059606Y-011575X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+077500Y-042900X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046890Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054016Y-010591X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046457Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045039Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045748Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+051850Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+051260Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054646Y-011142X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+043819Y-011929X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046102Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059646Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050079Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056594Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045118Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+061122Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+043346Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056693Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+044055Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+052559Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050197Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048228Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045669Y-007087X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+063386Y-011220X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+060433Y-005591X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+060472Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045699Y-017156X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048661Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+049724Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048091Y-016535X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048917Y-031102X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+053858Y-011693X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+049843Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059232Y-011575X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055709Y-011220X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058169Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+044094Y-011654X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+061654Y-008071X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050551Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+049370Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042402Y-009213X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+059980Y-011594X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056181Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+044409Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055276Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+056181Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045394Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+060748Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+044685Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055276Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+051142Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055748Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045827Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+052835Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+053189Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+047953Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+052205Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+053780Y-010315X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058465Y-005591X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046181Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+051496Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+053583Y-011378X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+049016Y-034154X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+045472Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+058543Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054331Y-010866X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046811Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046555Y-030512X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+052913Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+043701Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048307Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+061181Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+049488Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+047520Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+060059Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042283Y-013386X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+044764Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+055709Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+060827Y-012323X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+054134Y-011969X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+046535Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+043504Y-012205X0315Y0000R000S3
|
||||
317GND VIA MD1181PA00X+041575Y-007087X1575Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050906Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042992Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+040945Y-034646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+063386Y-012598X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+047598Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+047874Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042756Y-009291X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+050433Y-009646X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+048583Y-011260X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+057185Y-011614X0315Y0000R000S3
|
||||
317GND VIA MD0157PA00X+042953Y-012756X0315Y0000R000S3
|
||||
3273_3V R19 -2 A01X+048898Y-022037X0315Y0374R270S2
|
||||
327TEMP R19 -1 A01X+048898Y-022687X0315Y0374R270S2
|
||||
3173_3V U5 -1 D0394PA00X+046339Y-019764X0669Y0669R000S0
|
||||
317(U5-VBAT-PAD2) U5 -2 D0394PA00X+046339Y-020764X0669Y0000R000S0
|
||||
317VBAT U5 -2 D0394PA00X+046339Y-020764X0669Y0000R000S0
|
||||
317SDA U5 -3 D0394PA00X+046339Y-021764X0669Y0000R000S0
|
||||
317SCL U5 -4 D0394PA00X+046339Y-022764X0669Y0000R000S0
|
||||
317CD_PROBE U5 -5 D0394PA00X+046339Y-023764X0669Y0000R000S0
|
||||
317GND U5 -6 D0394PA00X+046339Y-024764X0669Y0000R000S0
|
||||
317GND U5 -7 D0197PA00X+062835Y-021063X0335Y0335R000S0
|
||||
317GND U5 -8 D0197PA00X+078583Y-019488X0335Y0335R000S0
|
||||
317CAN+ U5 -6 D0394PA00X+046339Y-024764X0669Y0000R000S0
|
||||
317CAN- U5 -7 D0394PA00X+046339Y-025764X0669Y0000R000S0
|
||||
317GND U5 -8 D0394PA00X+046339Y-026764X0669Y0000R000S0
|
||||
317GND U5 -9 D0197PA00X+078583Y-034646X0335Y0335R000S0
|
||||
317GND U5 -10 D0197PA00X+062835Y-031693X0335Y0335R000S0
|
||||
317GND U5 -11 D0197PA00X+046102Y-034646X0335Y0335R000S0
|
||||
317GND U5 -12 D0197PA00X+062835Y-021063X0335Y0335R000S0
|
||||
317GND U5 -13 D0197PA00X+078583Y-019488X0335Y0335R000S0
|
||||
327GND D11 -1 A01X+046506Y-030000X0581Y0236R180S2
|
||||
327VBAT D11 -2 A01X+046506Y-029252X0581Y0236R180S2
|
||||
327NET-(D10-K) D11 -3 A01X+045768Y-029626X0581Y0236R180S2
|
||||
@@ -163,8 +186,8 @@ P arrayDim N
|
||||
317GND U3 -9 D0394PA00X+050827Y-017869X0669Y0669R000S0
|
||||
317GND U3 -10 D0394PA00X+059685Y-010782X0669Y0669R000S0
|
||||
317GND U3 -11 D0394PA00X+059685Y-017869X0669Y0669R000S0
|
||||
327GND Reset1-1 A01X+059843Y-006024X0591Y0591R090S2
|
||||
327NET-(C4-PAD2) Reset1-2 A01X+059843Y-009094X0591Y0591R090S2
|
||||
327GND Reset1-1 A01X+060394Y-006024X0591Y0591R090S2
|
||||
327CONFIG2 Reset1-2 A01X+060394Y-009094X0591Y0591R090S2
|
||||
317GND U6 -1 D0394PA00X+078465Y-036024X0669Y0669R090S0
|
||||
317GND U6 -2 D0394PA00X+071378Y-044016X0669Y0669R000S0
|
||||
317GND U6 -3 D0394PA00X+047756Y-044016X0669Y0669R000S0
|
||||
@@ -183,10 +206,10 @@ P arrayDim N
|
||||
327SDA R11 -2 A01X+072904Y-010630X0315Y0374R180S2
|
||||
327GND C2 -1 A01X+062062Y-008268X0423Y0374R000S2
|
||||
327EN C2 -2 A01X+062741Y-008268X0423Y0374R000S2
|
||||
327GND Boot1 -1 A01X+056299Y-006024X0591Y0591R090S2
|
||||
327T-(BOOT1-PAD2) Boot1 -2 A01X+056299Y-009094X0591Y0591R090S2
|
||||
327GND Boot1 -1 A01X+058425Y-006024X0591Y0591R090S2
|
||||
327T-(BOOT1-PAD2) Boot1 -2 A01X+058425Y-009094X0591Y0591R090S2
|
||||
327EN R7 -1 A01X+061614Y-011152X0315Y0374R270S2
|
||||
327NET-(C4-PAD2) R7 -2 A01X+061614Y-010502X0315Y0374R270S2
|
||||
327CONFIG2 R7 -2 A01X+061614Y-010502X0315Y0374R270S2
|
||||
317GND J5 -1 D0295PA00X+042323Y-021457X0472Y0689R270S0
|
||||
3173_3V J5 -2 D0295PA00X+042323Y-020669X0472Y0689R270S0
|
||||
317FLOW J5 -3 D0295PA00X+042323Y-019882X0472Y0689R270S0
|
||||
@@ -197,9 +220,9 @@ P arrayDim N
|
||||
327GND R16 -2 A01X+048091Y-016043X0315Y0374R180S2
|
||||
327NET-(Q2-G) R22 -1 A01X+047805Y-034843X0315Y0374R000S2
|
||||
327GND R22 -2 A01X+048455Y-034843X0315Y0374R000S2
|
||||
327FLOW D5 -3 A01X+047288Y-023228X0581Y0236R180S2
|
||||
3273_3V D5 -2 A01X+048027Y-022854X0581Y0236R180S2
|
||||
327GND D5 -1 A01X+048027Y-023602X0581Y0236R180S2
|
||||
327FLOW D5 -3 A01X+047288Y-020295X0581Y0236R180S2
|
||||
3273_3V D5 -2 A01X+048027Y-019921X0581Y0236R180S2
|
||||
327GND D5 -1 A01X+048027Y-020669X0581Y0236R180S2
|
||||
327NET-(D2-K) D2 -1 A01X+043701Y-006570X0384Y0551R270S2
|
||||
327WARN_LED D2 -2 A01X+043701Y-005832X0384Y0551R270S2
|
||||
327GND D6 -1 A01X+046043Y-016811X0581Y0236R180S2
|
||||
@@ -207,25 +230,25 @@ P arrayDim N
|
||||
327TANK_SENSOR D6 -3 A01X+045305Y-016437X0581Y0236R180S2
|
||||
327NET-(CD1-A) R9 -1 A01X+058661Y-010305X0315Y0374R090S2
|
||||
327WORKING R9 -2 A01X+058661Y-010955X0315Y0374R090S2
|
||||
317GND J6 -1 D0394PA00X+041319Y-014661X0669Y0669R180S0
|
||||
3173_3V J6 -2 D0394PA00X+041319Y-013661X0669Y0000R180S0
|
||||
317SDA J6 -3 D0394PA00X+041319Y-012661X0669Y0000R180S0
|
||||
317SCL J6 -4 D0394PA00X+041319Y-011661X0669Y0000R180S0
|
||||
317SQW J6 -5 D0394PA00X+041319Y-010661X0669Y0000R180S0
|
||||
31732K J6 -6 D0394PA00X+041319Y-009661X0669Y0000R180S0
|
||||
317GND J6 -1 D0394PA00X+046906Y-006220X0669Y0669R270S0
|
||||
3173_3V J6 -2 D0394PA00X+047906Y-006220X0669Y0000R270S0
|
||||
317SDA J6 -3 D0394PA00X+048906Y-006220X0669Y0000R270S0
|
||||
317SCL J6 -4 D0394PA00X+049906Y-006220X0669Y0000R270S0
|
||||
317SQW J6 -5 D0394PA00X+050906Y-006220X0669Y0000R270S0
|
||||
31732K J6 -6 D0394PA00X+051906Y-006220X0669Y0000R270S0
|
||||
327NET-(D8-K) D8 -1 A01X+040945Y-033243X0384Y0551R270S2
|
||||
327NET-(D8-A) D8 -2 A01X+040945Y-032505X0384Y0551R270S2
|
||||
327NET-(J2-PIN_2) R2 -1 A01X+046457Y-005581X0315Y0374R090S2
|
||||
327GND R2 -2 A01X+046457Y-006230X0315Y0374R090S2
|
||||
327USB_D+ U1 -1 A01X+050251Y-009286X0522Y0236R180S2
|
||||
327GND U1 -2 A01X+050251Y-008912X0522Y0236R180S2
|
||||
327USB_D- U1 -3 A01X+050251Y-008538X0522Y0236R180S2
|
||||
327SLASH}O2-PAD4) U1 -4 A01X+049355Y-008538X0522Y0236R180S2
|
||||
327USB_BUS U1 -5 A01X+049355Y-008912X0522Y0236R180S2
|
||||
327SLASH}O1-PAD6) U1 -6 A01X+049355Y-009286X0522Y0236R180S2
|
||||
327TEMP D7 -3 A01X+047288Y-025295X0581Y0236R180S2
|
||||
3273_3V D7 -2 A01X+048027Y-024921X0581Y0236R180S2
|
||||
327GND D7 -1 A01X+048027Y-025669X0581Y0236R180S2
|
||||
327NET-(J2-PIN_2) R2 -1 A01X+042943Y-014764X0315Y0374R000S2
|
||||
327GND R2 -2 A01X+043593Y-014764X0315Y0374R000S2
|
||||
327USB_D+ U1 -1 A01X+044124Y-010945X0522Y0236R180S2
|
||||
327GND U1 -2 A01X+044124Y-010571X0522Y0236R180S2
|
||||
327USB_D- U1 -3 A01X+044124Y-010197X0522Y0236R180S2
|
||||
327SLASH}O2-PAD4) U1 -4 A01X+043228Y-010197X0522Y0236R180S2
|
||||
327USB_BUS U1 -5 A01X+043228Y-010571X0522Y0236R180S2
|
||||
327SLASH}O1-PAD6) U1 -6 A01X+043228Y-010945X0522Y0236R180S2
|
||||
327TEMP D7 -3 A01X+047288Y-022362X0581Y0236R180S2
|
||||
3273_3V D7 -2 A01X+048027Y-021988X0581Y0236R180S2
|
||||
327GND D7 -1 A01X+048027Y-022736X0581Y0236R180S2
|
||||
327VBAT C8 -1 A01X+042534Y-036024X0463Y0571R180S2
|
||||
327GND C8 -2 A01X+041718Y-036024X0463Y0571R180S2
|
||||
327NET-(R3-PAD1) R3 -1 A01X+057677Y-012933X0315Y0374R090S2
|
||||
@@ -234,13 +257,18 @@ P arrayDim N
|
||||
327ENABLE_TANK R14 -2 A01X+050089Y-016043X0315Y0374R000S2
|
||||
327GND C1 -1 A01X+056299Y-011112X0423Y0374R270S2
|
||||
327T-(BOOT1-PAD2) C1 -2 A01X+056299Y-010433X0423Y0374R270S2
|
||||
327GND D3 -1 A01X+046752Y-012106X0581Y0236R000S2
|
||||
3273_3V D3 -2 A01X+046752Y-012854X0581Y0236R000S2
|
||||
327SCL D3 -3 A01X+047490Y-012480X0581Y0236R000S2
|
||||
327TEMP R19 -1 A01X+049099Y-025295X0315Y0374R000S2
|
||||
3273_3V R19 -2 A01X+049749Y-025295X0315Y0374R000S2
|
||||
327GND D3 -1 A01X+051102Y-007992X0581Y0236R000S2
|
||||
3273_3V D3 -2 A01X+051102Y-008740X0581Y0236R000S2
|
||||
327SCL D3 -3 A01X+051841Y-008366X0581Y0236R000S2
|
||||
3173_3V C9 -1 D0315PA00X+046165Y-012441X0630Y0630R000S0
|
||||
3173_3V C9 -1 D0315PA00X+046429Y-013071X0630Y0630R000S0
|
||||
317GND C9 -2 D0315PA00X+047413Y-013071X0630Y0000R000S0
|
||||
317GND C9 -2 D0315PA00X+047677Y-013701X0630Y0000R000S0
|
||||
3273_3V C6 -1 A01X+062205Y-007392X0463Y0571R270S2
|
||||
327GND C6 -2 A01X+062205Y-006575X0463Y0571R270S2
|
||||
317WARN_LED J8 -1 D0394PA00X+055787Y-006386X0669Y0669R000S0
|
||||
317GND J8 -2 D0394PA00X+055787Y-007386X0669Y0000R000S0
|
||||
317CONFIG2 J8 -3 D0394PA00X+055787Y-008386X0669Y0000R000S0
|
||||
327NET-(Q3-G) R21 -1 A01X+047805Y-031102X0315Y0374R000S2
|
||||
327GND R21 -2 A01X+048455Y-031102X0315Y0374R000S2
|
||||
317LED_ENABLE U4 -1 D0394PA00X+074063Y-009173X0669Y0000R090S0
|
||||
@@ -261,31 +289,80 @@ P arrayDim N
|
||||
327BOOT_SEL C5 -2 A01X+062992Y-009700X0423Y0374R270S2
|
||||
327TANK_SENSOR R12 -1 A01X+047215Y-016831X0404Y0551R270S2
|
||||
3273_3V R12 -2 A01X+047215Y-016112X0404Y0551R270S2
|
||||
327NET-(D2-K) R1 -1 A01X+045935Y-007874X0315Y0374R000S2
|
||||
327GND R1 -2 A01X+046585Y-007874X0315Y0374R000S2
|
||||
327NET-(D2-K) R1 -1 A01X+044488Y-008317X0315Y0374R270S2
|
||||
327GND R1 -2 A01X+044488Y-007667X0315Y0374R270S2
|
||||
327EXTRA_1 R20 -1 A01X+048455Y-031890X0315Y0374R180S2
|
||||
327NET-(Q3-G) R20 -2 A01X+047805Y-031890X0315Y0374R180S2
|
||||
327GND U2 -1 A01X+064094Y-005709X0591Y0354R000S2
|
||||
3273_3V U2 -2 A01X+064094Y-006209X0591Y0354R000S2
|
||||
327EN U2 -3 A01X+064094Y-006709X0591Y0354R000S2
|
||||
327FLOW U2 -4 A01X+064094Y-007209X0591Y0354R000S2
|
||||
327TANK_SENSOR U2 -5 A01X+064094Y-007709X0591Y0354R000S2
|
||||
327EXTRA_1 U2 -6 A01X+064094Y-008209X0591Y0354R000S2
|
||||
327ISDAY U2 -7 A01X+064094Y-008709X0591Y0354R000S2
|
||||
327CAN+ U2 -8 A01X+064094Y-009209X0591Y0354R000S2
|
||||
327BOOT_SEL U2 -9 A01X+064094Y-009709X0591Y0354R000S2
|
||||
327(U2-IO8-PAD10) U2 -10 A01X+064094Y-010209X0591Y0354R000S2
|
||||
327LED_ENABLE U2 -11 A01X+064094Y-010709X0591Y0354R000S2
|
||||
327ENABLE_TANK U2 -12 A01X+064094Y-011209X0591Y0354R000S2
|
||||
327USB_D- U2 -13 A01X+064094Y-011709X0591Y0354R000S2
|
||||
327USB_D+ U2 -14 A01X+064094Y-012209X0591Y0354R000S2
|
||||
327BOOT_SEL U2 -15 A01X+070984Y-012209X0591Y0354R000S2
|
||||
327TEMP U2 -16 A01X+070984Y-011709X0591Y0354R000S2
|
||||
327SCL U2 -17 A01X+070984Y-011209X0591Y0354R000S2
|
||||
327SDA U2 -18 A01X+070984Y-010709X0591Y0354R000S2
|
||||
327WORKING U2 -19 A01X+070984Y-010209X0591Y0354R000S2
|
||||
327CD_PROBE U2 -20 A01X+070984Y-009709X0591Y0354R000S2
|
||||
327WARN_LED U2 -21 A01X+070984Y-009209X0591Y0354R000S2
|
||||
327-(U2-NC-PAD22) U2 -22 A01X+070984Y-008709X0591Y0354R000S2
|
||||
327EXTRA_2 U2 -23 A01X+070984Y-008209X0591Y0354R000S2
|
||||
327ESP_RX U2 -24 A01X+070984Y-007709X0591Y0354R000S2
|
||||
327ESP_TX U2 -25 A01X+070984Y-007209X0591Y0354R000S2
|
||||
327CHARGE U2 -26 A01X+070984Y-006709X0591Y0354R000S2
|
||||
327CAN- U2 -27 A01X+070984Y-006209X0591Y0354R000S2
|
||||
327GND U2 -28 A01X+070984Y-005709X0591Y0354R000S2
|
||||
327GND U2 -29_1 A01X+066455Y-007469X0315Y0315R000S2
|
||||
327GND U2 -29_2 A01X+066947Y-007469X0315Y0315R000S2
|
||||
327GND U2 -29_3 A01X+067439Y-007469X0315Y0315R000S2
|
||||
327GND U2 -29_4 A01X+066455Y-007961X0315Y0315R000S2
|
||||
327GND U2 -29_5 A01X+066947Y-007961X0315Y0315R000S2
|
||||
327GND U2 -29_6 A01X+067439Y-007961X0315Y0315R000S2
|
||||
327GND U2 -29_7 A01X+066455Y-008453X0315Y0315R000S2
|
||||
327GND U2 -29_8 A01X+066947Y-008453X0315Y0315R000S2
|
||||
327GND U2 -29_9 A01X+067439Y-008453X0315Y0315R000S2
|
||||
317GND U2 -30_1 D0098PA00X+066701Y-007469X0138Y0000R000S3
|
||||
317GND U2 -30_2 D0098PA00X+067193Y-007469X0138Y0000R000S3
|
||||
317GND U2 -30_3 D0098PA00X+066455Y-007715X0138Y0000R000S3
|
||||
317GND U2 -30_4 D0098PA00X+066947Y-007715X0138Y0000R000S3
|
||||
317GND U2 -30_5 D0098PA00X+067439Y-007715X0138Y0000R000S3
|
||||
317GND U2 -30_6 D0098PA00X+066701Y-007961X0138Y0000R000S3
|
||||
317GND U2 -30_7 D0098PA00X+067193Y-007961X0138Y0000R000S3
|
||||
317GND U2 -30_8 D0098PA00X+066455Y-008207X0138Y0000R000S3
|
||||
317GND U2 -30_9 D0098PA00X+066947Y-008207X0138Y0000R000S3
|
||||
317GND U2 -30_1 D0098PA00X+067439Y-008207X0138Y0000R000S3
|
||||
317GND U2 -30_1 D0098PA00X+066701Y-008453X0138Y0000R000S3
|
||||
317GND U2 -30_1 D0098PA00X+067193Y-008453X0138Y0000R000S3
|
||||
317NET-(D10-K) Extra_-1 D0394PA00X+042283Y-029616X0669Y0787R270S0
|
||||
317VBAT Extra_-2 D0394PA00X+042283Y-028632X0669Y0787R270S0
|
||||
327GND D1 -1 A01X+047441Y-014469X0581Y0236R180S2
|
||||
3273_3V D1 -2 A01X+047441Y-013720X0581Y0236R180S2
|
||||
327SDA D1 -3 A01X+046703Y-014094X0581Y0236R180S2
|
||||
327GND D1 -1 A01X+046033Y-007933X0581Y0236R000S2
|
||||
3273_3V D1 -2 A01X+046033Y-008681X0581Y0236R000S2
|
||||
327SDA D1 -3 A01X+046772Y-008307X0581Y0236R000S2
|
||||
3273_3V R10 -1 A01X+073553Y-011417X0315Y0374R180S2
|
||||
327SCL R10 -2 A01X+072904Y-011417X0315Y0374R180S2
|
||||
327EXTRA_2 R23 -1 A01X+048455Y-035728X0315Y0374R180S2
|
||||
327NET-(Q2-G) R23 -2 A01X+047805Y-035728X0315Y0374R180S2
|
||||
327VBAT R18 -1 A01X+046033Y-028445X0315Y0374R000S2
|
||||
327NET-(D10-A) R18 -2 A01X+046683Y-028445X0315Y0374R000S2
|
||||
327NET-(J2-PIN_5) R4 -1 A01X+053150Y-005581X0315Y0374R090S2
|
||||
327GND R4 -2 A01X+053150Y-006230X0315Y0374R090S2
|
||||
327NET-(J2-PIN_3) R4 -1 A01X+042943Y-014134X0315Y0374R000S2
|
||||
327GND R4 -2 A01X+043593Y-014134X0315Y0374R000S2
|
||||
327NET-(D10-K) D10 -1 A01X+040945Y-029542X0384Y0551R270S2
|
||||
327NET-(D10-A) D10 -2 A01X+040945Y-028804X0384Y0551R270S2
|
||||
317NET-(J4-PIN_1) J4 -1 D0295PA00X+042323Y-017638X0472Y0689R270S0
|
||||
317TANK_SENSOR J4 -2 D0295PA00X+042323Y-016850X0472Y0689R270S0
|
||||
327NET-(CD2-K) CD2 -1 A01X+040945Y-017594X0384Y0551R270S2
|
||||
3273_3V CD2 -2 A01X+040945Y-016855X0384Y0551R270S2
|
||||
317ESP_TX J3 -1 D0394PA00X+077559Y-005709X0669Y0669R270S0
|
||||
317ESP_RX J3 -2 D0394PA00X+078559Y-005709X0669Y0000R270S0
|
||||
317ESP_TX J3 -1 D0394PA00X+073051Y-006457X0669Y0669R270S0
|
||||
317ESP_RX J3 -2 D0394PA00X+074051Y-006457X0669Y0000R270S0
|
||||
327BOOT_SEL R5 -1 A01X+057677Y-010305X0315Y0374R090S2
|
||||
327T-(BOOT1-PAD2) R5 -2 A01X+057677Y-010955X0315Y0374R090S2
|
||||
327NET-(J4-PIN_1) R13 -1 A01X+047047Y-018346X0315Y0374R090S2
|
||||
@@ -296,15 +373,15 @@ P arrayDim N
|
||||
327GND CD1 -1 A01X+045177Y-006570X0384Y0551R270S2
|
||||
327NET-(CD1-A) CD1 -2 A01X+045177Y-005832X0384Y0551R270S2
|
||||
327GND C4 -1 A01X+060630Y-011166X0423Y0374R270S2
|
||||
327NET-(C4-PAD2) C4 -2 A01X+060630Y-010487X0423Y0374R270S2
|
||||
317USB_BUS J2 -1 D0295PA00X+047835Y-006142X0472Y0689R000S0
|
||||
317NET-(J2-PIN_2) J2 -2 D0295PA00X+048622Y-006142X0472Y0689R000S0
|
||||
317USB_D+ J2 -3 D0295PA00X+049409Y-006142X0472Y0689R000S0
|
||||
317USB_D- J2 -4 D0295PA00X+050197Y-006142X0472Y0689R000S0
|
||||
317NET-(J2-PIN_5) J2 -5 D0295PA00X+050984Y-006142X0472Y0689R000S0
|
||||
317GND J2 -6 D0295PA00X+051772Y-006142X0472Y0689R000S0
|
||||
3273_3V R15 -1 A01X+049680Y-023228X0315Y0374R180S2
|
||||
327FLOW R15 -2 A01X+049031Y-023228X0315Y0374R180S2
|
||||
327CONFIG2 C4 -2 A01X+060630Y-010487X0423Y0374R270S2
|
||||
317USB_BUS J2 -1 D0295PA00X+041260Y-009803X0472Y0689R090S0
|
||||
317NET-(J2-PIN_2) J2 -2 D0295PA00X+041260Y-010591X0472Y0689R090S0
|
||||
317NET-(J2-PIN_3) J2 -3 D0295PA00X+041260Y-011378X0472Y0689R090S0
|
||||
317USB_D- J2 -4 D0295PA00X+041260Y-012165X0472Y0689R090S0
|
||||
317USB_D+ J2 -5 D0295PA00X+041260Y-012953X0472Y0689R090S0
|
||||
317GND J2 -6 D0295PA00X+041260Y-013740X0472Y0689R090S0
|
||||
3273_3V R15 -1 A01X+048858Y-019990X0315Y0374R090S2
|
||||
327FLOW R15 -2 A01X+048858Y-020640X0315Y0374R090S2
|
||||
327NET-(Q1-G) Q1 -1 A01X+048770Y-016831X0354Y0315R090S2
|
||||
327GND Q1 -2 A01X+048022Y-016831X0354Y0315R090S2
|
||||
327NET-(J4-PIN_1) Q1 -3 A01X+048396Y-017618X0354Y0315R090S2
|
||||
@@ -313,12 +390,12 @@ P arrayDim N
|
||||
327NET-(Q2-G) Q2 -1 A01X+047776Y-034142X0354Y0315R270S2
|
||||
327GND Q2 -2 A01X+048524Y-034142X0354Y0315R270S2
|
||||
327NET-(D8-K) Q2 -3 A01X+048150Y-033354X0354Y0315R270S2
|
||||
317VBAT U7 -1 D0433PA00X+042795Y-040315X0750Y0787R180S0
|
||||
317GND U7 -2 D0433PA00X+041795Y-040315X0750Y0787R180S0
|
||||
3173_3V U7 -3 D0433PA00X+040795Y-040315X0750Y0787R180S0
|
||||
317GND J1 -1 D0394PA00X+044882Y-012047X0669Y0669R000S0
|
||||
317SCL J1 -2 D0394PA00X+044882Y-013047X0669Y0000R000S0
|
||||
317SDA J1 -3 D0394PA00X+044882Y-014047X0669Y0000R000S0
|
||||
317VBAT U7 -1 D0433PA00X+042795Y-037835X0750Y0787R180S0
|
||||
317GND U7 -2 D0433PA00X+041795Y-037835X0750Y0787R180S0
|
||||
3173_3V U7 -3 D0433PA00X+040795Y-037835X0750Y0787R180S0
|
||||
317GND J1 -1 D0394PA00X+047913Y-008346X0669Y0669R270S0
|
||||
317SDA J1 -2 D0394PA00X+048913Y-008346X0669Y0000R270S0
|
||||
317SCL J1 -3 D0394PA00X+049913Y-008346X0669Y0000R270S0
|
||||
327BOOT_SEL R6 -1 A01X+057677Y-011683X0315Y0374R090S2
|
||||
327NET-(R3-PAD1) R6 -2 A01X+057677Y-012333X0315Y0374R090S2
|
||||
999
|
||||
|
BIN
case/PlantCtrl Case v9.f3z
Normal file
BIN
case/PlantCtrl Case v9.f3z
Normal file
Binary file not shown.
BIN
case/case.3mf
BIN
case/case.3mf
Binary file not shown.
@@ -1,26 +1,32 @@
|
||||
[build]
|
||||
#target = "xtensa-esp32-espidf"
|
||||
target = "riscv32imac-esp-espidf"
|
||||
rustflags = [
|
||||
# Required to obtain backtraces (e.g. when using the "esp-backtrace" crate.)
|
||||
# NOTE: May negatively impact performance of produced code
|
||||
"-C", "force-frame-pointers",
|
||||
"-Z", "stack-protector=all",
|
||||
"-C", "link-arg=-Tlinkall.x",
|
||||
]
|
||||
|
||||
[target.riscv32imac-esp-espidf]
|
||||
linker = "ldproxy"
|
||||
target = "riscv32imac-unknown-none-elf"
|
||||
|
||||
[target.riscv32imac-unknown-none-elf]
|
||||
runner = "espflash flash --monitor --chip esp32c6 --baud 921600 --partition-table partitions.csv"
|
||||
#runner = "espflash flash --monitor --baud 921600 --partition-table partitions.csv -b no-reset" # Select this runner in case of usb ttl
|
||||
runner = "espflash flash --monitor --baud 921600 --flash-size 16mb --partition-table partitions.csv"
|
||||
#runner = "espflash flash --monitor"
|
||||
#runner = "cargo runner"
|
||||
|
||||
|
||||
#runner = "espflash flash --monitor --partition-table partitions.csv -b no-reset" # create upgrade image file for webupload
|
||||
# runner = espflash erase-parts otadata //ensure flash is clean
|
||||
|
||||
rustflags = [ "--cfg", "espidf_time64"] # Extending time_t for ESP IDF 5: https://github.com/esp-rs/rust/issues/110
|
||||
|
||||
[unstable]
|
||||
build-std = ["std", "panic_abort"]
|
||||
|
||||
[env]
|
||||
MCU="esp32c6"
|
||||
# Note: this variable is not used by the pio builder (`cargo build --features pio`)
|
||||
ESP_IDF_VERSION = "v5.2.1"
|
||||
CHRONO_TZ_TIMEZONE_FILTER = "UTC|America/New_York|America/Chicago|America/Los_Angeles|Europe/London|Europe/Berlin|Europe/Paris|Asia/Tokyo|Asia/Shanghai|Asia/Kolkata|Australia/Sydney|America/Sao_Paulo|Africa/Johannesburg|Asia/Dubai|Pacific/Auckland"
|
||||
CARGO_WORKSPACE_DIR = { value = "", relative = true }
|
||||
RUST_BACKTRACE = "full"
|
||||
ESP_LOG = "info"
|
||||
PATH = { value = "../bin:/usr/bin:/usr/local/bin", force = true, relative = true }
|
||||
|
||||
|
||||
|
||||
[unstable]
|
||||
build-std = ["alloc", "core"]
|
||||
|
||||
|
7
rust/.idea/dictionaries/project.xml
generated
7
rust/.idea/dictionaries/project.xml
generated
@@ -1,7 +1,14 @@
|
||||
<component name="ProjectDictionaryState">
|
||||
<dictionary name="project">
|
||||
<words>
|
||||
<w>buildtime</w>
|
||||
<w>deepsleep</w>
|
||||
<w>githash</w>
|
||||
<w>lightstate</w>
|
||||
<w>mppt</w>
|
||||
<w>plantstate</w>
|
||||
<w>sntp</w>
|
||||
<w>vergen</w>
|
||||
</words>
|
||||
</dictionary>
|
||||
</component>
|
@@ -1,6 +1,11 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<Languages>
|
||||
<language minSize="102" name="Rust" />
|
||||
</Languages>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
171
rust/Cargo.toml
171
rust/Cargo.toml
@@ -1,24 +1,17 @@
|
||||
[package]
|
||||
name = "plant-ctrl2"
|
||||
version = "0.1.0"
|
||||
authors = ["Empire Phoenix"]
|
||||
edition = "2021"
|
||||
resolver = "2"
|
||||
#rust-version = "1.71"
|
||||
name = "plant-ctrl2"
|
||||
rust-version = "1.86"
|
||||
version = "0.1.0"
|
||||
|
||||
[profile.dev]
|
||||
# Explicitly disable LTO which the Xtensa codegen backend has issues
|
||||
lto = false
|
||||
strip = false
|
||||
debug = true
|
||||
overflow-checks = true
|
||||
panic = "abort"
|
||||
incremental = true
|
||||
opt-level = "s"
|
||||
|
||||
[profile.dev.build-override]
|
||||
opt-level = 1
|
||||
incremental = true
|
||||
# Explicitly configure the binary target and disable building it as a test/bench.
|
||||
[[bin]]
|
||||
name = "plant-ctrl2"
|
||||
path = "src/main.rs"
|
||||
# Prevent IDEs/Cargo from trying to compile a test harness for this no_std binary.
|
||||
test = false
|
||||
bench = false
|
||||
doc = false
|
||||
|
||||
[package.metadata.cargo_runner]
|
||||
# The string `$TARGET_FILE` will be replaced with the path from cargo.
|
||||
@@ -34,69 +27,127 @@ command = [
|
||||
]
|
||||
|
||||
|
||||
lto = "fat"
|
||||
strip = true
|
||||
debug = false
|
||||
overflow-checks = true
|
||||
panic = "abort"
|
||||
incremental = true
|
||||
opt-level = "z"
|
||||
|
||||
|
||||
[package.metadata.espflash]
|
||||
partition_table = "partitions.csv"
|
||||
|
||||
[features]
|
||||
default = ["std", "embassy", "esp-idf-svc/native"]
|
||||
pio = ["esp-idf-svc/pio"]
|
||||
std = ["alloc", "esp-idf-svc/binstart", "esp-idf-svc/std"]
|
||||
alloc = ["esp-idf-svc/alloc"]
|
||||
nightly = ["esp-idf-svc/nightly"]
|
||||
experimental = ["esp-idf-svc/experimental"]
|
||||
embassy = ["esp-idf-svc/embassy-sync", "esp-idf-svc/critical-section", "esp-idf-svc/embassy-time-driver"]
|
||||
|
||||
[dependencies]
|
||||
#ESP stuff
|
||||
embedded-svc = { version = "0.28.1", features = ["experimental"] }
|
||||
esp-idf-hal = "0.45.2"
|
||||
esp-idf-sys = { version = "0.36.1", features = ["binstart", "native"] }
|
||||
esp-idf-svc = { version = "0.51.0", default-features = false }
|
||||
esp-bootloader-esp-idf = { version = "0.2.0", features = ["esp32c6"] }
|
||||
esp-hal = { version = "=1.0.0-rc.0", features = [
|
||||
"esp32c6",
|
||||
"log-04",
|
||||
"unstable",
|
||||
"rt"
|
||||
] }
|
||||
log = "0.4.27"
|
||||
|
||||
embassy-net = { version = "0.7.1", default-features = false, features = [
|
||||
"dhcpv4",
|
||||
"log",
|
||||
"medium-ethernet",
|
||||
"tcp",
|
||||
"udp",
|
||||
] }
|
||||
embedded-io = "0.6.1"
|
||||
embedded-io-async = "0.6.1"
|
||||
esp-alloc = "0.8.0"
|
||||
esp-backtrace = { version = "0.17.0", features = [
|
||||
"esp32c6",
|
||||
"exception-handler",
|
||||
"panic-handler",
|
||||
"println",
|
||||
"colors",
|
||||
"custom-halt"
|
||||
] }
|
||||
esp-println = { version = "0.15.0", features = ["esp32c6", "log-04"] }
|
||||
# for more networking protocol support see https://crates.io/crates/edge-net
|
||||
embassy-executor = { version = "0.7.0", features = [
|
||||
"log",
|
||||
"task-arena-size-64",
|
||||
"nightly"
|
||||
] }
|
||||
embassy-time = { version = "0.5.0", features = ["log"], default-features = false }
|
||||
esp-hal-embassy = { version = "0.9.0", features = ["esp32c6", "log-04"] }
|
||||
esp-storage = { version = "0.7.0", features = ["esp32c6"] }
|
||||
|
||||
esp-wifi = { version = "0.15.0", features = [
|
||||
"builtin-scheduler",
|
||||
"esp-alloc",
|
||||
"esp32c6",
|
||||
"log-04",
|
||||
"smoltcp",
|
||||
"wifi",
|
||||
] }
|
||||
smoltcp = { version = "0.12.0", default-features = false, features = [
|
||||
"alloc",
|
||||
"log",
|
||||
"medium-ethernet",
|
||||
"multicast",
|
||||
"proto-dhcpv4",
|
||||
"proto-dns",
|
||||
"proto-ipv4",
|
||||
"socket-dns",
|
||||
"socket-icmp",
|
||||
"socket-raw",
|
||||
"socket-tcp",
|
||||
"socket-udp",
|
||||
] }
|
||||
#static_cell = "2.1.1"
|
||||
embedded-hal = "1.0.0"
|
||||
heapless = { version = "0.8", features = ["serde"] }
|
||||
embedded-hal-bus = { version = "0.2.0", features = ["std"] }
|
||||
embedded-hal-bus = { version = "0.3.0" }
|
||||
|
||||
#Hardware additional driver
|
||||
ds18b20 = "0.1.1"
|
||||
bq34z100 = { version = "0.3.0", features = ["flashstream"] }
|
||||
one-wire-bus = "0.1.1"
|
||||
|
||||
#bq34z100 = { version = "0.3.0", default-features = false }
|
||||
onewire = "0.4.0"
|
||||
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
|
||||
measurements = "0.11.0"
|
||||
ds323x = "0.6.0"
|
||||
|
||||
#pure code dependencies
|
||||
once_cell = "1.19.0"
|
||||
anyhow = { version = "1.0.75", features = ["std", "backtrace"] }
|
||||
strum = { version = "0.27.0", features = ["derive"] }
|
||||
measurements = "0.11.0"
|
||||
|
||||
#json
|
||||
serde = { version = "1.0.192", features = ["derive"] }
|
||||
serde_json = "1.0.108"
|
||||
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
|
||||
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
|
||||
|
||||
#timezone
|
||||
chrono = { version = "0.4.23", default-features = false , features = ["iana-time-zone" , "alloc", "serde"] }
|
||||
chrono-tz = {version="0.8.0", default-features = false , features = [ "filter-by-regex" ]}
|
||||
chrono = { version = "0.4.42", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
|
||||
chrono-tz = { version = "0.10.4", default-features = false, features = ["filter-by-regex"] }
|
||||
eeprom24x = "0.7.2"
|
||||
url = "2.5.3"
|
||||
crc = "3.2.1"
|
||||
bincode = "1.3.3"
|
||||
ringbuffer = "0.15.0"
|
||||
text-template = "0.1.0"
|
||||
strum_macros = "0.27.0"
|
||||
esp-ota = { version = "0.2.2", features = ["log"] }
|
||||
unit-enum = "1.4.1"
|
||||
pca9535 = { version = "2.0.0", features = ["std"] }
|
||||
ina219 = { version = "0.2.0", features = ["std"] }
|
||||
|
||||
pca9535 = { version = "2.0.0" }
|
||||
ina219 = { version = "0.2.0" }
|
||||
embedded-storage = "=0.3.1"
|
||||
ekv = "1.0.0"
|
||||
embedded-can = "0.4.1"
|
||||
portable-atomic = "1.11.1"
|
||||
embassy-sync = { version = "0.7.2", features = ["log"] }
|
||||
async-trait = "0.1.89"
|
||||
bq34z100 = { version = "0.4.0", default-features = false }
|
||||
edge-dhcp = "0.6.0"
|
||||
edge-nal = "0.5.0"
|
||||
edge-nal-embassy = "0.6.0"
|
||||
static_cell = "2.1.1"
|
||||
edge-http = { version = "0.6.1", features = ["log"] }
|
||||
littlefs2 = { version = "0.6.1", features = ["c-stubs", "alloc"] }
|
||||
littlefs2-core = "0.1.1"
|
||||
bytemuck = { version = "1.23.2", features = ["derive", "min_const_generics", "pod_saturating", "extern_crate_alloc"] }
|
||||
deranged = "0.5.3"
|
||||
embassy-embedded-hal = "0.5.0"
|
||||
bincode = { version = "2.0.1", default-features = false, features = ["derive"] }
|
||||
|
||||
[patch.crates-io]
|
||||
#esp-idf-hal = { git = "https://github.com/esp-rs/esp-idf-hal.git" }
|
||||
#esp-idf-hal = { git = "https://github.com/empirephoenix/esp-idf-hal.git" }
|
||||
#esp-idf-sys = { git = "https://github.com/empirephoenix/esp-idf-sys.git" }
|
||||
#esp-idf-sys = { git = "https://github.com/esp-rs/esp-idf-sys.git" }
|
||||
#esp-idf-svc = { git = "https://github.com/esp-rs/esp-idf-svc.git" }
|
||||
#bq34z100 = { path = "../../bq34z100_rust" }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "=1.1.30"
|
||||
embuild = { version= "0.32.0", features = ["espidf"]}
|
||||
vergen = { version = "8.2.6", features = ["build", "git", "gitcl"] }
|
||||
|
@@ -1,10 +1,67 @@
|
||||
use std::process::Command;
|
||||
use std::{collections::VecDeque, env, process::Command};
|
||||
|
||||
use vergen::EmitBuilder;
|
||||
|
||||
fn linker_be_nice() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.len() > 1 {
|
||||
let kind = &args[1];
|
||||
let what = &args[2];
|
||||
|
||||
match kind.as_str() {
|
||||
"undefined-symbol" => match what.as_str() {
|
||||
"_defmt_timestamp" => {
|
||||
eprintln!();
|
||||
eprintln!("💡 `defmt` not found - make sure `defmt.x` is added as a linker script and you have included `use defmt_rtt as _;`");
|
||||
eprintln!();
|
||||
}
|
||||
"_stack_start" => {
|
||||
eprintln!();
|
||||
eprintln!("💡 Is the linker script `linkall.x` missing?");
|
||||
eprintln!();
|
||||
}
|
||||
"esp_wifi_preempt_enable"
|
||||
| "esp_wifi_preempt_yield_task"
|
||||
| "esp_wifi_preempt_task_create" => {
|
||||
eprintln!();
|
||||
eprintln!("💡 `esp-wifi` has no scheduler enabled. Make sure you have the `builtin-scheduler` feature enabled, or that you provide an external scheduler.");
|
||||
eprintln!();
|
||||
}
|
||||
"embedded_test_linker_file_not_added_to_rustflags" => {
|
||||
eprintln!();
|
||||
eprintln!("💡 `embedded-test` not found - make sure `embedded-test.x` is added as a linker script for tests");
|
||||
eprintln!();
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
// we don't have anything helpful for "missing-lib" yet
|
||||
_ => {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
println!(
|
||||
"cargo:rustc-link-arg=--error-handling-script={}",
|
||||
std::env::current_exe().unwrap().display()
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=./src/src_webpack");
|
||||
if Command::new("podman").arg("--version").output().is_err() {
|
||||
println!("Could not find `podman` installation, assuming the developer has setup all required tool for build manually! … ")
|
||||
}
|
||||
webpack();
|
||||
linker_be_nice();
|
||||
let _ = EmitBuilder::builder().all_git().all_build().emit();
|
||||
}
|
||||
|
||||
fn webpack() {
|
||||
//println!("cargo:rerun-if-changed=./src/src_webpack");
|
||||
Command::new("rm")
|
||||
.arg("./src/webserver/bundle.js")
|
||||
.arg("./src/webserver/bundle.js.gz")
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
@@ -22,6 +79,22 @@ fn main() {
|
||||
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
|
||||
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(output.status.success());
|
||||
|
||||
// move webpack results to rust webserver src
|
||||
let _ = Command::new("cmd")
|
||||
.arg("/K")
|
||||
.arg("move")
|
||||
.arg("./src_webpack/bundle.js.gz")
|
||||
.arg("./src/webserver")
|
||||
.output()
|
||||
.unwrap();
|
||||
let _ = Command::new("cmd")
|
||||
.arg("/K")
|
||||
.arg("move")
|
||||
.arg("./src_webpack/index.html.gz")
|
||||
.arg("./src/webserver")
|
||||
.output()
|
||||
.unwrap();
|
||||
}
|
||||
Err(_) => {
|
||||
println!("Assuming build on linux");
|
||||
@@ -34,9 +107,18 @@ fn main() {
|
||||
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
|
||||
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(output.status.success());
|
||||
|
||||
// move webpack results to rust webserver src
|
||||
let _ = Command::new("mv")
|
||||
.arg("./src_webpack/bundle.js.gz")
|
||||
.arg("./src/webserver")
|
||||
.output()
|
||||
.unwrap();
|
||||
let _ = Command::new("mv")
|
||||
.arg("./src_webpack/index.html.gz")
|
||||
.arg("./src/webserver")
|
||||
.output()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
embuild::espidf::sysenv::output();
|
||||
let _ = EmitBuilder::builder().all_git().all_build().emit();
|
||||
}
|
||||
|
8
rust/espflash.toml
Normal file
8
rust/espflash.toml
Normal file
@@ -0,0 +1,8 @@
|
||||
[connection]
|
||||
|
||||
[[usb_device]]
|
||||
vid = "303a"
|
||||
pid = "1001"
|
||||
|
||||
[flash]
|
||||
size = "16MB"
|
@@ -1,6 +1,6 @@
|
||||
nvs, data, nvs, , 16k,
|
||||
otadata, data, ota, , 8k,
|
||||
phy_init, data, phy, , 4k,
|
||||
ota_0, app, ota_0, , 5632k,
|
||||
ota_1, app, ota_1, , 5632k,
|
||||
storage, data, spiffs, , 5000k,
|
||||
ota_0, app, ota_0, , 3968k,
|
||||
ota_1, app, ota_1, , 3968k,
|
||||
storage, data, littlefs,, 8M,
|
||||
|
|
@@ -1,3 +1,2 @@
|
||||
[toolchain]
|
||||
channel = "nightly"
|
||||
toolchain = "esp"
|
||||
|
@@ -1,32 +1,21 @@
|
||||
use crate::config::PlantControllerConfig;
|
||||
use crate::hal::battery::BatteryInteraction;
|
||||
use crate::hal::esp::ESP;
|
||||
use crate::hal::rtc::RTCModuleInteraction;
|
||||
use crate::hal::water::TankSensor;
|
||||
use crate::hal::{
|
||||
deep_sleep, BackupHeader, BoardInteraction, FreePeripherals, Sensor, V3Constants, I2C_DRIVER,
|
||||
PLANT_COUNT, REPEAT_MOIST_MEASURE, TANK_MULTI_SAMPLE, X25,
|
||||
deep_sleep, BoardInteraction, FreePeripherals, Sensor, PLANT_COUNT,
|
||||
};
|
||||
use crate::log::{log, LogMessage};
|
||||
use anyhow::{anyhow, bail, Ok, Result};
|
||||
use chrono::{DateTime, Utc};
|
||||
use ds18b20::Ds18b20;
|
||||
use ds323x::{DateTimeAccess, Ds323x};
|
||||
use eeprom24x::{Eeprom24x, Eeprom24xTrait, SlaveAddr};
|
||||
use embedded_hal::digital::OutputPin;
|
||||
use embedded_hal_bus::i2c::MutexDevice;
|
||||
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
|
||||
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
|
||||
use esp_idf_hal::adc::{attenuation, Resolution};
|
||||
use esp_idf_hal::delay::Delay;
|
||||
use esp_idf_hal::gpio::{AnyInputPin, Gpio5, IOPin, InputOutput, PinDriver, Pull};
|
||||
use esp_idf_hal::i2c::I2cDriver;
|
||||
use esp_idf_hal::pcnt::{
|
||||
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex,
|
||||
use crate::{
|
||||
config::PlantControllerConfig,
|
||||
hal::{battery::BatteryInteraction, esp::Esp},
|
||||
};
|
||||
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
|
||||
use one_wire_bus::OneWire;
|
||||
use anyhow::{bail, Ok, Result};
|
||||
use embedded_hal::digital::OutputPin;
|
||||
use measurements::{Current, Voltage};
|
||||
use plant_ctrl2::sipo::ShiftRegister40;
|
||||
use std::result::Result::Ok as OkStd;
|
||||
use std::sync::Arc;
|
||||
use core::result::Result::Ok as OkStd;
|
||||
use alloc::string::ToString;
|
||||
use alloc::boxed::Box;
|
||||
use esp_hall::gpio::Pull;
|
||||
|
||||
const PUMP8_BIT: usize = 0;
|
||||
const PUMP1_BIT: usize = 1;
|
||||
@@ -73,41 +62,37 @@ const FAULT_4: usize = 21;
|
||||
const FAULT_1: usize = 22;
|
||||
const FAULT_2: usize = 23;
|
||||
|
||||
const REPEAT_MOIST_MEASURE: usize = 1;
|
||||
|
||||
|
||||
pub struct V3<'a> {
|
||||
config: PlantControllerConfig,
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
esp: ESP<'a>,
|
||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||
esp: Esp<'a>,
|
||||
shift_register: ShiftRegister40<
|
||||
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
>,
|
||||
shift_register_enable_invert:
|
||||
_shift_register_enable_invert:
|
||||
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Output>,
|
||||
tank_channel: AdcChannelDriver<'a, Gpio5, AdcDriver<'a, esp_idf_hal::adc::ADC1>>,
|
||||
tank_sensor: TankSensor<'a>,
|
||||
solar_is_day: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
|
||||
light: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
main_pump: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
tank_power: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
signal_counter: PcntDriver<'a>,
|
||||
one_wire_bus: OneWire<PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>>,
|
||||
rtc:
|
||||
Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
|
||||
eeprom: Eeprom24x<
|
||||
MutexDevice<'a, I2cDriver<'a>>,
|
||||
eeprom24x::page_size::B32,
|
||||
eeprom24x::addr_size::TwoBytes,
|
||||
eeprom24x::unique_serial::No,
|
||||
>,
|
||||
}
|
||||
|
||||
pub(crate) fn create_v3(
|
||||
peripherals: FreePeripherals,
|
||||
esp: ESP<'static>,
|
||||
esp: Esp<'static>,
|
||||
config: PlantControllerConfig,
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
) -> Result<Box<dyn BoardInteraction + Send + '_>> {
|
||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
||||
log::info!("Start v3");
|
||||
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
|
||||
clock.set_pull(Pull::Floating)?;
|
||||
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;
|
||||
@@ -138,39 +123,19 @@ pub(crate) fn create_v3(
|
||||
let ms4 = &mut shift_register.decompose()[MS_4];
|
||||
ms4.set_high()?;
|
||||
|
||||
println!("Init battery driver");
|
||||
let one_wire_pin = peripherals.gpio18.downgrade();
|
||||
let tank_power_pin = peripherals.gpio11.downgrade();
|
||||
|
||||
println!("Init rtc driver");
|
||||
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
|
||||
let flow_sensor_pin = peripherals.gpio4.downgrade();
|
||||
|
||||
println!("Init rtc eeprom driver");
|
||||
let mut eeprom = {
|
||||
Eeprom24x::new_24x32(
|
||||
MutexDevice::new(&I2C_DRIVER),
|
||||
SlaveAddr::Alternative(true, true, true),
|
||||
)
|
||||
};
|
||||
|
||||
let mut one_wire_pin = PinDriver::input_output_od(peripherals.gpio18.downgrade())?;
|
||||
one_wire_pin.set_pull(Pull::Floating)?;
|
||||
|
||||
let rtc_time = rtc.datetime();
|
||||
match rtc_time {
|
||||
OkStd(tt) => {
|
||||
println!("Rtc Module reports time at UTC {}", tt);
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Rtc Module could not be read {:?}", err);
|
||||
}
|
||||
}
|
||||
match eeprom.read_byte(0) {
|
||||
OkStd(byte) => {
|
||||
println!("Read first byte with status {}", byte);
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Eeprom could not read first byte {:?}", err);
|
||||
}
|
||||
}
|
||||
let tank_sensor = TankSensor::create(
|
||||
one_wire_pin,
|
||||
peripherals.adc1,
|
||||
peripherals.gpio5,
|
||||
tank_power_pin,
|
||||
flow_sensor_pin,
|
||||
peripherals.pcnt1,
|
||||
)?;
|
||||
|
||||
let mut signal_counter = PcntDriver::new(
|
||||
peripherals.pcnt0,
|
||||
@@ -194,15 +159,6 @@ pub(crate) fn create_v3(
|
||||
},
|
||||
)?;
|
||||
|
||||
let adc_config = AdcChannelConfig {
|
||||
attenuation: attenuation::DB_11,
|
||||
resolution: Resolution::Resolution12Bit,
|
||||
calibration: esp_idf_hal::adc::oneshot::config::Calibration::Curve,
|
||||
};
|
||||
let tank_driver = AdcDriver::new(peripherals.adc1)?;
|
||||
let tank_channel: AdcChannelDriver<Gpio5, AdcDriver<esp_idf_hal::adc::ADC1>> =
|
||||
AdcChannelDriver::new(tank_driver, peripherals.gpio5, &adc_config)?;
|
||||
|
||||
let mut solar_is_day = PinDriver::input(peripherals.gpio7.downgrade())?;
|
||||
solar_is_day.set_pull(Pull::Floating)?;
|
||||
|
||||
@@ -212,15 +168,11 @@ pub(crate) fn create_v3(
|
||||
let mut main_pump = PinDriver::input_output(peripherals.gpio2.downgrade())?;
|
||||
main_pump.set_pull(Pull::Floating)?;
|
||||
main_pump.set_low()?;
|
||||
let mut tank_power = PinDriver::input_output(peripherals.gpio11.downgrade())?;
|
||||
tank_power.set_pull(Pull::Floating)?;
|
||||
|
||||
let mut general_fault = PinDriver::input_output(peripherals.gpio6.downgrade())?;
|
||||
general_fault.set_pull(Pull::Floating)?;
|
||||
general_fault.set_low()?;
|
||||
|
||||
let one_wire_bus = OneWire::new(one_wire_pin)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
|
||||
let mut shift_register_enable_invert = PinDriver::output(peripherals.gpio21.downgrade())?;
|
||||
|
||||
unsafe { gpio_hold_dis(shift_register_enable_invert.pin()) };
|
||||
@@ -230,24 +182,25 @@ pub(crate) fn create_v3(
|
||||
Ok(Box::new(V3 {
|
||||
config,
|
||||
battery_monitor,
|
||||
rtc_module,
|
||||
esp,
|
||||
shift_register,
|
||||
shift_register_enable_invert,
|
||||
tank_channel,
|
||||
_shift_register_enable_invert: shift_register_enable_invert,
|
||||
tank_sensor,
|
||||
solar_is_day,
|
||||
light,
|
||||
main_pump,
|
||||
tank_power,
|
||||
general_fault,
|
||||
signal_counter,
|
||||
one_wire_bus,
|
||||
rtc,
|
||||
eeprom,
|
||||
}))
|
||||
}
|
||||
|
||||
impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
fn get_esp(&mut self) -> &mut ESP<'a> {
|
||||
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>> {
|
||||
Some(&mut self.tank_sensor)
|
||||
}
|
||||
|
||||
fn get_esp(&mut self) -> &mut Esp<'a> {
|
||||
&mut self.esp
|
||||
}
|
||||
|
||||
@@ -255,10 +208,13 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
&self.config
|
||||
}
|
||||
|
||||
fn get_battery_monitor(&mut self) -> &mut Box<(dyn BatteryInteraction + Send + 'static)> {
|
||||
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send + 'static> {
|
||||
&mut self.battery_monitor
|
||||
}
|
||||
|
||||
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
|
||||
&mut self.rtc_module
|
||||
}
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> Result<()> {
|
||||
Ok(self.shift_register.decompose()[CHARGING].set_state(charging.into())?)
|
||||
}
|
||||
@@ -268,157 +224,16 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
deep_sleep(duration_in_ms)
|
||||
}
|
||||
|
||||
fn get_backup_info(&mut self) -> Result<BackupHeader> {
|
||||
let store = bincode::serialize(&BackupHeader::default())?.len();
|
||||
let mut header_page_buffer = vec![0_u8; store];
|
||||
|
||||
self.eeprom
|
||||
.read_data(0, &mut header_page_buffer)
|
||||
.map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
|
||||
|
||||
println!("Raw header is {:?} with size {}", header_page_buffer, store);
|
||||
let header: BackupHeader = bincode::deserialize(&header_page_buffer)?;
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
fn get_backup_config(&mut self) -> Result<Vec<u8>> {
|
||||
let store = bincode::serialize(&BackupHeader::default())?.len();
|
||||
let mut header_page_buffer = vec![0_u8; store];
|
||||
|
||||
self.eeprom
|
||||
.read_data(0, &mut header_page_buffer)
|
||||
.map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
|
||||
|
||||
let header: BackupHeader = bincode::deserialize(&header_page_buffer)?;
|
||||
|
||||
//skip page 0, used by the header
|
||||
let data_start_address = self.eeprom.page_size() as u32;
|
||||
let mut data_buffer = vec![0_u8; header.size];
|
||||
self.eeprom
|
||||
.read_data(data_start_address, &mut data_buffer)
|
||||
.map_err(|err| anyhow!("Error reading eeprom data {:?}", err))?;
|
||||
|
||||
let checksum = X25.checksum(&data_buffer);
|
||||
if checksum != header.crc16 {
|
||||
bail!(
|
||||
"Invalid checksum, got {} but expected {}",
|
||||
checksum,
|
||||
header.crc16
|
||||
);
|
||||
}
|
||||
|
||||
Ok(data_buffer)
|
||||
}
|
||||
|
||||
fn backup_config(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
let time = self.get_rtc_time()?.timestamp_millis();
|
||||
|
||||
let delay = Delay::new_default();
|
||||
|
||||
let checksum = X25.checksum(bytes);
|
||||
let page_size = self.eeprom.page_size();
|
||||
|
||||
let header = BackupHeader {
|
||||
crc16: checksum,
|
||||
timestamp: time,
|
||||
size: bytes.len(),
|
||||
};
|
||||
|
||||
let encoded = bincode::serialize(&header)?;
|
||||
if encoded.len() > page_size {
|
||||
bail!(
|
||||
"Size limit reached header is {}, but firest page is only {}",
|
||||
encoded.len(),
|
||||
page_size
|
||||
)
|
||||
}
|
||||
let as_u8: &[u8] = &encoded;
|
||||
|
||||
match self.eeprom.write_page(0, as_u8) {
|
||||
OkStd(_) => {}
|
||||
Err(err) => bail!("Error writing eeprom {:?}", err),
|
||||
};
|
||||
delay.delay_ms(5);
|
||||
|
||||
let to_write = bytes.chunks(page_size);
|
||||
|
||||
let mut lastiter = 0;
|
||||
let mut current_page = 1;
|
||||
for chunk in to_write {
|
||||
let address = current_page * page_size as u32;
|
||||
self.eeprom
|
||||
.write_page(address, chunk)
|
||||
.map_err(|err| anyhow!("Error writing eeprom {:?}", err))?;
|
||||
current_page += 1;
|
||||
|
||||
let iter = (current_page % 8) as usize;
|
||||
if iter != lastiter {
|
||||
for i in 0..PLANT_COUNT {
|
||||
let _ = self.fault(i, iter == i);
|
||||
}
|
||||
lastiter = iter;
|
||||
}
|
||||
|
||||
delay.delay_ms(5);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_day(&self) -> bool {
|
||||
self.solar_is_day.get_level().into()
|
||||
}
|
||||
|
||||
fn water_temperature_c(&mut self) -> Result<f32> {
|
||||
self.one_wire_bus
|
||||
.reset(&mut self.esp.delay)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
let first = self.one_wire_bus.devices(false, &mut self.esp.delay).next();
|
||||
if first.is_none() {
|
||||
bail!("Not found any one wire Ds18b20");
|
||||
}
|
||||
let device_address = first
|
||||
.unwrap()
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
|
||||
let water_temp_sensor = Ds18b20::new::<EspError>(device_address)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
|
||||
water_temp_sensor
|
||||
.start_temp_measurement(&mut self.one_wire_bus, &mut self.esp.delay)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
ds18b20::Resolution::Bits12.delay_for_measurement_time(&mut self.esp.delay);
|
||||
let sensor_data = water_temp_sensor
|
||||
.read_data(&mut self.one_wire_bus, &mut self.esp.delay)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
if sensor_data.temperature == 85_f32 {
|
||||
bail!("Ds18b20 dummy temperature returned");
|
||||
}
|
||||
Ok(sensor_data.temperature / 10_f32)
|
||||
}
|
||||
|
||||
fn tank_sensor_voltage(&mut self) -> Result<f32> {
|
||||
self.tank_power.set_high()?;
|
||||
//let stabilize
|
||||
self.esp.delay.delay_ms(100);
|
||||
|
||||
let mut store = [0_u16; TANK_MULTI_SAMPLE];
|
||||
for multisample in 0..TANK_MULTI_SAMPLE {
|
||||
let value = self.tank_channel.read()?;
|
||||
store[multisample] = value;
|
||||
}
|
||||
self.tank_power.set_low()?;
|
||||
|
||||
store.sort();
|
||||
let median_mv = store[6] as f32 / 1000_f32;
|
||||
Ok(median_mv)
|
||||
}
|
||||
fn light(&mut self, enable: bool) -> Result<()> {
|
||||
unsafe { gpio_hold_dis(self.light.pin()) };
|
||||
self.light.set_state(enable.into())?;
|
||||
unsafe { gpio_hold_en(self.light.pin()) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pump(&mut self, plant: usize, enable: bool) -> Result<()> {
|
||||
if enable {
|
||||
self.main_pump.set_high()?;
|
||||
@@ -435,7 +250,6 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
7 => PUMP8_BIT,
|
||||
_ => bail!("Invalid pump {plant}",),
|
||||
};
|
||||
//currently infallible error, keep for future as result anyway
|
||||
self.shift_register.decompose()[index].set_state(enable.into())?;
|
||||
|
||||
if !enable {
|
||||
@@ -444,6 +258,10 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pump_current(&mut self, _plant: usize) -> Result<Current> {
|
||||
bail!("Not implemented in v3")
|
||||
}
|
||||
|
||||
fn fault(&mut self, plant: usize, enable: bool) -> Result<()> {
|
||||
let index = match plant {
|
||||
0 => FAULT_1,
|
||||
@@ -522,8 +340,8 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
self.shift_register.decompose()[MS_4].set_low()?;
|
||||
self.shift_register.decompose()[SENSOR_ON].set_high()?;
|
||||
|
||||
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
|
||||
let factor = 1000f32 / measurement as f32;
|
||||
let measurement = 100; //how long to measure and then extrapolate to hz
|
||||
let factor = 1000f32 / measurement as f32; //scale raw cound by this number to get hz
|
||||
|
||||
//give some time to stabilize
|
||||
self.esp.delay.delay_ms(10);
|
||||
@@ -557,41 +375,6 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
unsafe { gpio_hold_en(self.general_fault.pin()) };
|
||||
}
|
||||
|
||||
fn factory_reset(&mut self) -> Result<()> {
|
||||
println!("factory resetting");
|
||||
self.esp.delete_config()?;
|
||||
//destroy backup header
|
||||
let dummy: [u8; 0] = [];
|
||||
self.backup_config(&dummy)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
|
||||
match self.rtc.datetime() {
|
||||
OkStd(rtc_time) => Ok(rtc_time.and_utc()),
|
||||
Err(err) => {
|
||||
bail!("Error getting rtc time {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> Result<()> {
|
||||
let naive_time = time.naive_utc();
|
||||
match self.rtc.set_datetime(&naive_time) {
|
||||
OkStd(_) => Ok(()),
|
||||
Err(err) => {
|
||||
bail!("Error getting rtc time {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn test_pump(&mut self, plant: usize) -> Result<()> {
|
||||
self.pump(plant, true)?;
|
||||
unsafe { vTaskDelay(30000) };
|
||||
self.pump(plant, false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn test(&mut self) -> Result<()> {
|
||||
self.general_fault(true);
|
||||
self.esp.delay.delay_ms(100);
|
||||
@@ -630,9 +413,22 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_config(&mut self, config: PlantControllerConfig) -> anyhow::Result<()> {
|
||||
fn set_config(&mut self, config: PlantControllerConfig) -> Result<()> {
|
||||
self.config = config;
|
||||
self.esp.save_config(&self.config)?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
fn get_mptt_voltage(&mut self) -> Result<Voltage> {
|
||||
//assuming module to work, these are the hardware set values
|
||||
if self.is_day() {
|
||||
Ok(Voltage::from_volts(15_f64))
|
||||
} else {
|
||||
Ok(Voltage::from_volts(0_f64))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_mptt_current(&mut self) -> Result<Current> {
|
||||
bail!("Board does not have current sensor")
|
||||
}
|
||||
}
|
@@ -1,7 +1,8 @@
|
||||
use alloc::string::String;
|
||||
use core::str::FromStr;
|
||||
use crate::hal::PLANT_COUNT;
|
||||
use crate::plant_state::PlantWateringMode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
#[serde(default)]
|
||||
@@ -11,6 +12,8 @@ pub struct NetworkConfig {
|
||||
pub password: Option<heapless::String<64>>,
|
||||
pub mqtt_url: Option<heapless::String<128>>,
|
||||
pub base_topic: Option<heapless::String<64>>,
|
||||
pub mqtt_user: Option<heapless::String<32>>,
|
||||
pub mqtt_password: Option<heapless::String<64>>,
|
||||
pub max_wait: u32,
|
||||
}
|
||||
impl Default for NetworkConfig {
|
||||
@@ -21,6 +24,8 @@ impl Default for NetworkConfig {
|
||||
password: None,
|
||||
mqtt_url: None,
|
||||
base_topic: None,
|
||||
mqtt_user: None,
|
||||
mqtt_password: None,
|
||||
max_wait: 10000,
|
||||
}
|
||||
}
|
||||
@@ -58,6 +63,7 @@ pub struct TankConfig {
|
||||
pub tank_warn_percent: u8,
|
||||
pub tank_empty_percent: u8,
|
||||
pub tank_full_percent: u8,
|
||||
pub ml_per_pulse: f32,
|
||||
}
|
||||
impl Default for TankConfig {
|
||||
fn default() -> Self {
|
||||
@@ -68,6 +74,7 @@ impl Default for TankConfig {
|
||||
tank_warn_percent: 40,
|
||||
tank_empty_percent: 5,
|
||||
tank_full_percent: 95,
|
||||
ml_per_pulse: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,7 +116,9 @@ pub struct PlantControllerConfig {
|
||||
pub struct PlantConfig {
|
||||
pub mode: PlantWateringMode,
|
||||
pub target_moisture: f32,
|
||||
pub min_moisture: f32,
|
||||
pub pump_time_s: u16,
|
||||
pub pump_limit_ml: u16,
|
||||
pub pump_cooldown_min: u16,
|
||||
pub pump_hour_start: u8,
|
||||
pub pump_hour_end: u8,
|
||||
@@ -118,6 +127,9 @@ pub struct PlantConfig {
|
||||
pub max_consecutive_pump_count: u8,
|
||||
pub moisture_sensor_min_frequency: Option<f32>, // Optional min frequency
|
||||
pub moisture_sensor_max_frequency: Option<f32>, // Optional max frequency
|
||||
pub min_pump_current_ma: u16,
|
||||
pub max_pump_current_ma: u16,
|
||||
pub ignore_current_error: bool,
|
||||
}
|
||||
|
||||
impl Default for PlantConfig {
|
||||
@@ -125,7 +137,9 @@ impl Default for PlantConfig {
|
||||
Self {
|
||||
mode: PlantWateringMode::OFF,
|
||||
target_moisture: 40.,
|
||||
min_moisture: 30.,
|
||||
pump_time_s: 30,
|
||||
pump_limit_ml: 5000,
|
||||
pump_cooldown_min: 60,
|
||||
pump_hour_start: 9,
|
||||
pump_hour_end: 20,
|
||||
@@ -134,6 +148,9 @@ impl Default for PlantConfig {
|
||||
max_consecutive_pump_count: 10,
|
||||
moisture_sensor_min_frequency: None, // No override by default
|
||||
moisture_sensor_max_frequency: None, // No override by default
|
||||
min_pump_current_ma: 10,
|
||||
max_pump_current_ma: 3000,
|
||||
ignore_current_error: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
259
rust/src/fat_error.rs
Normal file
259
rust/src/fat_error.rs
Normal file
@@ -0,0 +1,259 @@
|
||||
use alloc::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use core::convert::Infallible;
|
||||
use core::fmt;
|
||||
use core::str::Utf8Error;
|
||||
use embassy_embedded_hal::shared_bus::I2cDeviceError;
|
||||
use embassy_executor::SpawnError;
|
||||
use embassy_sync::mutex::TryLockError;
|
||||
use esp_hal::i2c::master::ConfigError;
|
||||
use esp_wifi::wifi::WifiError;
|
||||
use ina219::errors::{BusVoltageReadError, ShuntVoltageReadError};
|
||||
use littlefs2_core::PathError;
|
||||
use onewire::Error;
|
||||
use pca9535::ExpanderError;
|
||||
|
||||
//All error superconstruct
|
||||
#[derive(Debug)]
|
||||
pub enum FatError {
|
||||
OneWireError {
|
||||
error: Error<Infallible>,
|
||||
},
|
||||
String {
|
||||
error: String,
|
||||
},
|
||||
LittleFSError {
|
||||
error: littlefs2_core::Error,
|
||||
},
|
||||
PathError {
|
||||
error: PathError,
|
||||
},
|
||||
TryLockError {
|
||||
error: TryLockError,
|
||||
},
|
||||
WifiError {
|
||||
error: WifiError,
|
||||
},
|
||||
SerdeError {
|
||||
error: serde_json::Error,
|
||||
},
|
||||
PreconditionFailed {
|
||||
error: String,
|
||||
},
|
||||
NoBatteryMonitor,
|
||||
SpawnError {
|
||||
error: SpawnError,
|
||||
},
|
||||
PartitionError {
|
||||
error: esp_bootloader_esp_idf::partitions::Error,
|
||||
},
|
||||
I2CConfigError {
|
||||
error: ConfigError,
|
||||
},
|
||||
DS323 {
|
||||
error: String,
|
||||
},
|
||||
Eeprom24x {
|
||||
error: String,
|
||||
},
|
||||
ExpanderError {
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub type FatResult<T> = Result<T, FatError>;
|
||||
|
||||
impl fmt::Display for FatError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
FatError::SpawnError { error } => {
|
||||
write!(f, "SpawnError {:?}", error.to_string())
|
||||
}
|
||||
FatError::OneWireError { error } => write!(f, "OneWireError {:?}", error),
|
||||
FatError::String { error } => write!(f, "{}", error),
|
||||
FatError::LittleFSError { error } => write!(f, "LittleFSError {:?}", error),
|
||||
FatError::PathError { error } => write!(f, "PathError {:?}", error),
|
||||
FatError::TryLockError { error } => write!(f, "TryLockError {:?}", error),
|
||||
FatError::WifiError { error } => write!(f, "WifiError {:?}", error),
|
||||
FatError::SerdeError { error } => write!(f, "SerdeError {:?}", error),
|
||||
FatError::PreconditionFailed { error } => write!(f, "PreconditionFailed {:?}", error),
|
||||
FatError::PartitionError { error } => {
|
||||
write!(f, "PartitionError {:?}", error)
|
||||
}
|
||||
FatError::NoBatteryMonitor => {
|
||||
write!(f, "No Battery Monitor")
|
||||
}
|
||||
FatError::I2CConfigError { error } => write!(f, "I2CConfigError {:?}", error),
|
||||
FatError::DS323 { error } => write!(f, "DS323 {:?}", error),
|
||||
FatError::Eeprom24x { error } => write!(f, "Eeprom24x {:?}", error),
|
||||
FatError::ExpanderError { error } => write!(f, "ExpanderError {:?}", error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! bail {
|
||||
($msg:literal $(,)?) => {
|
||||
return $crate::fat_error::fat_bail($msg)
|
||||
};
|
||||
($fmt:literal, $($arg:tt)*) => {
|
||||
return $crate::fat_error::fat_bail(&alloc::format!($fmt, $($arg)*))
|
||||
};
|
||||
}
|
||||
|
||||
pub fn fat_bail<X>(message: &str) -> Result<X, FatError> {
|
||||
Err(FatError::String {
|
||||
error: message.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub trait ContextExt<T> {
|
||||
fn context<C>(self, context: C) -> Result<T, FatError>
|
||||
where
|
||||
C: AsRef<str>;
|
||||
}
|
||||
impl<T> ContextExt<T> for Option<T> {
|
||||
fn context<C>(self, context: C) -> Result<T, FatError>
|
||||
where
|
||||
C: AsRef<str>,
|
||||
{
|
||||
match self {
|
||||
Some(value) => Ok(value),
|
||||
None => Err(FatError::PreconditionFailed {
|
||||
error: context.as_ref().to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error<Infallible>> for FatError {
|
||||
fn from(error: Error<Infallible>) -> Self {
|
||||
FatError::OneWireError { error }
|
||||
}
|
||||
}
|
||||
impl From<littlefs2_core::Error> for FatError {
|
||||
fn from(value: littlefs2_core::Error) -> Self {
|
||||
FatError::LittleFSError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathError> for FatError {
|
||||
fn from(value: PathError) -> Self {
|
||||
FatError::PathError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TryLockError> for FatError {
|
||||
fn from(value: TryLockError) -> Self {
|
||||
FatError::TryLockError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WifiError> for FatError {
|
||||
fn from(value: WifiError) -> Self {
|
||||
FatError::WifiError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::error::Error> for FatError {
|
||||
fn from(value: serde_json::Error) -> Self {
|
||||
FatError::SerdeError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SpawnError> for FatError {
|
||||
fn from(value: SpawnError) -> Self {
|
||||
FatError::SpawnError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<esp_bootloader_esp_idf::partitions::Error> for FatError {
|
||||
fn from(value: esp_bootloader_esp_idf::partitions::Error) -> Self {
|
||||
FatError::PartitionError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Utf8Error> for FatError {
|
||||
fn from(value: Utf8Error) -> Self {
|
||||
FatError::String {
|
||||
error: value.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: core::fmt::Debug> From<edge_http::io::Error<E>> for FatError {
|
||||
fn from(value: edge_http::io::Error<E>) -> Self {
|
||||
FatError::String {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: core::fmt::Debug> From<ds323x::Error<E>> for FatError {
|
||||
fn from(value: ds323x::Error<E>) -> Self {
|
||||
FatError::DS323 {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: core::fmt::Debug> From<eeprom24x::Error<E>> for FatError {
|
||||
fn from(value: eeprom24x::Error<E>) -> Self {
|
||||
FatError::Eeprom24x {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: core::fmt::Debug> From<ExpanderError<I2cDeviceError<E>>> for FatError {
|
||||
fn from(value: ExpanderError<I2cDeviceError<E>>) -> Self {
|
||||
FatError::ExpanderError {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bincode::error::DecodeError> for FatError {
|
||||
fn from(value: bincode::error::DecodeError) -> Self {
|
||||
FatError::Eeprom24x {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bincode::error::EncodeError> for FatError {
|
||||
fn from(value: bincode::error::EncodeError) -> Self {
|
||||
FatError::Eeprom24x {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ConfigError> for FatError {
|
||||
fn from(value: ConfigError) -> Self {
|
||||
FatError::I2CConfigError { error: value }
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: core::fmt::Debug> From<I2cDeviceError<E>> for FatError {
|
||||
fn from(value: I2cDeviceError<E>) -> Self {
|
||||
FatError::String {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: core::fmt::Debug> From<BusVoltageReadError<I2cDeviceError<E>>> for FatError {
|
||||
fn from(value: BusVoltageReadError<I2cDeviceError<E>>) -> Self {
|
||||
FatError::String {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<E: core::fmt::Debug> From<ShuntVoltageReadError<I2cDeviceError<E>>> for FatError {
|
||||
fn from(value: ShuntVoltageReadError<I2cDeviceError<E>>) -> Self {
|
||||
FatError::String {
|
||||
error: format!("{:?}", value),
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,23 +1,28 @@
|
||||
use crate::to_string;
|
||||
use anyhow::anyhow;
|
||||
use bq34z100::{Bq34Z100Error, Bq34z100g1, Bq34z100g1Driver};
|
||||
use embedded_hal_bus::i2c::MutexDevice;
|
||||
use esp_idf_hal::delay::Delay;
|
||||
use esp_idf_hal::i2c::{I2cDriver, I2cError};
|
||||
use crate::hal::Box;
|
||||
use crate::fat_error::{FatError, FatResult};
|
||||
use alloc::string::String;
|
||||
use async_trait::async_trait;
|
||||
use bq34z100::{Bq34z100g1, Bq34z100g1Driver, Flags};
|
||||
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use esp_hal::delay::Delay;
|
||||
use esp_hal::i2c::master::I2c;
|
||||
use esp_hal::Blocking;
|
||||
use measurements::Temperature;
|
||||
use serde::Serialize;
|
||||
|
||||
#[async_trait]
|
||||
pub trait BatteryInteraction {
|
||||
fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
|
||||
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
||||
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
||||
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
||||
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
|
||||
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
|
||||
fn cycle_count(&mut self) -> Result<u16, BatteryError>;
|
||||
fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
|
||||
fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
|
||||
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
|
||||
async fn state_charge_percent(&mut self) -> FatResult<f32>;
|
||||
async fn remaining_milli_ampere_hour(&mut self) -> FatResult<u16>;
|
||||
async fn max_milli_ampere_hour(&mut self) -> FatResult<u16>;
|
||||
async fn design_milli_ampere_hour(&mut self) -> FatResult<u16>;
|
||||
async fn voltage_milli_volt(&mut self) -> FatResult<u16>;
|
||||
async fn average_current_milli_ampere(&mut self) -> FatResult<i16>;
|
||||
async fn cycle_count(&mut self) -> FatResult<u16>;
|
||||
async fn state_health_percent(&mut self) -> FatResult<u16>;
|
||||
async fn bat_temperature(&mut self) -> FatResult<u16>;
|
||||
async fn get_battery_state(&mut self) -> FatResult<BatteryState>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -38,13 +43,13 @@ pub enum BatteryError {
|
||||
CommunicationError(String),
|
||||
}
|
||||
|
||||
impl From<Bq34Z100Error<esp_idf_hal::i2c::I2cError>> for BatteryError {
|
||||
fn from(err: Bq34Z100Error<esp_idf_hal::i2c::I2cError>) -> Self {
|
||||
BatteryError::CommunicationError(
|
||||
anyhow!("failed to communicate with battery monitor: {:?}", err).to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
// impl From<Bq34Z100Error<esp_idf_hal::i2c::I2cError>> for BatteryError {
|
||||
// fn from(err: Bq34Z100Error<esp_idf_hal::i2c::I2cError>) -> Self {
|
||||
// BatteryError::CommunicationError(
|
||||
// anyhow!("failed to communicate with battery monitor: {:?}", err).to_string(),
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub enum BatteryState {
|
||||
@@ -54,161 +59,214 @@ pub enum BatteryState {
|
||||
|
||||
/// If no battery monitor is installed this implementation will be used
|
||||
pub struct NoBatteryMonitor {}
|
||||
|
||||
#[async_trait]
|
||||
impl BatteryInteraction for NoBatteryMonitor {
|
||||
fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn state_charge_percent(&mut self) -> FatResult<f32> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn remaining_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn max_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn design_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn voltage_milli_volt(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn average_current_milli_ampere(&mut self) -> FatResult<i16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn cycle_count(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn cycle_count(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn state_health_percent(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
|
||||
Err(BatteryError::NoBatteryMonitor)
|
||||
async fn bat_temperature(&mut self) -> FatResult<u16> {
|
||||
Err(FatError::NoBatteryMonitor)
|
||||
}
|
||||
|
||||
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
|
||||
async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
|
||||
Ok(BatteryState::Unknown)
|
||||
}
|
||||
}
|
||||
|
||||
//TODO implement this battery monitor kind once controller is complete
|
||||
#[allow(dead_code)]
|
||||
pub struct WchI2cSlave {}
|
||||
|
||||
pub struct BQ34Z100G1<'a> {
|
||||
pub battery_driver: Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>,
|
||||
pub type I2cDev = I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>;
|
||||
|
||||
pub struct BQ34Z100G1 {
|
||||
pub battery_driver: Bq34z100g1Driver<I2cDev, Delay>,
|
||||
}
|
||||
|
||||
impl BatteryInteraction for BQ34Z100G1<'_> {
|
||||
fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
|
||||
Ok(self.battery_driver.state_of_charge().map(f32::from)?)
|
||||
#[async_trait]
|
||||
impl BatteryInteraction for BQ34Z100G1 {
|
||||
async fn state_charge_percent(&mut self) -> FatResult<f32> {
|
||||
self.battery_driver
|
||||
.state_of_charge()
|
||||
.map(|v| v as f32)
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.remaining_capacity()?)
|
||||
async fn remaining_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver
|
||||
.remaining_capacity()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.full_charge_capacity()?)
|
||||
async fn max_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver
|
||||
.full_charge_capacity()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.design_capacity()?)
|
||||
async fn design_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver
|
||||
.design_capacity()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.voltage()?)
|
||||
async fn voltage_milli_volt(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver.voltage().map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
|
||||
Ok(self.battery_driver.average_current()?)
|
||||
async fn average_current_milli_ampere(&mut self) -> FatResult<i16> {
|
||||
self.battery_driver
|
||||
.average_current()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn cycle_count(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.cycle_count()?)
|
||||
async fn cycle_count(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver
|
||||
.cycle_count()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.state_of_health()?)
|
||||
async fn state_health_percent(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver
|
||||
.state_of_health()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
|
||||
Ok(self.battery_driver.temperature()?)
|
||||
async fn bat_temperature(&mut self) -> FatResult<u16> {
|
||||
self.battery_driver
|
||||
.temperature()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
|
||||
fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
|
||||
async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
|
||||
Ok(BatteryState::Info(BatteryInfo {
|
||||
voltage_milli_volt: self.voltage_milli_volt()?,
|
||||
average_current_milli_ampere: self.average_current_milli_ampere()?,
|
||||
cycle_count: self.cycle_count()?,
|
||||
design_milli_ampere_hour: self.design_milli_ampere_hour()?,
|
||||
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour()?,
|
||||
state_of_charge: self.state_charge_percent()?,
|
||||
state_of_health: self.state_health_percent()?,
|
||||
temperature: self.bat_temperature()?,
|
||||
voltage_milli_volt: self.voltage_milli_volt().await?,
|
||||
average_current_milli_ampere: self.average_current_milli_ampere().await?,
|
||||
cycle_count: self.cycle_count().await?,
|
||||
design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
|
||||
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
|
||||
state_of_charge: self.state_charge_percent().await?,
|
||||
state_of_health: self.state_health_percent().await?,
|
||||
temperature: self.bat_temperature().await?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_battery_bq34z100(
|
||||
battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
|
||||
) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
|
||||
println!("Try communicating with battery");
|
||||
battery_driver: &mut Bq34z100g1Driver<I2cDevice<CriticalSectionRawMutex, I2c<Blocking>>, Delay>,
|
||||
) -> FatResult<()> {
|
||||
log::info!("Try communicating with battery");
|
||||
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
|
||||
println!("Firmware {:?}", e);
|
||||
log::info!("Firmware {:?}", e);
|
||||
0
|
||||
});
|
||||
println!("fw version is {}", fwversion);
|
||||
log::info!("fw version is {}", fwversion);
|
||||
|
||||
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
|
||||
println!("Design capacity {:?}", e);
|
||||
log::info!("Design capacity {:?}", e);
|
||||
0
|
||||
});
|
||||
println!("Design Capacity {}", design_capacity);
|
||||
log::info!("Design Capacity {}", design_capacity);
|
||||
if design_capacity == 1000 {
|
||||
println!("Still stock configuring battery, readouts are likely to be wrong!");
|
||||
log::info!("Still stock configuring battery, readouts are likely to be wrong!");
|
||||
}
|
||||
|
||||
let flags = battery_driver.get_flags_decoded()?;
|
||||
println!("Flags {:?}", flags);
|
||||
let flags = battery_driver.get_flags_decoded().unwrap_or(Flags {
|
||||
fast_charge_allowed: false,
|
||||
full_chage: false,
|
||||
charging_not_allowed: false,
|
||||
charge_inhibit: false,
|
||||
bat_low: false,
|
||||
bat_high: false,
|
||||
over_temp_discharge: false,
|
||||
over_temp_charge: false,
|
||||
discharge: false,
|
||||
state_of_charge_f: false,
|
||||
state_of_charge_1: false,
|
||||
cf: false,
|
||||
ocv_taken: false,
|
||||
});
|
||||
log::info!("Flags {:?}", flags);
|
||||
|
||||
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
|
||||
println!("Chemid {:?}", e);
|
||||
log::info!("Chemid {:?}", e);
|
||||
0
|
||||
});
|
||||
|
||||
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
|
||||
println!("Bat Temp {:?}", e);
|
||||
log::info!("Bat Temp {:?}", e);
|
||||
0
|
||||
});
|
||||
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
|
||||
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
|
||||
println!("Bat volt {:?}", e);
|
||||
log::info!("Bat volt {:?}", e);
|
||||
0
|
||||
});
|
||||
let current = battery_driver.current().unwrap_or_else(|e| {
|
||||
println!("Bat current {:?}", e);
|
||||
log::info!("Bat current {:?}", e);
|
||||
0
|
||||
});
|
||||
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
|
||||
println!("Bat Soc {:?}", e);
|
||||
log::info!("Bat Soc {:?}", e);
|
||||
0
|
||||
});
|
||||
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
|
||||
println!("Bat Charge Volt {:?}", e);
|
||||
log::info!("Bat Charge Volt {:?}", e);
|
||||
0
|
||||
});
|
||||
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
|
||||
println!("Bat Charge Current {:?}", e);
|
||||
log::info!("Bat Charge Current {:?}", e);
|
||||
0
|
||||
});
|
||||
println!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
|
||||
log::info!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
|
||||
let _ = battery_driver.unsealed();
|
||||
let _ = battery_driver.it_enable();
|
||||
anyhow::Result::Ok(())
|
||||
Ok(())
|
||||
}
|
||||
|
1161
rust/src/hal/esp.rs
1161
rust/src/hal/esp.rs
File diff suppressed because it is too large
Load Diff
@@ -1,44 +1,80 @@
|
||||
use crate::config::{BoardHardware, PlantControllerConfig};
|
||||
use crate::hal::battery::{BatteryInteraction, NoBatteryMonitor};
|
||||
use crate::hal::esp::ESP;
|
||||
use crate::hal::{deep_sleep, BackupHeader, BoardInteraction, FreePeripherals, Sensor};
|
||||
use anyhow::{bail, Result};
|
||||
use crate::alloc::boxed::Box;
|
||||
use crate::hal::esp::Esp;
|
||||
use crate::hal::rtc::{BackupHeader, RTCModuleInteraction};
|
||||
use crate::hal::water::TankSensor;
|
||||
use crate::hal::{BoardInteraction, FreePeripherals, Sensor};
|
||||
use crate::fat_error::{FatError, FatResult};
|
||||
use crate::{
|
||||
bail,
|
||||
config::PlantControllerConfig,
|
||||
hal::battery::{BatteryInteraction, NoBatteryMonitor},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use embedded_hal::digital::OutputPin;
|
||||
use esp_idf_hal::gpio::{IOPin, Pull};
|
||||
use esp_idf_hal::gpio::{InputOutput, PinDriver};
|
||||
use esp_hal::gpio::{Level, Output, OutputConfig};
|
||||
use measurements::{Current, Voltage};
|
||||
|
||||
pub struct Initial<'a> {
|
||||
pub(crate) general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
pub(crate) esp: ESP<'a>,
|
||||
pub(crate) general_fault: Output<'a>,
|
||||
pub(crate) esp: Esp<'a>,
|
||||
pub(crate) config: PlantControllerConfig,
|
||||
pub(crate) battery: Box<dyn BatteryInteraction + Send>,
|
||||
pub rtc: Box<dyn RTCModuleInteraction + Send>,
|
||||
}
|
||||
|
||||
pub(crate) struct NoRTC {}
|
||||
|
||||
#[async_trait]
|
||||
impl RTCModuleInteraction for NoRTC {
|
||||
async fn get_backup_info(&mut self) -> Result<BackupHeader, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
async fn get_backup_config(&mut self, _chunk: usize) -> FatResult<([u8; 32], usize, u16)> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
async fn backup_config(&mut self, _offset: usize, _bytes: &[u8]) -> FatResult<()> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
async fn backup_config_finalize(&mut self, _crc: u16, _length: usize) -> FatResult<()> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
async fn get_rtc_time(&mut self) -> Result<DateTime<Utc>, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
async fn set_rtc_time(&mut self, _time: &DateTime<Utc>) -> Result<(), FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_initial_board(
|
||||
free_pins: FreePeripherals,
|
||||
fs_mount_error: bool,
|
||||
free_pins: FreePeripherals<'static>,
|
||||
config: PlantControllerConfig,
|
||||
esp: ESP<'static>,
|
||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
||||
let mut general_fault = PinDriver::input_output(free_pins.gpio6.downgrade())?;
|
||||
general_fault.set_pull(Pull::Floating)?;
|
||||
general_fault.set_low()?;
|
||||
|
||||
if fs_mount_error {
|
||||
general_fault.set_high()?
|
||||
}
|
||||
esp: Esp<'static>,
|
||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>, FatError> {
|
||||
log::info!("Start initial");
|
||||
let general_fault = Output::new(free_pins.gpio23, Level::Low, OutputConfig::default());
|
||||
let v = Initial {
|
||||
general_fault,
|
||||
config,
|
||||
esp,
|
||||
battery: Box::new(NoBatteryMonitor {}),
|
||||
rtc: Box::new(NoRTC {}),
|
||||
};
|
||||
Ok(Box::new(v))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<'a> BoardInteraction<'a> for Initial<'a> {
|
||||
fn get_esp(&mut self) -> &mut ESP<'a> {
|
||||
fn get_tank_sensor(&mut self) -> Result<&mut TankSensor<'a>, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn get_esp(&mut self) -> &mut Esp<'a> {
|
||||
&mut self.esp
|
||||
}
|
||||
|
||||
@@ -50,77 +86,61 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
|
||||
&mut self.battery
|
||||
}
|
||||
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> Result<()> {
|
||||
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
|
||||
&mut self.rtc
|
||||
}
|
||||
|
||||
fn set_charge_indicator(&mut self, _charging: bool) -> Result<(), FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
||||
deep_sleep(duration_in_ms)
|
||||
async fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
||||
self.esp.deep_sleep(duration_in_ms).await;
|
||||
}
|
||||
|
||||
fn get_backup_info(&mut self) -> Result<BackupHeader> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn get_backup_config(&mut self) -> Result<Vec<u8>> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn backup_config(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn is_day(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn water_temperature_c(&mut self) -> Result<f32> {
|
||||
async fn light(&mut self, _enable: bool) -> Result<(), FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn tank_sensor_voltage(&mut self) -> Result<f32> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
fn light(&mut self, enable: bool) -> Result<()> {
|
||||
async fn pump(&mut self, _plant: usize, _enable: bool) -> Result<(), FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn pump(&mut self, plant: usize, enable: bool) -> Result<()> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
fn fault(&mut self, plant: usize, _enable: bool) -> Result<()> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32> {
|
||||
async fn pump_current(&mut self, _plant: usize) -> Result<Current, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn general_fault(&mut self, enable: bool) {
|
||||
let _ = self.general_fault.set_state(enable.into());
|
||||
}
|
||||
|
||||
fn factory_reset(&mut self) -> Result<()> {
|
||||
async fn fault(&mut self, _plant: usize, _enable: bool) -> Result<(), FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
|
||||
async fn measure_moisture_hz(
|
||||
&mut self,
|
||||
_plant: usize,
|
||||
_sensor: Sensor,
|
||||
) -> Result<f32, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> Result<()> {
|
||||
bail!("Please configure board revision")
|
||||
async fn general_fault(&mut self, enable: bool) {
|
||||
self.general_fault.set_level(enable.into());
|
||||
}
|
||||
fn test_pump(&mut self, plant: usize) -> Result<()> {
|
||||
|
||||
async fn test(&mut self) -> Result<(), FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn test(&mut self) -> Result<()> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
fn set_config(&mut self, config: PlantControllerConfig) -> anyhow::Result<()> {
|
||||
fn set_config(&mut self, config: PlantControllerConfig) {
|
||||
self.config = config;
|
||||
self.esp.save_config(&self.config)?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
async fn get_mptt_voltage(&mut self) -> Result<Voltage, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
|
||||
async fn get_mptt_current(&mut self) -> Result<Current, FatError> {
|
||||
bail!("Please configure board revision")
|
||||
}
|
||||
}
|
||||
|
63
rust/src/hal/little_fs2storage_adapter.rs
Normal file
63
rust/src/hal/little_fs2storage_adapter.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use embedded_storage::{ReadStorage, Storage};
|
||||
use esp_bootloader_esp_idf::partitions::FlashRegion;
|
||||
use esp_storage::FlashStorage;
|
||||
use littlefs2::consts::U512 as lfsCache;
|
||||
use littlefs2::consts::U512 as lfsLookahead;
|
||||
use littlefs2::driver::Storage as lfs2Storage;
|
||||
use littlefs2::io::Error as lfs2Error;
|
||||
use littlefs2::io::Result as lfs2Result;
|
||||
use log::error;
|
||||
|
||||
pub struct LittleFs2Filesystem {
|
||||
pub(crate) storage: &'static mut FlashRegion<'static, FlashStorage>,
|
||||
}
|
||||
|
||||
impl lfs2Storage for LittleFs2Filesystem {
|
||||
const READ_SIZE: usize = 256;
|
||||
const WRITE_SIZE: usize = 512;
|
||||
const BLOCK_SIZE: usize = 512; //usually optimal for flash access
|
||||
const BLOCK_COUNT: usize = 8 * 1024 * 1024 / 512; //8mb in 32kb blocks
|
||||
const BLOCK_CYCLES: isize = 100;
|
||||
type CACHE_SIZE = lfsCache;
|
||||
type LOOKAHEAD_SIZE = lfsLookahead;
|
||||
|
||||
fn read(&mut self, off: usize, buf: &mut [u8]) -> lfs2Result<usize> {
|
||||
let read_size: usize = Self::READ_SIZE;
|
||||
assert_eq!(off % read_size, 0);
|
||||
assert_eq!(buf.len() % read_size, 0);
|
||||
match self.storage.read(off as u32, buf) {
|
||||
Ok(..) => Ok(buf.len()),
|
||||
Err(err) => {
|
||||
error!("Littlefs2Filesystem read error: {:?}", err);
|
||||
Err(lfs2Error::IO)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&mut self, off: usize, data: &[u8]) -> lfs2Result<usize> {
|
||||
let write_size: usize = Self::WRITE_SIZE;
|
||||
assert_eq!(off % write_size, 0);
|
||||
assert_eq!(data.len() % write_size, 0);
|
||||
match self.storage.write(off as u32, data) {
|
||||
Ok(..) => Ok(data.len()),
|
||||
Err(err) => {
|
||||
error!("Littlefs2Filesystem write error: {:?}", err);
|
||||
Err(lfs2Error::IO)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn erase(&mut self, off: usize, len: usize) -> lfs2Result<usize> {
|
||||
let block_size: usize = Self::BLOCK_SIZE;
|
||||
debug_assert!(off % block_size == 0);
|
||||
debug_assert!(len % block_size == 0);
|
||||
//match self.storage.erase(off as u32, len as u32) {
|
||||
//anyhow::Result::Ok(..) => lfs2Result::Ok(len),
|
||||
//Err(err) => {
|
||||
//error!("Littlefs2Filesystem erase error: {:?}", err);
|
||||
//Err(lfs2Error::IO)
|
||||
// }
|
||||
//}
|
||||
lfs2Result::Ok(len)
|
||||
}
|
||||
}
|
@@ -1,89 +1,120 @@
|
||||
pub(crate) mod battery;
|
||||
mod esp;
|
||||
pub mod esp;
|
||||
mod initial_hal;
|
||||
mod v3_hal;
|
||||
mod little_fs2storage_adapter;
|
||||
pub(crate) mod rtc;
|
||||
mod v4_hal;
|
||||
mod v4_sensor;
|
||||
mod water;
|
||||
|
||||
use battery::BQ34Z100G1;
|
||||
use crate::alloc::string::ToString;
|
||||
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
|
||||
use esp_hal::peripherals::Peripherals;
|
||||
use esp_hal::peripherals::ADC1;
|
||||
use esp_hal::peripherals::APB_SARADC;
|
||||
use esp_hal::peripherals::GPIO0;
|
||||
use esp_hal::peripherals::GPIO1;
|
||||
use esp_hal::peripherals::GPIO10;
|
||||
use esp_hal::peripherals::GPIO11;
|
||||
use esp_hal::peripherals::GPIO12;
|
||||
use esp_hal::peripherals::GPIO13;
|
||||
use esp_hal::peripherals::GPIO14;
|
||||
use esp_hal::peripherals::GPIO15;
|
||||
use esp_hal::peripherals::GPIO16;
|
||||
use esp_hal::peripherals::GPIO17;
|
||||
use esp_hal::peripherals::GPIO18;
|
||||
use esp_hal::peripherals::GPIO2;
|
||||
use esp_hal::peripherals::GPIO21;
|
||||
use esp_hal::peripherals::GPIO22;
|
||||
use esp_hal::peripherals::GPIO23;
|
||||
use esp_hal::peripherals::GPIO24;
|
||||
use esp_hal::peripherals::GPIO25;
|
||||
use esp_hal::peripherals::GPIO26;
|
||||
use esp_hal::peripherals::GPIO27;
|
||||
use esp_hal::peripherals::GPIO28;
|
||||
use esp_hal::peripherals::GPIO29;
|
||||
use esp_hal::peripherals::GPIO3;
|
||||
use esp_hal::peripherals::GPIO30;
|
||||
use esp_hal::peripherals::GPIO4;
|
||||
use esp_hal::peripherals::GPIO5;
|
||||
use esp_hal::peripherals::GPIO6;
|
||||
use esp_hal::peripherals::GPIO7;
|
||||
use esp_hal::peripherals::GPIO8;
|
||||
use esp_hal::peripherals::PCNT;
|
||||
use esp_hal::peripherals::TWAI0;
|
||||
|
||||
use crate::{
|
||||
bail,
|
||||
config::{BatteryBoardVersion, BoardVersion, PlantControllerConfig},
|
||||
hal::{
|
||||
battery::{BatteryInteraction, NoBatteryMonitor},
|
||||
esp::Esp,
|
||||
},
|
||||
log::LogMessage,
|
||||
BOARD_ACCESS,
|
||||
};
|
||||
use alloc::boxed::Box;
|
||||
use alloc::format;
|
||||
use alloc::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use bq34z100::Bq34z100g1Driver;
|
||||
|
||||
use crate::log::LogMessage;
|
||||
use ds323x::DateTimeAccess;
|
||||
use esp_ota::mark_app_valid;
|
||||
|
||||
use eeprom24x::Eeprom24xTrait;
|
||||
use embedded_hal_bus::i2c::MutexDevice;
|
||||
|
||||
use esp_idf_hal::adc::ADC1;
|
||||
use esp_idf_hal::i2c::{APBTickType, I2cConfig, I2cDriver};
|
||||
use esp_idf_hal::units::FromValueType;
|
||||
use esp_idf_svc::eventloop::EspSystemEventLoop;
|
||||
use esp_idf_svc::nvs::EspDefaultNvsPartition;
|
||||
use esp_idf_svc::wifi::EspWifi;
|
||||
use esp_idf_sys::esp_restart;
|
||||
use esp_idf_sys::{
|
||||
esp_deep_sleep, esp_sleep_enable_ext1_wakeup,
|
||||
esp_sleep_ext1_wakeup_mode_t_ESP_EXT1_WAKEUP_ANY_LOW,
|
||||
use chrono::{DateTime, FixedOffset, Utc};
|
||||
use core::cell::RefCell;
|
||||
use ds323x::ic::DS3231;
|
||||
use ds323x::interface::I2cInterface;
|
||||
use ds323x::{DateTimeAccess, Ds323x};
|
||||
use eeprom24x::addr_size::TwoBytes;
|
||||
use eeprom24x::page_size::B32;
|
||||
use eeprom24x::unique_serial::No;
|
||||
use eeprom24x::{Eeprom24x, SlaveAddr, Storage};
|
||||
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_sync::blocking_mutex::CriticalSectionMutex;
|
||||
//use battery::BQ34Z100G1;
|
||||
//use bq34z100::Bq34z100g1Driver;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use esp_bootloader_esp_idf::partitions::{
|
||||
AppPartitionSubType, DataPartitionSubType, FlashRegion, PartitionEntry,
|
||||
};
|
||||
use once_cell::sync::Lazy;
|
||||
use esp_hal::clock::CpuClock;
|
||||
use esp_hal::gpio::{Input, InputConfig, Pull};
|
||||
use measurements::{Current, Voltage};
|
||||
|
||||
use anyhow::{Ok, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::hal::battery::{print_battery_bq34z100, BQ34Z100G1};
|
||||
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
|
||||
use crate::hal::water::TankSensor;
|
||||
use crate::log::LOG_ACCESS;
|
||||
use crate::fat_error::FatError;
|
||||
use embassy_sync::mutex::Mutex;
|
||||
use embassy_sync::once_lock::OnceLock;
|
||||
use esp_alloc as _;
|
||||
use esp_backtrace as _;
|
||||
use esp_bootloader_esp_idf::ota::Slot;
|
||||
use esp_hal::delay::Delay;
|
||||
use esp_hal::i2c::master::{BusTimeout, Config, I2c};
|
||||
use esp_hal::pcnt::unit::Unit;
|
||||
use esp_hal::pcnt::Pcnt;
|
||||
use esp_hal::rng::Rng;
|
||||
use esp_hal::rtc_cntl::{Rtc, SocResetReason};
|
||||
use esp_hal::system::reset_reason;
|
||||
use esp_hal::time::Rate;
|
||||
use esp_hal::timer::timg::TimerGroup;
|
||||
use esp_hal::Blocking;
|
||||
use esp_storage::FlashStorage;
|
||||
use esp_wifi::{init, EspWifiController};
|
||||
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
|
||||
use littlefs2::object_safe::DynStorage;
|
||||
use log::{info, warn};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::result::Result::Ok as OkStd;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::{BatteryBoardVersion, BoardVersion, PlantControllerConfig};
|
||||
use crate::hal::battery::{print_battery_bq34z100, BatteryInteraction, NoBatteryMonitor};
|
||||
use crate::hal::esp::ESP;
|
||||
use crate::hal::initial_hal::Initial;
|
||||
use crate::log::log;
|
||||
use embedded_hal::digital::OutputPin;
|
||||
use esp_idf_hal::delay::Delay;
|
||||
use esp_idf_hal::gpio::{
|
||||
Gpio0, Gpio1, Gpio10, Gpio11, Gpio12, Gpio13, Gpio14, Gpio15, Gpio16, Gpio17, Gpio18, Gpio2,
|
||||
Gpio21, Gpio22, Gpio23, Gpio24, Gpio25, Gpio26, Gpio27, Gpio28, Gpio29, Gpio3, Gpio30, Gpio4,
|
||||
Gpio5, Gpio6, Gpio7, Gpio8, IOPin, PinDriver, Pull,
|
||||
};
|
||||
use esp_idf_hal::pcnt::PCNT0;
|
||||
use esp_idf_hal::prelude::Peripherals;
|
||||
use esp_idf_hal::reset::ResetReason;
|
||||
use pca9535::StandardExpanderInterface;
|
||||
pub static TIME_ACCESS: OnceLock<Rtc> = OnceLock::new();
|
||||
|
||||
//Only support for 8 right now!
|
||||
pub const PLANT_COUNT: usize = 8;
|
||||
const REPEAT_MOIST_MEASURE: usize = 1;
|
||||
|
||||
const TANK_MULTI_SAMPLE: usize = 11;
|
||||
|
||||
pub static I2C_DRIVER: Lazy<Mutex<I2cDriver<'static>>> = Lazy::new(PlantHal::create_i2c);
|
||||
|
||||
#[non_exhaustive]
|
||||
struct V3Constants;
|
||||
|
||||
impl V3Constants {}
|
||||
|
||||
const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
|
||||
|
||||
fn deep_sleep(duration_in_ms: u64) -> ! {
|
||||
unsafe {
|
||||
//if we don't do this here, we might just revert newly flashed firmware
|
||||
mark_app_valid();
|
||||
//allow early wakeup by pressing the boot button
|
||||
if duration_in_ms == 0 {
|
||||
esp_restart();
|
||||
} else {
|
||||
//configure gpio 1 to wakeup on low, reused boot button for this
|
||||
esp_sleep_enable_ext1_wakeup(
|
||||
0b10u64,
|
||||
esp_sleep_ext1_wakeup_mode_t_ESP_EXT1_WAKEUP_ANY_LOW,
|
||||
);
|
||||
esp_deep_sleep(duration_in_ms);
|
||||
}
|
||||
};
|
||||
}
|
||||
pub static I2C_DRIVER: OnceLock<
|
||||
embassy_sync::blocking_mutex::Mutex<CriticalSectionRawMutex, RefCell<I2c<Blocking>>>,
|
||||
> = OnceLock::new();
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Sensor {
|
||||
@@ -97,187 +128,369 @@ pub struct HAL<'a> {
|
||||
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
pub struct BackupHeader {
|
||||
pub timestamp: i64,
|
||||
crc16: u16,
|
||||
pub size: usize,
|
||||
}
|
||||
|
||||
impl Default for BackupHeader {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
timestamp: Default::default(),
|
||||
crc16: Default::default(),
|
||||
size: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait BoardInteraction<'a> {
|
||||
fn get_esp(&mut self) -> &mut ESP<'a>;
|
||||
fn get_tank_sensor(&mut self) -> Result<&mut TankSensor<'a>, FatError>;
|
||||
fn get_esp(&mut self) -> &mut Esp<'a>;
|
||||
fn get_config(&mut self) -> &PlantControllerConfig;
|
||||
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> Result<()>;
|
||||
fn deep_sleep(&mut self, duration_in_ms: u64) -> !;
|
||||
fn get_backup_info(&mut self) -> Result<BackupHeader>;
|
||||
fn get_backup_config(&mut self) -> Result<Vec<u8>>;
|
||||
fn backup_config(&mut self, bytes: &[u8]) -> Result<()>;
|
||||
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send>;
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> Result<(), FatError>;
|
||||
async fn deep_sleep(&mut self, duration_in_ms: u64) -> !;
|
||||
|
||||
fn is_day(&self) -> bool;
|
||||
//should be multsampled
|
||||
fn water_temperature_c(&mut self) -> Result<f32>;
|
||||
/// return median tank sensor value in milli volt
|
||||
fn tank_sensor_voltage(&mut self) -> Result<f32>;
|
||||
fn light(&mut self, enable: bool) -> Result<()>;
|
||||
fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
|
||||
fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
|
||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
|
||||
fn general_fault(&mut self, enable: bool);
|
||||
fn factory_reset(&mut self) -> Result<()>;
|
||||
fn get_rtc_time(&mut self) -> Result<DateTime<Utc>>;
|
||||
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> Result<()>;
|
||||
fn test_pump(&mut self, plant: usize) -> Result<()>;
|
||||
fn test(&mut self) -> Result<()>;
|
||||
fn set_config(&mut self, config: PlantControllerConfig) -> Result<()>;
|
||||
}
|
||||
async fn light(&mut self, enable: bool) -> Result<(), FatError>;
|
||||
async fn pump(&mut self, plant: usize, enable: bool) -> Result<(), FatError>;
|
||||
async fn pump_current(&mut self, plant: usize) -> Result<Current, FatError>;
|
||||
async fn fault(&mut self, plant: usize, enable: bool) -> Result<(), FatError>;
|
||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32, FatError>;
|
||||
async fn general_fault(&mut self, enable: bool);
|
||||
async fn test(&mut self) -> Result<(), FatError>;
|
||||
fn set_config(&mut self, config: PlantControllerConfig);
|
||||
async fn get_mptt_voltage(&mut self) -> Result<Voltage, FatError>;
|
||||
async fn get_mptt_current(&mut self) -> Result<Current, FatError>;
|
||||
|
||||
pub struct FreePeripherals {
|
||||
pub gpio0: Gpio0,
|
||||
pub gpio1: Gpio1,
|
||||
pub gpio2: Gpio2,
|
||||
pub gpio3: Gpio3,
|
||||
pub gpio4: Gpio4,
|
||||
pub gpio5: Gpio5,
|
||||
pub gpio6: Gpio6,
|
||||
pub gpio7: Gpio7,
|
||||
pub gpio8: Gpio8,
|
||||
//config button here
|
||||
pub gpio10: Gpio10,
|
||||
pub gpio11: Gpio11,
|
||||
pub gpio12: Gpio12,
|
||||
pub gpio13: Gpio13,
|
||||
pub gpio14: Gpio14,
|
||||
pub gpio15: Gpio15,
|
||||
pub gpio16: Gpio16,
|
||||
pub gpio17: Gpio17,
|
||||
pub gpio18: Gpio18,
|
||||
//i2c here
|
||||
pub gpio21: Gpio21,
|
||||
pub gpio22: Gpio22,
|
||||
pub gpio23: Gpio23,
|
||||
pub gpio24: Gpio24,
|
||||
pub gpio25: Gpio25,
|
||||
pub gpio26: Gpio26,
|
||||
pub gpio27: Gpio27,
|
||||
pub gpio28: Gpio28,
|
||||
pub gpio29: Gpio29,
|
||||
pub gpio30: Gpio30,
|
||||
pub pcnt0: PCNT0,
|
||||
pub adc1: ADC1,
|
||||
}
|
||||
|
||||
impl PlantHal {
|
||||
fn create_i2c() -> Mutex<I2cDriver<'static>> {
|
||||
let peripherals = unsafe { Peripherals::new() };
|
||||
|
||||
let config = I2cConfig::new()
|
||||
.scl_enable_pullup(true)
|
||||
.sda_enable_pullup(true)
|
||||
.baudrate(100_u32.kHz().into())
|
||||
.timeout(APBTickType::from(Duration::from_millis(100)));
|
||||
|
||||
let i2c = peripherals.i2c0;
|
||||
let scl = peripherals.pins.gpio19.downgrade();
|
||||
let sda = peripherals.pins.gpio20.downgrade();
|
||||
|
||||
Mutex::new(I2cDriver::new(i2c, sda, scl, &config).unwrap())
|
||||
async fn progress(&mut self, counter: u32) {
|
||||
let current = counter % PLANT_COUNT as u32;
|
||||
for led in 0..PLANT_COUNT {
|
||||
if let Err(err) = self.fault(led, current == led as u32).await {
|
||||
warn!("Fault on plant {}: {:?}", led, err);
|
||||
}
|
||||
}
|
||||
let even = counter % 2 == 0;
|
||||
let _ = self.general_fault(even.into()).await;
|
||||
}
|
||||
|
||||
pub fn create() -> Result<Mutex<HAL<'static>>> {
|
||||
let peripherals = Peripherals::take()?;
|
||||
let sys_loop = EspSystemEventLoop::take()?;
|
||||
let nvs = EspDefaultNvsPartition::take()?;
|
||||
let wifi_driver = EspWifi::new(peripherals.modem, sys_loop, Some(nvs))?;
|
||||
async fn clear_progress(&mut self) {
|
||||
for led in 0..PLANT_COUNT {
|
||||
if let Err(err) = self.fault(led, false).await {
|
||||
warn!("Fault on plant {}: {:?}", led, err);
|
||||
}
|
||||
}
|
||||
let _ = self.general_fault(false).await;
|
||||
}
|
||||
}
|
||||
|
||||
let mut boot_button = PinDriver::input(peripherals.pins.gpio9.downgrade())?;
|
||||
boot_button.set_pull(Pull::Floating)?;
|
||||
#[allow(dead_code)]
|
||||
pub struct FreePeripherals<'a> {
|
||||
pub gpio0: GPIO0<'a>,
|
||||
pub gpio1: GPIO1<'a>,
|
||||
pub gpio2: GPIO2<'a>,
|
||||
pub gpio3: GPIO3<'a>,
|
||||
pub gpio4: GPIO4<'a>,
|
||||
pub gpio5: GPIO5<'a>,
|
||||
pub gpio6: GPIO6<'a>,
|
||||
pub gpio7: GPIO7<'a>,
|
||||
pub gpio8: GPIO8<'a>,
|
||||
// //config button here
|
||||
pub gpio10: GPIO10<'a>,
|
||||
pub gpio11: GPIO11<'a>,
|
||||
pub gpio12: GPIO12<'a>,
|
||||
pub gpio13: GPIO13<'a>,
|
||||
pub gpio14: GPIO14<'a>,
|
||||
pub gpio15: GPIO15<'a>,
|
||||
pub gpio16: GPIO16<'a>,
|
||||
pub gpio17: GPIO17<'a>,
|
||||
pub gpio18: GPIO18<'a>,
|
||||
// //i2c here
|
||||
pub gpio21: GPIO21<'a>,
|
||||
pub gpio22: GPIO22<'a>,
|
||||
pub gpio23: GPIO23<'a>,
|
||||
pub gpio24: GPIO24<'a>,
|
||||
pub gpio25: GPIO25<'a>,
|
||||
pub gpio26: GPIO26<'a>,
|
||||
pub gpio27: GPIO27<'a>,
|
||||
pub gpio28: GPIO28<'a>,
|
||||
pub gpio29: GPIO29<'a>,
|
||||
pub gpio30: GPIO30<'a>,
|
||||
pub twai: TWAI0<'a>,
|
||||
pub pcnt0: Unit<'a, 0>,
|
||||
pub pcnt1: Unit<'a, 1>,
|
||||
pub adc1: ADC1<'a>,
|
||||
}
|
||||
|
||||
macro_rules! mk_static {
|
||||
($t:ty,$val:expr) => {{
|
||||
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
||||
#[deny(unused_attributes)]
|
||||
let x = STATIC_CELL.uninit().write(($val));
|
||||
x
|
||||
}};
|
||||
}
|
||||
|
||||
const GW_IP_ADDR_ENV: Option<&'static str> = option_env!("GATEWAY_IP");
|
||||
|
||||
impl PlantHal {
|
||||
pub async fn create(
|
||||
spawner: Spawner,
|
||||
) -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
|
||||
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
|
||||
let peripherals: Peripherals = esp_hal::init(config);
|
||||
|
||||
esp_alloc::heap_allocator!(size: 64 * 1024);
|
||||
esp_alloc::heap_allocator!(#[link_section = ".dram2_uninit"] size: 64000);
|
||||
|
||||
let rtc: Rtc = Rtc::new(peripherals.LPWR);
|
||||
TIME_ACCESS.init(rtc).map_err(|_| FatError::String {
|
||||
error: "Init error rct".to_string(),
|
||||
})?;
|
||||
|
||||
let systimer = SystemTimer::new(peripherals.SYSTIMER);
|
||||
|
||||
let boot_button = Input::new(
|
||||
peripherals.GPIO9,
|
||||
InputConfig::default().with_pull(Pull::None),
|
||||
);
|
||||
|
||||
let rng = Rng::new(peripherals.RNG);
|
||||
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
||||
let esp_wifi_ctrl = &*mk_static!(
|
||||
EspWifiController<'static>,
|
||||
init(timg0.timer0, rng.clone()).expect("Could not init wifi controller")
|
||||
);
|
||||
|
||||
let (controller, interfaces) =
|
||||
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).expect("Could not init wifi");
|
||||
|
||||
use esp_hal::timer::systimer::SystemTimer;
|
||||
esp_hal_embassy::init(systimer.alarm0);
|
||||
|
||||
//let mut adc1 = Adc::new(peripherals.ADC1, adc1_config);
|
||||
//
|
||||
|
||||
let pcnt_module = Pcnt::new(peripherals.PCNT);
|
||||
|
||||
let free_pins = FreePeripherals {
|
||||
adc1: peripherals.adc1,
|
||||
pcnt0: peripherals.pcnt0,
|
||||
gpio0: peripherals.pins.gpio0,
|
||||
gpio1: peripherals.pins.gpio1,
|
||||
gpio2: peripherals.pins.gpio2,
|
||||
gpio3: peripherals.pins.gpio3,
|
||||
gpio4: peripherals.pins.gpio4,
|
||||
gpio5: peripherals.pins.gpio5,
|
||||
gpio6: peripherals.pins.gpio6,
|
||||
gpio7: peripherals.pins.gpio7,
|
||||
gpio8: peripherals.pins.gpio8,
|
||||
gpio10: peripherals.pins.gpio10,
|
||||
gpio11: peripherals.pins.gpio11,
|
||||
gpio12: peripherals.pins.gpio12,
|
||||
gpio13: peripherals.pins.gpio13,
|
||||
gpio14: peripherals.pins.gpio14,
|
||||
gpio15: peripherals.pins.gpio15,
|
||||
gpio16: peripherals.pins.gpio16,
|
||||
gpio17: peripherals.pins.gpio17,
|
||||
gpio18: peripherals.pins.gpio18,
|
||||
gpio21: peripherals.pins.gpio21,
|
||||
gpio22: peripherals.pins.gpio22,
|
||||
gpio23: peripherals.pins.gpio23,
|
||||
gpio24: peripherals.pins.gpio24,
|
||||
gpio25: peripherals.pins.gpio25,
|
||||
gpio26: peripherals.pins.gpio26,
|
||||
gpio27: peripherals.pins.gpio27,
|
||||
gpio28: peripherals.pins.gpio28,
|
||||
gpio29: peripherals.pins.gpio29,
|
||||
gpio30: peripherals.pins.gpio30,
|
||||
// can: peripherals.can,
|
||||
// adc1: peripherals.adc1,
|
||||
// pcnt0: peripherals.pcnt0,
|
||||
// pcnt1: peripherals.pcnt1,
|
||||
gpio0: peripherals.GPIO0,
|
||||
gpio1: peripherals.GPIO1,
|
||||
gpio2: peripherals.GPIO2,
|
||||
gpio3: peripherals.GPIO3,
|
||||
gpio4: peripherals.GPIO4,
|
||||
gpio5: peripherals.GPIO5,
|
||||
gpio6: peripherals.GPIO6,
|
||||
gpio7: peripherals.GPIO7,
|
||||
gpio8: peripherals.GPIO8,
|
||||
gpio10: peripherals.GPIO10,
|
||||
gpio11: peripherals.GPIO11,
|
||||
gpio12: peripherals.GPIO12,
|
||||
gpio13: peripherals.GPIO13,
|
||||
gpio14: peripherals.GPIO14,
|
||||
gpio15: peripherals.GPIO15,
|
||||
gpio16: peripherals.GPIO16,
|
||||
gpio17: peripherals.GPIO17,
|
||||
gpio18: peripherals.GPIO18,
|
||||
gpio21: peripherals.GPIO21,
|
||||
gpio22: peripherals.GPIO22,
|
||||
gpio23: peripherals.GPIO23,
|
||||
gpio24: peripherals.GPIO24,
|
||||
gpio25: peripherals.GPIO25,
|
||||
gpio26: peripherals.GPIO26,
|
||||
gpio27: peripherals.GPIO27,
|
||||
gpio28: peripherals.GPIO28,
|
||||
gpio29: peripherals.GPIO29,
|
||||
gpio30: peripherals.GPIO30,
|
||||
twai: peripherals.TWAI0,
|
||||
pcnt0: pcnt_module.unit0,
|
||||
pcnt1: pcnt_module.unit1,
|
||||
adc1: peripherals.ADC1,
|
||||
};
|
||||
|
||||
let mut esp = ESP {
|
||||
mqtt_client: None,
|
||||
wifi_driver,
|
||||
let tablebuffer = mk_static!(
|
||||
[u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN],
|
||||
[0u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN]
|
||||
);
|
||||
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
|
||||
let pt =
|
||||
esp_bootloader_esp_idf::partitions::read_partition_table(storage_ota, tablebuffer)?;
|
||||
|
||||
// List all partitions - this is just FYI
|
||||
for i in 0..pt.len() {
|
||||
info!("{:?}", pt.get_partition(i));
|
||||
}
|
||||
let ota_data = mk_static!(
|
||||
PartitionEntry,
|
||||
pt.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
|
||||
DataPartitionSubType::Ota,
|
||||
))?
|
||||
.expect("No OTA data partition found")
|
||||
);
|
||||
|
||||
let ota_data = mk_static!(
|
||||
FlashRegion<FlashStorage>,
|
||||
ota_data.as_embedded_storage(storage_ota)
|
||||
);
|
||||
|
||||
let mut ota = esp_bootloader_esp_idf::ota::Ota::new(ota_data)?;
|
||||
|
||||
let ota_partition = match ota.current_slot()? {
|
||||
Slot::None => {
|
||||
panic!("No OTA slot active?");
|
||||
}
|
||||
Slot::Slot0 => pt
|
||||
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
|
||||
AppPartitionSubType::Ota0,
|
||||
))?
|
||||
.expect("No OTA slot0 found"),
|
||||
Slot::Slot1 => pt
|
||||
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
|
||||
AppPartitionSubType::Ota1,
|
||||
))?
|
||||
.expect("No OTA slot1 found"),
|
||||
};
|
||||
|
||||
let ota_next = mk_static!(PartitionEntry, ota_partition);
|
||||
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
|
||||
let ota_next = mk_static!(
|
||||
FlashRegion<FlashStorage>,
|
||||
ota_next.as_embedded_storage(storage_ota)
|
||||
);
|
||||
|
||||
let data_partition = pt
|
||||
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
|
||||
DataPartitionSubType::LittleFs,
|
||||
))?
|
||||
.expect("Data partition with littlefs not found");
|
||||
let data_partition = mk_static!(PartitionEntry, data_partition);
|
||||
|
||||
let storage_data = mk_static!(FlashStorage, FlashStorage::new());
|
||||
let data = mk_static!(
|
||||
FlashRegion<FlashStorage>,
|
||||
data_partition.as_embedded_storage(storage_data)
|
||||
);
|
||||
let lfs2filesystem = mk_static!(LittleFs2Filesystem, LittleFs2Filesystem { storage: data });
|
||||
let alloc = mk_static!(Allocation<LittleFs2Filesystem>, lfs2Filesystem::allocate());
|
||||
if lfs2filesystem.is_mountable() {
|
||||
log::info!("Littlefs2 filesystem is mountable");
|
||||
} else {
|
||||
match lfs2filesystem.format() {
|
||||
Result::Ok(..) => {
|
||||
log::info!("Littlefs2 filesystem is formatted");
|
||||
}
|
||||
Err(err) => {
|
||||
bail!("Littlefs2 filesystem could not be formatted: {:?}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fs = Arc::new(Mutex::new(
|
||||
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
|
||||
));
|
||||
|
||||
let mut esp = Esp {
|
||||
fs,
|
||||
rng,
|
||||
controller: Arc::new(Mutex::new(controller)),
|
||||
interfaces: Some(interfaces),
|
||||
boot_button,
|
||||
delay: Delay::new(1000),
|
||||
mqtt_client: None,
|
||||
ota,
|
||||
ota_next,
|
||||
};
|
||||
|
||||
//init,reset rtc memory depending on cause
|
||||
let mut init_rtc_store: bool = false;
|
||||
let mut to_config_mode: bool = false;
|
||||
let reasons = ResetReason::get();
|
||||
match reasons {
|
||||
ResetReason::Software => {}
|
||||
ResetReason::ExternalPin => {}
|
||||
ResetReason::Watchdog => {
|
||||
init_rtc_store = true;
|
||||
}
|
||||
ResetReason::Sdio => init_rtc_store = true,
|
||||
ResetReason::Panic => init_rtc_store = true,
|
||||
ResetReason::InterruptWatchdog => init_rtc_store = true,
|
||||
ResetReason::PowerOn => init_rtc_store = true,
|
||||
ResetReason::Unknown => init_rtc_store = true,
|
||||
ResetReason::Brownout => init_rtc_store = true,
|
||||
ResetReason::TaskWatchdog => init_rtc_store = true,
|
||||
ResetReason::DeepSleep => {}
|
||||
ResetReason::USBPeripheral => {
|
||||
init_rtc_store = true;
|
||||
to_config_mode = true;
|
||||
}
|
||||
ResetReason::JTAG => init_rtc_store = true,
|
||||
let reasons = match reset_reason() {
|
||||
None => "unknown",
|
||||
Some(reason) => match reason {
|
||||
SocResetReason::ChipPowerOn => "power on",
|
||||
SocResetReason::CoreSw => "software reset",
|
||||
SocResetReason::CoreDeepSleep => "deep sleep",
|
||||
SocResetReason::CoreSDIO => "sdio reset",
|
||||
SocResetReason::CoreMwdt0 => "Watchdog Main",
|
||||
SocResetReason::CoreMwdt1 => "Watchdog 1",
|
||||
SocResetReason::CoreRtcWdt => "Watchdog RTC",
|
||||
SocResetReason::Cpu0Mwdt0 => "Watchdog MCpu0",
|
||||
SocResetReason::Cpu0Sw => "software reset cpu0",
|
||||
SocResetReason::Cpu0RtcWdt => {
|
||||
init_rtc_store = true;
|
||||
"Watchdog RTC cpu0"
|
||||
}
|
||||
SocResetReason::SysBrownOut => "sys brown out",
|
||||
SocResetReason::SysRtcWdt => "Watchdog Sys rtc",
|
||||
SocResetReason::Cpu0Mwdt1 => "cpu0 mwdt1",
|
||||
SocResetReason::SysSuperWdt => "Watchdog Super",
|
||||
SocResetReason::CoreEfuseCrc => "core efuse crc",
|
||||
SocResetReason::CoreUsbUart => {
|
||||
to_config_mode = true;
|
||||
"core usb uart"
|
||||
}
|
||||
SocResetReason::CoreUsbJtag => "core usb jtag",
|
||||
SocResetReason::Cpu0JtagCpu => "cpu0 jtag cpu",
|
||||
},
|
||||
};
|
||||
log(
|
||||
LogMessage::ResetReason,
|
||||
init_rtc_store as u32,
|
||||
to_config_mode as u32,
|
||||
"",
|
||||
&format!("{reasons:?}"),
|
||||
);
|
||||
LOG_ACCESS
|
||||
.lock()
|
||||
.await
|
||||
.log(
|
||||
LogMessage::ResetReason,
|
||||
init_rtc_store as u32,
|
||||
to_config_mode as u32,
|
||||
"",
|
||||
&format!("{reasons:?}"),
|
||||
)
|
||||
.await;
|
||||
|
||||
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode);
|
||||
let fs_mount_error = esp.mount_file_system().is_err();
|
||||
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode)
|
||||
.await;
|
||||
|
||||
let config = esp.load_config();
|
||||
let config = esp.load_config().await;
|
||||
|
||||
log::info!("Init rtc driver");
|
||||
|
||||
let sda = peripherals.GPIO20;
|
||||
let scl = peripherals.GPIO19;
|
||||
|
||||
let i2c = I2c::new(
|
||||
peripherals.I2C0,
|
||||
Config::default()
|
||||
.with_frequency(Rate::from_hz(100))
|
||||
.with_timeout(BusTimeout::Maximum),
|
||||
)?
|
||||
.with_scl(scl)
|
||||
.with_sda(sda);
|
||||
let i2c_bus: embassy_sync::blocking_mutex::Mutex<
|
||||
CriticalSectionRawMutex,
|
||||
RefCell<I2c<Blocking>>,
|
||||
> = CriticalSectionMutex::new(RefCell::new(i2c));
|
||||
|
||||
I2C_DRIVER.init(i2c_bus).expect("Could not init i2c driver");
|
||||
|
||||
let i2c_bus = I2C_DRIVER.get().await;
|
||||
let rtc_device = I2cDevice::new(&i2c_bus);
|
||||
let eeprom_device = I2cDevice::new(&i2c_bus);
|
||||
|
||||
let mut rtc: Ds323x<
|
||||
I2cInterface<I2cDevice<CriticalSectionRawMutex, I2c<Blocking>>>,
|
||||
DS3231,
|
||||
> = Ds323x::new_ds3231(rtc_device);
|
||||
|
||||
info!("Init rtc eeprom driver");
|
||||
let eeprom = Eeprom24x::new_24x32(eeprom_device, SlaveAddr::Alternative(true, true, true));
|
||||
let rtc_time = rtc.datetime();
|
||||
match rtc_time {
|
||||
Ok(tt) => {
|
||||
log::info!("Rtc Module reports time at UTC {}", tt);
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Rtc Module could not be read {:?}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let storage: Storage<
|
||||
I2cDevice<'static, CriticalSectionRawMutex, I2c<Blocking>>,
|
||||
B32,
|
||||
TwoBytes,
|
||||
No,
|
||||
Delay,
|
||||
> = Storage::new(eeprom, Delay::new());
|
||||
let rtc_module: Box<dyn RTCModuleInteraction + Send> =
|
||||
Box::new(DS3231Module { rtc, storage }) as Box<dyn RTCModuleInteraction + Send>;
|
||||
|
||||
let hal = match config {
|
||||
Result::Ok(config) => {
|
||||
@@ -285,22 +498,27 @@ impl PlantHal {
|
||||
match config.hardware.battery {
|
||||
BatteryBoardVersion::Disabled => Box::new(NoBatteryMonitor {}),
|
||||
BatteryBoardVersion::BQ34Z100G1 => {
|
||||
let battery_device = I2cDevice::new(I2C_DRIVER.get().await);
|
||||
let mut battery_driver = Bq34z100g1Driver {
|
||||
i2c: MutexDevice::new(&I2C_DRIVER),
|
||||
delay: Delay::new(0),
|
||||
i2c: battery_device,
|
||||
delay: Delay::new(),
|
||||
flash_block_data: [0; 32],
|
||||
};
|
||||
let status = print_battery_bq34z100(&mut battery_driver);
|
||||
match status {
|
||||
OkStd(_) => {}
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
log(
|
||||
LogMessage::BatteryCommunicationError,
|
||||
0u32,
|
||||
0,
|
||||
"",
|
||||
&format!("{err:?})"),
|
||||
);
|
||||
LOG_ACCESS
|
||||
.lock()
|
||||
.await
|
||||
.log(
|
||||
LogMessage::BatteryCommunicationError,
|
||||
0u32,
|
||||
0,
|
||||
"",
|
||||
&format!("{err:?})"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Box::new(BQ34Z100G1 { battery_driver })
|
||||
@@ -313,30 +531,37 @@ impl PlantHal {
|
||||
|
||||
let board_hal: Box<dyn BoardInteraction + Send> = match config.hardware.board {
|
||||
BoardVersion::INITIAL => {
|
||||
initial_hal::create_initial_board(free_pins, fs_mount_error, config, esp)?
|
||||
}
|
||||
BoardVersion::V3 => {
|
||||
v3_hal::create_v3(free_pins, esp, config, battery_interaction)?
|
||||
initial_hal::create_initial_board(free_pins, config, esp)?
|
||||
}
|
||||
// BoardVersion::V3 => {
|
||||
// v3_hal::create_v3(free_pins, esp, config, battery_interaction, rtc_module)?
|
||||
// }
|
||||
BoardVersion::V4 => {
|
||||
v4_hal::create_v4(free_pins, esp, config, battery_interaction)?
|
||||
v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)
|
||||
.await?
|
||||
}
|
||||
_ => {
|
||||
bail!("Unknown board version");
|
||||
}
|
||||
};
|
||||
|
||||
HAL { board_hal }
|
||||
}
|
||||
Err(err) => {
|
||||
log(
|
||||
LogMessage::ConfigModeMissingConfig,
|
||||
0,
|
||||
0,
|
||||
"",
|
||||
&err.to_string(),
|
||||
);
|
||||
LOG_ACCESS
|
||||
.lock()
|
||||
.await
|
||||
.log(
|
||||
LogMessage::ConfigModeMissingConfig,
|
||||
0,
|
||||
0,
|
||||
"",
|
||||
&err.to_string(),
|
||||
)
|
||||
.await;
|
||||
HAL {
|
||||
board_hal: initial_hal::create_initial_board(
|
||||
free_pins,
|
||||
fs_mount_error,
|
||||
PlantControllerConfig::default(),
|
||||
esp,
|
||||
)?,
|
||||
@@ -347,3 +572,23 @@ impl PlantHal {
|
||||
Ok(Mutex::new(hal))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn esp_time() -> DateTime<Utc> {
|
||||
DateTime::from_timestamp_micros(TIME_ACCESS.get().await.current_time_us() as i64).unwrap()
|
||||
}
|
||||
|
||||
pub async fn esp_set_time(time: DateTime<FixedOffset>) {
|
||||
TIME_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.set_current_time_us(time.timestamp_micros() as u64);
|
||||
BOARD_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.set_rtc_time(&time.to_utc())
|
||||
.await;
|
||||
}
|
||||
|
133
rust/src/hal/rtc.rs
Normal file
133
rust/src/hal/rtc.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use crate::hal::Box;
|
||||
use crate::fat_error::FatResult;
|
||||
use async_trait::async_trait;
|
||||
use bincode::config::Configuration;
|
||||
use bincode::{config, Decode, Encode};
|
||||
use chrono::{DateTime, Utc};
|
||||
use ds323x::ic::DS3231;
|
||||
use ds323x::interface::I2cInterface;
|
||||
use ds323x::{DateTimeAccess, Ds323x};
|
||||
use eeprom24x::addr_size::TwoBytes;
|
||||
use eeprom24x::page_size::B32;
|
||||
use eeprom24x::unique_serial::No;
|
||||
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embedded_storage::{ReadStorage, Storage};
|
||||
use esp_hal::delay::Delay;
|
||||
use esp_hal::i2c::master::I2c;
|
||||
use esp_hal::Blocking;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
|
||||
const CONFIG: Configuration = config::standard();
|
||||
//
|
||||
#[async_trait]
|
||||
pub trait RTCModuleInteraction {
|
||||
async fn get_backup_info(&mut self) -> FatResult<BackupHeader>;
|
||||
async fn get_backup_config(&mut self, chunk: usize) -> FatResult<([u8; 32], usize, u16)>;
|
||||
async fn backup_config(&mut self, offset: usize, bytes: &[u8]) -> FatResult<()>;
|
||||
async fn backup_config_finalize(&mut self, crc: u16, length: usize) -> FatResult<()>;
|
||||
async fn get_rtc_time(&mut self) -> FatResult<DateTime<Utc>>;
|
||||
async fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> FatResult<()>;
|
||||
}
|
||||
//
|
||||
const BACKUP_HEADER_MAX_SIZE: usize = 64;
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Encode, Decode)]
|
||||
pub struct BackupHeader {
|
||||
pub timestamp: i64,
|
||||
crc16: u16,
|
||||
pub size: u16,
|
||||
}
|
||||
//
|
||||
pub struct DS3231Module {
|
||||
pub(crate) rtc: Ds323x<
|
||||
I2cInterface<I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>>,
|
||||
DS3231,
|
||||
>,
|
||||
|
||||
pub(crate) storage: eeprom24x::Storage<
|
||||
I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>,
|
||||
B32,
|
||||
TwoBytes,
|
||||
No,
|
||||
Delay,
|
||||
>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RTCModuleInteraction for DS3231Module {
|
||||
async fn get_backup_info(&mut self) -> FatResult<BackupHeader> {
|
||||
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
||||
|
||||
self.storage.read(0, &mut header_page_buffer)?;
|
||||
|
||||
let (header, len): (BackupHeader, usize) =
|
||||
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
||||
|
||||
log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
async fn get_backup_config(&mut self, chunk: usize) -> FatResult<([u8; 32], usize, u16)> {
|
||||
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
||||
|
||||
self.storage.read(0, &mut header_page_buffer)?;
|
||||
let (header, _header_size): (BackupHeader, usize) =
|
||||
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
||||
|
||||
let mut buf = [0_u8; 32];
|
||||
let offset = chunk * buf.len() + BACKUP_HEADER_MAX_SIZE;
|
||||
|
||||
let end: usize = header.size as usize + BACKUP_HEADER_MAX_SIZE;
|
||||
let current_end = offset + buf.len();
|
||||
let chunk_size = if current_end > end {
|
||||
end - offset
|
||||
} else {
|
||||
buf.len()
|
||||
};
|
||||
if chunk_size == 0 {
|
||||
Ok((buf, 0, header.crc16))
|
||||
} else {
|
||||
self.storage.read(offset as u32, &mut buf)?;
|
||||
//&buf[..chunk_size];
|
||||
Ok((buf, chunk_size, header.crc16))
|
||||
}
|
||||
}
|
||||
async fn backup_config(&mut self, offset: usize, bytes: &[u8]) -> FatResult<()> {
|
||||
//skip header and write after
|
||||
self.storage
|
||||
.write((BACKUP_HEADER_MAX_SIZE + offset) as u32, &bytes)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn backup_config_finalize(&mut self, crc: u16, length: usize) -> FatResult<()> {
|
||||
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
||||
|
||||
let time = self.get_rtc_time().await?.timestamp_millis();
|
||||
let header = BackupHeader {
|
||||
crc16: crc,
|
||||
timestamp: time,
|
||||
size: length as u16,
|
||||
};
|
||||
let config = config::standard();
|
||||
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
|
||||
log::info!(
|
||||
"Raw header is {:?} with size {}",
|
||||
header_page_buffer,
|
||||
encoded
|
||||
);
|
||||
self.storage.write(0, &header_page_buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_rtc_time(&mut self) -> FatResult<DateTime<Utc>> {
|
||||
Ok(self.rtc.datetime()?.and_utc())
|
||||
}
|
||||
|
||||
async fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> FatResult<()> {
|
||||
let naive_time = time.naive_utc();
|
||||
Ok(self.rtc.set_datetime(&naive_time)?)
|
||||
}
|
||||
}
|
@@ -1,163 +1,247 @@
|
||||
use crate::config::PlantControllerConfig;
|
||||
use crate::hal::battery::BatteryInteraction;
|
||||
use crate::hal::esp::ESP;
|
||||
use crate::hal::{
|
||||
deep_sleep, BackupHeader, BoardInteraction, FreePeripherals, Sensor, I2C_DRIVER, PLANT_COUNT,
|
||||
REPEAT_MOIST_MEASURE, TANK_MULTI_SAMPLE, X25,
|
||||
};
|
||||
use crate::log::{log, LogMessage};
|
||||
use anyhow::{anyhow, bail};
|
||||
use chrono::{DateTime, Utc};
|
||||
use ds18b20::Ds18b20;
|
||||
use ds323x::{DateTimeAccess, Ds323x};
|
||||
use eeprom24x::{Eeprom24x, Eeprom24xTrait, SlaveAddr};
|
||||
use embedded_hal::digital::OutputPin;
|
||||
use embedded_hal_bus::i2c::MutexDevice;
|
||||
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
|
||||
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
|
||||
use esp_idf_hal::adc::{attenuation, Resolution};
|
||||
use esp_idf_hal::delay::Delay;
|
||||
use esp_idf_hal::gpio::{AnyInputPin, Gpio5, IOPin, InputOutput, Output, PinDriver, Pull};
|
||||
use esp_idf_hal::i2c::I2cDriver;
|
||||
use esp_idf_hal::pcnt::{
|
||||
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex,
|
||||
};
|
||||
use esp_idf_sys::{gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
|
||||
use ina219::address::Address;
|
||||
use ina219::calibration::{Calibration, UnCalibrated};
|
||||
use crate::hal::esp::Esp;
|
||||
use crate::hal::rtc::RTCModuleInteraction;
|
||||
use crate::hal::water::TankSensor;
|
||||
use crate::hal::{BoardInteraction, FreePeripherals, Sensor, I2C_DRIVER, PLANT_COUNT};
|
||||
use alloc::boxed::Box;
|
||||
use alloc::string::ToString;
|
||||
use async_trait::async_trait;
|
||||
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_time::Timer;
|
||||
use esp_hal::analog::adc::{Adc, AdcConfig, Attenuation};
|
||||
use esp_hal::{twai, Blocking};
|
||||
//use embedded_hal_bus::i2c::MutexDevice;
|
||||
use crate::bail;
|
||||
use crate::hal::v4_sensor::{SensorImpl, SensorInteraction};
|
||||
use crate::fat_error::{FatError, FatResult};
|
||||
use esp_hal::gpio::{Flex, Input, InputConfig, Level, Output, OutputConfig, Pull};
|
||||
use esp_hal::i2c::master::I2c;
|
||||
use esp_hal::pcnt::Pcnt;
|
||||
use esp_hal::twai::{EspTwaiFrame, StandardId, TwaiMode};
|
||||
use esp_println::println;
|
||||
use ina219::address::{Address, Pin};
|
||||
use ina219::calibration::UnCalibrated;
|
||||
use ina219::configuration::{Configuration, OperatingMode, Resolution};
|
||||
use ina219::SyncIna219;
|
||||
use one_wire_bus::OneWire;
|
||||
use measurements::Resistance;
|
||||
use measurements::{Current, Voltage};
|
||||
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
||||
use std::result::Result::Ok as OkStd;
|
||||
use crate::log::{LogMessage, LOG_ACCESS};
|
||||
|
||||
const MS0: u8 = 1_u8;
|
||||
const MS1: u8 = 0_u8;
|
||||
const MS2: u8 = 3_u8;
|
||||
const MS3: u8 = 4_u8;
|
||||
const MS4: u8 = 2_u8;
|
||||
const SENSOR_ON: u8 = 5_u8;
|
||||
const MPPT_CURRENT_SHUNT_OHMS: f64 = 0.05_f64;
|
||||
const TWAI_BAUDRATE: twai::BaudRate = twai::BaudRate::B125K;
|
||||
|
||||
pub struct V4<'a> {
|
||||
mppt_ina: SyncIna219<MutexDevice<'a, I2cDriver<'a>>, UnCalibrated>,
|
||||
esp: ESP<'a>,
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
config: PlantControllerConfig,
|
||||
tank_channel: AdcChannelDriver<'a, Gpio5, AdcDriver<'a, esp_idf_hal::adc::ADC1>>,
|
||||
solar_is_day: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
|
||||
signal_counter: PcntDriver<'a>,
|
||||
charge_indicator: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
awake: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
|
||||
light: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
tank_power: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
one_wire_bus: OneWire<PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>>,
|
||||
rtc:
|
||||
Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
|
||||
eeprom: Eeprom24x<
|
||||
MutexDevice<'a, I2cDriver<'a>>,
|
||||
eeprom24x::page_size::B32,
|
||||
eeprom24x::addr_size::TwoBytes,
|
||||
eeprom24x::unique_serial::No,
|
||||
>,
|
||||
general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
||||
pump_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
|
||||
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
|
||||
pub enum Charger<'a> {
|
||||
SolarMpptV1 {
|
||||
mppt_ina: SyncIna219<
|
||||
I2cDevice<'a, CriticalSectionRawMutex, I2c<'static, Blocking>>,
|
||||
UnCalibrated,
|
||||
>,
|
||||
solar_is_day: Input<'a>,
|
||||
charge_indicator: Output<'a>,
|
||||
},
|
||||
ErrorInit {},
|
||||
}
|
||||
|
||||
pub(crate) fn create_v4(
|
||||
peripherals: FreePeripherals,
|
||||
esp: ESP<'static>,
|
||||
impl<'a> Charger<'a> {
|
||||
pub(crate) fn get_mppt_current(&mut self) -> FatResult<Current> {
|
||||
match self {
|
||||
Charger::SolarMpptV1 { mppt_ina, .. } => {
|
||||
let v = mppt_ina.shunt_voltage()?;
|
||||
let shunt_voltage = Voltage::from_microvolts(v.shunt_voltage_uv().abs() as f64);
|
||||
let shut_value = Resistance::from_ohms(MPPT_CURRENT_SHUNT_OHMS);
|
||||
let current = shunt_voltage.as_volts() / shut_value.as_ohms();
|
||||
Ok(Current::from_amperes(current))
|
||||
}
|
||||
Charger::ErrorInit { .. } => {
|
||||
bail!("hardware error during init");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_mptt_voltage(&mut self) -> FatResult<Voltage> {
|
||||
match self {
|
||||
Charger::SolarMpptV1 { mppt_ina, .. } => {
|
||||
let v = mppt_ina.bus_voltage()?;
|
||||
Ok(Voltage::from_millivolts(v.voltage_mv() as f64))
|
||||
}
|
||||
Charger::ErrorInit { .. } => {
|
||||
bail!("hardware error during init");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Charger<'_> {
|
||||
pub(crate) fn power_save(&mut self) {
|
||||
match self {
|
||||
Charger::SolarMpptV1 { mppt_ina, .. } => {
|
||||
let _ = mppt_ina
|
||||
.set_configuration(Configuration {
|
||||
reset: Default::default(),
|
||||
bus_voltage_range: Default::default(),
|
||||
shunt_voltage_range: Default::default(),
|
||||
bus_resolution: Default::default(),
|
||||
shunt_resolution: Default::default(),
|
||||
operating_mode: OperatingMode::PowerDown,
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::info!(
|
||||
"Error setting ina mppt configuration during deep sleep preparation{:?}",
|
||||
e
|
||||
);
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> FatResult<()> {
|
||||
match self {
|
||||
Self::SolarMpptV1 {
|
||||
charge_indicator, ..
|
||||
} => {
|
||||
charge_indicator.set_level(charging.into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_day(&self) -> bool {
|
||||
match self {
|
||||
Charger::SolarMpptV1 { solar_is_day, .. } => solar_is_day.is_high(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct V4<'a> {
|
||||
esp: Esp<'a>,
|
||||
tank_sensor: TankSensor<'a>,
|
||||
charger: Charger<'a>,
|
||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
config: PlantControllerConfig,
|
||||
|
||||
awake: Output<'a>,
|
||||
light: Output<'a>,
|
||||
general_fault: Output<'a>,
|
||||
pump_expander: Pca9535Immediate<I2cDevice<'a, CriticalSectionRawMutex, I2c<'static, Blocking>>>,
|
||||
pump_ina: Option<
|
||||
SyncIna219<I2cDevice<'a, CriticalSectionRawMutex, I2c<'static, Blocking>>, UnCalibrated>,
|
||||
>,
|
||||
sensor: SensorImpl,
|
||||
extra1: Output<'a>,
|
||||
extra2: Output<'a>,
|
||||
}
|
||||
|
||||
struct InputOutput<'a> {
|
||||
pin: Flex<'a>,
|
||||
}
|
||||
|
||||
pub(crate) async fn create_v4(
|
||||
peripherals: FreePeripherals<'static>,
|
||||
esp: Esp<'static>,
|
||||
config: PlantControllerConfig,
|
||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||
) -> anyhow::Result<Box<dyn BoardInteraction + Send + '_>> {
|
||||
let mut awake = PinDriver::output(peripherals.gpio15.downgrade())?;
|
||||
awake.set_high()?;
|
||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||
) -> Result<Box<dyn BoardInteraction<'static> + Send + 'static>, FatError> {
|
||||
log::info!("Start v4");
|
||||
let mut awake = Output::new(peripherals.gpio21, Level::High, OutputConfig::default());
|
||||
awake.set_high();
|
||||
|
||||
let mut general_fault = PinDriver::input_output(peripherals.gpio6.downgrade())?;
|
||||
general_fault.set_pull(Pull::Floating)?;
|
||||
general_fault.set_low()?;
|
||||
let mut general_fault = Output::new(peripherals.gpio23, Level::Low, OutputConfig::default());
|
||||
general_fault.set_low();
|
||||
|
||||
println!("Init rtc driver");
|
||||
let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
|
||||
let extra1 = Output::new(peripherals.gpio6, Level::Low, OutputConfig::default());
|
||||
let extra2 = Output::new(peripherals.gpio15, Level::Low, OutputConfig::default());
|
||||
|
||||
println!("Init rtc eeprom driver");
|
||||
let mut eeprom = {
|
||||
Eeprom24x::new_24x32(
|
||||
MutexDevice::new(&I2C_DRIVER),
|
||||
SlaveAddr::Alternative(true, true, true),
|
||||
)
|
||||
};
|
||||
let one_wire_pin = Flex::new(peripherals.gpio18);
|
||||
let tank_power_pin = Output::new(peripherals.gpio11, Level::Low, OutputConfig::default());
|
||||
let flow_sensor_pin = Input::new(
|
||||
peripherals.gpio4,
|
||||
InputConfig::default().with_pull(Pull::Up),
|
||||
);
|
||||
|
||||
let mut one_wire_pin = PinDriver::input_output_od(peripherals.gpio18.downgrade())?;
|
||||
one_wire_pin.set_pull(Pull::Floating)?;
|
||||
|
||||
let one_wire_bus = OneWire::new(one_wire_pin)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
|
||||
let rtc_time = rtc.datetime();
|
||||
match rtc_time {
|
||||
OkStd(tt) => {
|
||||
println!("Rtc Module reports time at UTC {}", tt);
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Rtc Module could not be read {:?}", err);
|
||||
}
|
||||
}
|
||||
match eeprom.read_byte(0) {
|
||||
OkStd(byte) => {
|
||||
println!("Read first byte with status {}", byte);
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Eeprom could not read first byte {:?}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let mut signal_counter = PcntDriver::new(
|
||||
peripherals.pcnt0,
|
||||
Some(peripherals.gpio22),
|
||||
Option::<AnyInputPin>::None,
|
||||
Option::<AnyInputPin>::None,
|
||||
Option::<AnyInputPin>::None,
|
||||
let tank_sensor = TankSensor::create(
|
||||
one_wire_pin,
|
||||
peripherals.adc1,
|
||||
peripherals.gpio5,
|
||||
tank_power_pin,
|
||||
flow_sensor_pin,
|
||||
peripherals.pcnt1,
|
||||
)?;
|
||||
|
||||
signal_counter.channel_config(
|
||||
PcntChannel::Channel0,
|
||||
PinIndex::Pin0,
|
||||
PinIndex::Pin1,
|
||||
&PcntChannelConfig {
|
||||
lctrl_mode: PcntControlMode::Keep,
|
||||
hctrl_mode: PcntControlMode::Keep,
|
||||
pos_mode: PcntCountMode::Increment,
|
||||
neg_mode: PcntCountMode::Hold,
|
||||
counter_h_lim: i16::MAX,
|
||||
counter_l_lim: 0,
|
||||
},
|
||||
)?;
|
||||
let sensor_expander_device = I2cDevice::new(I2C_DRIVER.get().await);
|
||||
let mut sensor_expander = Pca9535Immediate::new(sensor_expander_device, 34);
|
||||
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
|
||||
Ok(_) => {
|
||||
log::info!("SensorExpander answered");
|
||||
//pulse counter version
|
||||
// let mut signal_counter = PcntDriver::new(
|
||||
// peripherals.pcnt0,
|
||||
// Some(peripherals.gpio22),
|
||||
// Option::<AnyInputPin>::None,
|
||||
// Option::<AnyInputPin>::None,
|
||||
// Option::<AnyInputPin>::None,
|
||||
// )?;
|
||||
//
|
||||
// signal_counter.channel_config(
|
||||
// PcntChannel::Channel0,
|
||||
// PinIndex::Pin0,
|
||||
// PinIndex::Pin1,
|
||||
// &PcntChannelConfig {
|
||||
// lctrl_mode: PcntControlMode::Keep,
|
||||
// hctrl_mode: PcntControlMode::Keep,
|
||||
// pos_mode: PcntCountMode::Increment,
|
||||
// neg_mode: PcntCountMode::Hold,
|
||||
// counter_h_lim: i16::MAX,
|
||||
// counter_l_lim: 0,
|
||||
// },
|
||||
// )?;
|
||||
|
||||
let adc_config = AdcChannelConfig {
|
||||
attenuation: attenuation::DB_11,
|
||||
resolution: Resolution::Resolution12Bit,
|
||||
calibration: esp_idf_hal::adc::oneshot::config::Calibration::Curve,
|
||||
for pin in 0..8 {
|
||||
let _ = sensor_expander.pin_into_output(GPIOBank::Bank0, pin);
|
||||
let _ = sensor_expander.pin_into_output(GPIOBank::Bank1, pin);
|
||||
let _ = sensor_expander.pin_set_low(GPIOBank::Bank0, pin);
|
||||
let _ = sensor_expander.pin_set_low(GPIOBank::Bank1, pin);
|
||||
}
|
||||
|
||||
SensorImpl::PulseCounter {
|
||||
// signal_counter,
|
||||
sensor_expander,
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
log::info!("Can bus mode ");
|
||||
let twai_config = twai::TwaiConfiguration::new(
|
||||
peripherals.twai,
|
||||
peripherals.gpio0,
|
||||
peripherals.gpio2,
|
||||
TWAI_BAUDRATE,
|
||||
TwaiMode::Normal,
|
||||
);
|
||||
|
||||
let mut twai = twai_config.start();
|
||||
let frame = EspTwaiFrame::new(StandardId::ZERO, &[1, 2, 3]).unwrap();
|
||||
|
||||
twai.transmit(&frame).unwrap();
|
||||
|
||||
// let frame = twai.receive().unwrap();
|
||||
println!("Received a frame: {frame:?}");
|
||||
//can bus version
|
||||
SensorImpl::CanBus { twai }
|
||||
}
|
||||
};
|
||||
let tank_driver = AdcDriver::new(peripherals.adc1)?;
|
||||
let tank_channel: AdcChannelDriver<Gpio5, AdcDriver<esp_idf_hal::adc::ADC1>> =
|
||||
AdcChannelDriver::new(tank_driver, peripherals.gpio5, &adc_config)?;
|
||||
|
||||
let mut solar_is_day = PinDriver::input(peripherals.gpio7.downgrade())?;
|
||||
solar_is_day.set_pull(Pull::Floating)?;
|
||||
let solar_is_day = Input::new(peripherals.gpio7, InputConfig::default());
|
||||
let light = Output::new(peripherals.gpio10, Level::Low, Default::default());
|
||||
let charge_indicator = Output::new(peripherals.gpio3, Level::Low, Default::default());
|
||||
|
||||
let mut light = PinDriver::input_output(peripherals.gpio10.downgrade())?;
|
||||
light.set_pull(Pull::Floating)?;
|
||||
|
||||
let mut tank_power = PinDriver::input_output(peripherals.gpio11.downgrade())?;
|
||||
tank_power.set_pull(Pull::Floating)?;
|
||||
|
||||
let mut charge_indicator = PinDriver::input_output(peripherals.gpio3.downgrade())?;
|
||||
charge_indicator.set_pull(Pull::Floating)?;
|
||||
charge_indicator.set_low()?;
|
||||
|
||||
let mut pump_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 32);
|
||||
|
||||
//todo error handing if init error
|
||||
let pump_device = I2cDevice::new(I2C_DRIVER.get().await);
|
||||
let mut pump_expander = Pca9535Immediate::new(pump_device, 32);
|
||||
for pin in 0..8 {
|
||||
let _ = pump_expander.pin_into_output(GPIOBank::Bank0, pin);
|
||||
let _ = pump_expander.pin_into_output(GPIOBank::Bank1, pin);
|
||||
@@ -165,52 +249,82 @@ pub(crate) fn create_v4(
|
||||
let _ = pump_expander.pin_set_low(GPIOBank::Bank1, pin);
|
||||
}
|
||||
|
||||
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
|
||||
for pin in 0..8 {
|
||||
let _ = sensor_expander.pin_into_output(GPIOBank::Bank0, pin);
|
||||
let _ = sensor_expander.pin_into_output(GPIOBank::Bank1, pin);
|
||||
let _ = sensor_expander.pin_set_low(GPIOBank::Bank0, pin);
|
||||
let _ = sensor_expander.pin_set_low(GPIOBank::Bank1, pin);
|
||||
}
|
||||
let mppt_current = I2cDevice::new(I2C_DRIVER.get().await);
|
||||
let mppt_ina = match SyncIna219::new(mppt_current, Address::from_pins(Pin::Vcc, Pin::Gnd)) {
|
||||
Ok(mut ina) => {
|
||||
// Prefer higher averaging for more stable readings
|
||||
let _ = ina.set_configuration(Configuration {
|
||||
reset: Default::default(),
|
||||
bus_voltage_range: Default::default(),
|
||||
shunt_voltage_range: Default::default(),
|
||||
bus_resolution: Default::default(),
|
||||
shunt_resolution: Resolution::Avg128,
|
||||
operating_mode: Default::default(),
|
||||
});
|
||||
Some(ina)
|
||||
}
|
||||
Err(err) => {
|
||||
log::info!("Error creating mppt ina: {:?}", err);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let mut mppt_ina = SyncIna219::new(MutexDevice::new(&I2C_DRIVER), Address::from_byte(68)?)?;
|
||||
esp.delay.delay_ms(
|
||||
mppt_ina
|
||||
.configuration()?
|
||||
.conversion_time()
|
||||
.unwrap()
|
||||
.as_millis() as u32,
|
||||
);
|
||||
println!("Bus Voltage: {}", mppt_ina.bus_voltage()?);
|
||||
println!("Shunt Voltage: {}", mppt_ina.shunt_voltage()?);
|
||||
let volt = (mppt_ina.shunt_voltage()?.shunt_voltage_mv()) as f32 / 1000_f32;
|
||||
let current = volt / 0.05;
|
||||
println!("Shunt Current: {}", current);
|
||||
let pump_current_dev = I2cDevice::new(I2C_DRIVER.get().await);
|
||||
let pump_ina = match SyncIna219::new(pump_current_dev, Address::from_pins(Pin::Gnd, Pin::Sda)) {
|
||||
Ok(ina) => Some(ina),
|
||||
Err(err) => {
|
||||
log::info!("Error creating pump ina: {:?}", err);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let charger = match mppt_ina {
|
||||
Some(mut mppt_ina) => {
|
||||
mppt_ina.set_configuration(Configuration {
|
||||
reset: Default::default(),
|
||||
bus_voltage_range: Default::default(),
|
||||
shunt_voltage_range: Default::default(),
|
||||
bus_resolution: Default::default(),
|
||||
shunt_resolution: ina219::configuration::Resolution::Avg128,
|
||||
operating_mode: Default::default(),
|
||||
})?;
|
||||
|
||||
Charger::SolarMpptV1 {
|
||||
mppt_ina,
|
||||
solar_is_day,
|
||||
charge_indicator,
|
||||
}
|
||||
}
|
||||
None => Charger::ErrorInit {},
|
||||
};
|
||||
|
||||
let v = V4 {
|
||||
mppt_ina,
|
||||
rtc_module,
|
||||
esp,
|
||||
awake,
|
||||
tank_channel,
|
||||
solar_is_day,
|
||||
signal_counter,
|
||||
tank_sensor,
|
||||
light,
|
||||
tank_power,
|
||||
one_wire_bus,
|
||||
rtc,
|
||||
eeprom,
|
||||
general_fault,
|
||||
//pump_ina,
|
||||
pump_expander,
|
||||
sensor_expander,
|
||||
charge_indicator,
|
||||
config,
|
||||
battery_monitor,
|
||||
pump_ina,
|
||||
charger,
|
||||
extra1,
|
||||
extra2,
|
||||
sensor,
|
||||
};
|
||||
Ok(Box::new(v))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<'a> BoardInteraction<'a> for V4<'a> {
|
||||
fn get_esp(&mut self) -> &mut ESP<'a> {
|
||||
fn get_tank_sensor(&mut self) -> Result<&mut TankSensor<'a>, FatError> {
|
||||
Ok(&mut self.tank_sensor)
|
||||
}
|
||||
|
||||
fn get_esp(&mut self) -> &mut Esp<'a> {
|
||||
&mut self.esp
|
||||
}
|
||||
|
||||
@@ -222,350 +336,134 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
|
||||
&mut self.battery_monitor
|
||||
}
|
||||
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> anyhow::Result<()> {
|
||||
self.charge_indicator
|
||||
.set_state(charging.into())
|
||||
.expect("cannot fail");
|
||||
Ok(())
|
||||
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
|
||||
&mut self.rtc_module
|
||||
}
|
||||
|
||||
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
||||
self.awake.set_low().unwrap();
|
||||
deep_sleep(duration_in_ms);
|
||||
fn set_charge_indicator(&mut self, charging: bool) -> Result<(), FatError> {
|
||||
self.charger.set_charge_indicator(charging)
|
||||
}
|
||||
|
||||
fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader> {
|
||||
let store = bincode::serialize(&BackupHeader::default())?.len();
|
||||
let mut header_page_buffer = vec![0_u8; store];
|
||||
|
||||
self.eeprom
|
||||
.read_data(0, &mut header_page_buffer)
|
||||
.map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
|
||||
|
||||
println!("Raw header is {:?} with size {}", header_page_buffer, store);
|
||||
let header: BackupHeader = bincode::deserialize(&header_page_buffer)?;
|
||||
anyhow::Ok(header)
|
||||
}
|
||||
|
||||
fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>> {
|
||||
let store = bincode::serialize(&BackupHeader::default())?.len();
|
||||
let mut header_page_buffer = vec![0_u8; store];
|
||||
|
||||
self.eeprom
|
||||
.read_data(0, &mut header_page_buffer)
|
||||
.map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
|
||||
|
||||
let header: BackupHeader = bincode::deserialize(&header_page_buffer)?;
|
||||
|
||||
//skip page 0, used by the header
|
||||
let data_start_address = self.eeprom.page_size() as u32;
|
||||
let mut data_buffer = vec![0_u8; header.size];
|
||||
self.eeprom
|
||||
.read_data(data_start_address, &mut data_buffer)
|
||||
.map_err(|err| anyhow!("Error reading eeprom data {:?}", err))?;
|
||||
|
||||
let checksum = X25.checksum(&data_buffer);
|
||||
if checksum != header.crc16 {
|
||||
bail!(
|
||||
"Invalid checksum, got {} but expected {}",
|
||||
checksum,
|
||||
header.crc16
|
||||
);
|
||||
}
|
||||
|
||||
anyhow::Ok(data_buffer)
|
||||
}
|
||||
|
||||
fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
|
||||
let time = self.get_rtc_time()?.timestamp_millis();
|
||||
|
||||
let delay = Delay::new_default();
|
||||
|
||||
let checksum = X25.checksum(bytes);
|
||||
let page_size = self.eeprom.page_size();
|
||||
|
||||
let header = BackupHeader {
|
||||
crc16: checksum,
|
||||
timestamp: time,
|
||||
size: bytes.len(),
|
||||
};
|
||||
|
||||
let encoded = bincode::serialize(&header)?;
|
||||
if encoded.len() > page_size {
|
||||
bail!(
|
||||
"Size limit reached header is {}, but firest page is only {}",
|
||||
encoded.len(),
|
||||
page_size
|
||||
)
|
||||
}
|
||||
let as_u8: &[u8] = &encoded;
|
||||
|
||||
match self.eeprom.write_page(0, as_u8) {
|
||||
OkStd(_) => {}
|
||||
Err(err) => bail!("Error writing eeprom {:?}", err),
|
||||
};
|
||||
delay.delay_ms(5);
|
||||
|
||||
let to_write = bytes.chunks(page_size);
|
||||
|
||||
let mut lastiter = 0;
|
||||
let mut current_page = 1;
|
||||
for chunk in to_write {
|
||||
let address = current_page * page_size as u32;
|
||||
self.eeprom
|
||||
.write_page(address, chunk)
|
||||
.map_err(|err| anyhow!("Error writing eeprom {:?}", err))?;
|
||||
current_page += 1;
|
||||
|
||||
let iter = (current_page % 8) as usize;
|
||||
if iter != lastiter {
|
||||
for i in 0..PLANT_COUNT {
|
||||
let _ = self.fault(i, iter == i);
|
||||
}
|
||||
lastiter = iter;
|
||||
}
|
||||
|
||||
delay.delay_ms(5);
|
||||
}
|
||||
anyhow::Ok(())
|
||||
async fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
||||
self.awake.set_low();
|
||||
//self.charger.power_save();
|
||||
self.esp.deep_sleep(duration_in_ms).await;
|
||||
}
|
||||
|
||||
fn is_day(&self) -> bool {
|
||||
self.solar_is_day.get_level().into()
|
||||
self.charger.is_day()
|
||||
}
|
||||
|
||||
fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
|
||||
self.one_wire_bus
|
||||
.reset(&mut self.esp.delay)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
let first = self.one_wire_bus.devices(false, &mut self.esp.delay).next();
|
||||
if first.is_none() {
|
||||
bail!("Not found any one wire Ds18b20");
|
||||
}
|
||||
let device_address = first
|
||||
.unwrap()
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
|
||||
let water_temp_sensor = Ds18b20::new::<EspError>(device_address)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
|
||||
water_temp_sensor
|
||||
.start_temp_measurement(&mut self.one_wire_bus, &mut self.esp.delay)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
ds18b20::Resolution::Bits12.delay_for_measurement_time(&mut self.esp.delay);
|
||||
let sensor_data = water_temp_sensor
|
||||
.read_data(&mut self.one_wire_bus, &mut self.esp.delay)
|
||||
.map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
||||
if sensor_data.temperature == 85_f32 {
|
||||
bail!("Ds18b20 dummy temperature returned");
|
||||
}
|
||||
anyhow::Ok(sensor_data.temperature / 10_f32)
|
||||
async fn light(&mut self, enable: bool) -> Result<(), FatError> {
|
||||
// unsafe { gpio_hold_dis(self.light.pin()) };
|
||||
self.light.set_level(enable.into());
|
||||
// unsafe { gpio_hold_en(self.light.pin()) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
|
||||
self.tank_power.set_high()?;
|
||||
//let stabilize
|
||||
self.esp.delay.delay_ms(100);
|
||||
|
||||
let mut store = [0_u16; TANK_MULTI_SAMPLE];
|
||||
for multisample in 0..TANK_MULTI_SAMPLE {
|
||||
let value = self.tank_channel.read()?;
|
||||
store[multisample] = value;
|
||||
}
|
||||
self.tank_power.set_low()?;
|
||||
|
||||
store.sort();
|
||||
let median_mv = store[6] as f32 / 1000_f32;
|
||||
anyhow::Ok(median_mv)
|
||||
}
|
||||
|
||||
fn light(&mut self, enable: bool) -> anyhow::Result<()> {
|
||||
unsafe { gpio_hold_dis(self.light.pin()) };
|
||||
self.light.set_state(enable.into())?;
|
||||
unsafe { gpio_hold_en(self.light.pin()) };
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
fn pump(&mut self, plant: usize, enable: bool) -> anyhow::Result<()> {
|
||||
async fn pump(&mut self, plant: usize, enable: bool) -> FatResult<()> {
|
||||
if enable {
|
||||
self.pump_expander
|
||||
.pin_set_high(GPIOBank::Bank0, plant.try_into()?)?;
|
||||
.pin_set_high(GPIOBank::Bank0, plant as u8)?;
|
||||
} else {
|
||||
self.pump_expander
|
||||
.pin_set_low(GPIOBank::Bank0, plant.try_into()?)?;
|
||||
.pin_set_low(GPIOBank::Bank0, plant as u8)?;
|
||||
}
|
||||
anyhow::Ok(())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fault(&mut self, plant: usize, enable: bool) -> anyhow::Result<()> {
|
||||
async fn pump_current(&mut self, _plant: usize) -> Result<Current, FatError> {
|
||||
// sensor is shared for all pumps, ignore plant id
|
||||
match self.pump_ina.as_mut() {
|
||||
None => {
|
||||
bail!("pump current sensor not available");
|
||||
}
|
||||
Some(pump_ina) => {
|
||||
let v = pump_ina
|
||||
.shunt_voltage()
|
||||
.map_err(|e| FatError::String {
|
||||
error: alloc::format!("{:?}", e),
|
||||
})
|
||||
.map(|v| {
|
||||
let shunt_voltage =
|
||||
Voltage::from_microvolts(v.shunt_voltage_uv().abs() as f64);
|
||||
let shut_value = Resistance::from_ohms(0.05_f64);
|
||||
let current = shunt_voltage.as_volts() / shut_value.as_ohms();
|
||||
Current::from_amperes(current)
|
||||
})?;
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fault(&mut self, plant: usize, enable: bool) -> FatResult<()> {
|
||||
if enable {
|
||||
self.pump_expander
|
||||
.pin_set_high(GPIOBank::Bank1, plant.try_into()?)?
|
||||
.pin_set_high(GPIOBank::Bank1, plant as u8)?;
|
||||
} else {
|
||||
self.pump_expander
|
||||
.pin_set_low(GPIOBank::Bank1, plant.try_into()?)?
|
||||
.pin_set_low(GPIOBank::Bank1, plant as u8)?;
|
||||
}
|
||||
anyhow::Ok(())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
|
||||
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
||||
for repeat in 0..REPEAT_MOIST_MEASURE {
|
||||
self.signal_counter.counter_pause()?;
|
||||
self.signal_counter.counter_clear()?;
|
||||
|
||||
//Disable all
|
||||
self.sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||
|
||||
let sensor_channel = match sensor {
|
||||
Sensor::A => plant as u32,
|
||||
Sensor::B => (15 - plant) as u32,
|
||||
};
|
||||
|
||||
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
|
||||
if is_bit_set(0) {
|
||||
self.sensor_expander.pin_set_high(GPIOBank::Bank0, MS0)?;
|
||||
} else {
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
||||
}
|
||||
if is_bit_set(1) {
|
||||
self.sensor_expander.pin_set_high(GPIOBank::Bank0, MS1)?;
|
||||
} else {
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
||||
}
|
||||
if is_bit_set(2) {
|
||||
self.sensor_expander.pin_set_high(GPIOBank::Bank0, MS2)?;
|
||||
} else {
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
||||
}
|
||||
if is_bit_set(3) {
|
||||
self.sensor_expander.pin_set_high(GPIOBank::Bank0, MS3)?;
|
||||
} else {
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
|
||||
}
|
||||
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
|
||||
self.sensor_expander
|
||||
.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
|
||||
|
||||
let delay = Delay::new_default();
|
||||
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
|
||||
let factor = 1000f32 / measurement as f32;
|
||||
|
||||
//give some time to stabilize
|
||||
delay.delay_ms(10);
|
||||
self.signal_counter.counter_resume()?;
|
||||
delay.delay_ms(measurement);
|
||||
self.signal_counter.counter_pause()?;
|
||||
self.sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||
self.sensor_expander
|
||||
.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
||||
self.sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
|
||||
delay.delay_ms(10);
|
||||
let unscaled = self.signal_counter.get_counter_value()? as i32;
|
||||
let hz = unscaled as f32 * factor;
|
||||
log(
|
||||
LogMessage::RawMeasure,
|
||||
unscaled as u32,
|
||||
hz as u32,
|
||||
&plant.to_string(),
|
||||
&format!("{sensor:?}"),
|
||||
);
|
||||
results[repeat] = hz;
|
||||
}
|
||||
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
|
||||
|
||||
let mid = results.len() / 2;
|
||||
let median = results[mid];
|
||||
anyhow::Ok(median)
|
||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32, FatError> {
|
||||
self.sensor.measure_moisture_hz(plant, sensor).await
|
||||
}
|
||||
|
||||
fn general_fault(&mut self, enable: bool) {
|
||||
unsafe { gpio_hold_dis(self.general_fault.pin()) };
|
||||
self.general_fault.set_state(enable.into()).unwrap();
|
||||
unsafe { gpio_hold_en(self.general_fault.pin()) };
|
||||
async fn general_fault(&mut self, enable: bool) {
|
||||
//FIXME unsafe { gpio_hold_dis(self.general_fault.pin()) };
|
||||
self.general_fault.set_level(enable.into());
|
||||
//FIXME unsafe { gpio_hold_en(self.general_fault.pin()) };
|
||||
}
|
||||
|
||||
fn factory_reset(&mut self) -> anyhow::Result<()> {
|
||||
println!("factory resetting");
|
||||
self.esp.delete_config()?;
|
||||
//destroy backup header
|
||||
let dummy: [u8; 0] = [];
|
||||
self.backup_config(&dummy)?;
|
||||
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>> {
|
||||
match self.rtc.datetime() {
|
||||
OkStd(rtc_time) => anyhow::Ok(rtc_time.and_utc()),
|
||||
Err(err) => {
|
||||
bail!("Error getting rtc time {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()> {
|
||||
let naive_time = time.naive_utc();
|
||||
match self.rtc.set_datetime(&naive_time) {
|
||||
OkStd(_) => anyhow::Ok(()),
|
||||
Err(err) => {
|
||||
bail!("Error getting rtc time {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn test_pump(&mut self, plant: usize) -> anyhow::Result<()> {
|
||||
self.pump(plant, true)?;
|
||||
self.esp.delay.delay_ms(30000);
|
||||
self.pump(plant, false)?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
fn test(&mut self) -> anyhow::Result<()> {
|
||||
self.general_fault(true);
|
||||
self.esp.delay.delay_ms(100);
|
||||
self.general_fault(false);
|
||||
self.esp.delay.delay_ms(500);
|
||||
self.light(true)?;
|
||||
self.esp.delay.delay_ms(500);
|
||||
self.light(false)?;
|
||||
self.esp.delay.delay_ms(500);
|
||||
async fn test(&mut self) -> Result<(), FatError> {
|
||||
self.general_fault(true).await;
|
||||
Timer::after_millis(100).await;
|
||||
self.general_fault(false).await;
|
||||
Timer::after_millis(500).await;
|
||||
self.light(true).await?;
|
||||
Timer::after_millis(500).await;
|
||||
self.light(false).await?;
|
||||
Timer::after_millis(500).await;
|
||||
for i in 0..PLANT_COUNT {
|
||||
self.fault(i, true)?;
|
||||
self.esp.delay.delay_ms(500);
|
||||
self.fault(i, false)?;
|
||||
self.esp.delay.delay_ms(500);
|
||||
self.fault(i, true).await?;
|
||||
Timer::after_millis(500).await;
|
||||
self.fault(i, false).await?;
|
||||
Timer::after_millis(500).await;
|
||||
}
|
||||
for i in 0..PLANT_COUNT {
|
||||
self.pump(i, true)?;
|
||||
self.esp.delay.delay_ms(100);
|
||||
self.pump(i, false)?;
|
||||
self.esp.delay.delay_ms(100);
|
||||
}
|
||||
for plant in 0..PLANT_COUNT {
|
||||
let a = self.measure_moisture_hz(plant, Sensor::A);
|
||||
let b = self.measure_moisture_hz(plant, Sensor::B);
|
||||
let aa = match a {
|
||||
OkStd(a) => a as u32,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
let bb = match b {
|
||||
OkStd(b) => b as u32,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
log(LogMessage::TestSensor, aa, bb, &plant.to_string(), "");
|
||||
}
|
||||
self.esp.delay.delay_ms(10);
|
||||
anyhow::Ok(())
|
||||
for i in 0..PLANT_COUNT {
|
||||
self.pump(i, true).await?;
|
||||
Timer::after_millis(100).await;
|
||||
self.pump(i, false).await?;
|
||||
Timer::after_millis(100).await;
|
||||
}
|
||||
for plant in 0..PLANT_COUNT {
|
||||
let a = self.measure_moisture_hz(plant, Sensor::A).await;
|
||||
let b = self.measure_moisture_hz(plant, Sensor::B).await;
|
||||
let aa = match a {
|
||||
Ok(a) => a as u32,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
let bb = match b {
|
||||
Ok(b) => b as u32,
|
||||
Err(_) => u32::MAX,
|
||||
};
|
||||
LOG_ACCESS.lock().await.log(LogMessage::TestSensor, aa, bb, &plant.to_string(), "").await;
|
||||
}
|
||||
Timer::after_millis(10).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_config(&mut self, config: PlantControllerConfig) -> anyhow::Result<()> {
|
||||
fn set_config(&mut self, config: PlantControllerConfig) {
|
||||
self.config = config;
|
||||
self.esp.save_config(&self.config)?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
async fn get_mptt_voltage(&mut self) -> Result<Voltage, FatError> {
|
||||
self.charger.get_mptt_voltage()
|
||||
}
|
||||
|
||||
async fn get_mptt_current(&mut self) -> Result<Current, FatError> {
|
||||
self.charger.get_mppt_current()
|
||||
}
|
||||
}
|
||||
|
129
rust/src/hal/v4_sensor.rs
Normal file
129
rust/src/hal/v4_sensor.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use crate::hal::Box;
|
||||
use crate::hal::Sensor;
|
||||
use crate::log::{LogMessage, LOG_ACCESS};
|
||||
use crate::fat_error::{FatError, FatResult};
|
||||
use alloc::format;
|
||||
use alloc::string::ToString;
|
||||
use async_trait::async_trait;
|
||||
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_time::Timer;
|
||||
use esp_hal::i2c::master::I2c;
|
||||
use esp_hal::twai::Twai;
|
||||
use esp_hal::Blocking;
|
||||
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
||||
|
||||
const REPEAT_MOIST_MEASURE: usize = 10;
|
||||
|
||||
#[async_trait]
|
||||
pub trait SensorInteraction {
|
||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> FatResult<f32>;
|
||||
}
|
||||
|
||||
const MS0: u8 = 1_u8;
|
||||
const MS1: u8 = 0_u8;
|
||||
const MS2: u8 = 3_u8;
|
||||
const MS3: u8 = 4_u8;
|
||||
const MS4: u8 = 2_u8;
|
||||
const SENSOR_ON: u8 = 5_u8;
|
||||
|
||||
pub enum SensorImpl {
|
||||
PulseCounter {
|
||||
//signal_counter: PcntDriver<'a>,
|
||||
sensor_expander:
|
||||
Pca9535Immediate<I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>>,
|
||||
},
|
||||
CanBus {
|
||||
twai: Twai<'static, Blocking>,
|
||||
},
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SensorInteraction for SensorImpl {
|
||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> FatResult<f32> {
|
||||
match self {
|
||||
SensorImpl::PulseCounter {
|
||||
//signal_counter,
|
||||
sensor_expander,
|
||||
..
|
||||
} => {
|
||||
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
||||
for repeat in 0..REPEAT_MOIST_MEASURE {
|
||||
//signal_counter.counter_pause()?;
|
||||
//signal_counter.counter_clear()?;
|
||||
|
||||
//Disable all
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||
|
||||
let sensor_channel = match sensor {
|
||||
Sensor::A => plant as u32,
|
||||
Sensor::B => (15 - plant) as u32,
|
||||
};
|
||||
|
||||
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
|
||||
if is_bit_set(0) {
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS0)?;
|
||||
} else {
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
||||
}
|
||||
if is_bit_set(1) {
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS1)?;
|
||||
} else {
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
||||
}
|
||||
if is_bit_set(2) {
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS2)?;
|
||||
} else {
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
||||
}
|
||||
if is_bit_set(3) {
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS3)?;
|
||||
} else {
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
|
||||
}
|
||||
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
|
||||
|
||||
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
|
||||
let factor = 1000f32 / measurement as f32;
|
||||
|
||||
//give some time to stabilize
|
||||
Timer::after_millis(10).await;
|
||||
//signal_counter.counter_resume()?;
|
||||
Timer::after_millis(measurement).await;
|
||||
//signal_counter.counter_pause()?;
|
||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
|
||||
Timer::after_millis(10).await;
|
||||
let unscaled = 1337; //signal_counter.get_counter_value()? as i32;
|
||||
let hz = unscaled as f32 * factor;
|
||||
LOG_ACCESS
|
||||
.lock()
|
||||
.await
|
||||
.log(
|
||||
LogMessage::RawMeasure,
|
||||
unscaled as u32,
|
||||
hz as u32,
|
||||
&plant.to_string(),
|
||||
&format!("{sensor:?}"),
|
||||
)
|
||||
.await;
|
||||
results[repeat] = hz;
|
||||
}
|
||||
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
|
||||
|
||||
let mid = results.len() / 2;
|
||||
let median = results[mid];
|
||||
Ok(median)
|
||||
}
|
||||
SensorImpl::CanBus { twai } => {
|
||||
Err(FatError::String {error: "Not yet implemented".to_string()})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
171
rust/src/hal/water.rs
Normal file
171
rust/src/hal/water.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
use crate::bail;
|
||||
use crate::hal::{ADC1, TANK_MULTI_SAMPLE};
|
||||
use crate::fat_error::FatError;
|
||||
use embassy_time::Timer;
|
||||
use esp_hal::analog::adc::{Adc, AdcConfig, AdcPin, Attenuation};
|
||||
use esp_hal::delay::Delay;
|
||||
use esp_hal::gpio::{Flex, Input, Output, OutputConfig, Pull};
|
||||
use esp_hal::pcnt::unit::Unit;
|
||||
use esp_hal::peripherals::GPIO5;
|
||||
use esp_hal::Blocking;
|
||||
use esp_println::println;
|
||||
use littlefs2::object_safe::DynStorage;
|
||||
use onewire::{ds18b20, Device, DeviceSearch, OneWire, DS18B20};
|
||||
|
||||
pub struct TankSensor<'a> {
|
||||
one_wire_bus: OneWire<Flex<'a>>,
|
||||
tank_channel: Adc<'a, ADC1<'a>, Blocking>,
|
||||
tank_power: Output<'a>,
|
||||
tank_pin: AdcPin<GPIO5<'a>, ADC1<'a>>,
|
||||
// flow_counter: PcntDriver<'a>,
|
||||
// delay: Delay,
|
||||
}
|
||||
|
||||
impl<'a> TankSensor<'a> {
|
||||
pub(crate) fn create(
|
||||
mut one_wire_pin: Flex<'a>,
|
||||
adc1: ADC1<'a>,
|
||||
gpio5: GPIO5<'a>,
|
||||
tank_power: Output<'a>,
|
||||
flow_sensor: Input,
|
||||
pcnt1: Unit<'a, 1>,
|
||||
) -> Result<TankSensor<'a>, FatError> {
|
||||
one_wire_pin.apply_output_config(&OutputConfig::default().with_pull(Pull::None));
|
||||
|
||||
let mut adc1_config = AdcConfig::new();
|
||||
let tank_pin = adc1_config.enable_pin(gpio5, Attenuation::_11dB);
|
||||
let mut tank_channel = Adc::new(adc1, adc1_config);
|
||||
|
||||
let one_wire_bus = OneWire::new(one_wire_pin, false);
|
||||
|
||||
//
|
||||
// let mut flow_counter = PcntDriver::new(
|
||||
// pcnt1,
|
||||
// Some(flow_sensor_pin),
|
||||
// Option::<AnyInputPin>::None,
|
||||
// Option::<AnyInputPin>::None,
|
||||
// Option::<AnyInputPin>::None,
|
||||
// )?;
|
||||
//
|
||||
// flow_counter.channel_config(
|
||||
// PcntChannel::Channel1,
|
||||
// PinIndex::Pin0,
|
||||
// PinIndex::Pin1,
|
||||
// &PcntChannelConfig {
|
||||
// lctrl_mode: PcntControlMode::Keep,
|
||||
// hctrl_mode: PcntControlMode::Keep,
|
||||
// pos_mode: PcntCountMode::Increment,
|
||||
// neg_mode: PcntCountMode::Hold,
|
||||
// counter_h_lim: i16::MAX,
|
||||
// counter_l_lim: 0,
|
||||
// },
|
||||
// )?;
|
||||
//
|
||||
Ok(TankSensor {
|
||||
one_wire_bus,
|
||||
tank_channel,
|
||||
tank_power,
|
||||
tank_pin, // flow_counter,
|
||||
// delay: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn reset_flow_meter(&mut self) {
|
||||
// self.flow_counter.counter_pause().unwrap();
|
||||
// self.flow_counter.counter_clear().unwrap();
|
||||
}
|
||||
|
||||
pub fn start_flow_meter(&mut self) {
|
||||
//self.flow_counter.counter_resume().unwrap();
|
||||
}
|
||||
|
||||
pub fn get_flow_meter_value(&mut self) -> i16 {
|
||||
//self.flow_counter.get_counter_value().unwrap()
|
||||
5_i16
|
||||
}
|
||||
|
||||
pub fn stop_flow_meter(&mut self) -> i16 {
|
||||
//self.flow_counter.counter_pause().unwrap();
|
||||
self.get_flow_meter_value()
|
||||
}
|
||||
|
||||
pub async fn water_temperature_c(&mut self) -> Result<f32, FatError> {
|
||||
//multisample should be moved to water_temperature_c
|
||||
let mut attempt = 1;
|
||||
let mut delay = Delay::new();
|
||||
self.one_wire_bus.reset(&mut delay)?;
|
||||
let mut search = DeviceSearch::new();
|
||||
let mut water_temp_sensor: Option<Device> = None;
|
||||
while let Some(device) = self.one_wire_bus.search_next(&mut search, &mut delay)? {
|
||||
if device.address[0] == ds18b20::FAMILY_CODE {
|
||||
water_temp_sensor = Some(device);
|
||||
break;
|
||||
}
|
||||
}
|
||||
match water_temp_sensor {
|
||||
Some(device) => {
|
||||
println!("Found one wire device: {:?}", device);
|
||||
let mut water_temp_sensor = DS18B20::new(device)?;
|
||||
|
||||
let water_temp: Result<f32, FatError> = loop {
|
||||
let temp = self
|
||||
.single_temperature_c(&mut water_temp_sensor, &mut delay)
|
||||
.await;
|
||||
match &temp {
|
||||
Ok(res) => {
|
||||
println!("Water temp is {}", res);
|
||||
break temp;
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Could not get water temp {} attempt {}", err, attempt)
|
||||
}
|
||||
}
|
||||
if attempt == 5 {
|
||||
break temp;
|
||||
}
|
||||
attempt += 1;
|
||||
};
|
||||
water_temp
|
||||
}
|
||||
None => {
|
||||
bail!("Not found any one wire Ds18b20");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn single_temperature_c(
|
||||
&mut self,
|
||||
sensor: &mut DS18B20,
|
||||
delay: &mut Delay,
|
||||
) -> Result<f32, FatError> {
|
||||
let resolution = sensor.measure_temperature(&mut self.one_wire_bus, delay)?;
|
||||
Timer::after_millis(resolution.time_ms() as u64).await;
|
||||
let temperature = sensor.read_temperature(&mut self.one_wire_bus, delay)? as f32;
|
||||
if temperature == 85_f32 {
|
||||
bail!("Ds18b20 dummy temperature returned");
|
||||
}
|
||||
Ok(temperature / 10_f32)
|
||||
}
|
||||
|
||||
pub async fn tank_sensor_voltage(&mut self) -> Result<f32, FatError> {
|
||||
self.tank_power.set_high();
|
||||
//let stabilize
|
||||
Timer::after_millis(100).await;
|
||||
|
||||
let mut store = [0_u16; TANK_MULTI_SAMPLE];
|
||||
for multisample in 0..TANK_MULTI_SAMPLE {
|
||||
let mut asy = (&mut self.tank_channel);
|
||||
|
||||
let value = asy.read_oneshot(&mut self.tank_pin);
|
||||
//force yield
|
||||
Timer::after_millis(10).await;
|
||||
store[multisample] = value.unwrap();
|
||||
}
|
||||
self.tank_power.set_low();
|
||||
|
||||
store.sort();
|
||||
//TODO probably wrong? check!
|
||||
let median_mv = store[6] as f32 * 3300_f32 / 4096_f32;
|
||||
Ok(median_mv)
|
||||
}
|
||||
}
|
@@ -1,4 +0,0 @@
|
||||
#![allow(dead_code)]
|
||||
extern crate embedded_hal as hal;
|
||||
|
||||
pub mod sipo;
|
@@ -1,42 +1,142 @@
|
||||
use crate::hal::TIME_ACCESS;
|
||||
use crate::vec;
|
||||
use alloc::string::ToString;
|
||||
use alloc::vec::Vec;
|
||||
use bytemuck::{AnyBitPattern, Pod, Zeroable};
|
||||
use deranged::RangedU8;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::Mutex;
|
||||
use esp_hal::Persistable;
|
||||
use log::info;
|
||||
use serde::Serialize;
|
||||
use std::{collections::HashMap, sync::Mutex};
|
||||
use strum::EnumIter;
|
||||
use strum_macros::IntoStaticStr;
|
||||
|
||||
use esp_idf_svc::systime::EspSystemTime;
|
||||
use once_cell::sync::Lazy;
|
||||
use ringbuffer::{ConstGenericRingBuffer, RingBuffer};
|
||||
use text_template::Template;
|
||||
use unit_enum::UnitEnum;
|
||||
|
||||
const LOG_ARRAY_SIZE: u8 = 220;
|
||||
const MAX_LOG_ARRAY_INDEX: u8 = LOG_ARRAY_SIZE - 1;
|
||||
#[esp_hal::ram(rtc_fast, persistent)]
|
||||
static mut LOG_ARRAY: LogArray = LogArray {
|
||||
buffer: [LogEntryInner {
|
||||
timestamp: 0,
|
||||
message_id: 0,
|
||||
a: 0,
|
||||
b: 0,
|
||||
txt_short: [0; TXT_SHORT_LENGTH],
|
||||
txt_long: [0; TXT_LONG_LENGTH],
|
||||
}; LOG_ARRAY_SIZE as usize],
|
||||
head: 0,
|
||||
};
|
||||
pub static LOG_ACCESS: Mutex<CriticalSectionRawMutex, &'static mut LogArray> =
|
||||
unsafe { Mutex::new(&mut *&raw mut LOG_ARRAY) };
|
||||
|
||||
const TXT_SHORT_LENGTH: usize = 8;
|
||||
const TXT_LONG_LENGTH: usize = 32;
|
||||
|
||||
const BUFFER_SIZE: usize = 220;
|
||||
#[derive(Debug, Clone, Copy, AnyBitPattern)]
|
||||
#[repr(C)]
|
||||
pub struct LogArray {
|
||||
buffer: [LogEntryInner; LOG_ARRAY_SIZE as usize],
|
||||
head: u8,
|
||||
}
|
||||
|
||||
#[link_section = ".rtc.data"]
|
||||
static mut BUFFER: ConstGenericRingBuffer<LogEntry, BUFFER_SIZE> =
|
||||
ConstGenericRingBuffer::<LogEntry, BUFFER_SIZE>::new();
|
||||
#[allow(static_mut_refs)]
|
||||
static BUFFER_ACCESS: Lazy<Mutex<&mut ConstGenericRingBuffer<LogEntry, BUFFER_SIZE>>> =
|
||||
Lazy::new(|| unsafe { Mutex::new(&mut BUFFER) });
|
||||
unsafe impl Persistable for LogArray {}
|
||||
unsafe impl Zeroable for LogEntryInner {}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
unsafe impl Pod for LogEntryInner {}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct LogEntryInner {
|
||||
pub timestamp: u64,
|
||||
pub message_id: u16,
|
||||
pub a: u32,
|
||||
pub b: u32,
|
||||
pub txt_short: [u8; TXT_SHORT_LENGTH],
|
||||
pub txt_long: [u8; TXT_LONG_LENGTH],
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct LogEntry {
|
||||
pub timestamp: u64,
|
||||
pub message_id: u16,
|
||||
pub a: u32,
|
||||
pub b: u32,
|
||||
pub txt_short: heapless::String<TXT_SHORT_LENGTH>,
|
||||
pub txt_long: heapless::String<TXT_LONG_LENGTH>,
|
||||
pub txt_short: alloc::string::String,
|
||||
pub txt_long: alloc::string::String,
|
||||
}
|
||||
|
||||
pub fn init() {
|
||||
unsafe {
|
||||
BUFFER = ConstGenericRingBuffer::<LogEntry, BUFFER_SIZE>::new();
|
||||
};
|
||||
let mut access = BUFFER_ACCESS.lock().unwrap();
|
||||
access.drain().for_each(|_| {});
|
||||
impl From<LogEntryInner> for LogEntry {
|
||||
fn from(value: LogEntryInner) -> Self {
|
||||
LogEntry {
|
||||
timestamp: value.timestamp,
|
||||
message_id: value.message_id,
|
||||
a: value.a,
|
||||
b: value.b,
|
||||
txt_short: alloc::string::String::from_utf8_lossy_owned(value.txt_short.to_vec()),
|
||||
txt_long: alloc::string::String::from_utf8_lossy_owned(value.txt_long.to_vec()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogArray {
|
||||
pub fn get(&mut self) -> Vec<LogEntry> {
|
||||
let head: RangedU8<0, MAX_LOG_ARRAY_INDEX> =
|
||||
RangedU8::new(self.head).unwrap_or(RangedU8::new(0).unwrap());
|
||||
|
||||
let mut rv: Vec<LogEntry> = Vec::new();
|
||||
let mut index = head.wrapping_sub(1);
|
||||
for _ in 0..self.buffer.len() {
|
||||
let entry = self.buffer[index.get() as usize];
|
||||
if (entry.message_id as usize) != LogMessage::Empty.ordinal() {
|
||||
rv.push(entry.into());
|
||||
}
|
||||
index = index.wrapping_sub(1);
|
||||
}
|
||||
rv
|
||||
}
|
||||
|
||||
pub async fn log(
|
||||
&mut self,
|
||||
message_key: LogMessage,
|
||||
number_a: u32,
|
||||
number_b: u32,
|
||||
txt_short: &str,
|
||||
txt_long: &str,
|
||||
) {
|
||||
let mut head: RangedU8<0, MAX_LOG_ARRAY_INDEX> =
|
||||
RangedU8::new(self.head).unwrap_or(RangedU8::new(0).unwrap());
|
||||
|
||||
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
|
||||
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
|
||||
|
||||
limit_length(txt_short, &mut txt_short_stack);
|
||||
limit_length(txt_long, &mut txt_long_stack);
|
||||
|
||||
let time = TIME_ACCESS.get().await.current_time_us() / 1000;
|
||||
|
||||
let ordinal = message_key.ordinal() as u16;
|
||||
let template: &str = message_key.into();
|
||||
let mut template_string = template.to_string();
|
||||
template_string = template_string.replace("${number_a}", number_a.to_string().as_str());
|
||||
template_string = template_string.replace("${number_b}", number_b.to_string().as_str());
|
||||
template_string = template_string.replace("${txt_long}", txt_long);
|
||||
template_string = template_string.replace("${txt_short}", txt_short);
|
||||
|
||||
info!("{}", template_string);
|
||||
|
||||
let to_modify = &mut self.buffer[head.get() as usize];
|
||||
to_modify.timestamp = time;
|
||||
to_modify.message_id = ordinal;
|
||||
to_modify.a = number_a;
|
||||
to_modify.b = number_b;
|
||||
to_modify
|
||||
.txt_short
|
||||
.clone_from_slice(&txt_short_stack.as_bytes());
|
||||
to_modify
|
||||
.txt_long
|
||||
.clone_from_slice(&txt_long_stack.as_bytes());
|
||||
head = head.wrapping_add(1);
|
||||
self.head = head.get();
|
||||
}
|
||||
}
|
||||
|
||||
fn limit_length<const LIMIT: usize>(input: &str, target: &mut heapless::String<LIMIT>) {
|
||||
@@ -55,78 +155,15 @@ fn limit_length<const LIMIT: usize>(input: &str, target: &mut heapless::String<L
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_log() -> Vec<LogEntry> {
|
||||
let buffer = BUFFER_ACCESS.lock().unwrap();
|
||||
let mut read_copy = Vec::new();
|
||||
for entry in buffer.iter() {
|
||||
let copy = entry.clone();
|
||||
read_copy.push(copy);
|
||||
}
|
||||
drop(buffer);
|
||||
return read_copy;
|
||||
}
|
||||
|
||||
pub fn log(message_key: LogMessage, number_a: u32, number_b: u32, txt_short: &str, txt_long: &str) {
|
||||
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
|
||||
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
|
||||
|
||||
limit_length(txt_short, &mut txt_short_stack);
|
||||
limit_length(txt_long, &mut txt_long_stack);
|
||||
|
||||
let time = EspSystemTime {}.now().as_millis() as u64;
|
||||
|
||||
let ordinal = message_key.ordinal() as u16;
|
||||
let template_string: &str = message_key.into();
|
||||
|
||||
let mut values: HashMap<&str, &str> = HashMap::new();
|
||||
let number_a_str = number_a.to_string();
|
||||
let number_b_str = number_b.to_string();
|
||||
|
||||
values.insert("number_a", &number_a_str);
|
||||
values.insert("number_b", &number_b_str);
|
||||
values.insert("txt_short", txt_short);
|
||||
values.insert("txt_long", txt_long);
|
||||
|
||||
let template = Template::from(template_string);
|
||||
let serial_entry = template.fill_in(&values);
|
||||
|
||||
println!("{serial_entry}");
|
||||
|
||||
let entry = LogEntry {
|
||||
timestamp: time,
|
||||
message_id: ordinal,
|
||||
a: number_a,
|
||||
b: number_b,
|
||||
txt_short: txt_short_stack,
|
||||
txt_long: txt_long_stack,
|
||||
};
|
||||
|
||||
let mut buffer = BUFFER_ACCESS.lock().unwrap();
|
||||
buffer.push(entry);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn within_limit() {
|
||||
let test = "12345678";
|
||||
|
||||
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
|
||||
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
|
||||
limit_length(test, &mut txt_short_stack);
|
||||
limit_length(test, &mut txt_long_stack);
|
||||
|
||||
assert_eq!(txt_short_stack.as_str(), test);
|
||||
assert_eq!(txt_long_stack.as_str(), test);
|
||||
while target.len() < LIMIT {
|
||||
target.push(' ').unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(IntoStaticStr, EnumIter, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone, UnitEnum)]
|
||||
#[derive(IntoStaticStr, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone, UnitEnum)]
|
||||
pub enum LogMessage {
|
||||
#[strum(serialize = "")]
|
||||
Empty,
|
||||
#[strum(
|
||||
serialize = "Reset due to ${txt_long} requires rtc clear ${number_a} and force config mode ${number_b}"
|
||||
)]
|
||||
@@ -193,6 +230,16 @@ pub enum LogMessage {
|
||||
serialize = "Pumped multiple times, but plant is still to try attempt: ${number_a} limit :: ${number_b} plant: ${txt_short}"
|
||||
)]
|
||||
ConsecutivePumpCountLimit,
|
||||
#[strum(
|
||||
serialize = "Pump Overcurrent error, pump: ${number_a} tripped overcurrent ${number_b} limit was ${txt_short} @s ${txt_long}"
|
||||
)]
|
||||
PumpOverCurrent,
|
||||
#[strum(
|
||||
serialize = "Pump Open loop error, pump: ${number_a} is low, ${number_b} limit was ${txt_short} @s ${txt_long}"
|
||||
)]
|
||||
PumpOpenLoopCurrent,
|
||||
#[strum(serialize = "Pump Open current sensor required but did not work: ${number_a}")]
|
||||
PumpMissingSensorCurrent,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
|
1254
rust/src/main.rs
1254
rust/src/main.rs
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,13 @@
|
||||
use crate::{
|
||||
config::PlantConfig,
|
||||
hal::{Sensor, HAL},
|
||||
in_time_range,
|
||||
};
|
||||
use alloc::string::{String, ToString};
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use chrono_tz::Tz;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::hal::{BoardInteraction, Sensor, HAL};
|
||||
use crate::{config::PlantConfig, in_time_range};
|
||||
|
||||
const MOIST_SENSOR_MAX_FREQUENCY: f32 = 7500.; // 60kHz (500Hz margin)
|
||||
const MOIST_SENSOR_MIN_FREQUENCY: f32 = 150.; // this is really, really dry, think like cactus levels
|
||||
|
||||
@@ -76,6 +79,7 @@ impl PumpState {
|
||||
pub enum PlantWateringMode {
|
||||
OFF,
|
||||
TargetMoisture,
|
||||
MinMoisture,
|
||||
TimerOnly,
|
||||
}
|
||||
|
||||
@@ -112,9 +116,9 @@ fn map_range_moisture(
|
||||
}
|
||||
|
||||
impl PlantState {
|
||||
pub fn read_hardware_state(plant_id: usize, board: &mut HAL) -> Self {
|
||||
pub async fn read_hardware_state(plant_id: usize, board: &mut HAL<'_>) -> Self {
|
||||
let sensor_a = if board.board_hal.get_config().plants[plant_id].sensor_a {
|
||||
match board.board_hal.measure_moisture_hz(plant_id, Sensor::A) {
|
||||
match board.board_hal.measure_moisture_hz(plant_id, Sensor::A).await {
|
||||
Ok(raw) => match map_range_moisture(
|
||||
raw,
|
||||
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
|
||||
@@ -135,7 +139,7 @@ impl PlantState {
|
||||
};
|
||||
|
||||
let sensor_b = if board.board_hal.get_config().plants[plant_id].sensor_b {
|
||||
match board.board_hal.measure_moisture_hz(plant_id, Sensor::B) {
|
||||
match board.board_hal.measure_moisture_hz(plant_id, Sensor::B).await {
|
||||
Ok(raw) => match map_range_moisture(
|
||||
raw,
|
||||
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
|
||||
@@ -233,47 +237,77 @@ impl PlantState {
|
||||
false
|
||||
}
|
||||
}
|
||||
PlantWateringMode::MinMoisture => {
|
||||
let (moisture_percent, _) = self.plant_moisture();
|
||||
if let Some(_moisture_percent) = moisture_percent {
|
||||
if self.pump_in_timeout(plant_conf, current_time) {
|
||||
false
|
||||
} else if !in_time_range(
|
||||
current_time,
|
||||
plant_conf.pump_hour_start,
|
||||
plant_conf.pump_hour_end,
|
||||
) {
|
||||
false
|
||||
} else if true {
|
||||
//if not cooldown min and below max
|
||||
true
|
||||
} else if true {
|
||||
//if below min disable cooldown min
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
PlantWateringMode::TimerOnly => !self.pump_in_timeout(plant_conf, current_time),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_mqtt_info(&self, plant_conf: &PlantConfig, current_time: &DateTime<Tz>) -> PlantInfo {
|
||||
PlantInfo {
|
||||
sensor_a: &self.sensor_a,
|
||||
sensor_b: &self.sensor_b,
|
||||
mode: plant_conf.mode,
|
||||
do_water: self.needs_to_be_watered(plant_conf, current_time),
|
||||
dry: if let Some(moisture_percent) = self.plant_moisture().0 {
|
||||
moisture_percent < plant_conf.target_moisture
|
||||
} else {
|
||||
false
|
||||
},
|
||||
cooldown: self.pump_in_timeout(plant_conf, current_time),
|
||||
out_of_work_hour: in_time_range(
|
||||
current_time,
|
||||
plant_conf.pump_hour_start,
|
||||
plant_conf.pump_hour_end,
|
||||
),
|
||||
consecutive_pump_count: self.pump.consecutive_pump_count,
|
||||
pump_error: self.pump.is_err(plant_conf),
|
||||
last_pump: self
|
||||
.pump
|
||||
.previous_pump
|
||||
.map(|t| t.with_timezone(¤t_time.timezone())),
|
||||
next_pump: if matches!(
|
||||
plant_conf.mode,
|
||||
PlantWateringMode::TimerOnly | PlantWateringMode::TargetMoisture
|
||||
) {
|
||||
self.pump.previous_pump.and_then(|last_pump| {
|
||||
last_pump
|
||||
.checked_add_signed(TimeDelta::minutes(plant_conf.pump_cooldown_min.into()))
|
||||
.map(|t| t.with_timezone(¤t_time.timezone()))
|
||||
})
|
||||
} else {
|
||||
None
|
||||
},
|
||||
}
|
||||
}
|
||||
//
|
||||
// pub fn to_mqtt_info(
|
||||
// &self,
|
||||
// plant_conf: &PlantConfig,
|
||||
// current_time: &DateTime<Tz>,
|
||||
// ) -> PlantInfo<'_> {
|
||||
// PlantInfo {
|
||||
// sensor_a: &self.sensor_a,
|
||||
// sensor_b: &self.sensor_b,
|
||||
// mode: plant_conf.mode,
|
||||
// do_water: self.needs_to_be_watered(plant_conf, current_time),
|
||||
// dry: if let Some(moisture_percent) = self.plant_moisture().0 {
|
||||
// moisture_percent < plant_conf.target_moisture
|
||||
// } else {
|
||||
// false
|
||||
// },
|
||||
// cooldown: self.pump_in_timeout(plant_conf, current_time),
|
||||
// out_of_work_hour: in_time_range(
|
||||
// current_time,
|
||||
// plant_conf.pump_hour_start,
|
||||
// plant_conf.pump_hour_end,
|
||||
// ),
|
||||
// consecutive_pump_count: self.pump.consecutive_pump_count,
|
||||
// pump_error: self.pump.is_err(plant_conf),
|
||||
// last_pump: self
|
||||
// .pump
|
||||
// .previous_pump
|
||||
// .map(|t| t.with_timezone(¤t_time.timezone())),
|
||||
// next_pump: if matches!(
|
||||
// plant_conf.mode,
|
||||
// PlantWateringMode::TimerOnly
|
||||
// | PlantWateringMode::TargetMoisture
|
||||
// | PlantWateringMode::MinMoisture
|
||||
// ) {
|
||||
// self.pump.previous_pump.and_then(|last_pump| {
|
||||
// last_pump
|
||||
// .checked_add_signed(TimeDelta::minutes(plant_conf.pump_cooldown_min.into()))
|
||||
// .map(|t| t.with_timezone(¤t_time.timezone()))
|
||||
// })
|
||||
// } else {
|
||||
// None
|
||||
// },
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize)]
|
||||
@@ -296,8 +330,8 @@ pub struct PlantInfo<'a> {
|
||||
/// how often has the pump been watered without reaching target moisture
|
||||
consecutive_pump_count: u32,
|
||||
pump_error: Option<PumpError>,
|
||||
/// last time when the pump was active
|
||||
last_pump: Option<DateTime<Tz>>,
|
||||
/// next time when pump should activate
|
||||
next_pump: Option<DateTime<Tz>>,
|
||||
// /// last time when the pump was active
|
||||
// last_pump: Option<DateTime<Tz>>,
|
||||
// /// next time when pump should activate
|
||||
// next_pump: Option<DateTime<Tz>>,
|
||||
}
|
||||
|
@@ -1,10 +1,11 @@
|
||||
//! Serial-in parallel-out shift register
|
||||
|
||||
use core::cell::RefCell;
|
||||
use core::convert::Infallible;
|
||||
use core::iter::Iterator;
|
||||
use core::mem::{self, MaybeUninit};
|
||||
use std::convert::Infallible;
|
||||
|
||||
use hal::digital::OutputPin;
|
||||
use core::result::{Result, Result::Ok};
|
||||
use embedded_hal::digital::OutputPin;
|
||||
|
||||
trait ShiftRegisterInternal {
|
||||
fn update(&self, index: usize, command: bool) -> Result<(), ()>;
|
||||
@@ -100,7 +101,7 @@ macro_rules! ShiftRegisterBuilder {
|
||||
}
|
||||
|
||||
/// Get embedded-hal output pins to control the shift register outputs
|
||||
pub fn decompose(&self) -> [ShiftRegisterPin; $size] {
|
||||
pub fn decompose(&self) -> [ShiftRegisterPin<'_>; $size] {
|
||||
// Create an uninitialized array of `MaybeUninit`. The `assume_init` is
|
||||
// safe because the type we are claiming to have initialized here is a
|
||||
// bunch of `MaybeUninit`s, which do not require initialization.
|
||||
|
@@ -1,7 +1,10 @@
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::alloc::string::{String, ToString};
|
||||
use crate::config::TankConfig;
|
||||
use crate::hal::{BoardInteraction, HAL};
|
||||
use crate::hal::HAL;
|
||||
use crate::fat_error::FatResult;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::MutexGuard;
|
||||
use serde::Serialize;
|
||||
|
||||
const OPEN_TANK_VOLTAGE: f32 = 3.0;
|
||||
pub const WATER_FROZEN_THRESH: f32 = 4.0;
|
||||
@@ -114,7 +117,7 @@ impl TankState {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_mqtt_info(&self, config: &TankConfig, water_temp: &anyhow::Result<f32>) -> TankInfo {
|
||||
pub fn as_mqtt_info(&self, config: &TankConfig, water_temp: &FatResult<f32>) -> TankInfo {
|
||||
let mut tank_err: Option<TankError> = None;
|
||||
let left_ml = match self.left_ml(config) {
|
||||
Err(err) => {
|
||||
@@ -151,10 +154,16 @@ impl TankState {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn determine_tank_state(board: &mut std::sync::MutexGuard<'_, HAL<'_>>) -> TankState {
|
||||
pub async fn determine_tank_state(
|
||||
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
||||
) -> TankState {
|
||||
if board.board_hal.get_config().tank.tank_sensor_enabled {
|
||||
match board.board_hal.tank_sensor_voltage() {
|
||||
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv),
|
||||
match board
|
||||
.board_hal
|
||||
.get_tank_sensor()
|
||||
.and_then(|f| core::prelude::v1::Ok(f.tank_sensor_voltage()))
|
||||
{
|
||||
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()),
|
||||
Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
|
||||
}
|
||||
} else {
|
||||
@@ -166,20 +175,20 @@ pub fn determine_tank_state(board: &mut std::sync::MutexGuard<'_, HAL<'_>>) -> T
|
||||
/// Information structure send to mqtt for monitoring purposes
|
||||
pub struct TankInfo {
|
||||
/// there is enough water in the tank
|
||||
enough_water: bool,
|
||||
pub(crate) enough_water: bool,
|
||||
/// warning that water needs to be refilled soon
|
||||
warn_level: bool,
|
||||
pub(crate) warn_level: bool,
|
||||
/// estimation how many ml are still in the tank
|
||||
left_ml: Option<f32>,
|
||||
pub(crate) left_ml: Option<f32>,
|
||||
/// if there is an issue with the water level sensor
|
||||
sensor_error: Option<TankError>,
|
||||
pub(crate) sensor_error: Option<TankError>,
|
||||
/// raw water sensor value
|
||||
raw: Option<f32>,
|
||||
pub(crate) raw: Option<f32>,
|
||||
/// percent value
|
||||
percent: Option<f32>,
|
||||
pub(crate) percent: Option<f32>,
|
||||
/// water in the tank might be frozen
|
||||
water_frozen: bool,
|
||||
pub(crate) water_frozen: bool,
|
||||
/// water temperature
|
||||
water_temp: Option<f32>,
|
||||
temp_sensor_error: Option<String>,
|
||||
pub(crate) water_temp: Option<f32>,
|
||||
pub(crate) temp_sensor_error: Option<String>,
|
||||
}
|
||||
|
2
rust/src/webserver/.gitignore
vendored
Normal file
2
rust/src/webserver/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
index.html.gz
|
||||
bundle.js.gz
|
919
rust/src/webserver/mod.rs
Normal file
919
rust/src/webserver/mod.rs
Normal file
@@ -0,0 +1,919 @@
|
||||
//offer ota and config mode
|
||||
|
||||
use crate::config::PlantControllerConfig;
|
||||
use crate::hal::rtc::X25;
|
||||
use crate::hal::{esp_set_time, esp_time};
|
||||
use crate::log::LOG_ACCESS;
|
||||
use crate::tank::determine_tank_state;
|
||||
use crate::fat_error::{FatError, FatResult};
|
||||
use crate::{bail, do_secure_pump, get_version, log::LogMessage, BOARD_ACCESS};
|
||||
use alloc::borrow::ToOwned;
|
||||
use alloc::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::sync::Arc;
|
||||
use alloc::vec::Vec;
|
||||
use chrono::DateTime;
|
||||
use core::fmt::{Debug, Display};
|
||||
use core::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use core::result::Result::Ok;
|
||||
use core::str::{from_utf8, FromStr};
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
use chrono_tz::Tz;
|
||||
use edge_http::io::server::{Connection, Handler, Server};
|
||||
use edge_http::Method;
|
||||
use edge_nal::TcpBind;
|
||||
use edge_nal_embassy::{Tcp, TcpBuffers};
|
||||
use embassy_net::Stack;
|
||||
use embassy_time::Instant;
|
||||
use embedded_io_async::{Read, Write};
|
||||
use esp_println::println;
|
||||
use log::info;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct SSIDList {
|
||||
ssids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct LoadData<'a> {
|
||||
rtc: &'a str,
|
||||
native: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct Moistures {
|
||||
moisture_a: Vec<String>,
|
||||
moisture_b: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct SolarState {
|
||||
mppt_voltage: f32,
|
||||
mppt_current: f32,
|
||||
is_day: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct SetTime<'a> {
|
||||
time: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct TestPump {
|
||||
pump: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
pub struct WebBackupHeader {
|
||||
timestamp: String,
|
||||
size: u16,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NightLampCommand {
|
||||
active: bool,
|
||||
}
|
||||
//
|
||||
//
|
||||
|
||||
//
|
||||
|
||||
//
|
||||
// fn get_live_moisture(
|
||||
// _request: &mut Request<&mut EspHttpConnection>,
|
||||
// ) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
// let mut board = BOARD_ACCESS.lock().expect("Should never fail");
|
||||
// let plant_state =
|
||||
// Vec::from_iter((0..PLANT_COUNT).map(|i| PlantState::read_hardware_state(i, &mut board)));
|
||||
// let a = Vec::from_iter(plant_state.iter().map(|s| match &s.sensor_a {
|
||||
// MoistureSensorState::Disabled => "disabled".to_string(),
|
||||
// MoistureSensorState::MoistureValue {
|
||||
// raw_hz,
|
||||
// moisture_percent,
|
||||
// } => {
|
||||
// format!("{moisture_percent:.2}% {raw_hz}hz",)
|
||||
// }
|
||||
// MoistureSensorState::SensorError(err) => format!("{err:?}"),
|
||||
// }));
|
||||
// let b = Vec::from_iter(plant_state.iter().map(|s| match &s.sensor_b {
|
||||
// MoistureSensorState::Disabled => "disabled".to_string(),
|
||||
// MoistureSensorState::MoistureValue {
|
||||
// raw_hz,
|
||||
// moisture_percent,
|
||||
// } => {
|
||||
// format!("{moisture_percent:.2}% {raw_hz}hz",)
|
||||
// }
|
||||
// MoistureSensorState::SensorError(err) => format!("{err:?}"),
|
||||
// }));
|
||||
//
|
||||
// let data = Moistures {
|
||||
// moisture_a: a,
|
||||
// moisture_b: b,
|
||||
// };
|
||||
// let json = serde_json::to_string(&data)?;
|
||||
//
|
||||
// anyhow::Ok(Some(json))
|
||||
// }
|
||||
//
|
||||
//
|
||||
// fn ota(
|
||||
// request: &mut Request<&mut EspHttpConnection>,
|
||||
// ) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
// let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
// let mut ota = OtaUpdate::begin()?;
|
||||
// log::info!("start ota");
|
||||
//
|
||||
// //having a larger buffer is not really faster, requires more stack and prevents the progress bar from working ;)
|
||||
// const BUFFER_SIZE: usize = 512;
|
||||
// let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
|
||||
// let mut total_read: usize = 0;
|
||||
// let mut lastiter = 0;
|
||||
// loop {
|
||||
// let read = request.read(&mut buffer)?;
|
||||
// total_read += read;
|
||||
// let to_write = &buffer[0..read];
|
||||
// //delay for watchdog and wifi stuff
|
||||
// board.board_hal.get_esp().delay.delay_ms(1);
|
||||
//
|
||||
// let iter = (total_read / 1024) % 8;
|
||||
// if iter != lastiter {
|
||||
// board.board_hal.general_fault(iter % 5 == 0);
|
||||
// for i in 0..PLANT_COUNT {
|
||||
// let _ = board.board_hal.fault(i, iter == i);
|
||||
// }
|
||||
// lastiter = iter;
|
||||
// }
|
||||
//
|
||||
// ota.write(to_write)?;
|
||||
// if read == 0 {
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// log::info!("wrote bytes ota {total_read}");
|
||||
// log::info!("finish ota");
|
||||
// let partition = ota.raw_partition();
|
||||
// log::info!("finalizing and changing boot partition to {partition:?}");
|
||||
//
|
||||
// let mut finalizer = ota.finalize()?;
|
||||
// log::info!("changing boot partition");
|
||||
// board.board_hal.get_esp().set_restart_to_conf(true);
|
||||
// drop(board);
|
||||
// finalizer.set_as_boot_partition()?;
|
||||
// anyhow::Ok(None)
|
||||
// }
|
||||
//
|
||||
|
||||
struct HttpHandler {
|
||||
reboot_now: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Handler for HttpHandler {
|
||||
type Error<E: Debug> = FatError;
|
||||
async fn handle<'a, T, const N: usize>(
|
||||
&self,
|
||||
_task_id: impl Display + Copy,
|
||||
conn: &mut Connection<'a, T, N>,
|
||||
) -> Result<(), FatError>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let start = Instant::now();
|
||||
let headers = conn.headers()?;
|
||||
|
||||
let method = headers.method;
|
||||
let path = headers.path;
|
||||
|
||||
let prefix = "/file?filename=";
|
||||
let status = if path.starts_with(prefix) {
|
||||
let filename = &path[prefix.len()..];
|
||||
info!("file request for {} with method {}", filename, method);
|
||||
match method {
|
||||
Method::Delete => {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.delete_file(filename.to_owned())
|
||||
.await?;
|
||||
Some(200)
|
||||
}
|
||||
Method::Get => {
|
||||
let disp = format!("attachment; filename=\"{filename}\"");
|
||||
let size = {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.get_size(filename.to_owned())
|
||||
.await?
|
||||
};
|
||||
|
||||
conn.initiate_response(
|
||||
200,
|
||||
Some("OK"),
|
||||
&[
|
||||
("Content-Type", "application/octet-stream"),
|
||||
("Content-Disposition", disp.as_str()),
|
||||
("Content-Length", &format!("{}", size)),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut chunk = 0;
|
||||
loop {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.progress(chunk as u32).await;
|
||||
let read_chunk = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.get_file(filename.to_owned(), chunk)
|
||||
.await?;
|
||||
let length = read_chunk.1;
|
||||
if length == 0 {
|
||||
info!("file request for {} finished", filename);
|
||||
break;
|
||||
}
|
||||
let data = &read_chunk.0[0..length];
|
||||
conn.write_all(data).await?;
|
||||
if length < read_chunk.0.len() {
|
||||
info!("file request for {} finished", filename);
|
||||
break;
|
||||
}
|
||||
chunk = chunk + 1;
|
||||
}
|
||||
BOARD_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.board_hal
|
||||
.clear_progress()
|
||||
.await;
|
||||
Some(200)
|
||||
}
|
||||
Method::Post => {
|
||||
{
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
//ensure file is deleted, otherwise we would need to truncate the file which will not work with streaming
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.delete_file(filename.to_owned())
|
||||
.await;
|
||||
}
|
||||
|
||||
let mut offset = 0_usize;
|
||||
let mut chunk = 0;
|
||||
loop {
|
||||
let mut buf = [0_u8; 1024];
|
||||
let to_write = conn.read(&mut buf).await?;
|
||||
if to_write == 0 {
|
||||
info!("file request for {} finished", filename);
|
||||
break;
|
||||
} else {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.progress(chunk as u32).await;
|
||||
board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.write_file(filename.to_owned(), offset as u32, &buf[0..to_write])
|
||||
.await?;
|
||||
}
|
||||
offset = offset + to_write;
|
||||
chunk = chunk + 1;
|
||||
}
|
||||
BOARD_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.board_hal
|
||||
.clear_progress()
|
||||
.await;
|
||||
Some(200)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
match method {
|
||||
Method::Get => match path {
|
||||
"/favicon.ico" => {
|
||||
conn.initiate_response(
|
||||
200,
|
||||
Some("OK"),
|
||||
&[("Content-Type", "image/x-icon")],
|
||||
)
|
||||
.await?;
|
||||
conn.write_all(include_bytes!("favicon.ico")).await?;
|
||||
Some(200)
|
||||
}
|
||||
"/" => {
|
||||
conn.initiate_response(
|
||||
200,
|
||||
Some("OK"),
|
||||
&[("Content-Type", "text/html"), ("Content-Encoding", "gzip")],
|
||||
)
|
||||
.await?;
|
||||
conn.write_all(include_bytes!("index.html.gz")).await?;
|
||||
Some(200)
|
||||
}
|
||||
"/bundle.js" => {
|
||||
conn.initiate_response(
|
||||
200,
|
||||
Some("OK"),
|
||||
&[
|
||||
("Content-Type", "text/javascript"),
|
||||
("Content-Encoding", "gzip"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
conn.write_all(include_bytes!("bundle.js.gz")).await?;
|
||||
Some(200)
|
||||
}
|
||||
"/log" => {
|
||||
get_log(conn).await?;
|
||||
Some(200)
|
||||
}
|
||||
"/get_backup_config" => {
|
||||
get_backup_config(conn).await?;
|
||||
Some(200)
|
||||
}
|
||||
&_ => {
|
||||
let json = match path {
|
||||
"/version" => Some(get_version_web(conn).await),
|
||||
"/time" => Some(get_time(conn).await),
|
||||
"/battery" => Some(get_battery_state(conn).await),
|
||||
"/solar" => Some(get_solar_state(conn).await),
|
||||
"/get_config" => Some(get_config(conn).await),
|
||||
"/files" => Some(list_files(conn).await),
|
||||
"/log_localization" => Some(get_log_localization_config(conn).await),
|
||||
"/tank" => Some(tank_info(conn).await),
|
||||
"/backup_info" => Some(backup_info(conn).await),
|
||||
"/timezones" => Some(get_timezones(conn).await),
|
||||
_ => None,
|
||||
};
|
||||
match json {
|
||||
None => None,
|
||||
Some(json) => Some(handle_json(conn, json).await?),
|
||||
}
|
||||
}
|
||||
},
|
||||
Method::Post => {
|
||||
let json = match path {
|
||||
"/wifiscan" => Some(wifi_scan(conn).await),
|
||||
"/set_config" => Some(set_config(conn).await),
|
||||
"/time" => Some(write_time(conn).await),
|
||||
"/backup_config" => Some(backup_config(conn).await),
|
||||
"/pumptest" => Some(pump_test(conn).await),
|
||||
"/lamptest" => Some(night_lamp_test(conn).await),
|
||||
"/boardtest" => Some(board_test(conn).await),
|
||||
"/reboot" => {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.get_esp().set_restart_to_conf(true);
|
||||
self.reboot_now.store(true, Ordering::Relaxed);
|
||||
Some(Ok(None))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match json {
|
||||
None => None,
|
||||
Some(json) => Some(handle_json(conn, json).await?),
|
||||
}
|
||||
}
|
||||
Method::Options | Method::Delete | Method::Head | Method::Put => None,
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let code = match status {
|
||||
None => {
|
||||
conn.initiate_response(404, Some("Not found"), &[]).await?;
|
||||
404
|
||||
}
|
||||
Some(code) => code,
|
||||
};
|
||||
|
||||
conn.complete().await?;
|
||||
let response_time = Instant::now().duration_since(start).as_millis();
|
||||
|
||||
info!("\"{method} {path}\" {code} {response_time}ms");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_timezones<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
// Get all timezones using chrono-tz
|
||||
let timezones: Vec<&'static str> = chrono_tz::TZ_VARIANTS.iter().map(|tz| tz.name()).collect();
|
||||
let json = serde_json::to_string(&timezones)?;
|
||||
Ok(Some(json))
|
||||
}
|
||||
|
||||
async fn board_test<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.test().await?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn pump_test<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let actual_data = read_up_to_bytes_from_request(request, None).await?;
|
||||
let pump_test: TestPump = serde_json::from_slice(&actual_data)?;
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
|
||||
let config = &board.board_hal.get_config().plants[pump_test.pump].clone();
|
||||
let pump_result = do_secure_pump(&mut board, pump_test.pump, config, false).await;
|
||||
//ensure it is disabled before unwrapping
|
||||
board.board_hal.pump(pump_test.pump, false).await?;
|
||||
|
||||
Ok(Some(serde_json::to_string(&pump_result?)?))
|
||||
}
|
||||
|
||||
async fn night_lamp_test<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let actual_data = read_up_to_bytes_from_request(request, None).await?;
|
||||
let light_command: NightLampCommand = serde_json::from_slice(&actual_data)?;
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.light(light_command.active).await?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn get_backup_config<T, const N: usize>(
|
||||
conn: &mut Connection<'_, T, { N }>,
|
||||
) -> Result<(), FatError>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
// First pass: verify checksum without sending data
|
||||
let mut checksum = X25.digest();
|
||||
let mut chunk = 0_usize;
|
||||
loop {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.progress(chunk as u32).await;
|
||||
let (buf, len, expected_crc) = board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.get_backup_config(chunk)
|
||||
.await?;
|
||||
|
||||
// Update checksum with the actual data bytes of this chunk
|
||||
checksum.update(&buf[..len]);
|
||||
|
||||
let is_last = len == 0 || len < buf.len();
|
||||
if is_last {
|
||||
let actual_crc = checksum.finalize();
|
||||
if actual_crc != expected_crc {
|
||||
BOARD_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.board_hal
|
||||
.clear_progress()
|
||||
.await;
|
||||
conn.initiate_response(
|
||||
409,
|
||||
Some(
|
||||
format!(
|
||||
"Checksum mismatch expected {} got {}",
|
||||
expected_crc, actual_crc
|
||||
)
|
||||
.as_str(),
|
||||
),
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
break;
|
||||
}
|
||||
chunk += 1;
|
||||
}
|
||||
|
||||
// Second pass: stream data
|
||||
conn.initiate_response(200, Some("OK"), &[]).await?;
|
||||
|
||||
let mut chunk = 0_usize;
|
||||
loop {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.progress(chunk as u32).await;
|
||||
let (buf, len, _expected_crc) = board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.get_backup_config(chunk)
|
||||
.await?;
|
||||
|
||||
if len == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
conn.write_all(&buf[..len]).await?;
|
||||
|
||||
if len < buf.len() {
|
||||
break;
|
||||
}
|
||||
chunk += 1;
|
||||
}
|
||||
BOARD_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.board_hal
|
||||
.clear_progress()
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn backup_config<T, const N: usize>(
|
||||
conn: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let mut offset = 0_usize;
|
||||
let mut buf = [0_u8; 32];
|
||||
|
||||
let mut checksum = crate::hal::rtc::X25.digest();
|
||||
|
||||
let mut counter = 0;
|
||||
loop {
|
||||
let to_write = conn.read(&mut buf).await?;
|
||||
if to_write == 0 {
|
||||
info!("backup finished");
|
||||
break;
|
||||
} else {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.progress(counter).await;
|
||||
|
||||
counter = counter + 1;
|
||||
board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.backup_config(offset, &buf[0..to_write])
|
||||
.await?;
|
||||
checksum.update(&buf[0..to_write]);
|
||||
}
|
||||
offset = offset + to_write;
|
||||
}
|
||||
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.backup_config_finalize(checksum.finalize(), offset)
|
||||
.await?;
|
||||
board.board_hal.clear_progress().await;
|
||||
Ok(Some("saved".to_owned()))
|
||||
}
|
||||
|
||||
async fn backup_info<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> Result<Option<String>, FatError>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let header = board.board_hal.get_rtc_module().get_backup_info().await;
|
||||
let json = match header {
|
||||
Ok(h) => {
|
||||
let timestamp = DateTime::from_timestamp_millis(h.timestamp).unwrap();
|
||||
let wbh = WebBackupHeader {
|
||||
timestamp: timestamp.to_rfc3339(),
|
||||
size: h.size,
|
||||
};
|
||||
serde_json::to_string(&wbh)?
|
||||
}
|
||||
Err(err) => {
|
||||
let wbh = WebBackupHeader {
|
||||
timestamp: err.to_string(),
|
||||
size: 0,
|
||||
};
|
||||
serde_json::to_string(&wbh)?
|
||||
}
|
||||
};
|
||||
Ok(Some(json))
|
||||
}
|
||||
|
||||
async fn tank_info<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> Result<Option<String>, FatError>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let tank_state = determine_tank_state(&mut board).await;
|
||||
//should be multisampled
|
||||
let sensor = board.board_hal.get_tank_sensor()?;
|
||||
|
||||
let water_temp: FatResult<f32> = sensor.water_temperature_c().await;
|
||||
Ok(Some(serde_json::to_string(&tank_state.as_mqtt_info(
|
||||
&board.board_hal.get_config().tank,
|
||||
&water_temp,
|
||||
))?))
|
||||
}
|
||||
|
||||
async fn write_time<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let actual_data = read_up_to_bytes_from_request(request, None).await?;
|
||||
let time: SetTime = serde_json::from_slice(&actual_data)?;
|
||||
let parsed = DateTime::parse_from_rfc3339(time.time).unwrap();
|
||||
esp_set_time(parsed).await;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn set_config<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let all = read_up_to_bytes_from_request(request, Some(4096)).await?;
|
||||
let length = all.len();
|
||||
let config: PlantControllerConfig = serde_json::from_slice(&all)?;
|
||||
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
board.board_hal.get_esp().save_config(all).await?;
|
||||
log::info!("Wrote config config {:?} with size {}", config, length);
|
||||
board.board_hal.set_config(config);
|
||||
Ok(Some("saved".to_string()))
|
||||
}
|
||||
|
||||
async fn read_up_to_bytes_from_request<T, const N: usize>(
|
||||
request: &mut Connection<'_, T, N>,
|
||||
limit: Option<usize>,
|
||||
) -> FatResult<Vec<u8>>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let max_read = limit.unwrap_or(1024);
|
||||
let mut data_store = Vec::new();
|
||||
let mut total_read = 0;
|
||||
loop {
|
||||
let mut buf = [0_u8; 64];
|
||||
let read = request.read(&mut buf).await?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
let actual_data = &buf[0..read];
|
||||
total_read += read;
|
||||
if total_read > max_read {
|
||||
bail!("Request too large {total_read} > {max_read}");
|
||||
}
|
||||
data_store.push(actual_data.to_owned());
|
||||
}
|
||||
let allvec = data_store.concat();
|
||||
log::info!("Raw data {}", from_utf8(&allvec)?);
|
||||
Ok(allvec)
|
||||
}
|
||||
|
||||
async fn wifi_scan<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
info!("start wifi scan");
|
||||
let mut ssids: Vec<String> = Vec::new();
|
||||
let scan_result = board.board_hal.get_esp().wifi_scan().await?;
|
||||
scan_result
|
||||
.iter()
|
||||
.for_each(|s| ssids.push(s.ssid.to_string()));
|
||||
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
|
||||
info!("Sending ssid list {}", &ssid_json);
|
||||
Ok(Some(ssid_json))
|
||||
}
|
||||
|
||||
async fn get_log<T, const N: usize>(conn: &mut Connection<'_, T, N>) -> FatResult<()>
|
||||
where
|
||||
T: Read + Write,
|
||||
{
|
||||
let log = LOG_ACCESS.lock().await.get();
|
||||
conn.initiate_response(200, Some("OK"), &[("Content-Type", "text/javascript")])
|
||||
.await?;
|
||||
conn.write_all("[".as_bytes()).await?;
|
||||
let mut append = false;
|
||||
for entry in log {
|
||||
if append {
|
||||
conn.write_all(",".as_bytes()).await?;
|
||||
}
|
||||
append = true;
|
||||
let json = serde_json::to_string(&entry)?;
|
||||
conn.write_all(json.as_bytes()).await?;
|
||||
}
|
||||
conn.write_all("]".as_bytes()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_log_localization_config<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
Ok(Some(serde_json::to_string(
|
||||
&LogMessage::to_log_localisation_config(),
|
||||
)?))
|
||||
}
|
||||
async fn list_files<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let result = board.board_hal.get_esp().list_files().await?;
|
||||
let file_list_json = serde_json::to_string(&result)?;
|
||||
Ok(Some(file_list_json))
|
||||
}
|
||||
async fn get_config<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let json = serde_json::to_string(&board.board_hal.get_config())?;
|
||||
Ok(Some(json))
|
||||
}
|
||||
|
||||
async fn get_solar_state<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let state = SolarState {
|
||||
mppt_voltage: board.board_hal.get_mptt_voltage().await?.as_millivolts() as f32,
|
||||
mppt_current: board.board_hal.get_mptt_current().await?.as_milliamperes() as f32,
|
||||
is_day: board.board_hal.is_day(),
|
||||
};
|
||||
Ok(Some(serde_json::to_string(&state)?))
|
||||
}
|
||||
|
||||
async fn get_battery_state<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let battery_state = board
|
||||
.board_hal
|
||||
.get_battery_monitor()
|
||||
.get_battery_state()
|
||||
.await?;
|
||||
Ok(Some(serde_json::to_string(&battery_state)?))
|
||||
}
|
||||
|
||||
async fn get_version_web<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
Ok(Some(serde_json::to_string(&get_version(&mut board).await)?))
|
||||
}
|
||||
|
||||
async fn get_time<T, const N: usize>(
|
||||
_request: &mut Connection<'_, T, N>,
|
||||
) -> FatResult<Option<String>> {
|
||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||
let conf = board.board_hal.get_config();
|
||||
let tz = Tz::from_str(conf.timezone.as_ref().unwrap().as_str()).unwrap();
|
||||
let native = esp_time().await.with_timezone(&tz).to_rfc3339();
|
||||
|
||||
let rtc = match board.board_hal.get_rtc_module().get_rtc_time().await {
|
||||
Ok(time) => time.with_timezone(&tz).to_rfc3339(),
|
||||
Err(err) => {
|
||||
format!("Error getting time: {}", err)
|
||||
}
|
||||
};
|
||||
|
||||
let data = LoadData {
|
||||
rtc: rtc.as_str(),
|
||||
native: native.as_str(),
|
||||
};
|
||||
let json = serde_json::to_string(&data)?;
|
||||
|
||||
Ok(Some(json))
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn httpd(reboot_now: Arc<AtomicBool>, stack: Stack<'static>) {
|
||||
let buffer: TcpBuffers<2, 1024, 1024> = TcpBuffers::new();
|
||||
let tcp = Tcp::new(stack, &buffer);
|
||||
let acceptor = tcp
|
||||
.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 80))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut server: Server<2, 512, 15> = Server::new();
|
||||
server
|
||||
.run(Some(5000), acceptor, HttpHandler { reboot_now })
|
||||
.await
|
||||
.expect("TODO: panic message");
|
||||
println!("Wait for connection...");
|
||||
|
||||
// server
|
||||
// .fn_handler("/moisture", Method::Get, |request| {
|
||||
// handle_error_to500(request, get_live_moisture)
|
||||
// })
|
||||
// .unwrap();
|
||||
|
||||
// server
|
||||
// .fn_handler("/ota", Method::Post, |request| {
|
||||
// handle_error_to500(request, ota)
|
||||
// })
|
||||
// .unwrap();
|
||||
// server
|
||||
// .fn_handler("/ota", Method::Options, |request| {
|
||||
// cors_response(request, 200, "")
|
||||
// })
|
||||
// .unwrap();
|
||||
// let reboot_now_for_reboot = reboot_now.clone();
|
||||
// server
|
||||
// .fn_handler("/reboot", Method::Post, move |_| {
|
||||
// BOARD_ACCESS
|
||||
// .lock()
|
||||
// .unwrap()
|
||||
// .board_hal
|
||||
// .get_esp()
|
||||
// .set_restart_to_conf(true);
|
||||
// reboot_now_for_reboot.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
// anyhow::Ok(())
|
||||
// })
|
||||
// .unwrap();
|
||||
//
|
||||
// unsafe { vTaskDelay(1) };
|
||||
//
|
||||
// let reboot_now_for_exit = reboot_now.clone();
|
||||
// server
|
||||
// .fn_handler("/exit", Method::Post, move |_| {
|
||||
// reboot_now_for_exit.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
// anyhow::Ok(())
|
||||
// })
|
||||
// .unwrap();
|
||||
// server
|
||||
}
|
||||
|
||||
async fn handle_json<'a, T, const N: usize>(
|
||||
conn: &mut Connection<'a, T, N>,
|
||||
chain: FatResult<Option<String>>,
|
||||
) -> FatResult<u32>
|
||||
where
|
||||
T: Read + Write,
|
||||
<T as embedded_io_async::ErrorType>::Error: Debug,
|
||||
{
|
||||
match chain {
|
||||
Ok(answer) => match answer {
|
||||
Some(json) => {
|
||||
conn.initiate_response(
|
||||
200,
|
||||
Some("OK"),
|
||||
&[
|
||||
("Access-Control-Allow-Origin", "*"),
|
||||
("Access-Control-Allow-Headers", "*"),
|
||||
("Access-Control-Allow-Methods", "*"),
|
||||
("Content-Type", "application/json"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
conn.write_all(json.as_bytes()).await?;
|
||||
Ok(200)
|
||||
}
|
||||
None => {
|
||||
conn.initiate_response(
|
||||
200,
|
||||
Some("OK"),
|
||||
&[
|
||||
("Access-Control-Allow-Origin", "*"),
|
||||
("Access-Control-Allow-Headers", "*"),
|
||||
("Access-Control-Allow-Methods", "*"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
Ok(200)
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
let error_text = err.to_string();
|
||||
info!("error handling process {}", error_text);
|
||||
conn.initiate_response(
|
||||
500,
|
||||
Some("OK"),
|
||||
&[
|
||||
("Access-Control-Allow-Origin", "*"),
|
||||
("Access-Control-Allow-Headers", "*"),
|
||||
("Access-Control-Allow-Methods", "*"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
conn.write_all(error_text.as_bytes()).await?;
|
||||
Ok(500)
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,692 +0,0 @@
|
||||
//offer ota and config mode
|
||||
|
||||
use crate::hal::battery::BatteryInteraction;
|
||||
use crate::{
|
||||
determine_tank_state, get_version, log::LogMessage, plant_state::PlantState, BOARD_ACCESS,
|
||||
};
|
||||
use anyhow::bail;
|
||||
use chrono::DateTime;
|
||||
use core::result::Result::Ok;
|
||||
use embedded_svc::http::Method;
|
||||
use esp_idf_svc::http::server::{Configuration, EspHttpConnection, EspHttpServer, Request};
|
||||
use esp_idf_sys::{settimeofday, timeval, vTaskDelay};
|
||||
use esp_ota::OtaUpdate;
|
||||
use heapless::String;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
str::from_utf8,
|
||||
sync::{atomic::AtomicBool, Arc},
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
use crate::config::PlantControllerConfig;
|
||||
use crate::hal::{BoardInteraction, PLANT_COUNT};
|
||||
use crate::plant_state::MoistureSensorState;
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct SSIDList<'a> {
|
||||
ssids: Vec<&'a String<32>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct LoadData<'a> {
|
||||
rtc: &'a str,
|
||||
native: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct Moistures {
|
||||
moisture_a: Vec<std::string::String>,
|
||||
moisture_b: Vec<std::string::String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct SetTime<'a> {
|
||||
time: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||
pub struct TestPump {
|
||||
pump: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
pub struct WebBackupHeader {
|
||||
timestamp: std::string::String,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NightLampCommand {
|
||||
active: bool,
|
||||
}
|
||||
|
||||
fn write_time(
|
||||
request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let actual_data = read_up_to_bytes_from_request(request, None)?;
|
||||
let time: SetTime = serde_json::from_slice(&actual_data)?;
|
||||
let parsed = DateTime::parse_from_rfc3339(time.time).map_err(|err| anyhow::anyhow!(err))?;
|
||||
let mut board = BOARD_ACCESS.lock().expect("board access");
|
||||
|
||||
let now = timeval {
|
||||
tv_sec: parsed.to_utc().timestamp(),
|
||||
tv_usec: 0,
|
||||
};
|
||||
unsafe { settimeofday(&now, core::ptr::null_mut()) };
|
||||
board.board_hal.set_rtc_time(&parsed.to_utc())?;
|
||||
anyhow::Ok(None)
|
||||
}
|
||||
|
||||
fn get_time(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().expect("board access");
|
||||
let native = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.time()
|
||||
.map(|t| t.to_rfc3339())
|
||||
.unwrap_or("error".to_string());
|
||||
let rtc = board
|
||||
.board_hal
|
||||
.get_rtc_time()
|
||||
.map(|t| t.to_rfc3339())
|
||||
.unwrap_or("error".to_string());
|
||||
|
||||
let data = LoadData {
|
||||
rtc: rtc.as_str(),
|
||||
native: native.as_str(),
|
||||
};
|
||||
let json = serde_json::to_string(&data)?;
|
||||
|
||||
anyhow::Ok(Some(json))
|
||||
}
|
||||
|
||||
fn get_timezones(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
// Get all timezones using chrono-tz
|
||||
let timezones: Vec<&'static str> = chrono_tz::TZ_VARIANTS.iter().map(|tz| tz.name()).collect();
|
||||
|
||||
// Convert to JSON
|
||||
let json = serde_json::to_string(&timezones)?;
|
||||
anyhow::Ok(Some(json))
|
||||
}
|
||||
|
||||
fn get_live_moisture(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().expect("Should never fail");
|
||||
let plant_state =
|
||||
Vec::from_iter((0..PLANT_COUNT).map(|i| PlantState::read_hardware_state(i, &mut board)));
|
||||
let a = Vec::from_iter(plant_state.iter().map(|s| match &s.sensor_a {
|
||||
MoistureSensorState::Disabled => "disabled".to_string(),
|
||||
MoistureSensorState::MoistureValue {
|
||||
raw_hz,
|
||||
moisture_percent,
|
||||
} => {
|
||||
format!("{moisture_percent:.2}% {raw_hz}hz",)
|
||||
}
|
||||
MoistureSensorState::SensorError(err) => format!("{err:?}"),
|
||||
}));
|
||||
let b = Vec::from_iter(plant_state.iter().map(|s| match &s.sensor_b {
|
||||
MoistureSensorState::Disabled => "disabled".to_string(),
|
||||
MoistureSensorState::MoistureValue {
|
||||
raw_hz,
|
||||
moisture_percent,
|
||||
} => {
|
||||
format!("{moisture_percent:.2}% {raw_hz}hz",)
|
||||
}
|
||||
MoistureSensorState::SensorError(err) => format!("{err:?}"),
|
||||
}));
|
||||
|
||||
let data = Moistures {
|
||||
moisture_a: a,
|
||||
moisture_b: b,
|
||||
};
|
||||
let json = serde_json::to_string(&data)?;
|
||||
|
||||
anyhow::Ok(Some(json))
|
||||
}
|
||||
|
||||
fn get_config(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().expect("Should never fail");
|
||||
let json = serde_json::to_string(&board.board_hal.get_config())?;
|
||||
anyhow::Ok(Some(json))
|
||||
}
|
||||
|
||||
fn backup_config(
|
||||
request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let all = read_up_to_bytes_from_request(request, Some(3072))?;
|
||||
let mut board = BOARD_ACCESS.lock().expect("board access");
|
||||
board.board_hal.backup_config(&all)?;
|
||||
anyhow::Ok(Some("saved".to_owned()))
|
||||
}
|
||||
|
||||
fn get_backup_config(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().expect("board access");
|
||||
let json = match board.board_hal.get_backup_config() {
|
||||
Ok(config) => from_utf8(&config)?.to_owned(),
|
||||
Err(err) => {
|
||||
println!("Error get backup config {:?}", err);
|
||||
err.to_string()
|
||||
}
|
||||
};
|
||||
anyhow::Ok(Some(json))
|
||||
}
|
||||
|
||||
fn backup_info(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().expect("Should never fail");
|
||||
let header = board.board_hal.get_backup_info();
|
||||
let json = match header {
|
||||
Ok(h) => {
|
||||
let timestamp = DateTime::from_timestamp_millis(h.timestamp).unwrap();
|
||||
let wbh = WebBackupHeader {
|
||||
timestamp: timestamp.to_rfc3339(),
|
||||
size: h.size,
|
||||
};
|
||||
serde_json::to_string(&wbh)?
|
||||
}
|
||||
Err(_) => {
|
||||
//TODO make better
|
||||
let wbh = WebBackupHeader {
|
||||
timestamp: "no backup".to_owned(),
|
||||
size: 0,
|
||||
};
|
||||
serde_json::to_string(&wbh)?
|
||||
}
|
||||
};
|
||||
anyhow::Ok(Some(json))
|
||||
}
|
||||
|
||||
fn set_config(
|
||||
request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let all = read_up_to_bytes_from_request(request, Some(3072))?;
|
||||
let config: PlantControllerConfig = serde_json::from_slice(&all)?;
|
||||
|
||||
let mut board = BOARD_ACCESS.lock().expect("board access");
|
||||
board.board_hal.set_config(config);
|
||||
anyhow::Ok(Some("saved".to_owned()))
|
||||
}
|
||||
|
||||
fn get_battery_state(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().expect("board access");
|
||||
let battery_state = board.board_hal.get_battery_monitor().get_battery_state();
|
||||
anyhow::Ok(Some(serde_json::to_string(&battery_state)?))
|
||||
}
|
||||
|
||||
fn get_log(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let output = crate::log::get_log();
|
||||
anyhow::Ok(Some(serde_json::to_string(&output)?))
|
||||
}
|
||||
|
||||
fn get_log_localization_config() -> Result<std::string::String, anyhow::Error> {
|
||||
anyhow::Ok(serde_json::to_string(
|
||||
&LogMessage::to_log_localisation_config(),
|
||||
)?)
|
||||
}
|
||||
|
||||
fn get_version_web(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
anyhow::Ok(Some(serde_json::to_string(&get_version())?))
|
||||
}
|
||||
|
||||
fn pump_test(
|
||||
request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let actual_data = read_up_to_bytes_from_request(request, None)?;
|
||||
let pump_test: TestPump = serde_json::from_slice(&actual_data)?;
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
board.board_hal.test_pump(pump_test.pump)?;
|
||||
anyhow::Ok(None)
|
||||
}
|
||||
|
||||
fn tank_info(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
let tank_info = determine_tank_state(&mut board);
|
||||
//should be multsampled
|
||||
let water_temp = board.board_hal.water_temperature_c();
|
||||
Ok(Some(serde_json::to_string(&tank_info.as_mqtt_info(
|
||||
&board.board_hal.get_config().tank,
|
||||
&water_temp,
|
||||
))?))
|
||||
}
|
||||
|
||||
fn night_lamp_test(
|
||||
request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let actual_data = read_up_to_bytes_from_request(request, None)?;
|
||||
let light_command: NightLampCommand = serde_json::from_slice(&actual_data)?;
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
board.board_hal.light(light_command.active)?;
|
||||
anyhow::Ok(None)
|
||||
}
|
||||
|
||||
fn wifi_scan(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
let scan_result = board.board_hal.get_esp().wifi_scan()?;
|
||||
let mut ssids: Vec<&String<32>> = Vec::new();
|
||||
scan_result.iter().for_each(|s| ssids.push(&s.ssid));
|
||||
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
|
||||
println!("Sending ssid list {}", &ssid_json);
|
||||
anyhow::Ok(Some(ssid_json))
|
||||
}
|
||||
|
||||
fn list_files(
|
||||
_request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS
|
||||
.lock()
|
||||
.expect("It should be possible to lock the board for exclusive fs access");
|
||||
let result = board.board_hal.get_esp().list_files();
|
||||
let file_list_json = serde_json::to_string(&result)?;
|
||||
anyhow::Ok(Some(file_list_json))
|
||||
}
|
||||
|
||||
fn ota(
|
||||
request: &mut Request<&mut EspHttpConnection>,
|
||||
) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
let mut ota = OtaUpdate::begin()?;
|
||||
println!("start ota");
|
||||
|
||||
//having a larger buffer is not really faster, requires more stack and prevents the progress bar from working ;)
|
||||
const BUFFER_SIZE: usize = 512;
|
||||
let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
|
||||
let mut total_read: usize = 0;
|
||||
let mut lastiter = 0;
|
||||
loop {
|
||||
let read = request.read(&mut buffer)?;
|
||||
total_read += read;
|
||||
let to_write = &buffer[0..read];
|
||||
//delay for watchdog and wifi stuff
|
||||
board.board_hal.get_esp().delay.delay_ms(1);
|
||||
|
||||
let iter = (total_read / 1024) % 8;
|
||||
if iter != lastiter {
|
||||
for i in 0..PLANT_COUNT {
|
||||
let _ = board.board_hal.fault(i, iter == i);
|
||||
}
|
||||
lastiter = iter;
|
||||
}
|
||||
|
||||
ota.write(to_write)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
println!("wrote bytes ota {total_read}");
|
||||
println!("finish ota");
|
||||
let partition = ota.raw_partition();
|
||||
println!("finalizing and changing boot partition to {partition:?}");
|
||||
|
||||
let mut finalizer = ota.finalize()?;
|
||||
println!("changing boot partition");
|
||||
board.board_hal.get_esp().set_restart_to_conf(true);
|
||||
drop(board);
|
||||
finalizer.set_as_boot_partition()?;
|
||||
anyhow::Ok(None)
|
||||
}
|
||||
|
||||
fn query_param(uri: &str, param_name: &str) -> Option<std::string::String> {
|
||||
println!("{uri} get {param_name}");
|
||||
let parsed = Url::parse(&format!("http://127.0.0.1/{uri}")).unwrap();
|
||||
let value = parsed.query_pairs().find(|it| it.0 == param_name);
|
||||
match value {
|
||||
Some(found) => Some(found.1.into_owned()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn httpd(reboot_now: Arc<AtomicBool>) -> Box<EspHttpServer<'static>> {
|
||||
let server_config = Configuration {
|
||||
stack_size: 32768,
|
||||
..Default::default()
|
||||
};
|
||||
let mut server: Box<EspHttpServer<'static>> =
|
||||
Box::new(EspHttpServer::new(&server_config).unwrap());
|
||||
server
|
||||
.fn_handler("/version", Method::Get, |request| {
|
||||
handle_error_to500(request, get_version_web)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/log", Method::Get, |request| {
|
||||
handle_error_to500(request, get_log)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/log_localization", Method::Get, |request| {
|
||||
cors_response(request, 200, &get_log_localization_config().unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/battery", Method::Get, |request| {
|
||||
handle_error_to500(request, get_battery_state)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/time", Method::Get, |request| {
|
||||
handle_error_to500(request, get_time)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/moisture", Method::Get, |request| {
|
||||
handle_error_to500(request, get_live_moisture)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/time", Method::Post, |request| {
|
||||
handle_error_to500(request, write_time)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/tank", Method::Get, |request| {
|
||||
handle_error_to500(request, tank_info)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/pumptest", Method::Post, |request| {
|
||||
handle_error_to500(request, pump_test)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/lamptest", Method::Post, |request| {
|
||||
handle_error_to500(request, night_lamp_test)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/boardtest", Method::Post, move |_| {
|
||||
BOARD_ACCESS.lock().unwrap().board_hal.test()
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/wifiscan", Method::Post, move |request| {
|
||||
handle_error_to500(request, wifi_scan)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/ota", Method::Post, |request| {
|
||||
handle_error_to500(request, ota)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/ota", Method::Options, |request| {
|
||||
cors_response(request, 200, "")
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/get_config", Method::Get, move |request| {
|
||||
handle_error_to500(request, get_config)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/get_backup_config", Method::Get, move |request| {
|
||||
handle_error_to500(request, get_backup_config)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
server
|
||||
.fn_handler("/set_config", Method::Post, move |request| {
|
||||
handle_error_to500(request, set_config)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/backup_config", Method::Post, move |request| {
|
||||
handle_error_to500(request, backup_config)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/backup_info", Method::Get, move |request| {
|
||||
handle_error_to500(request, backup_info)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/files", Method::Get, move |request| {
|
||||
handle_error_to500(request, list_files)
|
||||
})
|
||||
.unwrap();
|
||||
let reboot_now_for_reboot = reboot_now.clone();
|
||||
server
|
||||
.fn_handler("/reboot", Method::Post, move |_| {
|
||||
BOARD_ACCESS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.set_restart_to_conf(true);
|
||||
reboot_now_for_reboot.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
unsafe { vTaskDelay(1) };
|
||||
|
||||
let reboot_now_for_exit = reboot_now.clone();
|
||||
server
|
||||
.fn_handler("/exit", Method::Post, move |_| {
|
||||
reboot_now_for_exit.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/file", Method::Get, move |request| {
|
||||
let filename = query_param(request.uri(), "filename").unwrap();
|
||||
let file_handle = BOARD_ACCESS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.get_file_handle(&filename, false);
|
||||
match file_handle {
|
||||
Ok(mut file_handle) => {
|
||||
let headers = [("Access-Control-Allow-Origin", "*")];
|
||||
let mut response = request.into_response(200, None, &headers)?;
|
||||
const BUFFER_SIZE: usize = 512;
|
||||
let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
|
||||
let mut total_read: usize = 0;
|
||||
loop {
|
||||
unsafe { vTaskDelay(1) };
|
||||
let read = std::io::Read::read(&mut file_handle, &mut buffer)?;
|
||||
total_read += read;
|
||||
let to_write = &buffer[0..read];
|
||||
response.write(to_write)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
println!("wrote {total_read} for file {filename}");
|
||||
drop(file_handle);
|
||||
response.flush()?;
|
||||
}
|
||||
Err(err) => {
|
||||
//todo set headers here for filename to be error
|
||||
let error_text = err.to_string();
|
||||
println!("error handling get file {}", error_text);
|
||||
cors_response(request, 500, &error_text)?;
|
||||
}
|
||||
}
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/file", Method::Post, move |mut request| {
|
||||
let filename = query_param(request.uri(), "filename").unwrap();
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
let file_handle = board.board_hal.get_esp().get_file_handle(&filename, true);
|
||||
match file_handle {
|
||||
//TODO get free filesystem size, check against during write if not to large
|
||||
Ok(mut file_handle) => {
|
||||
const BUFFER_SIZE: usize = 512;
|
||||
let mut buffer: [u8; BUFFER_SIZE] = [0; BUFFER_SIZE];
|
||||
let mut total_read: usize = 0;
|
||||
let mut lastiter = 0;
|
||||
loop {
|
||||
let iter = (total_read / 1024) % 8;
|
||||
if iter != lastiter {
|
||||
for i in 0..PLANT_COUNT {
|
||||
let _ = board.board_hal.fault(i, iter == i);
|
||||
}
|
||||
lastiter = iter;
|
||||
}
|
||||
|
||||
let read = request.read(&mut buffer)?;
|
||||
total_read += read;
|
||||
let to_write = &buffer[0..read];
|
||||
std::io::Write::write(&mut file_handle, to_write)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
cors_response(request, 200, &format!("saved {total_read} bytes"))?;
|
||||
}
|
||||
Err(err) => {
|
||||
//todo set headers here for filename to be error
|
||||
let error_text = err.to_string();
|
||||
println!("error handling get file {}", error_text);
|
||||
cors_response(request, 500, &error_text)?;
|
||||
}
|
||||
}
|
||||
drop(board);
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
server
|
||||
.fn_handler("/file", Method::Delete, move |request| {
|
||||
let filename = query_param(request.uri(), "filename").unwrap();
|
||||
let copy = filename.clone();
|
||||
let mut board = BOARD_ACCESS.lock().unwrap();
|
||||
match board.board_hal.get_esp().delete_file(&filename) {
|
||||
Ok(_) => {
|
||||
let info = format!("Deleted file {copy}");
|
||||
cors_response(request, 200, &info)?;
|
||||
}
|
||||
Err(err) => {
|
||||
let info = format!("Could not delete file {copy} {err:?}");
|
||||
cors_response(request, 400, &info)?;
|
||||
}
|
||||
}
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/file", Method::Options, |request| {
|
||||
cors_response(request, 200, "")
|
||||
})
|
||||
.unwrap();
|
||||
unsafe { vTaskDelay(1) };
|
||||
server
|
||||
.fn_handler("/", Method::Get, move |request| {
|
||||
let mut response = request.into_ok_response()?;
|
||||
response.write(include_bytes!("index.html"))?;
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/favicon.ico", Method::Get, |request| {
|
||||
request
|
||||
.into_ok_response()?
|
||||
.write(include_bytes!("favicon.ico"))?;
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/bundle.js", Method::Get, |request| {
|
||||
request
|
||||
.into_ok_response()?
|
||||
.write(include_bytes!("bundle.js"))?;
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
.fn_handler("/timezones", Method::Get, move |request| {
|
||||
handle_error_to500(request, get_timezones)
|
||||
})
|
||||
.unwrap();
|
||||
server
|
||||
}
|
||||
|
||||
fn cors_response(
|
||||
request: Request<&mut EspHttpConnection>,
|
||||
status: u16,
|
||||
body: &str,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let headers = [
|
||||
("Access-Control-Allow-Origin", "*"),
|
||||
("Access-Control-Allow-Headers", "*"),
|
||||
("Access-Control-Allow-Methods", "*"),
|
||||
];
|
||||
let mut response = request.into_response(status, None, &headers)?;
|
||||
response.write(body.as_bytes())?;
|
||||
response.flush()?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
type AnyhowHandler =
|
||||
fn(&mut Request<&mut EspHttpConnection>) -> Result<Option<std::string::String>, anyhow::Error>;
|
||||
fn handle_error_to500(
|
||||
mut request: Request<&mut EspHttpConnection>,
|
||||
chain: AnyhowHandler,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let error = chain(&mut request);
|
||||
match error {
|
||||
Ok(answer) => match answer {
|
||||
Some(json) => {
|
||||
cors_response(request, 200, &json)?;
|
||||
}
|
||||
None => {
|
||||
cors_response(request, 200, "")?;
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
let error_text = err.to_string();
|
||||
println!("error handling process {}", error_text);
|
||||
cors_response(request, 500, &error_text)?;
|
||||
}
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
|
||||
fn read_up_to_bytes_from_request(
|
||||
request: &mut Request<&mut EspHttpConnection<'_>>,
|
||||
limit: Option<usize>,
|
||||
) -> Result<Vec<u8>, anyhow::Error> {
|
||||
let max_read = limit.unwrap_or(1024);
|
||||
let mut data_store = Vec::new();
|
||||
let mut total_read = 0;
|
||||
loop {
|
||||
let mut buf = [0_u8; 64];
|
||||
let read = request.read(&mut buf)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
let actual_data = &buf[0..read];
|
||||
total_read += read;
|
||||
if total_read > max_read {
|
||||
bail!("Request too large {total_read} > {max_read}");
|
||||
}
|
||||
data_store.push(actual_data.to_owned());
|
||||
}
|
||||
let allvec = data_store.concat();
|
||||
println!("Raw data {}", from_utf8(&allvec)?);
|
||||
Ok(allvec)
|
||||
}
|
2
rust/src_webpack/.gitignore
vendored
Normal file
2
rust/src_webpack/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
bundle.js
|
||||
index.html
|
1540
rust/src_webpack/package-lock.json
generated
1540
rust/src_webpack/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"devDependencies": {
|
||||
"compression-webpack-plugin": "^11.1.0",
|
||||
"html-webpack-harddisk-plugin": "^2.0.0",
|
||||
"html-webpack-plugin": "^5.6.3",
|
||||
"raw-loader": "^4.0.2",
|
||||
|
@@ -1,168 +1,192 @@
|
||||
export interface LogArray extends Array<LogEntry>{}
|
||||
|
||||
export interface LogEntry {
|
||||
timestamp: string,
|
||||
message_id: number,
|
||||
a: number,
|
||||
b: number,
|
||||
txt_short: string,
|
||||
txt_long: string
|
||||
export interface LogArray extends Array<LogEntry> {
|
||||
}
|
||||
|
||||
export interface LogLocalisation extends Array<LogLocalisationEntry>{}
|
||||
export interface LogEntry {
|
||||
timestamp: string,
|
||||
message_id: number,
|
||||
a: number,
|
||||
b: number,
|
||||
txt_short: string,
|
||||
txt_long: string
|
||||
}
|
||||
|
||||
export interface LogLocalisation extends Array<LogLocalisationEntry> {
|
||||
}
|
||||
|
||||
export interface LogLocalisationEntry {
|
||||
msg_type: string,
|
||||
message: string
|
||||
msg_type: string,
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface BackupHeader {
|
||||
timestamp: string,
|
||||
size: number
|
||||
timestamp: string,
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface NetworkConfig {
|
||||
ap_ssid: string,
|
||||
ssid: string,
|
||||
password: string,
|
||||
mqtt_url: string,
|
||||
base_topic: string,
|
||||
max_wait: number
|
||||
ap_ssid: string,
|
||||
ssid: string,
|
||||
password: string,
|
||||
mqtt_url: string,
|
||||
base_topic: string,
|
||||
mqtt_user: string | null,
|
||||
mqtt_password: string | null,
|
||||
max_wait: number
|
||||
}
|
||||
|
||||
export interface FileList {
|
||||
total: number,
|
||||
used: number,
|
||||
files: FileInfo[],
|
||||
file_system_corrupt: string,
|
||||
iter_error: string,
|
||||
total: number,
|
||||
used: number,
|
||||
files: FileInfo[],
|
||||
file_system_corrupt: string,
|
||||
iter_error: string,
|
||||
}
|
||||
|
||||
export interface FileInfo{
|
||||
filename: string,
|
||||
size: number,
|
||||
export interface SolarState {
|
||||
mppt_voltage: number,
|
||||
mppt_current: number,
|
||||
is_day: boolean
|
||||
}
|
||||
|
||||
export interface FileInfo {
|
||||
filename: string,
|
||||
size: number,
|
||||
}
|
||||
|
||||
export interface NightLampConfig {
|
||||
enabled: boolean,
|
||||
night_lamp_hour_start: number,
|
||||
night_lamp_hour_end: number,
|
||||
night_lamp_only_when_dark: boolean,
|
||||
low_soc_cutoff: number,
|
||||
low_soc_restore: number
|
||||
enabled: boolean,
|
||||
night_lamp_hour_start: number,
|
||||
night_lamp_hour_end: number,
|
||||
night_lamp_only_when_dark: boolean,
|
||||
low_soc_cutoff: number,
|
||||
low_soc_restore: number
|
||||
}
|
||||
|
||||
export interface NightLampCommand {
|
||||
active: boolean
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export interface TankConfig {
|
||||
tank_sensor_enabled: boolean,
|
||||
tank_allow_pumping_if_sensor_error: boolean,
|
||||
tank_useable_ml: number,
|
||||
tank_warn_percent: number,
|
||||
tank_empty_percent: number,
|
||||
tank_full_percent: number,
|
||||
tank_sensor_enabled: boolean,
|
||||
tank_allow_pumping_if_sensor_error: boolean,
|
||||
tank_useable_ml: number,
|
||||
tank_warn_percent: number,
|
||||
tank_empty_percent: number,
|
||||
tank_full_percent: number,
|
||||
ml_per_pulse: number
|
||||
}
|
||||
|
||||
|
||||
export enum BatteryBoardVersion {
|
||||
Disabled = "Disabled",
|
||||
BQ34Z100G1 = "BQ34Z100G1",
|
||||
WchI2cSlave = "WchI2cSlave"
|
||||
Disabled = "Disabled",
|
||||
BQ34Z100G1 = "BQ34Z100G1",
|
||||
WchI2cSlave = "WchI2cSlave"
|
||||
}
|
||||
export enum BoardVersion{
|
||||
|
||||
export enum BoardVersion {
|
||||
INITIAL = "INITIAL",
|
||||
V3 = "V3",
|
||||
V4 = "V4"
|
||||
}
|
||||
|
||||
export interface BoardHardware {
|
||||
board: BoardVersion,
|
||||
battery: BatteryBoardVersion,
|
||||
board: BoardVersion,
|
||||
battery: BatteryBoardVersion,
|
||||
}
|
||||
|
||||
export interface PlantControllerConfig {
|
||||
hardware: BoardHardware,
|
||||
hardware: BoardHardware,
|
||||
|
||||
network: NetworkConfig,
|
||||
tank: TankConfig,
|
||||
night_lamp: NightLampConfig,
|
||||
plants: PlantConfig[]
|
||||
timezone?: string,
|
||||
network: NetworkConfig,
|
||||
tank: TankConfig,
|
||||
night_lamp: NightLampConfig,
|
||||
plants: PlantConfig[]
|
||||
timezone?: string,
|
||||
}
|
||||
|
||||
export interface PlantConfig {
|
||||
mode: string,
|
||||
target_moisture: number,
|
||||
pump_time_s: number,
|
||||
pump_cooldown_min: number,
|
||||
pump_hour_start: number,
|
||||
pump_hour_end: number,
|
||||
sensor_a: boolean,
|
||||
sensor_b: boolean,
|
||||
max_consecutive_pump_count: number,
|
||||
moisture_sensor_min_frequency: number | null;
|
||||
moisture_sensor_max_frequency: number | null;
|
||||
|
||||
mode: string,
|
||||
target_moisture: number,
|
||||
min_moisture: number,
|
||||
pump_time_s: number,
|
||||
pump_cooldown_min: number,
|
||||
pump_hour_start: number,
|
||||
pump_hour_end: number,
|
||||
sensor_a: boolean,
|
||||
sensor_b: boolean,
|
||||
max_consecutive_pump_count: number,
|
||||
moisture_sensor_min_frequency: number | null;
|
||||
moisture_sensor_max_frequency: number | null;
|
||||
min_pump_current_ma: number,
|
||||
max_pump_current_ma: number,
|
||||
ignore_current_error: boolean,
|
||||
}
|
||||
|
||||
export interface PumpTestResult {
|
||||
median_current_ma: number,
|
||||
max_current_ma: number,
|
||||
min_current_ma: number,
|
||||
flow_value_ml: number,
|
||||
flow_value_count: number,
|
||||
pump_time_s: number,
|
||||
error: boolean,
|
||||
}
|
||||
|
||||
export interface SSIDList {
|
||||
ssids: [string]
|
||||
ssids: [string]
|
||||
}
|
||||
|
||||
export interface TestPump {
|
||||
pump: number
|
||||
pump: number
|
||||
}
|
||||
|
||||
export interface SetTime {
|
||||
time: string
|
||||
time: string
|
||||
}
|
||||
|
||||
export interface GetTime {
|
||||
rtc: string,
|
||||
native: string
|
||||
rtc: string,
|
||||
native: string
|
||||
}
|
||||
|
||||
export interface Moistures {
|
||||
moisture_a: [string],
|
||||
moisture_b: [string],
|
||||
moisture_a: [string],
|
||||
moisture_b: [string],
|
||||
}
|
||||
|
||||
export interface VersionInfo {
|
||||
git_hash: string,
|
||||
build_time: string,
|
||||
partition: string
|
||||
git_hash: string,
|
||||
build_time: string,
|
||||
partition: string
|
||||
}
|
||||
|
||||
export interface BatteryState {
|
||||
temperature: string
|
||||
voltage_milli_volt: string,
|
||||
current_milli_ampere: string,
|
||||
cycle_count: string,
|
||||
design_milli_ampere: string,
|
||||
remaining_milli_ampere: string,
|
||||
state_of_charge: string,
|
||||
state_of_health: string
|
||||
temperature: string
|
||||
voltage_milli_volt: string,
|
||||
current_milli_ampere: string,
|
||||
cycle_count: string,
|
||||
design_milli_ampere: string,
|
||||
remaining_milli_ampere: string,
|
||||
state_of_charge: string,
|
||||
state_of_health: string
|
||||
}
|
||||
|
||||
export interface TankInfo {
|
||||
/// is there enough water in the tank
|
||||
enough_water: boolean,
|
||||
/// warning that water needs to be refilled soon
|
||||
warn_level: boolean,
|
||||
/// estimation how many ml are still in tank
|
||||
left_ml: number | null,
|
||||
/// if there is was an issue with the water level sensor
|
||||
sensor_error: string | null,
|
||||
/// raw water sensor value
|
||||
raw: number | null,
|
||||
/// percent value
|
||||
percent: number | null,
|
||||
/// water in tank might be frozen
|
||||
water_frozen: boolean,
|
||||
/// water temperature
|
||||
water_temp: number | null,
|
||||
temp_sensor_error: string | null
|
||||
}
|
||||
/// is there enough water in the tank
|
||||
enough_water: boolean,
|
||||
/// warning that water needs to be refilled soon
|
||||
warn_level: boolean,
|
||||
/// estimation how many ml are still in tank
|
||||
left_ml: number | null,
|
||||
/// if there is was an issue with the water level sensor
|
||||
sensor_error: string | null,
|
||||
/// raw water sensor value
|
||||
raw: number | null,
|
||||
/// percent value
|
||||
percent: number | null,
|
||||
/// water in tank might be frozen
|
||||
water_frozen: boolean,
|
||||
/// water temperature
|
||||
water_temp: number | null,
|
||||
temp_sensor_error: string | null
|
||||
}
|
@@ -13,7 +13,7 @@
|
||||
<select class="boardvalue" id="hardware_board_value">
|
||||
</select>
|
||||
</div>
|
||||
<div class="flexcontainer" style="text-decoration-line: line-through;">
|
||||
<div class="flexcontainer">
|
||||
<div class="boardkey">BatteryMonitor</div>
|
||||
<select class="boardvalue" id="hardware_battery_value">
|
||||
</select>
|
||||
|
@@ -75,15 +75,15 @@
|
||||
.subcontainer {
|
||||
min-width: 300px;
|
||||
max-width: 900px;
|
||||
flex-grow: 1;
|
||||
border-style: solid;
|
||||
border-width: 1px;
|
||||
flex-grow: 1;
|
||||
border-style: solid;
|
||||
border-width: 1px;
|
||||
padding: 8px;
|
||||
}
|
||||
.subcontainercontainer{
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
|
||||
.plantcontainer {
|
||||
flex-grow: 1;
|
||||
min-width: 100%;
|
||||
@@ -120,15 +120,15 @@
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
.plantlist {
|
||||
display: flex;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
flex-grow: 1;
|
||||
text-align: center;
|
||||
flex-grow: 1;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@@ -149,6 +149,8 @@
|
||||
</div>
|
||||
<div id="batteryview" class="subcontainer">
|
||||
</div>
|
||||
<div id="solarview" class="subcontainer">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -72,8 +72,20 @@
|
||||
</div>
|
||||
<input class="mqttvalue" type="text" id="base_topic" placeholder="plants/one">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="mqttkey">
|
||||
MQTT User
|
||||
</div>
|
||||
<input class="mqttvalue" type="text" id="mqtt_user" placeholder="">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="mqttkey">
|
||||
MQTT Password
|
||||
</div>
|
||||
<input class="mqttvalue" type="text" id="mqtt_password" placeholder="">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
@@ -16,6 +16,8 @@ export class NetworkConfigView {
|
||||
private readonly mqtt_url: HTMLInputElement;
|
||||
private readonly base_topic: HTMLInputElement;
|
||||
private readonly max_wait: HTMLInputElement;
|
||||
private readonly mqtt_user: HTMLInputElement;
|
||||
private readonly mqtt_password: HTMLInputElement;
|
||||
private readonly ssidlist: HTMLElement;
|
||||
|
||||
constructor(controller: Controller, publicIp: string) {
|
||||
@@ -37,6 +39,10 @@ export class NetworkConfigView {
|
||||
this.mqtt_url.onchange = controller.configChanged
|
||||
this.base_topic = document.getElementById("base_topic") as HTMLInputElement;
|
||||
this.base_topic.onchange = controller.configChanged
|
||||
this.mqtt_user = document.getElementById("mqtt_user") as HTMLInputElement;
|
||||
this.mqtt_user.onchange = controller.configChanged
|
||||
this.mqtt_password = document.getElementById("mqtt_password") as HTMLInputElement;
|
||||
this.mqtt_password.onchange = controller.configChanged
|
||||
|
||||
this.ssidlist = document.getElementById("ssidlist") as HTMLElement
|
||||
|
||||
@@ -52,6 +58,8 @@ export class NetworkConfigView {
|
||||
this.password.value = network.password;
|
||||
this.mqtt_url.value = network.mqtt_url;
|
||||
this.base_topic.value = network.base_topic;
|
||||
this.mqtt_user.value = network.mqtt_user ?? "";
|
||||
this.mqtt_password.value = network.mqtt_password ?? "";
|
||||
this.max_wait.value = network.max_wait.toString();
|
||||
}
|
||||
|
||||
@@ -62,7 +70,9 @@ export class NetworkConfigView {
|
||||
ssid: this.ssid.value ?? null,
|
||||
password: this.password.value ?? null,
|
||||
mqtt_url: this.mqtt_url.value ?? null,
|
||||
mqtt_user: this.mqtt_user.value ? this.mqtt_user.value : null,
|
||||
mqtt_password: this.mqtt_password.value ? this.mqtt_password.value : null,
|
||||
base_topic: this.base_topic.value ?? null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -20,7 +20,7 @@
|
||||
<div class="lightkey">Test Nightlight</div>
|
||||
<input class="lightcheckbox" type="checkbox" id="night_lamp_test">
|
||||
</div>
|
||||
<div class="flexcontainer" style="text-decoration-line: line-through;">
|
||||
<div class="flexcontainer">
|
||||
<div class="lightkey">Enable Nightlight</div>
|
||||
<input class="lightcheckbox" type="checkbox" id="night_lamp_enabled">
|
||||
</div>
|
||||
|
@@ -29,7 +29,7 @@ export class OTAView {
|
||||
};
|
||||
|
||||
test.onclick = () => {
|
||||
controller.selftest();
|
||||
controller.selfTest();
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,76 +1,45 @@
|
||||
<style>
|
||||
.plantsensorkey{
|
||||
min-width: 100px;
|
||||
}
|
||||
.plantsensorvalue{
|
||||
flex-grow: 1;
|
||||
}
|
||||
.plantsensorkey {
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.plantkey{
|
||||
min-width: 175px;
|
||||
}
|
||||
.plantvalue{
|
||||
flex-grow: 1;
|
||||
}
|
||||
.plantcheckbox{
|
||||
min-width: 20px;
|
||||
margin: 0;
|
||||
}
|
||||
.plantsensorvalue {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.plantkey {
|
||||
min-width: 195px;
|
||||
}
|
||||
|
||||
.plantvalue {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.plantcheckbox {
|
||||
min-width: 20px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.plantTargetEnabledOnly_ ${plantId} {
|
||||
}
|
||||
|
||||
.plantPumpEnabledOnly_ ${plantId} {
|
||||
}
|
||||
|
||||
.plantSensorEnabledOnly_ ${plantId} {
|
||||
}
|
||||
|
||||
.plantHidden_ ${plantId} {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
<div>
|
||||
<div class="subtitle"
|
||||
id="plant_${plantId}_header">
|
||||
id="plant_${plantId}_header">
|
||||
Plant ${plantId}
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">
|
||||
Mode:
|
||||
</div>
|
||||
<select class="plantvalue" id="plant_${plantId}_mode">
|
||||
<option value="OFF">Off</option>
|
||||
<option value="TargetMoisture">Target</option>
|
||||
<option value="TimerOnly">Timer</option>
|
||||
</select>
|
||||
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Target Moisture:</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_target_moisture" type="number" min="0" max="100" placeholder="0">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Pump Time (s):</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_pump_time_s" type="number" min="0" max="600" placeholder="30">
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Pump Cooldown (m):</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_pump_cooldown_min" type="number" min="0" max="600" placeholder="30">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">"Pump Hour Start":</div>
|
||||
<select class="plantvalue" id="plant_${plantId}_pump_hour_start">10</select>
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">"Pump Hour End":</div>
|
||||
<select class="plantvalue" id="plant_${plantId}_pump_hour_end">19</select>
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Warn Pump Count:</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_max_consecutive_pump_count" type="number" min="1" max="50"
|
||||
placeholder="10">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Min Frequency Override</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_min_frequency" type="number" min="1000" max="25000">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Max Frequency Override</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_max_frequency" type="number" min="1000" max="25000" >
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">Sensor A installed:</div>
|
||||
<input class="plantcheckbox" id="plant_${plantId}_sensor_a" type="checkbox">
|
||||
@@ -79,21 +48,114 @@
|
||||
<div class="plantkey">Sensor B installed:</div>
|
||||
<input class="plantcheckbox" id="plant_${plantId}_sensor_b" type="checkbox">
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<div class="plantkey">
|
||||
Mode:
|
||||
</div>
|
||||
<select class="plantvalue" id="plant_${plantId}_mode">
|
||||
<option value="OFF">Off</option>
|
||||
<option value="TargetMoisture">Target</option>
|
||||
<option value="MinMoisture">Min Moisture</option>
|
||||
<option value="TimerOnly">Timer</option>
|
||||
</select>
|
||||
|
||||
</div>
|
||||
<div class="flexcontainer plantTargetEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Target Moisture:</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_target_moisture" type="number" min="0" max="100" placeholder="0">
|
||||
</div>
|
||||
<div class="flexcontainer plantMinEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Minimum Moisture:</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_min_moisture" type="number" min="0" max="100" placeholder="0">
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Pump Time (s):</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_pump_time_s" type="number" min="0" max="600" placeholder="30">
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Pump Cooldown (m):</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_pump_cooldown_min" type="number" min="0" max="600"
|
||||
placeholder="30">
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">"Pump Hour Start":</div>
|
||||
<select class="plantvalue" id="plant_${plantId}_pump_hour_start">10</select>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">"Pump Hour End":</div>
|
||||
<select class="plantvalue" id="plant_${plantId}_pump_hour_end">19</select>
|
||||
</div>
|
||||
<div class="flexcontainer plantTargetEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Warn Pump Count:</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_max_consecutive_pump_count" type="number" min="1" max="50"
|
||||
placeholder="10">
|
||||
</div>
|
||||
<div class="flexcontainer plantSensorEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Min Frequency Override</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_min_frequency" type="number" min="1000" max="25000">
|
||||
</div>
|
||||
<div class="flexcontainer plantSensorEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Max Frequency Override</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_max_frequency" type="number" min="1000" max="25000">
|
||||
</div>
|
||||
|
||||
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<h2 class="plantkey">Current config:</h2>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Min current</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_min_pump_current_ma" type="number" min="0" max="4500">
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Max current</div>
|
||||
<input class="plantvalue" id="plant_${plantId}_max_pump_current_ma" type="number" min="0" max="4500">
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantkey">Ignore current sensor error</div>
|
||||
<input class="plantcheckbox" id="plant_${plantId}_ignore_current_error" type="checkbox">
|
||||
</div>
|
||||
|
||||
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<button class="subtitle" id="plant_${plantId}_test">Test Pump</button>
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<div class="flexcontainer plantSensorEnabledOnly_${plantId}">
|
||||
<div class="subtitle">Live:</div>
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="flexcontainer plantSensorEnabledOnly_${plantId}">
|
||||
<span class="plantsensorkey">Sensor A:</span>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_moisture_a">loading</span>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_moisture_a">not measured</span>
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="flexcontainer plantSensorEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Sensor B:</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_moisture_b">loading</span>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_moisture_b">not measured</span>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Max Current</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_pump_test_current_max">not_tested</span>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Min Current</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_pump_test_current_min">not_tested</span>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Average</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_pump_test_current_average">not_tested</span>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Pump Time</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_pump_test_pump_time">not_tested</span>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Flow ml</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_pump_test_flow_ml">not_tested</span>
|
||||
</div>
|
||||
<div class="flexcontainer plantPumpEnabledOnly_${plantId}">
|
||||
<div class="plantsensorkey">Flow raw</div>
|
||||
<span class="plantsensorvalue" id="plant_${plantId}_pump_test_flow_raw">not_tested</span>
|
||||
</div>
|
||||
|
||||
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import {PlantConfig} from "./api";
|
||||
import {PlantConfig, PumpTestResult} from "./api";
|
||||
|
||||
const PLANT_COUNT = 8;
|
||||
|
||||
@@ -9,39 +9,47 @@ export class PlantViews {
|
||||
private readonly measure_moisture: HTMLButtonElement;
|
||||
private readonly plants: PlantView[] = []
|
||||
private readonly plantsDiv: HTMLDivElement
|
||||
|
||||
constructor(syncConfig:Controller) {
|
||||
this.measure_moisture = document.getElementById("measure_moisture") as HTMLButtonElement
|
||||
this.measure_moisture.onclick = syncConfig.measure_moisture
|
||||
this.plantsDiv = document.getElementById("plants") as HTMLDivElement;
|
||||
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
|
||||
this.plants[plantId] = new PlantView(plantId, this.plantsDiv, syncConfig);
|
||||
}
|
||||
|
||||
constructor(syncConfig: Controller) {
|
||||
this.measure_moisture = document.getElementById("measure_moisture") as HTMLButtonElement
|
||||
this.measure_moisture.onclick = syncConfig.measure_moisture
|
||||
this.plantsDiv = document.getElementById("plants") as HTMLDivElement;
|
||||
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
|
||||
this.plants[plantId] = new PlantView(plantId, this.plantsDiv, syncConfig);
|
||||
}
|
||||
}
|
||||
|
||||
getConfig(): PlantConfig[] {
|
||||
const rv: PlantConfig[] = [];
|
||||
for (let i = 0; i < PLANT_COUNT; i++) {
|
||||
rv[i] = this.plants[i].getConfig();
|
||||
}
|
||||
return rv
|
||||
const rv: PlantConfig[] = [];
|
||||
for (let i = 0; i < PLANT_COUNT; i++) {
|
||||
rv[i] = this.plants[i].getConfig();
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
update(moisture_a: [string], moisture_b: [string]) {
|
||||
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
|
||||
const a = moisture_a[plantId]
|
||||
const b = moisture_b[plantId]
|
||||
this.plants[plantId].update(a,b)
|
||||
}
|
||||
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
|
||||
const a = moisture_a[plantId]
|
||||
const b = moisture_b[plantId]
|
||||
this.plants[plantId].setMeasurementResult(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
setConfig(plants: PlantConfig[]) {
|
||||
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
|
||||
const plantConfig = plants[plantId];
|
||||
const plantView = this.plants[plantId];
|
||||
plantView.setConfig(plantConfig)
|
||||
}
|
||||
for (let plantId = 0; plantId < PLANT_COUNT; plantId++) {
|
||||
const plantConfig = plants[plantId];
|
||||
const plantView = this.plants[plantId];
|
||||
plantView.setConfig(plantConfig)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setPumpTestCurrent(plantId: number, response: PumpTestResult) {
|
||||
const plantView = this.plants[plantId];
|
||||
plantView.setTestResult(response)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
export class PlantView {
|
||||
private readonly moistureSensorMinFrequency: HTMLInputElement;
|
||||
@@ -51,6 +59,7 @@ export class PlantView {
|
||||
private readonly header: HTMLElement;
|
||||
private readonly testButton: HTMLButtonElement;
|
||||
private readonly targetMoisture: HTMLInputElement;
|
||||
private readonly minMoisture: HTMLInputElement;
|
||||
private readonly pumpTimeS: HTMLInputElement;
|
||||
private readonly pumpCooldown: HTMLInputElement;
|
||||
private readonly pumpHourStart: HTMLSelectElement;
|
||||
@@ -61,111 +70,208 @@ export class PlantView {
|
||||
private readonly moistureA: HTMLElement;
|
||||
private readonly moistureB: HTMLElement;
|
||||
private readonly maxConsecutivePumpCount: HTMLInputElement;
|
||||
|
||||
|
||||
constructor(plantId: number, parent:HTMLDivElement, controller:Controller) {
|
||||
private readonly minPumpCurrentMa: HTMLInputElement;
|
||||
private readonly maxPumpCurrentMa: HTMLInputElement;
|
||||
private readonly ignoreCurrentError: HTMLInputElement;
|
||||
|
||||
private readonly pump_test_current_max: HTMLElement;
|
||||
private readonly pump_test_current_min: HTMLElement;
|
||||
private readonly pump_test_current_average: HTMLElement;
|
||||
private readonly pump_test_pump_time: HTMLElement;
|
||||
private readonly pump_test_flow_ml: HTMLElement;
|
||||
private readonly pump_test_flow_raw: HTMLElement;
|
||||
|
||||
|
||||
constructor(plantId: number, parent: HTMLDivElement, controller: Controller) {
|
||||
this.plantId = plantId;
|
||||
this.plantDiv = document.createElement("div")! as HTMLDivElement
|
||||
const template = require('./plant.html') as string;
|
||||
this.plantDiv = document.createElement("div")! as HTMLDivElement
|
||||
const template = require('./plant.html') as string;
|
||||
this.plantDiv.innerHTML = template.replaceAll("${plantId}", String(plantId))
|
||||
|
||||
this.plantDiv.classList.add("plantcontainer")
|
||||
parent.appendChild(this.plantDiv)
|
||||
|
||||
this.header = document.getElementById("plant_"+plantId+"_header")!
|
||||
this.header.innerText = "Plant "+ (this.plantId+1)
|
||||
|
||||
this.moistureA = document.getElementById("plant_"+plantId+"_moisture_a")! as HTMLElement;
|
||||
this.moistureB = document.getElementById("plant_"+plantId+"_moisture_b")! as HTMLElement;
|
||||
|
||||
this.testButton = document.getElementById("plant_"+plantId+"_test")! as HTMLButtonElement;
|
||||
this.testButton.onclick = function(){
|
||||
controller.testPlant(plantId)
|
||||
}
|
||||
this.plantDiv.classList.add("plantcontainer")
|
||||
parent.appendChild(this.plantDiv)
|
||||
|
||||
this.mode = document.getElementById("plant_"+plantId+"_mode") as HTMLSelectElement
|
||||
this.mode.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
this.header = document.getElementById("plant_" + plantId + "_header")!
|
||||
this.header.innerText = "Plant " + (this.plantId + 1)
|
||||
|
||||
this.targetMoisture = document.getElementById("plant_"+plantId+"_target_moisture")! as HTMLInputElement;
|
||||
this.targetMoisture.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
this.moistureA = document.getElementById("plant_" + plantId + "_moisture_a")! as HTMLElement;
|
||||
this.moistureB = document.getElementById("plant_" + plantId + "_moisture_b")! as HTMLElement;
|
||||
|
||||
this.pumpTimeS = document.getElementById("plant_"+plantId+"_pump_time_s") as HTMLInputElement;
|
||||
this.pumpTimeS.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
this.pump_test_current_max = document.getElementById("plant_" + plantId + "_pump_test_current_max")! as HTMLElement;
|
||||
this.pump_test_current_min = document.getElementById("plant_" + plantId + "_pump_test_current_min")! as HTMLElement;
|
||||
this.pump_test_current_average = document.getElementById("plant_" + plantId + "_pump_test_current_average")! as HTMLElement;
|
||||
this.pump_test_pump_time = document.getElementById("plant_" + plantId + "_pump_test_pump_time")! as HTMLElement;
|
||||
this.pump_test_flow_ml = document.getElementById("plant_" + plantId + "_pump_test_flow_ml")! as HTMLElement;
|
||||
this.pump_test_flow_raw = document.getElementById("plant_" + plantId + "_pump_test_flow_raw")! as HTMLElement;
|
||||
|
||||
this.pumpCooldown = document.getElementById("plant_"+plantId+"_pump_cooldown_min") as HTMLInputElement;
|
||||
this.pumpCooldown.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.pumpHourStart = document.getElementById("plant_"+plantId+"_pump_hour_start") as HTMLSelectElement;
|
||||
this.pumpHourStart.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
for (let i = 0; i < 24; i++) {
|
||||
let option = document.createElement("option");
|
||||
if (i == 10){
|
||||
option.selected = true
|
||||
this.testButton = document.getElementById("plant_" + plantId + "_test")! as HTMLButtonElement;
|
||||
this.testButton.onclick = function () {
|
||||
controller.testPlant(plantId)
|
||||
}
|
||||
option.innerText = i.toString();
|
||||
this.pumpHourStart.appendChild(option);
|
||||
}
|
||||
|
||||
this.pumpHourEnd = document.getElementById("plant_"+plantId+"_pump_hour_end") as HTMLSelectElement;
|
||||
this.pumpHourEnd.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
for (let i = 0; i < 24; i++) {
|
||||
let option = document.createElement("option");
|
||||
if (i == 19){
|
||||
option.selected = true
|
||||
this.mode = document.getElementById("plant_" + plantId + "_mode") as HTMLSelectElement
|
||||
this.mode.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
option.innerText = i.toString();
|
||||
this.pumpHourEnd.appendChild(option);
|
||||
}
|
||||
|
||||
this.sensorAInstalled = document.getElementById("plant_"+plantId+"_sensor_a") as HTMLInputElement;
|
||||
this.sensorAInstalled.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
this.targetMoisture = document.getElementById("plant_" + plantId + "_target_moisture")! as HTMLInputElement;
|
||||
this.targetMoisture.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.sensorBInstalled = document.getElementById("plant_"+plantId+"_sensor_b") as HTMLInputElement;
|
||||
this.sensorBInstalled.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
this.minMoisture = document.getElementById("plant_" + plantId + "_min_moisture")! as HTMLInputElement;
|
||||
this.minMoisture.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.maxConsecutivePumpCount = document.getElementById("plant_"+plantId+"_max_consecutive_pump_count") as HTMLInputElement;
|
||||
this.maxConsecutivePumpCount.onchange = function(){
|
||||
controller.configChanged()
|
||||
}
|
||||
this.pumpTimeS = document.getElementById("plant_" + plantId + "_pump_time_s") as HTMLInputElement;
|
||||
this.pumpTimeS.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.moistureSensorMinFrequency = document.getElementById("plant_"+plantId+"_min_frequency") as HTMLInputElement;
|
||||
this.moistureSensorMinFrequency.onchange = function(){
|
||||
this.pumpCooldown = document.getElementById("plant_" + plantId + "_pump_cooldown_min") as HTMLInputElement;
|
||||
this.pumpCooldown.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.pumpHourStart = document.getElementById("plant_" + plantId + "_pump_hour_start") as HTMLSelectElement;
|
||||
this.pumpHourStart.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
for (let i = 0; i < 24; i++) {
|
||||
let option = document.createElement("option");
|
||||
if (i == 10) {
|
||||
option.selected = true
|
||||
}
|
||||
option.innerText = i.toString();
|
||||
this.pumpHourStart.appendChild(option);
|
||||
}
|
||||
|
||||
this.pumpHourEnd = document.getElementById("plant_" + plantId + "_pump_hour_end") as HTMLSelectElement;
|
||||
this.pumpHourEnd.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
for (let i = 0; i < 24; i++) {
|
||||
let option = document.createElement("option");
|
||||
if (i == 19) {
|
||||
option.selected = true
|
||||
}
|
||||
option.innerText = i.toString();
|
||||
this.pumpHourEnd.appendChild(option);
|
||||
}
|
||||
|
||||
this.sensorAInstalled = document.getElementById("plant_" + plantId + "_sensor_a") as HTMLInputElement;
|
||||
this.sensorAInstalled.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.sensorBInstalled = document.getElementById("plant_" + plantId + "_sensor_b") as HTMLInputElement;
|
||||
this.sensorBInstalled.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.minPumpCurrentMa = document.getElementById("plant_" + plantId + "_min_pump_current_ma") as HTMLInputElement;
|
||||
this.minPumpCurrentMa.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.maxPumpCurrentMa = document.getElementById("plant_" + plantId + "_max_pump_current_ma") as HTMLInputElement;
|
||||
this.maxPumpCurrentMa.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.ignoreCurrentError = document.getElementById("plant_" + plantId + "_ignore_current_error") as HTMLInputElement;
|
||||
this.ignoreCurrentError.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
|
||||
this.maxConsecutivePumpCount = document.getElementById("plant_" + plantId + "_max_consecutive_pump_count") as HTMLInputElement;
|
||||
this.maxConsecutivePumpCount.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
|
||||
this.moistureSensorMinFrequency = document.getElementById("plant_" + plantId + "_min_frequency") as HTMLInputElement;
|
||||
this.moistureSensorMinFrequency.onchange = function () {
|
||||
controller.configChanged()
|
||||
}
|
||||
this.moistureSensorMinFrequency.onchange = () => {
|
||||
controller.configChanged();
|
||||
};
|
||||
|
||||
this.moistureSensorMaxFrequency = document.getElementById("plant_"+plantId+"_max_frequency") as HTMLInputElement;
|
||||
this.moistureSensorMaxFrequency = document.getElementById("plant_" + plantId + "_max_frequency") as HTMLInputElement;
|
||||
this.moistureSensorMaxFrequency.onchange = () => {
|
||||
controller.configChanged();
|
||||
};
|
||||
}
|
||||
|
||||
update(a: string, b: string) {
|
||||
updateVisibility(plantConfig: PlantConfig) {
|
||||
let sensorOnly = document.getElementsByClassName("plantSensorEnabledOnly_"+ this.plantId)
|
||||
let pumpOnly = document.getElementsByClassName("plantPumpEnabledOnly_"+ this.plantId)
|
||||
let targetOnly = document.getElementsByClassName("plantTargetEnabledOnly_"+ this.plantId)
|
||||
let minOnly = document.getElementsByClassName("plantMinEnabledOnly_"+ this.plantId)
|
||||
|
||||
console.log("updateVisibility plantConfig: " + plantConfig.mode)
|
||||
let showSensor = plantConfig.sensor_a || plantConfig.sensor_b
|
||||
let showPump = plantConfig.mode !== "OFF"
|
||||
let showTarget = plantConfig.mode === "TargetMoisture"
|
||||
let showMin = plantConfig.mode === "MinMoisture"
|
||||
|
||||
console.log("updateVisibility showsensor: " + showSensor + " pump " + showPump + " target " +showTarget + " min " + showMin)
|
||||
|
||||
for (const element of Array.from(sensorOnly)) {
|
||||
if (showSensor) {
|
||||
element.classList.remove("plantHidden_" + this.plantId)
|
||||
} else {
|
||||
element.classList.add("plantHidden_" + this.plantId)
|
||||
}
|
||||
}
|
||||
|
||||
for (const element of Array.from(pumpOnly)) {
|
||||
if (showPump) {
|
||||
element.classList.remove("plantHidden_" + this.plantId)
|
||||
} else {
|
||||
element.classList.add("plantHidden_" + this.plantId)
|
||||
}
|
||||
}
|
||||
|
||||
for (const element of Array.from(targetOnly)) {
|
||||
if (showTarget) {
|
||||
element.classList.remove("plantHidden_" + this.plantId)
|
||||
} else {
|
||||
element.classList.add("plantHidden_" + this.plantId)
|
||||
}
|
||||
}
|
||||
|
||||
for (const element of Array.from(minOnly)) {
|
||||
if (showMin) {
|
||||
element.classList.remove("plantHidden_" + this.plantId)
|
||||
} else {
|
||||
element.classList.add("plantHidden_" + this.plantId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setTestResult(result: PumpTestResult) {
|
||||
this.pump_test_current_max.innerText = result.max_current_ma.toString()
|
||||
this.pump_test_current_min.innerText = result.min_current_ma.toString()
|
||||
this.pump_test_current_average.innerText = result.median_current_ma.toString()
|
||||
|
||||
this.pump_test_flow_raw.innerText = result.flow_value_count.toString()
|
||||
this.pump_test_flow_ml.innerText = result.flow_value_ml.toString()
|
||||
|
||||
this.pump_test_pump_time.innerText = result.pump_time_s.toString()
|
||||
}
|
||||
|
||||
setMeasurementResult(a: string, b: string) {
|
||||
this.moistureA.innerText = a
|
||||
this.moistureB.innerText = b
|
||||
}
|
||||
|
||||
|
||||
setConfig(plantConfig: PlantConfig) {
|
||||
this.mode.value = plantConfig.mode;
|
||||
this.targetMoisture.value = plantConfig.target_moisture.toString();
|
||||
this.minMoisture.value = plantConfig.min_moisture?.toString() || "";
|
||||
this.pumpTimeS.value = plantConfig.pump_time_s.toString();
|
||||
this.pumpCooldown.value = plantConfig.pump_cooldown_min.toString();
|
||||
this.pumpHourStart.value = plantConfig.pump_hour_start.toString();
|
||||
@@ -173,18 +279,25 @@ export class PlantView {
|
||||
this.sensorBInstalled.checked = plantConfig.sensor_b;
|
||||
this.sensorAInstalled.checked = plantConfig.sensor_a;
|
||||
this.maxConsecutivePumpCount.value = plantConfig.max_consecutive_pump_count.toString();
|
||||
this.minPumpCurrentMa.value = plantConfig.min_pump_current_ma.toString();
|
||||
this.maxPumpCurrentMa.value = plantConfig.max_pump_current_ma.toString();
|
||||
this.ignoreCurrentError.checked = plantConfig.ignore_current_error;
|
||||
|
||||
// Set new fields
|
||||
this.moistureSensorMinFrequency.value =
|
||||
plantConfig.moisture_sensor_min_frequency?.toString() || "";
|
||||
this.moistureSensorMaxFrequency.value =
|
||||
plantConfig.moisture_sensor_max_frequency?.toString() || "";
|
||||
|
||||
this.updateVisibility(plantConfig);
|
||||
}
|
||||
|
||||
getConfig(): PlantConfig {
|
||||
return {
|
||||
|
||||
let conv: PlantConfig = {
|
||||
mode: this.mode.value,
|
||||
target_moisture: this.targetMoisture.valueAsNumber,
|
||||
min_moisture: this.minMoisture.valueAsNumber,
|
||||
pump_time_s: this.pumpTimeS.valueAsNumber,
|
||||
pump_cooldown_min: this.pumpCooldown.valueAsNumber,
|
||||
pump_hour_start: +this.pumpHourStart.value,
|
||||
@@ -193,7 +306,12 @@ export class PlantView {
|
||||
sensor_a: this.sensorAInstalled.checked,
|
||||
max_consecutive_pump_count: this.maxConsecutivePumpCount.valueAsNumber,
|
||||
moisture_sensor_min_frequency: this.moistureSensorMinFrequency.valueAsNumber || null,
|
||||
moisture_sensor_max_frequency: this.moistureSensorMaxFrequency.valueAsNumber || null
|
||||
moisture_sensor_max_frequency: this.moistureSensorMaxFrequency.valueAsNumber || null,
|
||||
min_pump_current_ma: this.minPumpCurrentMa.valueAsNumber,
|
||||
max_pump_current_ma: this.maxPumpCurrentMa.valueAsNumber,
|
||||
ignore_current_error: this.ignoreCurrentError.checked,
|
||||
};
|
||||
this.updateVisibility(conv);
|
||||
return conv;
|
||||
}
|
||||
}
|
||||
}
|
29
rust/src_webpack/src/solarview.html
Normal file
29
rust/src_webpack/src/solarview.html
Normal file
@@ -0,0 +1,29 @@
|
||||
<style>
|
||||
.solarflexkey {
|
||||
min-width: 150px;
|
||||
}
|
||||
.solarflexvalue {
|
||||
text-wrap: nowrap;
|
||||
flex-grow: 1;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<div class="subtitle">
|
||||
Mppt:
|
||||
</div>
|
||||
<input id="solar_auto_refresh" type="checkbox">⟳
|
||||
</div>
|
||||
|
||||
<div class="flexcontainer">
|
||||
<span class="solarflexkey">Mppt mV:</span>
|
||||
<span class="solarflexvalue" id="solar_voltage_milli_volt"></span>
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<span class="solarflexkey">Mppt mA:</span>
|
||||
<span class="solarflexvalue" id="solar_current_milli_ampere" ></span>
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<span class="solarflexkey">is Day:</span>
|
||||
<span class="solarflexvalue" id="solar_is_day" ></span>
|
||||
</div>
|
49
rust/src_webpack/src/solarview.ts
Normal file
49
rust/src_webpack/src/solarview.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Controller } from "./main";
|
||||
import {BatteryState, SolarState} from "./api";
|
||||
|
||||
export class SolarView{
|
||||
solar_voltage_milli_volt: HTMLSpanElement;
|
||||
solar_current_milli_ampere: HTMLSpanElement;
|
||||
solar_is_day: HTMLSpanElement;
|
||||
solar_auto_refresh: HTMLInputElement;
|
||||
timer: NodeJS.Timeout | undefined;
|
||||
controller: Controller;
|
||||
|
||||
constructor (controller:Controller) {
|
||||
(document.getElementById("solarview") as HTMLElement).innerHTML = require("./solarview.html")
|
||||
this.solar_voltage_milli_volt = document.getElementById("solar_voltage_milli_volt") as HTMLSpanElement;
|
||||
this.solar_current_milli_ampere = document.getElementById("solar_current_milli_ampere") as HTMLSpanElement;
|
||||
this.solar_is_day = document.getElementById("solar_is_day") as HTMLSpanElement;
|
||||
this.solar_auto_refresh = document.getElementById("solar_auto_refresh") as HTMLInputElement;
|
||||
|
||||
this.controller = controller
|
||||
this.solar_auto_refresh.onchange = () => {
|
||||
if(this.timer){
|
||||
clearTimeout(this.timer)
|
||||
}
|
||||
if(this.solar_auto_refresh.checked){
|
||||
controller.updateSolarData()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
update(solarState: SolarState|null){
|
||||
if (solarState == null) {
|
||||
this.solar_voltage_milli_volt.innerText = "N/A"
|
||||
this.solar_current_milli_ampere.innerText = "N/A"
|
||||
this.solar_is_day.innerText = "N/A"
|
||||
} else {
|
||||
this.solar_voltage_milli_volt.innerText = solarState.mppt_voltage.toFixed(0)
|
||||
this.solar_current_milli_ampere.innerText = solarState.mppt_current.toFixed(0)
|
||||
this.solar_is_day.innerText = solarState.is_day?"🌞":"🌙"
|
||||
}
|
||||
|
||||
if(this.solar_auto_refresh.checked){
|
||||
this.timer = setTimeout(this.controller.updateSolarData, 1000);
|
||||
} else {
|
||||
if(this.timer){
|
||||
clearTimeout(this.timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,61 +1,65 @@
|
||||
import { Controller } from "./main";
|
||||
import {Controller} from "./main";
|
||||
import {BackupHeader} from "./api";
|
||||
|
||||
export class SubmitView {
|
||||
json: HTMLDivElement;
|
||||
submitFormBtn: HTMLButtonElement;
|
||||
submit_status: HTMLElement;
|
||||
backupBtn: HTMLButtonElement;
|
||||
restoreBackupBtn: HTMLButtonElement;
|
||||
backuptimestamp: HTMLElement;
|
||||
backupsize: HTMLElement;
|
||||
backupjson: HTMLElement;
|
||||
json: HTMLDivElement;
|
||||
submitFormBtn: HTMLButtonElement;
|
||||
submit_status: HTMLElement;
|
||||
backupBtn: HTMLButtonElement;
|
||||
restoreBackupBtn: HTMLButtonElement;
|
||||
backuptimestamp: HTMLElement;
|
||||
backupsize: HTMLElement;
|
||||
backupjson: HTMLElement;
|
||||
|
||||
constructor(controller: Controller) {
|
||||
(document.getElementById("submitview") as HTMLElement).innerHTML = require("./submitview.html")
|
||||
constructor(controller: Controller) {
|
||||
(document.getElementById("submitview") as HTMLElement).innerHTML = require("./submitview.html")
|
||||
|
||||
let showJson = document.getElementById('showJson') as HTMLButtonElement
|
||||
let rawdata = document.getElementById('rawdata') as HTMLElement
|
||||
this.json = document.getElementById('json') as HTMLDivElement
|
||||
this.backupjson = document.getElementById('backupjson') as HTMLDivElement
|
||||
this.submitFormBtn = document.getElementById("submit") as HTMLButtonElement
|
||||
this.backupBtn = document.getElementById("backup") as HTMLButtonElement
|
||||
this.restoreBackupBtn = document.getElementById("restorebackup") as HTMLButtonElement
|
||||
this.backuptimestamp = document.getElementById("backuptimestamp") as HTMLElement
|
||||
this.backupsize = document.getElementById("backupsize") as HTMLElement
|
||||
this.submit_status = document.getElementById("submit_status") as HTMLElement
|
||||
this.submitFormBtn.onclick = () => {
|
||||
controller.uploadConfig(this.json.textContent as string, (status: string) => {
|
||||
this.submit_status.innerHTML = status;
|
||||
});
|
||||
let showJson = document.getElementById('showJson') as HTMLButtonElement
|
||||
let rawdata = document.getElementById('rawdata') as HTMLElement
|
||||
this.json = document.getElementById('json') as HTMLDivElement
|
||||
this.backupjson = document.getElementById('backupjson') as HTMLDivElement
|
||||
this.submitFormBtn = document.getElementById("submit") as HTMLButtonElement
|
||||
this.backupBtn = document.getElementById("backup") as HTMLButtonElement
|
||||
this.restoreBackupBtn = document.getElementById("restorebackup") as HTMLButtonElement
|
||||
this.backuptimestamp = document.getElementById("backuptimestamp") as HTMLElement
|
||||
this.backupsize = document.getElementById("backupsize") as HTMLElement
|
||||
this.submit_status = document.getElementById("submit_status") as HTMLElement
|
||||
this.submitFormBtn.onclick = () => {
|
||||
controller.uploadConfig(this.json.textContent as string, (status: string) => {
|
||||
this.submit_status.innerHTML = status;
|
||||
});
|
||||
}
|
||||
this.backupBtn.onclick = () => {
|
||||
controller.progressview.addIndeterminate("backup", "Backup to EEPROM running")
|
||||
controller.backupConfig(this.json.textContent as string).then(saveStatus => {
|
||||
controller.getBackupInfo().then(r => {
|
||||
controller.progressview.removeProgress("backup")
|
||||
this.submit_status.innerHTML = saveStatus;
|
||||
});
|
||||
});
|
||||
}
|
||||
this.restoreBackupBtn.onclick = () => {
|
||||
controller.getBackupConfig();
|
||||
}
|
||||
showJson.onclick = () => {
|
||||
if (rawdata.style.display == "none") {
|
||||
rawdata.style.display = "flex";
|
||||
} else {
|
||||
rawdata.style.display = "none";
|
||||
}
|
||||
}
|
||||
}
|
||||
this.backupBtn.onclick = () => {
|
||||
controller.backupConfig(this.json.textContent as string, (status: string) => {
|
||||
this.submit_status.innerHTML = status;
|
||||
});
|
||||
}
|
||||
this.restoreBackupBtn.onclick = () => {
|
||||
controller.getBackupConfig();
|
||||
}
|
||||
showJson.onclick = () => {
|
||||
if (rawdata.style.display == "none"){
|
||||
rawdata.style.display = "flex";
|
||||
} else {
|
||||
rawdata.style.display = "none";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setBackupInfo(header: BackupHeader) {
|
||||
this.backuptimestamp.innerText = header.timestamp
|
||||
this.backupsize.innerText = header.size.toString()
|
||||
}
|
||||
setBackupInfo(header: BackupHeader) {
|
||||
this.backuptimestamp.innerText = header.timestamp
|
||||
this.backupsize.innerText = header.size.toString()
|
||||
}
|
||||
|
||||
setJson(pretty: string) {
|
||||
this.json.textContent = pretty
|
||||
}
|
||||
setJson(pretty: string) {
|
||||
this.json.textContent = pretty
|
||||
}
|
||||
|
||||
setBackupJson(pretty: string) {
|
||||
this.backupjson.textContent = pretty
|
||||
}
|
||||
setBackupJson(pretty: string) {
|
||||
this.backupjson.textContent = pretty
|
||||
}
|
||||
}
|
@@ -7,14 +7,31 @@
|
||||
word-wrap: break-word;
|
||||
overflow: scroll;
|
||||
}
|
||||
.submitbutton{
|
||||
padding: 1em 1em;
|
||||
background: #667eea;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1.1em;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
letter-spacing: 1px;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.submitbutton:hover {
|
||||
background: #1c4e63;
|
||||
}
|
||||
</style>
|
||||
<button class="submitbutton" id="submit">Submit</button>
|
||||
<br>
|
||||
<button id="showJson">Show Json</button>
|
||||
<div id="rawdata" class="flexcontainer" style="display: none;">
|
||||
<div class="submitarea" id="json" contenteditable="true"></div>
|
||||
<div class="submitarea" id="backupjson">backup will be here</div>
|
||||
</div>
|
||||
<button id="submit">Submit</button>
|
||||
<div>BackupStatus:</div>
|
||||
<div id="backuptimestamp"></div>
|
||||
<div id="backupsize"></div>
|
||||
|
@@ -48,6 +48,10 @@
|
||||
<div class="tankkey">Full at %</div>
|
||||
<input class="tankvalue" type="number" min="0" max="100" id="tank_full_percent">
|
||||
</div>
|
||||
<div class="flexcontainer">
|
||||
<div class="tankkey">Flow Sensor ml per pulse</div>
|
||||
<input class="tankvalue" type="number" min="0" max="1000" step="0.01" id="ml_per_pulse">
|
||||
</div>
|
||||
<button id="tank_update">Update Tank</button>
|
||||
|
||||
|
||||
@@ -82,4 +86,4 @@
|
||||
<div class="flexcontainer">
|
||||
<div class="tankkey">Warn Level</div>
|
||||
<label class="tankvalue" id="tank_measure_warnlevel"></label>
|
||||
</div>
|
||||
</div>
|
@@ -8,6 +8,7 @@ export class TankConfigView {
|
||||
private readonly tank_warn_percent: HTMLInputElement;
|
||||
private readonly tank_sensor_enabled: HTMLInputElement;
|
||||
private readonly tank_allow_pumping_if_sensor_error: HTMLInputElement;
|
||||
private readonly ml_per_pulse: HTMLInputElement;
|
||||
private readonly tank_measure_error: HTMLLabelElement;
|
||||
private readonly tank_measure_ml: HTMLLabelElement;
|
||||
private readonly tank_measure_percent: HTMLLabelElement;
|
||||
@@ -54,6 +55,8 @@ export class TankConfigView {
|
||||
this.tank_sensor_enabled.onchange = controller.configChanged
|
||||
this.tank_allow_pumping_if_sensor_error = document.getElementById("tank_allow_pumping_if_sensor_error") as HTMLInputElement;
|
||||
this.tank_allow_pumping_if_sensor_error.onchange = controller.configChanged
|
||||
this.ml_per_pulse = document.getElementById("ml_per_pulse") as HTMLInputElement;
|
||||
this.ml_per_pulse.onchange = controller.configChanged
|
||||
|
||||
let tank_update = document.getElementById("tank_update") as HTMLInputElement;
|
||||
tank_update.onclick = () => {
|
||||
@@ -141,6 +144,7 @@ export class TankConfigView {
|
||||
this.tank_full_percent.value = String(tank.tank_full_percent)
|
||||
this.tank_sensor_enabled.checked = tank.tank_sensor_enabled
|
||||
this.tank_useable_ml.value = String(tank.tank_useable_ml)
|
||||
this.ml_per_pulse.value = String(tank.ml_per_pulse)
|
||||
}
|
||||
getConfig(): TankConfig {
|
||||
return {
|
||||
@@ -149,7 +153,8 @@ export class TankConfigView {
|
||||
tank_full_percent: this.tank_full_percent.valueAsNumber,
|
||||
tank_sensor_enabled: this.tank_sensor_enabled.checked,
|
||||
tank_useable_ml: this.tank_useable_ml.valueAsNumber,
|
||||
tank_warn_percent: this.tank_warn_percent.valueAsNumber
|
||||
tank_warn_percent: this.tank_warn_percent.valueAsNumber,
|
||||
ml_per_pulse: this.ml_per_pulse.valueAsNumber
|
||||
}
|
||||
}
|
||||
}
|
@@ -3,54 +3,60 @@ const path = require('path');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
|
||||
const CopyPlugin = require("copy-webpack-plugin");
|
||||
const CompressionPlugin = require("compression-webpack-plugin");
|
||||
|
||||
const isDevServer = process.env.WEBPACK_SERVE;
|
||||
console.log("Dev server is " + isDevServer);
|
||||
var host;
|
||||
if (isDevServer){
|
||||
//ensure no trailing /
|
||||
host = 'http://192.168.71.1';
|
||||
if (isDevServer) {
|
||||
//ensure no trailing /
|
||||
host = 'http://10.23.44.186';
|
||||
} else {
|
||||
host = '';
|
||||
host = '';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
mode: "development",
|
||||
entry: ['./src/main.ts'],
|
||||
devtool: 'inline-source-map',
|
||||
plugins: [
|
||||
new webpack.DefinePlugin({
|
||||
PUBLIC_URL: JSON.stringify(host),
|
||||
}),
|
||||
new webpack.EnvironmentPlugin({
|
||||
redirect: 'true'
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
alwaysWriteToDisk: true,
|
||||
title: "PlantCtrl",
|
||||
}),
|
||||
new HtmlWebpackHarddiskPlugin(),
|
||||
],
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.html$/,
|
||||
type: 'asset/source',
|
||||
},
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
}
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js', '.html'],
|
||||
},
|
||||
output: {
|
||||
filename: 'bundle.js',
|
||||
path: path.resolve(__dirname, '../src/webserver'),
|
||||
},
|
||||
devServer: {
|
||||
}
|
||||
mode: "development",
|
||||
entry: ['./src/main.ts'],
|
||||
devtool: 'inline-source-map',
|
||||
plugins: [
|
||||
new webpack.DefinePlugin({
|
||||
PUBLIC_URL: JSON.stringify(host),
|
||||
}),
|
||||
new webpack.EnvironmentPlugin({
|
||||
redirect: 'true'
|
||||
}),
|
||||
new HtmlWebpackPlugin({
|
||||
alwaysWriteToDisk: true,
|
||||
title: "PlantCtrl",
|
||||
}),
|
||||
new HtmlWebpackHarddiskPlugin(),
|
||||
new CompressionPlugin({
|
||||
algorithm: "gzip",
|
||||
test: /\.js$|\.css$|\.html$/,
|
||||
threshold: 0,
|
||||
minRatio: 0.8
|
||||
})
|
||||
],
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.html$/,
|
||||
type: 'asset/source',
|
||||
},
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
}
|
||||
]
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js', '.html'],
|
||||
},
|
||||
output: {
|
||||
filename: 'bundle.js',
|
||||
path: path.resolve(__dirname, '.'),
|
||||
},
|
||||
devServer: {}
|
||||
};
|
||||
|
Reference in New Issue
Block a user